<commit_before>#![deny(unused)]
#![cfg_attr(test, deny(warnings))]
#![recursion_limit="128"]

#[macro_use] extern crate failure;
#[macro_use] extern crate log;
#[macro_use] extern crate scoped_tls;
#[macro_use] extern crate serde_derive;
#[macro_use] extern crate serde_json;
extern crate atty;
extern crate crates_io as registry;
extern crate crossbeam;
extern crate curl;
extern crate docopt;
extern crate filetime;
extern crate flate2;
extern crate fs2;
extern crate git2;
extern crate glob;
extern crate hex;
extern crate home;
extern crate ignore;
extern crate jobserver;
extern crate lazycell;
extern crate libc;
extern crate libgit2_sys;
extern crate num_cpus;
extern crate same_file;
extern crate semver;
extern crate serde;
extern crate serde_ignored;
extern crate shell_escape;
extern crate tar;
extern crate tempdir;
extern crate termcolor;
extern crate toml;
extern crate url;
#[cfg(target_os = "macos")]
extern crate core_foundation;

use std::fmt;

use serde::Deserialize;
use serde::ser;
use docopt::Docopt;
use failure::Error;

use core::Shell;
use core::shell::Verbosity::Verbose;

pub use util::{CargoError, CargoResult, CliError, CliResult, Config};
pub use util::errors::Internal;

pub const CARGO_ENV: &'static str = "CARGO";

pub mod core;
pub mod ops;
pub mod sources;
pub mod util;

pub struct CommitInfo {
    pub short_commit_hash: String,
    pub commit_hash: String,
    pub commit_date: String,
}

pub struct CfgInfo {
    // Information about the git repository we may have been built from.
    pub commit_info: Option<CommitInfo>,
    // The release channel we were built for.
    pub release_channel: String,
}

pub struct VersionInfo {
    pub major: String,
    pub minor: String,
    pub patch: String,
    pub pre_release: Option<String>,
    // Information that's only available when we were built with
    // configure/make, rather than cargo itself.
    pub cfg_info: Option<CfgInfo>,
}

impl fmt::Display for VersionInfo {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "cargo {}.{}.{}",
               self.major, self.minor, self.patch)?;
        if let Some(channel) = self.cfg_info.as_ref().map(|ci| &ci.release_channel) {
            if channel != "stable" {
                write!(f, "-{}", channel)?;
                let empty = String::from("");
                write!(f, "{}", self.pre_release.as_ref().unwrap_or(&empty))?;
            }
        };

        if let Some(ref cfg) = self.cfg_info {
            if let Some(ref ci) = cfg.commit_info {
                write!(f, " ({} {})",
                       ci.short_commit_hash, ci.commit_date)?;
            }
        };
        Ok(())
    }
}

pub fn call_main_without_stdin<'de, Flags: Deserialize<'de>>(
            exec: fn(Flags, &mut Config) -> CliResult,
            config: &mut Config,
            usage: &str,
            args: &[String],
            options_first: bool) -> CliResult
{
    let docopt = Docopt::new(usage).unwrap()
        .options_first(options_first)
        .argv(args.iter().map(|s| &s[..]))
        .help(true);

    let flags = docopt.deserialize().map_err(|e| {
        let code = if e.fatal() {1} else {0};
        CliError::new(e.into(), code)
    })?;

    exec(flags, config)
}

pub fn print_json<T: ser::Serialize>(obj: &T) {
    let encoded = serde_json::to_string(&obj).unwrap();
    println!("{}", encoded);
}

pub fn exit_with_error(err: CliError, shell: &mut Shell) -> ! {
    debug!("exit_with_error; err={:?}", err);

    let CliError { error, exit_code, unknown } = err;
    // exit_code == 0 is non-fatal error, e.g. docopt version info
    let fatal = exit_code != 0;

    let hide = unknown && shell.verbosity() != Verbose;

    if let Some(error) = error {
        if hide {
            drop(shell.error("An unknown error occurred"))
        } else if fatal {
            drop(shell.error(&error))
        } else {
            println!("{}", error);
        }

        if !handle_cause(&error, shell) || hide {
            drop(writeln!(shell.err(), "\nTo learn more, run the command again \
                                        with --verbose."));
        }
    }

    std::process::exit(exit_code)
}

pub fn handle_error(err: CargoError, shell: &mut Shell) {
    debug!("handle_error; err={:?}", &err);

    let _ignored_result = shell.error(&err);
    handle_cause(&err, shell);
}

fn handle_cause(cargo_err: &Error, shell: &mut Shell) -> bool {
    fn print(error: String, shell: &mut Shell) {
        drop(writeln!(shell.err(), "\nCaused by:"));
        drop(writeln!(shell.err(), "  {}", error));
    }

    let verbose = shell.verbosity();

    if verbose == Verbose {
        // The first error has already been printed to the shell
        // Print all remaining errors
        for err in cargo_err.causes().skip(1) {
            print(err.to_string(), shell);
        }
    } else {
        // The first error has already been printed to the shell
        // Print remaining errors until one marked as Internal appears
        for err in cargo_err.causes().skip(1) {
            if err.downcast_ref::<Internal>().is_some() {
                return false;
            }

            print(err.to_string(), shell);
        }
    }

    true
}

pub fn version() -> VersionInfo {
    macro_rules! env_str {
        ($name:expr) => { env!($name).to_string() }
    }
    macro_rules! option_env_str {
        ($name:expr) => { option_env!($name).map(|s| s.to_string()) }
    }
    match option_env!("CFG_RELEASE_CHANNEL") {
        // We have environment variables set up from configure/make.
        Some(_) => {
            let commit_info =
                option_env!("CFG_COMMIT_HASH").map(|s| {
                    CommitInfo {
                        commit_hash: s.to_string(),
                        short_commit_hash: option_env_str!("CFG_SHORT_COMMIT_HASH").unwrap(),
                        commit_date: option_env_str!("CFG_COMMIT_DATE").unwrap(),
                    }
                });
            VersionInfo {
                major: env_str!("CARGO_PKG_VERSION_MAJOR"),
                minor: env_str!("CARGO_PKG_VERSION_MINOR"),
                patch: env_str!("CARGO_PKG_VERSION_PATCH"),
                pre_release: option_env_str!("CARGO_PKG_VERSION_PRE"),
                cfg_info: Some(CfgInfo {
                    release_channel: option_env_str!("CFG_RELEASE_CHANNEL").unwrap(),
                    commit_info: commit_info,
                }),
            }
        },
        // We are being compiled by Cargo itself.
        None => {
            VersionInfo {
                major: env_str!("CARGO_PKG_VERSION_MAJOR"),
                minor: env_str!("CARGO_PKG_VERSION_MINOR"),
                patch: env_str!("CARGO_PKG_VERSION_PATCH"),
                pre_release: option_env_str!("CARGO_PKG_VERSION_PRE"),
                cfg_info: None,
            }
        }
    }
}
<commit_msg>Fix DocOpt deserialization type bounds<commit_after>#![deny(unused)]
#![cfg_attr(test, deny(warnings))]
#![recursion_limit="128"]

#[macro_use] extern crate failure;
#[macro_use] extern crate log;
#[macro_use] extern crate scoped_tls;
#[macro_use] extern crate serde_derive;
#[macro_use] extern crate serde_json;
extern crate atty;
extern crate crates_io as registry;
extern crate crossbeam;
extern crate curl;
extern crate docopt;
extern crate filetime;
extern crate flate2;
extern crate fs2;
extern crate git2;
extern crate glob;
extern crate hex;
extern crate home;
extern crate ignore;
extern crate jobserver;
extern crate lazycell;
extern crate libc;
extern crate libgit2_sys;
extern crate num_cpus;
extern crate same_file;
extern crate semver;
extern crate serde;
extern crate serde_ignored;
extern crate shell_escape;
extern crate tar;
extern crate tempdir;
extern crate termcolor;
extern crate toml;
extern crate url;
#[cfg(target_os = "macos")]
extern crate core_foundation;

use std::fmt;

use serde::de::DeserializeOwned;
use serde::ser;
use docopt::Docopt;
use failure::Error;

use core::Shell;
use core::shell::Verbosity::Verbose;

pub use util::{CargoError, CargoResult, CliError, CliResult, Config};
pub use util::errors::Internal;

pub const CARGO_ENV: &'static str = "CARGO";

pub mod core;
pub mod ops;
pub mod sources;
pub mod util;

pub struct CommitInfo {
    pub short_commit_hash: String,
    pub commit_hash: String,
    pub commit_date: String,
}

pub struct CfgInfo {
    // Information about the git repository we may have been built from.
    pub commit_info: Option<CommitInfo>,
    // The release channel we were built for.
    pub release_channel: String,
}

pub struct VersionInfo {
    pub major: String,
    pub minor: String,
    pub patch: String,
    pub pre_release: Option<String>,
    // Information that's only available when we were built with
    // configure/make, rather than cargo itself.
    pub cfg_info: Option<CfgInfo>,
}

impl fmt::Display for VersionInfo {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "cargo {}.{}.{}",
               self.major, self.minor, self.patch)?;
        if let Some(channel) = self.cfg_info.as_ref().map(|ci| &ci.release_channel) {
            if channel != "stable" {
                write!(f, "-{}", channel)?;
                let empty = String::from("");
                write!(f, "{}", self.pre_release.as_ref().unwrap_or(&empty))?;
            }
        };

        if let Some(ref cfg) = self.cfg_info {
            if let Some(ref ci) = cfg.commit_info {
                write!(f, " ({} {})",
                       ci.short_commit_hash, ci.commit_date)?;
            }
        };
        Ok(())
    }
}

pub fn call_main_without_stdin<Flags: DeserializeOwned>(
            exec: fn(Flags, &mut Config) -> CliResult,
            config: &mut Config,
            usage: &str,
            args: &[String],
            options_first: bool) -> CliResult
{
    let docopt = Docopt::new(usage).unwrap()
        .options_first(options_first)
        .argv(args.iter().map(|s| &s[..]))
        .help(true);

    let flags = docopt.deserialize().map_err(|e| {
        let code = if e.fatal() {1} else {0};
        CliError::new(e.into(), code)
    })?;

    exec(flags, config)
}

pub fn print_json<T: ser::Serialize>(obj: &T) {
    let encoded = serde_json::to_string(&obj).unwrap();
    println!("{}", encoded);
}

pub fn exit_with_error(err: CliError, shell: &mut Shell) -> ! {
    debug!("exit_with_error; err={:?}", err);

    let CliError { error, exit_code, unknown } = err;
    // exit_code == 0 is non-fatal error, e.g. docopt version info
    let fatal = exit_code != 0;

    let hide = unknown && shell.verbosity() != Verbose;

    if let Some(error) = error {
        if hide {
            drop(shell.error("An unknown error occurred"))
        } else if fatal {
            drop(shell.error(&error))
        } else {
            println!("{}", error);
        }

        if !handle_cause(&error, shell) || hide {
            drop(writeln!(shell.err(), "\nTo learn more, run the command again \
                                        with --verbose."));
        }
    }

    std::process::exit(exit_code)
}

pub fn handle_error(err: CargoError, shell: &mut Shell) {
    debug!("handle_error; err={:?}", &err);

    let _ignored_result = shell.error(&err);
    handle_cause(&err, shell);
}

fn handle_cause(cargo_err: &Error, shell: &mut Shell) -> bool {
    fn print(error: String, shell: &mut Shell) {
        drop(writeln!(shell.err(), "\nCaused by:"));
        drop(writeln!(shell.err(), "  {}", error));
    }

    let verbose = shell.verbosity();

    if verbose == Verbose {
        // The first error has already been printed to the shell
        // Print all remaining errors
        for err in cargo_err.causes().skip(1) {
            print(err.to_string(), shell);
        }
    } else {
        // The first error has already been printed to the shell
        // Print remaining errors until one marked as Internal appears
        for err in cargo_err.causes().skip(1) {
            if err.downcast_ref::<Internal>().is_some() {
                return false;
            }

            print(err.to_string(), shell);
        }
    }

    true
}

pub fn version() -> VersionInfo {
    macro_rules! env_str {
        ($name:expr) => { env!($name).to_string() }
    }
    macro_rules! option_env_str {
        ($name:expr) => { option_env!($name).map(|s| s.to_string()) }
    }
    match option_env!("CFG_RELEASE_CHANNEL") {
        // We have environment variables set up from configure/make.
        Some(_) => {
            let commit_info =
                option_env!("CFG_COMMIT_HASH").map(|s| {
                    CommitInfo {
                        commit_hash: s.to_string(),
                        short_commit_hash: option_env_str!("CFG_SHORT_COMMIT_HASH").unwrap(),
                        commit_date: option_env_str!("CFG_COMMIT_DATE").unwrap(),
                    }
                });
            VersionInfo {
                major: env_str!("CARGO_PKG_VERSION_MAJOR"),
                minor: env_str!("CARGO_PKG_VERSION_MINOR"),
                patch: env_str!("CARGO_PKG_VERSION_PATCH"),
                pre_release: option_env_str!("CARGO_PKG_VERSION_PRE"),
                cfg_info: Some(CfgInfo {
                    release_channel: option_env_str!("CFG_RELEASE_CHANNEL").unwrap(),
                    commit_info: commit_info,
                }),
            }
        },
        // We are being compiled by Cargo itself.
        None => {
            VersionInfo {
                major: env_str!("CARGO_PKG_VERSION_MAJOR"),
                minor: env_str!("CARGO_PKG_VERSION_MINOR"),
                patch: env_str!("CARGO_PKG_VERSION_PATCH"),
                pre_release: option_env_str!("CARGO_PKG_VERSION_PRE"),
                cfg_info: None,
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Added a multiserver example supporting an arbitrary number of servers.<commit_after>extern crate futures;
extern crate irc;
extern crate tokio_core;

use std::default::Default;
use futures::future;
use irc::error;
use irc::client::prelude::*;
use tokio_core::reactor::Core;

fn main() {
    let cfg1 = Config {
        nickname: Some("pickles".to_owned()),
        server: Some("irc.fyrechat.net".to_owned()),
        channels: Some(vec!["#irc-crate".to_owned()]),
        ..Default::default()
    };
    let cfg2 = Config {
        nickname: Some("pickles".to_owned()),
        server: Some("irc.pdgn.co".to_owned()),
        channels: Some(vec!["#irc-crate".to_owned()]),
        use_ssl: Some(true),
        ..Default::default()
    };

    let configs = vec![cfg1, cfg2];

    // Create an event loop to run the multiple connections on.
    let mut reactor = Core::new().unwrap();
    let handle = reactor.handle();

    for config in configs {
        let server = IrcServer::from_config(config).unwrap();
        server.identify().unwrap();

        handle.spawn(server.stream().for_each(move |message| {
            process_msg(&server, message)
        }).map_err(|e| Err(e).unwrap()))
    }

    // You might instead want to join all the futures and run them directly.
    reactor.run(future::empty::<(), ()>()).unwrap();
}

fn process_msg(server: &IrcServer, message: Message) -> error::Result<()> {
    print!("{}", message);
    match message.command {
        Command::PRIVMSG(ref target, ref msg) => {
            if msg.contains("pickles") {
                server.send_privmsg(target, "Hi!")?;
            }
        }
        _ => (),
    }
    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>Rust: more Iterator<Rect> examples.<commit_after>use std::slice::Iter;
use std::iter::Filter;

fn make_vec() -> Vec<i32> {
    vec![4, 5, 6, -1, -100, 2, 400, 400, 500, 600, 11, 13, 15, 17, 19, 21, 23, 25]
}

pub fn run() {
    println!("********* Iterator - missing Linq examples *********");
    // demo_union();
    // demo_single();
    // demo_single_or_default();
    // demo_intersect();
    // demo_join();
    // demo_first();
    // demo_distinct();
}

<|endoftext|>


<commit_before><commit_msg>Initial commit<commit_after>extern crate diesel_demo;
extern crate diesel;

use self::diesel_demo::*;
use self::diesel_demo::models::*;
use self::diesel::prelude::*;

fn main()
{
    use diesel_demo::schema::posts::dsl::*;

    let connection = establish_connection();
    let results = posts.filter(published.eq(true))
        .limit(5)
        .load::<Post>(&connection)
        .expect("Error loading posts");

    println!("Displaying {} posts", results.len());
    for post in results
    {
        println!("{}", post.title);
        println!("--------\n");
        println!("{}", post.body);
    }
}<|endoftext|>


<commit_before><commit_msg>Document processes.<commit_after><|endoftext|>


<commit_before><commit_msg>Add sensor read methods<commit_after>use std;
use std::fs::File;
use std::io::prelude::*;

fn get<T>(filename : & str) -> T where T : std::str::FromStr, <T>::Err: std::fmt::Display {
    let mut file = match File::open(filename) {
        Err(why) => panic!("couldn't open {}: {}", filename, why),
        Ok(file) => file
    };

    let mut s = String::new();
    match file.read_to_string(&mut s) {
        Err(why) => panic!("couldn't read {}: {}", filename, why),
        Ok(_) => {
            let mut lines = s.lines();
            match lines.next() {
                None => panic!("couldn't extract line {}", s),
                Some(l) => match l.parse::<T>() {
                    Err(why) => panic!("couldn't parse {}: {}", l, why),
                    Ok(val) => val
                }
            }
        }
    }
}

pub fn get_pressure() -> f32 {
	get::<f32>("/sys/bus/i2c/devices/i2c-1/1-0076/iio:device1/in_pressure_input")
}

pub fn get_bmp280_temperature() -> i32 {
    get::<i32>("/sys/bus/i2c/devices/i2c-1/1-0076/iio:device1/in_temp_input")
}

pub fn get_htu21_temperature() -> i32{
    get::<i32>("/sys/bus/i2c/devices/i2c-1/1-0040/iio:device0/in_temp_input")
}

pub fn get_htu21_humidity() -> i32{
    get::<i32>("/sys/bus/i2c/devices/i2c-1/1-0040/iio:device0/in_humidityrelative_input")
}
<|endoftext|>


<commit_before><commit_msg>forgot to add the file itself<commit_after>//! pseudo authenticator for use with plain access tokens
use crate::error::Error;
use crate::types::TokenInfo;
use hyper::client::connect::Connection;
// use hyper::header;
use http::Uri;
// use serde::{Deserialize, Serialize};
use std::error::Error as StdError;
use tokio::io::{AsyncRead, AsyncWrite};
use tower_service::Service;
// use url::form_urlencoded;

/// the flow for the access token authenticator
pub struct AccessTokenFlow {
    pub(crate) access_token: String,
}

impl AccessTokenFlow {
    /// just return the access token
    pub(crate) async fn token<S, T>(
        &self,
        _hyper_client: &hyper::Client<S>,
        _scopes: &[T],
    ) -> Result<TokenInfo, Error>
    where
        T: AsRef<str>,
        S: Service<Uri> + Clone + Send + Sync + 'static,
        S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static,
        S::Future: Send + Unpin + 'static,
        S::Error: Into<Box<dyn StdError + Send + Sync>>,
    {
        Ok(TokenInfo {
            access_token: self.access_token.clone(),
            refresh_token: None,
            expires_at: None,
            id_token: None,
        })
    }
}
<|endoftext|>


<commit_before>use quote::{ToTokens, Tokens};
use syn::{Field, Meta, NestedMeta};

use api::strip_serde_attrs;

#[derive(Debug)]
pub struct Response {
    fields: Vec<ResponseField>,
}

impl Response {
    pub fn has_body_fields(&self) -> bool {
        self.fields.iter().any(|field| field.is_body())
    }

    pub fn has_fields(&self) -> bool {
        self.fields.len() != 0
    }

    pub fn has_header_fields(&self) -> bool {
        self.fields.iter().any(|field| field.is_header())
    }

    pub fn init_fields(&self) -> Tokens {
        let mut tokens = Tokens::new();

        for response_field in self.fields.iter() {
            match *response_field {
                ResponseField::Body(ref field) => {
                    let field_name = field.ident.as_ref()
                        .expect("expected body field to have a name");

                    tokens.append(quote! {
                        #field_name: response_body.#field_name,
                    });
                }
                ResponseField::Header(ref field) => {
                    let field_name = field.ident.as_ref()
                        .expect("expected body field to have a name");
                    let field_type = &field.ty;

                    tokens.append(quote! {
                        #field_name: headers.remove::<#field_type>()
                            .expect("missing expected request header"),
                    });
                }
                ResponseField::NewtypeBody(ref field) => {
                    let field_name = field.ident.as_ref()
                        .expect("expected body field to have a name");

                    tokens.append(quote! {
                        #field_name: response_body,
                    });
                }
            }
        }

        tokens
    }

    pub fn newtype_body_field(&self) -> Option<&Field> {
        for response_field in self.fields.iter() {
            match *response_field {
                ResponseField::NewtypeBody(ref field) => {

                    return Some(field);
                }
                _ => continue,
            }
        }

        None
    }

}

impl From<Vec<Field>> for Response {
    fn from(fields: Vec<Field>) -> Self {
        let mut has_newtype_body = false;

        let response_fields = fields.into_iter().map(|mut field| {
            let mut response_field_kind = ResponseFieldKind::Body;

            field.attrs = field.attrs.into_iter().filter(|attr| {
                let (attr_ident, nested_meta_items) = match attr.value {
                    Meta::List(ref attr_ident, ref nested_meta_items) => {
                        (attr_ident, nested_meta_items)
                    }
                    _ => return true,
                };

                if attr_ident != "ruma_api" {
                    return true;
                }

                for nested_meta_item in nested_meta_items {
                    match *nested_meta_item {
                        NestedMeta::Meta(ref meta_item) => {
                            match *meta_item {
                                Meta::Word(ref ident) => {
                                    if ident == "body" {
                                        has_newtype_body = true;
                                        response_field_kind = ResponseFieldKind::NewtypeBody;
                                    } else if ident == "header" {
                                        response_field_kind = ResponseFieldKind::Header;
                                    } else {
                                        panic!(
                                            "ruma_api! attribute meta item on responses must be: header"
                                        );
                                    }
                                }
                                _ => panic!(
                                    "ruma_api! attribute meta item on requests cannot be a list or name/value pair"
                                ),
                            }
                        }
                        NestedMeta::Literal(_) => panic!(
                            "ruma_api! attribute meta item on responses must be: header"
                        ),
                    }
                }

                false
            }).collect();

            match response_field_kind {
                ResponseFieldKind::Body => {
                    if has_newtype_body {
                        panic!("ruma_api! responses cannot have both normal body fields and a newtype body field");
                    } else {
                        return ResponseField::Body(field);
                    }
                }
                ResponseFieldKind::Header => ResponseField::Header(field),
                ResponseFieldKind::NewtypeBody => ResponseField::NewtypeBody(field),
            }
        }).collect();

        Response {
            fields: response_fields,
        }
    }
}

impl ToTokens for Response {
    fn to_tokens(&self, mut tokens: &mut Tokens) {
        tokens.append(quote! {
            /// Data in the response from this API endpoint.
            #[derive(Debug)]
            pub struct Response
        });

        if self.fields.len() == 0 {
            tokens.append(";");
        } else {
            tokens.append("{");

            for response_field in self.fields.iter() {
                strip_serde_attrs(response_field.field()).to_tokens(&mut tokens);

                tokens.append(",");
            }

            tokens.append("}");
        }

        if let Some(newtype_body_field) = self.newtype_body_field() {
            let mut field = newtype_body_field.clone();

            field.ident = None;

            tokens.append(quote! {
                /// Data in the response body.
                #[derive(Debug, Deserialize)]
                struct ResponseBody
            });

            tokens.append("(");

            field.to_tokens(&mut tokens);

            tokens.append(");");
        } else if self.has_body_fields() {
            tokens.append(quote! {
                /// Data in the response body.
                #[derive(Debug, Deserialize)]
                struct ResponseBody
            });

            tokens.append("{");

            for response_field in self.fields.iter() {
                match *response_field {
                    ResponseField::Body(ref field) => {
                        field.to_tokens(&mut tokens);

                        tokens.append(",");
                    }
                    _ => {}
                }
            }

            tokens.append("}");
        }
    }
}

#[derive(Debug)]
pub enum ResponseField {
    Body(Field),
    Header(Field),
    NewtypeBody(Field),
}

impl ResponseField {
    fn field(&self) -> &Field {
        match *self {
            ResponseField::Body(ref field) => field,
            ResponseField::Header(ref field) => field,
            ResponseField::NewtypeBody(ref field) => field,
        }
    }

    fn is_body(&self) -> bool {
        match *self {
            ResponseField::Body(_) => true,
            _ => false,
        }
    }

    fn is_header(&self) -> bool {
        match *self {
            ResponseField::Header(_) => true,
            _ => false,
        }
    }
}

enum ResponseFieldKind {
    Body,
    Header,
    NewtypeBody,
}
<commit_msg>ExprStruct --> Response<commit_after>use quote::{ToTokens, Tokens};
use syn::{ExprStruct, Field, FieldValue, FieldsNamed, Meta, NestedMeta};

use api::strip_serde_attrs;

pub struct Response {
    fields: Vec<ResponseField>,
}

impl Response {
    pub fn has_body_fields(&self) -> bool {
        self.fields.iter().any(|field| field.is_body())
    }

    pub fn has_fields(&self) -> bool {
        self.fields.len() != 0
    }

    pub fn has_header_fields(&self) -> bool {
        self.fields.iter().any(|field| field.is_header())
    }

    pub fn init_fields(&self) -> Tokens {
        let mut tokens = Tokens::new();

        for response_field in self.fields.iter() {
            match *response_field {
                ResponseField::Body(ref field) => {
                    let field_name = field.ident.as_ref()
                        .expect("expected body field to have a name");

                    tokens.append(quote! {
                        #field_name: response_body.#field_name,
                    });
                }
                ResponseField::Header(ref field) => {
                    let field_name = field.ident.as_ref()
                        .expect("expected body field to have a name");
                    let field_type = &field.ty;

                    tokens.append(quote! {
                        #field_name: headers.remove::<#field_type>()
                            .expect("missing expected request header"),
                    });
                }
                ResponseField::NewtypeBody(ref field) => {
                    let field_name = field.ident.as_ref()
                        .expect("expected body field to have a name");

                    tokens.append(quote! {
                        #field_name: response_body,
                    });
                }
            }
        }

        tokens
    }

    pub fn newtype_body_field(&self) -> Option<&Field> {
        for response_field in self.fields.iter() {
            match *response_field {
                ResponseField::NewtypeBody(ref field) => {

                    return Some(field);
                }
                _ => continue,
            }
        }

        None
    }

}

impl From<ExprStruct> for Response {
    fn from(expr: ExprStruct) -> Self {
        let mut has_newtype_body = false;

        let fields = expr.fields.into_iter().map(|mut field_value| {
            let mut field_kind = ResponseFieldKind::Body;

            field_value.attrs = field_value.attrs.into_iter().filter(|attr| {
                let meta = attr.interpret_meta()
                    .expect("ruma_api! could not parse response field attributes");

                let Meta::List(meta_list) = meta;

                if meta_list.ident.as_ref() != "ruma_api" {
                    return true;
                }

                for nested_meta_item in meta_list.nested {
                    match nested_meta_item {
                        NestedMeta::Meta(meta_item) => {
                            match meta_item {
                                Meta::Word(ident) => {
                                    match ident.as_ref() {
                                        "body" => {
                                        has_newtype_body = true;
                                        field_kind = ResponseFieldKind::NewtypeBody;
                                    }
                                    "header" => field_kind = ResponseFieldKind::Header,
                                    _ => panic!(
                                            "ruma_api! attribute meta item on responses must be: header"
                                        ),
                                    }
                                }
                                _ => panic!(
                                    "ruma_api! attribute meta item on responses cannot be a list or name/value pair"
                                ),
                            }
                        }
                        NestedMeta::Literal(_) => panic!(
                            "ruma_api! attribute meta item on responses must be: header"
                        ),
                    }
                }

                false
            }).collect();

            match field_kind {
                ResponseFieldKind::Body => {
                    if has_newtype_body {
                        panic!("ruma_api! responses cannot have both normal body fields and a newtype body field");
                    } else {
                        return ResponseField::Body(field_value);
                    }
                }
                ResponseFieldKind::Header => ResponseField::Header(field_value),
                ResponseFieldKind::NewtypeBody => ResponseField::NewtypeBody(field_value),
            }
        }).collect();

        Response {
            fields,
        }
    }
}

impl ToTokens for Response {
    fn to_tokens(&self, mut tokens: &mut Tokens) {
        tokens.append(quote! {
            /// Data in the response from this API endpoint.
            #[derive(Debug)]
            pub struct Response
        });

        if self.fields.len() == 0 {
            tokens.append(";");
        } else {
            tokens.append("{");

            for response_field in self.fields.iter() {
                strip_serde_attrs(response_field.field()).to_tokens(&mut tokens);

                tokens.append(",");
            }

            tokens.append("}");
        }

        if let Some(newtype_body_field) = self.newtype_body_field() {
            let mut field = newtype_body_field.clone();

            field.ident = None;

            tokens.append(quote! {
                /// Data in the response body.
                #[derive(Debug, Deserialize)]
                struct ResponseBody
            });

            tokens.append("(");

            field.to_tokens(&mut tokens);

            tokens.append(");");
        } else if self.has_body_fields() {
            tokens.append(quote! {
                /// Data in the response body.
                #[derive(Debug, Deserialize)]
                struct ResponseBody
            });

            tokens.append("{");

            for response_field in self.fields.iter() {
                match *response_field {
                    ResponseField::Body(ref field) => {
                        field.to_tokens(&mut tokens);

                        tokens.append(",");
                    }
                    _ => {}
                }
            }

            tokens.append("}");
        }
    }
}

pub enum ResponseField {
    Body(FieldValue),
    Header(FieldValue),
    NewtypeBody(FieldValue),
}

impl ResponseField {
    fn field(&self) -> &FieldValue {
        match *self {
            ResponseField::Body(ref field) => field,
            ResponseField::Header(ref field) => field,
            ResponseField::NewtypeBody(ref field) => field,
        }
    }

    fn is_body(&self) -> bool {
        match *self {
            ResponseField::Body(_) => true,
            _ => false,
        }
    }

    fn is_header(&self) -> bool {
        match *self {
            ResponseField::Header(_) => true,
            _ => false,
        }
    }
}

enum ResponseFieldKind {
    Body,
    Header,
    NewtypeBody,
}
<|endoftext|>


<commit_before>#![cfg(feature = "cognito-sync")]

extern crate rusoto_core;
extern crate rusoto_cognito_sync;

use rusoto_cognito_sync::{CognitoSync, CognitoSyncClient, ListIdentityPoolUsageRequest};
use rusoto_core::{DefaultCredentialsProvider, Region, default_tls_client};

#[test]
fn should_list_identity_pool_usage() {
    let credentials = DefaultCredentialsProvider::new().unwrap();
    let client = CognitoSyncClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
    let request = ListIdentityPoolUsageRequest::default();

    let result = client.list_identity_pool_usage(&request).unwrap();
	println!("{:#?}", result);
}<commit_msg>Fix whitespace issue in test.<commit_after>#![cfg(feature = "cognito-sync")]

extern crate rusoto_core;
extern crate rusoto_cognito_sync;

use rusoto_cognito_sync::{CognitoSync, CognitoSyncClient, ListIdentityPoolUsageRequest};
use rusoto_core::{DefaultCredentialsProvider, Region, default_tls_client};

#[test]
fn should_list_identity_pool_usage() {
    let credentials = DefaultCredentialsProvider::new().unwrap();
    let client = CognitoSyncClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
    let request = ListIdentityPoolUsageRequest::default();

    let result = client.list_identity_pool_usage(&request).unwrap();
    println!("{:#?}", result);
}<|endoftext|>


<commit_before>// Coherence phase
//
// The job of the coherence phase of typechecking is to ensure that each trait
// has at most one implementation for each type. Then we build a mapping from
// each trait in the system to its implementations.

import middle::ty::{get, t, ty_box, ty_uniq, ty_ptr, ty_rptr, ty_enum};
import middle::ty::{ty_class, ty_nil, ty_bot, ty_bool, ty_int, ty_uint};
import middle::ty::{ty_float, ty_str, ty_estr, ty_vec, ty_evec, ty_rec};
import middle::ty::{ty_fn, ty_trait, ty_tup, ty_var, ty_var_integral};
import middle::ty::{ty_param, ty_self, ty_constr, ty_type, ty_opaque_box};
import middle::ty::{ty_opaque_closure_ptr, ty_unboxed_vec, new_ty_hash};
import middle::ty::{subst};
import middle::typeck::infer::{infer_ctxt, mk_eqty, new_infer_ctxt};
import syntax::ast::{crate, def_id, item, item_impl, method, region_param};
import syntax::ast::{trait_ref};
import syntax::ast_util::{def_id_of_def, new_def_hash};
import syntax::visit::{default_simple_visitor, mk_simple_visitor};
import syntax::visit::{visit_crate};

import dvec::{dvec, extensions};
import result::{extensions};
import std::map::hashmap;
import uint::range;

class CoherenceInfo {
    // Contains implementations of methods that are inherent to a type.
    // Methods in these implementations don't need to be exported.
    let inherent_methods: hashmap<t,@dvec<@item>>;

    // Contains implementations of methods associated with a trait. For these,
    // the associated trait must be imported at the call site.
    let extension_methods: hashmap<def_id,@dvec<@item>>;

    new() {
        self.inherent_methods = new_ty_hash();
        self.extension_methods = new_def_hash();
    }
}

class CoherenceChecker {
    let crate_context: @crate_ctxt;
    let inference_context: infer_ctxt;
    let info: @CoherenceInfo;

    new(crate_context: @crate_ctxt) {
        self.crate_context = crate_context;
        self.inference_context = new_infer_ctxt(crate_context.tcx);
        self.info = @CoherenceInfo();
    }

    fn check_coherence(crate: @crate) {
        // Check implementations. This populates the tables containing the
        // inherent methods and extension methods.

        visit_crate(*crate, (), mk_simple_visitor(@{
            visit_item: |item| {
                alt item.node {
                    item_impl(_, _, associated_trait, self_type, _) {
                        self.check_implementation(item, associated_trait);
                    }
                    _ {
                        // Nothing to do.
                    }
                };
            }
            with *default_simple_visitor()
        }));

        // Check trait coherence.
        for self.info.extension_methods.each |def_id, items| {
            self.check_implementation_coherence(def_id, items);
        }
    }

    fn check_implementation(item: @item,
                            optional_associated_trait: option<@trait_ref>) {

        let self_type = self.crate_context.tcx.tcache.get(local_def(item.id));
        alt optional_associated_trait {
            none {
                alt self.get_base_type(self_type.ty) {
                    none {
                        let session = self.crate_context.tcx.sess;
                        session.span_warn(item.span,
                                          "no base type found for inherent \
                                           implementation; implement a trait \
                                           instead");
                    }
                    some(base_type) {
                        let implementation_list;
                        alt self.info.inherent_methods.find(base_type) {
                            none {
                                implementation_list = @dvec();
                            }
                            some(existing_implementation_list) {
                                implementation_list =
                                    existing_implementation_list;
                            }
                        }

                        implementation_list.push(item);
                    }
                }
            }
            some(associated_trait) {
                let def =
                    self.crate_context.tcx.def_map.get(associated_trait.id);
                let def_id = def_id_of_def(def);

                let implementation_list;
                alt self.info.extension_methods.find(def_id) {
                    none {
                        implementation_list = @dvec();
                    }
                    some(existing_implementation_list) {
                        implementation_list = existing_implementation_list;
                    }
                }

                implementation_list.push(item);
            }
        }
    }

    fn get_base_type(original_type: t) -> option<t> {
        alt get(original_type).struct {
            ty_box(base_mutability_and_type) |
            ty_uniq(base_mutability_and_type) |
            ty_ptr(base_mutability_and_type) |
            ty_rptr(_, base_mutability_and_type) {
                self.get_base_type(base_mutability_and_type.ty)
            }

            ty_enum(*) | ty_class(*) {
                some(original_type)
            }

            ty_nil | ty_bot | ty_bool | ty_int(*) | ty_uint(*) | ty_float(*) |
            ty_str | ty_estr(*) | ty_vec(*) | ty_evec(*) | ty_rec(*) |
            ty_fn(*) | ty_trait(*) | ty_tup(*) | ty_var(*) |
            ty_var_integral(*) | ty_param(*) | ty_self | ty_constr(*) |
            ty_type | ty_opaque_box | ty_opaque_closure_ptr(*) |
            ty_unboxed_vec(*) {
                none
            }
        }
    }

    fn check_implementation_coherence(_trait_def_id: def_id,
                                      implementations: @dvec<@item>) {

        // Unify pairs of polytypes.
        for implementations.eachi |i, implementation_a| {
            let polytype_a =
                self.get_self_type_for_implementation(implementation_a);
            for range(i + 1, implementations.len()) |j| {
                let implementation_b = implementations.get_elt(j);
                let polytype_b =
                    self.get_self_type_for_implementation(implementation_b);

                if self.polytypes_unify(polytype_a, polytype_b) {
                    let session = self.crate_context.tcx.sess;
                    session.span_err(implementation_b.span,
                                     "conflicting implementations for a \
                                      trait");
                    session.span_note(implementation_a.span,
                                      "note conflicting implementation here");
                }
            }
        }
    }

    fn polytypes_unify(polytype_a: ty_param_bounds_and_ty,
                       polytype_b: ty_param_bounds_and_ty)
                    -> bool {

        let monotype_a = self.universally_quantify_polytype(polytype_a);
        let monotype_b = self.universally_quantify_polytype(polytype_b);
        ret mk_eqty(self.inference_context, monotype_a, monotype_b).is_ok();
    }

    // Converts a polytype to a monotype by replacing all parameters with
    // type variables.
    fn universally_quantify_polytype(polytype: ty_param_bounds_and_ty) -> t {
        let self_region;
        alt polytype.rp {
            ast::rp_none {
                self_region = none;
            }
            ast::rp_self {
                self_region = some(self.inference_context.next_region_var())
            }
        };

        let bounds_count = polytype.bounds.len();
        let type_parameters =
            self.inference_context.next_ty_vars(bounds_count);

        let substitutions = {
            self_r: self_region,
            self_ty: none,
            tps: type_parameters
        };

        ret subst(self.crate_context.tcx, substitutions, polytype.ty);
    }

    fn get_self_type_for_implementation(implementation: @item)
                                     -> ty_param_bounds_and_ty {

        alt implementation.node {
            item_impl(*) {
                let def = local_def(implementation.id);
                ret self.crate_context.tcx.tcache.get(def);
            }
            _ {
                self.crate_context.tcx.sess.span_bug(implementation.span,
                                                     "not an implementation");
            }
        }
    }
}

fn check_coherence(crate_context: @crate_ctxt, crate: @crate) {
    CoherenceChecker(crate_context).check_coherence(crate);
}

<commit_msg>rustc: Add some more checks to coherence<commit_after>// Coherence phase
//
// The job of the coherence phase of typechecking is to ensure that each trait
// has at most one implementation for each type. Then we build a mapping from
// each trait in the system to its implementations.

import middle::ty::{get, t, ty_box, ty_uniq, ty_ptr, ty_rptr, ty_enum};
import middle::ty::{ty_class, ty_nil, ty_bot, ty_bool, ty_int, ty_uint};
import middle::ty::{ty_float, ty_str, ty_estr, ty_vec, ty_evec, ty_rec};
import middle::ty::{ty_fn, ty_trait, ty_tup, ty_var, ty_var_integral};
import middle::ty::{ty_param, ty_self, ty_constr, ty_type, ty_opaque_box};
import middle::ty::{ty_opaque_closure_ptr, ty_unboxed_vec, new_ty_hash};
import middle::ty::{subst};
import middle::typeck::infer::{infer_ctxt, mk_subty, new_infer_ctxt};
import syntax::ast::{crate, def_id, item, item_class, item_const, item_enum};
import syntax::ast::{item_fn, item_foreign_mod, item_impl, item_mac};
import syntax::ast::{item_mod, item_trait, item_ty, local_crate, method};
import syntax::ast::{node_id, region_param, rp_none, rp_self, trait_ref};
import syntax::ast_util::{def_id_of_def, new_def_hash};
import syntax::visit::{default_simple_visitor, default_visitor};
import syntax::visit::{mk_simple_visitor, mk_vt, visit_crate, visit_item};
import syntax::visit::{visit_mod};
import util::ppaux::ty_to_str;

import dvec::{dvec, extensions};
import result::{extensions};
import std::map::{hashmap, int_hash};
import uint::range;

class CoherenceInfo {
    // Contains implementations of methods that are inherent to a type.
    // Methods in these implementations don't need to be exported.
    let inherent_methods: hashmap<t,@dvec<@item>>;

    // Contains implementations of methods associated with a trait. For these,
    // the associated trait must be imported at the call site.
    let extension_methods: hashmap<def_id,@dvec<@item>>;

    new() {
        self.inherent_methods = new_ty_hash();
        self.extension_methods = new_def_hash();
    }
}

class CoherenceChecker {
    let crate_context: @crate_ctxt;
    let inference_context: infer_ctxt;
    let info: @CoherenceInfo;

    // A mapping from implementations to the corresponding base type
    // definition ID.
    let base_type_def_ids: hashmap<node_id,def_id>;

    // A set of implementations in privileged scopes; i.e. those
    // implementations that are defined in the same scope as their base types.
    let privileged_implementations: hashmap<node_id,()>;

    // The set of types that we are currently in the privileged scope of. This
    // is used while we traverse the AST while checking privileged scopes.
    let privileged_types: hashmap<def_id,()>;

    new(crate_context: @crate_ctxt) {
        self.crate_context = crate_context;
        self.inference_context = new_infer_ctxt(crate_context.tcx);
        self.info = @CoherenceInfo();

        self.base_type_def_ids = int_hash();
        self.privileged_implementations = int_hash();
        self.privileged_types = new_def_hash();
    }

    fn check_coherence(crate: @crate) {
        // Check implementations. This populates the tables containing the
        // inherent methods and extension methods.

        visit_crate(*crate, (), mk_simple_visitor(@{
            visit_item: |item| {
                alt item.node {
                    item_impl(_, _, associated_trait, self_type, _) {
                        self.check_implementation(item, associated_trait);
                    }
                    _ {
                        // Nothing to do.
                    }
                };
            }
            with *default_simple_visitor()
        }));

        // Check trait coherence.
        for self.info.extension_methods.each |def_id, items| {
            self.check_implementation_coherence(def_id, items);
        }

        // Check whether traits with base types are in privileged scopes.
        self.check_privileged_scopes(crate);
    }

    fn check_implementation(item: @item,
                            optional_associated_trait: option<@trait_ref>) {

        let self_type = self.crate_context.tcx.tcache.get(local_def(item.id));
        alt optional_associated_trait {
            none {
                alt self.get_base_type(self_type.ty) {
                    none {
                        let session = self.crate_context.tcx.sess;
                        session.span_warn(item.span,
                                          "no base type found for inherent \
                                           implementation; implement a trait \
                                           instead");
                    }
                    some(base_type) {
                        let implementation_list;
                        alt self.info.inherent_methods.find(base_type) {
                            none {
                                implementation_list = @dvec();
                            }
                            some(existing_implementation_list) {
                                implementation_list =
                                    existing_implementation_list;
                            }
                        }

                        implementation_list.push(item);
                    }
                }
            }
            some(associated_trait) {
                let def =
                    self.crate_context.tcx.def_map.get(associated_trait.id);
                let def_id = def_id_of_def(def);

                let implementation_list;
                alt self.info.extension_methods.find(def_id) {
                    none {
                        implementation_list = @dvec();
                    }
                    some(existing_implementation_list) {
                        implementation_list = existing_implementation_list;
                    }
                }

                implementation_list.push(item);
            }
        }

        // Add the implementation to the mapping from implementation to base
        // type def ID, if there is a base type for this implementation.
        alt self.get_base_type_def_id(self_type.ty) {
            none {
                // Nothing to do.
            }
            some(base_type_def_id) {
                self.base_type_def_ids.insert(item.id, base_type_def_id);
            }
        }
    }

    fn get_base_type(original_type: t) -> option<t> {
        alt get(original_type).struct {
            ty_box(base_mutability_and_type) |
            ty_uniq(base_mutability_and_type) |
            ty_ptr(base_mutability_and_type) |
            ty_rptr(_, base_mutability_and_type) {
                self.get_base_type(base_mutability_and_type.ty)
            }

            ty_enum(*) | ty_class(*) {
                some(original_type)
            }

            ty_nil | ty_bot | ty_bool | ty_int(*) | ty_uint(*) | ty_float(*) |
            ty_str | ty_estr(*) | ty_vec(*) | ty_evec(*) | ty_rec(*) |
            ty_fn(*) | ty_trait(*) | ty_tup(*) | ty_var(*) |
            ty_var_integral(*) | ty_param(*) | ty_self | ty_constr(*) |
            ty_type | ty_opaque_box | ty_opaque_closure_ptr(*) |
            ty_unboxed_vec(*) {
                none
            }
        }
    }

    // Returns the def ID of the base type.
    fn get_base_type_def_id(original_type: t) -> option<def_id> {
        alt self.get_base_type(original_type) {
            none {
                ret none;
            }
            some(base_type) {
                alt get(base_type).struct {
                    ty_enum(def_id, _) | ty_class(def_id, _) {
                        ret some(def_id);
                    }
                    _ {
                        fail "get_base_type() returned a type that wasn't an \
                              enum or class";
                    }
                }
            }
        }
    }

    fn check_implementation_coherence(_trait_def_id: def_id,
                                      implementations: @dvec<@item>) {

        // Unify pairs of polytypes.
        for implementations.eachi |i, implementation_a| {
            let polytype_a =
                self.get_self_type_for_implementation(implementation_a);
            for range(i + 1, implementations.len()) |j| {
                let implementation_b = implementations.get_elt(j);
                let polytype_b =
                    self.get_self_type_for_implementation(implementation_b);

                if self.polytypes_unify(polytype_a, polytype_b) {
                    let session = self.crate_context.tcx.sess;
                    session.span_err(implementation_b.span,
                                     "conflicting implementations for a \
                                      trait");
                    session.span_note(implementation_a.span,
                                      "note conflicting implementation here");
                }
            }
        }
    }

    fn polytypes_unify(polytype_a: ty_param_bounds_and_ty,
                       polytype_b: ty_param_bounds_and_ty)
                    -> bool {

        let monotype_a = self.universally_quantify_polytype(polytype_a);
        let monotype_b = self.universally_quantify_polytype(polytype_b);
        ret mk_subty(self.inference_context, monotype_a, monotype_b).is_ok()
         || mk_subty(self.inference_context, monotype_b, monotype_a).is_ok();
    }

    // Converts a polytype to a monotype by replacing all parameters with
    // type variables.
    fn universally_quantify_polytype(polytype: ty_param_bounds_and_ty) -> t {
        let self_region;
        alt polytype.rp {
            rp_none {
                self_region = none;
            }
            rp_self {
                self_region = some(self.inference_context.next_region_var())
            }
        };

        let bounds_count = polytype.bounds.len();
        let type_parameters =
            self.inference_context.next_ty_vars(bounds_count);

        let substitutions = {
            self_r: self_region,
            self_ty: none,
            tps: type_parameters
        };

        ret subst(self.crate_context.tcx, substitutions, polytype.ty);
    }

    fn get_self_type_for_implementation(implementation: @item)
                                     -> ty_param_bounds_and_ty {

        alt implementation.node {
            item_impl(*) {
                let def = local_def(implementation.id);
                ret self.crate_context.tcx.tcache.get(def);
            }
            _ {
                self.crate_context.tcx.sess.span_bug(implementation.span,
                                                     "not an implementation");
            }
        }
    }

    // Privileged scope checking

    fn check_privileged_scopes(crate: @crate) {
        visit_crate(*crate, (), mk_vt(@{
            visit_item: |item, _context, visitor| {
                alt item.node {
                    item_mod(module) {
                        // First, gather up all privileged types.
                        let privileged_types =
                            self.gather_privileged_types(module.items);
                        for privileged_types.each |privileged_type| {
                            #debug("(checking privileged scopes) entering \
                                    privileged scope of %d:%d",
                                   privileged_type.crate,
                                   privileged_type.node);

                            self.privileged_types.insert(privileged_type, ());
                        }

                        // Then visit the module items.
                        visit_mod(module, item.span, item.id, (), visitor);

                        // Finally, remove privileged types from the map.
                        for privileged_types.each |privileged_type| {
                            self.privileged_types.remove(privileged_type);
                        }
                    }
                    item_impl(_, _, optional_trait_ref, _, _) {
                        alt self.base_type_def_ids.find(item.id) {
                            none {
                                // Nothing to do.
                            }
                            some(base_type_def_id) {
                                // Check to see whether the implementation is
                                // in the scope of its base type.

                                let privileged_types = &self.privileged_types;
                                if privileged_types.
                                        contains_key(base_type_def_id) {

                                    // Record that this implementation is OK.
                                    self.privileged_implementations.insert
                                        (item.id, ());
                                } else {
                                    // This implementation is not in scope of
                                    // its base type. This still might be OK
                                    // if the trait is defined in the same
                                    // crate.

                                    alt optional_trait_ref {
                                        none {
                                            // There is no trait to implement,
                                            // so this is an error.

                                            let session =
                                                self.crate_context.tcx.sess;
                                            session.span_warn(item.span,
                                                              "cannot \
                                                               implement \
                                                               inherent \
                                                               methods for a \
                                                               type outside \
                                                               the scope the \
                                                               type was \
                                                               defined in; \
                                                               define and \
                                                               implement a \
                                                               trait \
                                                               instead");
                                        }
                                        some(trait_ref) {
                                            // This is OK if and only if the
                                            // trait was defined in this
                                            // crate.

                                            let def_map = self.crate_context
                                                .tcx.def_map;
                                            let trait_def =
                                                def_map.get(trait_ref.id);
                                            let trait_id =
                                                def_id_of_def(trait_def);
                                            if trait_id.crate != local_crate {
                                                let session = self
                                                    .crate_context.tcx.sess;
                                                session.span_warn(item.span,
                                                                  "cannot \
                                                                   provide \
                                                                   an \
                                                                   extension \
                                                                   implement\
                                                                      ation \
                                                                   for a \
                                                                   trait not \
                                                                   defined \
                                                                   in this \
                                                                   crate");
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        visit_item(item, (), visitor);
                    }
                    _ {
                        visit_item(item, (), visitor);
                    }
                }
            }
            with *default_visitor()
        }));
    }

    fn gather_privileged_types(items: ~[@item]) -> @dvec<def_id> {
        let results = @dvec();
        for items.each |item| {
            alt item.node {
                item_class(*) | item_enum(*) {
                    results.push(local_def(item.id));
                }

                item_const(*) | item_fn(*) | item_mod(*) |
                item_foreign_mod(*) | item_ty(*) | item_trait(*) |
                item_impl(*) | item_mac(*) {
                    // Nothing to do.
                }
            }
        }

        ret results;
    }
}

fn check_coherence(crate_context: @crate_ctxt, crate: @crate) {
    CoherenceChecker(crate_context).check_coherence(crate);
}

<|endoftext|>


<commit_before><commit_msg>Fix button click target<commit_after><|endoftext|>


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

mod A {
    struct C;
}

fn main() {
    A::C = 1;
    //~^ ERROR: illegal left-hand side expression
    //~| ERROR: mismatched types
}
<|endoftext|>


<commit_before><commit_msg>add regression test for #70217<commit_after>// check-pass
#![feature(const_generics)]
#![allow(incomplete_features)]

struct Struct<const N: usize>;

impl<const N: usize> Struct<N> {
    fn method<const M: usize>(&self) {}
}

fn test<const N: usize, const M: usize>(x: Struct<N>) {
    Struct::<N>::method::<M>(&x);
    x.method::<N>();
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Document zrange<commit_after><|endoftext|>


<commit_before>extern mod glfw;

fn main() {
    // Run this task on the main thread. Unlike C or C++, a Rust program
    // automatically starts a new thread, so this line is _essential_ to ensure
    // that the OS is able to update the window and recieve events from the user.
    do task::task().sched_mode(task::PlatformThread).spawn {

        glfw::set_error_callback(error_callback);

        if !glfw::init() {
            glfw::terminate();
            die!(~"Failed to initialize GLFW\n");
        }

        let window =
            match glfw::Window::create(300, 300, "Hello this is window", glfw::Windowed) {
                Some(w) => { w }
                None => {
                    glfw::terminate();
                    die!(~"Failed to open GLFW window");
                }
            };

        window.make_context_current();

        let mut done = false;

        while !done {
            glfw::poll_events();
            if (window.get_key(glfw::KEY_ESC) == glfw::PRESS || window.get_param(glfw::SHOULD_CLOSE) != 0) {
                done = true;
            }
        }

        window.destroy();
        glfw::terminate();
    }
}

fn error_callback(_error: libc::c_int, description: ~str) {
    io::println(fmt!("GLFW Error: %s", description));
}<commit_msg>Improve manual-init example<commit_after>extern mod glfw;

fn main() {
    // Run this task on the main thread. Unlike C or C++, a Rust program
    // automatically starts a new thread, so this line is _essential_ to ensure
    // that the OS is able to update the window and recieve events from the user.
    do task::task().sched_mode(task::PlatformThread).spawn  {
        use core::private::finally::Finally;

        do (|| {

            glfw::set_error_callback(error_callback);

            if !glfw::init() {
                die!(~"Failed to initialize GLFW\n");
            }

            let window =
                match glfw::Window::create(300, 300, "Hello this is window", glfw::Windowed) {
                    Some(w) => w,
                    None    => die!(~"Failed to open GLFW window")
                };

            window.make_context_current();

            let mut done = false;

            while !done {
                glfw::poll_events();
                if (window.get_key(glfw::KEY_ESC) == glfw::PRESS || window.get_param(glfw::SHOULD_CLOSE) != 0) {
                    done = true;
                }
            }

            window.destroy();

        }).finally {
            glfw::terminate();    // terminate glfw on completion
        }
    }
}

fn error_callback(_error: libc::c_int, description: ~str) {
    io::println(fmt!("GLFW Error: %s", description));
}<|endoftext|>


<commit_before><commit_msg>alloc memory from top to down<commit_after><|endoftext|>


<commit_before>/// A module for permission units
pub mod permission_unit;
/// A module for checking string (wildcard) matches
pub mod str_match;
/// A module for permissions
pub mod permission;

#[test]
fn test() {
    use str_match::*;
    use permission_unit::*;
    use permission::*;
    // Test string matches (wildcard chars)
    assert!(str_match("hey*hey", "heyabchey"));
    assert!(str_match("hey\\*hey*", "hey*heycatsarefunny"));
    // Test permission units
    assert!(PermissionUnit::from_str("rw=hey").read());
    assert!(!PermissionUnit::from_str("r=hey").write());
    assert!(PermissionUnit::from_str("r=hey").read_foc());
    assert!(PermissionUnit::from_str("r=file:home/*").applies(&PermissionUnit::from_str("R=file:home/lal")));
    assert!(PermissionUnit::from_str("R=file:home/lal").read_foc);
    assert!(PermissionUnit::from_str("r=file:home/lal").read_foc());
    assert!(!PermissionUnit::from_str("RW=http:*").read());
    // Test permissions
    assert!(Permission::from_str("rw=file:home/*-rw=file:veryimportant").test(PermissionUnit::from_str("rw=file:home/lal")));
    assert!(Permission::from_str("rw=file:home/*-rw=file:veryimportant").test(PermissionUnit::from_str("rw=file:home/veryimportant")));
    assert!(Permission::from_str("rw=i\\+can\\+do\\+like\\+this").test(PermissionUnit::from_str("rw=file:i+can+do+like+this")));
    // assert!(!Permission::from_str("RW=http:*+").test(PermissionUnit::from_str("rw=http://google.com")));
    // TODO: Failes when using uppercase RW
}
<commit_msg>It works! TODO: Focus<commit_after>/// A module for permission units
pub mod permission_unit;
/// A module for checking string (wildcard) matches
pub mod str_match;
/// A module for permissions
pub mod permission;

#[test]
fn test() {
    use str_match::*;
    use permission_unit::*;
    use permission::*;
    // Test string matches (wildcard chars)
    assert!(str_match("hey*hey", "heyabchey"));
    assert!(str_match("hey\\*hey*", "hey*heycatsarefunny"));
    // Test permission units
    assert!(PermissionUnit::from_str("rw=hey").read());
    assert!(!PermissionUnit::from_str("r=hey").write());
    assert!(PermissionUnit::from_str("r=hey").read_foc());
    assert!(PermissionUnit::from_str("r=file:home/*").applies(&PermissionUnit::from_str("R=file:home/lal")));
    assert!(PermissionUnit::from_str("R=file:home/lal").read_foc);
    assert!(PermissionUnit::from_str("r=file:home/lal").read_foc());
    assert!(!PermissionUnit::from_str("RW=http:*").read());
    // Test permissions
    assert!(Permission::from_str("rw=file:home/*-rw=file:veryimportant").test(PermissionUnit::from_str("rw=file:home/lal")));
    assert!(Permission::from_str("rw=file:home/*-rw=file:veryimportant").test(PermissionUnit::from_str("rw=file:home/veryimportant")));
    assert!(Permission::from_str("rw=i\\+can\\+do\\+like\\+this").test(PermissionUnit::from_str("rw=file:i+can+do+like+this")));

    // assert!(!Permission::from_str("RW=http:*").test(PermissionUnit::from_str("rw=http://google.com")));
    // TODO: Failes when using uppercase RW
}
<|endoftext|>


<commit_before><commit_msg>[Auto] lib/domain/contact: Fix Clippy warnings<commit_after><|endoftext|>


<commit_before><commit_msg>Calculate matches of qgram.<commit_after>// Copyright 2014 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.

use std::num::{Int, UnsignedInt, NumCast, cast};
use std::slice;

use alphabets::{Alphabet, RankTransform};

fn qgram_push<Q: UnsignedInt + NumCast>(qgram: &mut Q, a: u8) {
    *qgram = *qgram << 2;
    *qgram = *qgram | cast(a).unwrap();
}

struct QGrams<'a, Q: UnsignedInt + NumCast> {
    text: slice::Iter<'a, u8>,
    qgram: Q,
    q: usize,
    ranks: RankTransform,
}

impl<'a, Q: UnsignedInt + NumCast> QGrams<'a, Q> {
    pub fn new(q: usize, text: &'a [u8], alphabet: &Alphabet) -> Self {
        let ranks = RankTransform::new(alphabet);
        let mut qgram: Q = cast(0).unwrap();
        let mut qgrams = QGrams { text: text.iter(), qgram: qgram, q: q, ranks: ranks };
        for _ in 0..q-1 {
            qgrams.next();
        }

        qgrams
    }
}

impl<'a, Q: UnsignedInt + NumCast> Iterator for QGrams<'a, Q> {
    type Item = Q;

    fn next(&mut self) -> Option<Q> {
        match self.text.next() {
            Some(a) => {
                qgram_push(&mut self.qgram, self.ranks.get(*a));
                Some(self.qgram)
            },
            None    => None
        }
    }
}

pub struct QGramIndex<'a> {
    q: usize,
    alphabet: &'a Alphabet,
    address: Vec<usize>,
    pos: Vec<usize>,
}

impl<'a> QGramIndex<'a> {
    pub fn new(q: usize, text: &[u8], alphabet: &'a Alphabet) -> Self {
        let qgram_count = alphabet.len().pow(q as u32);
        let mut address = vec![0; qgram_count];
        let mut pos = vec![0; text.len()];

        for qgram in QGrams::<u32>::new(q, text, alphabet) {
            address[qgram as usize] += 1;
        }

        for i in 1..address.len() {
            address[i] += address[i - 1];
        }

        {
            let mut offset = vec![0; qgram_count];
            for (i, qgram) in QGrams::<u32>::new(q, text, alphabet).enumerate() {
                pos[address[qgram as usize] + offset[qgram as usize]] = i;
                offset[qgram as usize] += 1;
            }
        }

        QGramIndex { q: q, alphabet: alphabet, address: address, pos: pos }
    }

    pub fn matches(&self, qgram: u32) -> &[usize] {
        &self.pos[self.address[qgram as usize]..self.address[qgram as usize + 1]]
    }
}
<|endoftext|>


<commit_before><commit_msg>update torrent logic<commit_after><|endoftext|>


<commit_before><commit_msg>Add a check-procs script<commit_after>//! Check running processes

#![allow(unused_variables, dead_code)]

extern crate docopt;
extern crate nix;
extern crate regex;
extern crate rustc_serialize;

extern crate turbine_plugins;

use docopt::Docopt;
use nix::unistd::{getpid, getppid};
use regex::Regex;

use turbine_plugins::Status;
use turbine_plugins::procfs::RunningProcs;
use turbine_plugins::procfs::pid::Process;

static USAGE: &'static str = "
Usage:
    check-procs <pattern> (--crit-under <N> | --crit-over <N>)
    check-procs -h | --help

Check that an expected number of processes are running.

Required Arguments:

    pattern                Regex that command and its arguments must match

Options:
    -h, --help             Show this message and exit
    --crit-under=<N>       Error if there are fewer than this pattern procs
    --crit-over=<N>        Error if there are more than this pattern procs
";

#[derive(Debug, RustcDecodable)]
struct Args {
    arg_pattern: String,
    flag_crit_under: Option<usize>,
    flag_crit_over: Option<usize>
}

impl Args {
    fn parse() -> Args {
        Docopt::new(USAGE)
            .and_then(|d| d.decode())
            .unwrap_or_else(|e| e.exit())
    }
}

fn main() {
    let args = Args::parse();
    let procs = RunningProcs::currently_running().unwrap();
    let re = Regex::new(&args.arg_pattern).unwrap_or_else(|e| {
        println!("{}", e);
        Status::Critical.exit()
    });

    let me = getpid();
    let parent = getppid();

    let matches = procs.0.into_iter()
        .filter_map(
            |(pid, process): (i32, Process)|
            if re.is_match(&process.useful_cmdline()) &&
                !(pid == me || pid == parent) {
                    Some((pid, process))
                } else {
                    None
                })
        .collect::<Vec<(i32, Process)>>();

    let mut status = Status::Ok;
    if let Some(crit_over) = args.flag_crit_over {
        if matches.len() > crit_over {
            status = Status::Critical;
            println!("CRITICAL: there are {} process that match {:?} (greater than {})",
                     matches.len(), args.arg_pattern, crit_over);
        }
    };
    if let Some(crit_under) = args.flag_crit_under {
        if matches.len() < crit_under {
            status = Status::Critical;
            println!("CRITICAL: there are {} process that match {:?} (less than {})",
                     matches.len(), args.arg_pattern, crit_under);
        }
    }

    if status == Status::Ok {
        match (args.flag_crit_over, args.flag_crit_under) {
            (Some(o), Some(u)) => println!(
                "OKAY: There are {} matching procs (between {} and {})",
                matches.len(), o, u),
            (Some(o), None) => println!(
                "OKAY: There are {} matching procs (less than {})",
                matches.len(), o),
            (None, Some(u)) => println!(
                "OKAY: There are {} matching procs (greater than {})",
                matches.len(), u),
            (None, None) => unreachable!(),
        }
    }
    if matches.len() > 0 {
        println!("INFO: Matching processes:");
        for process in matches.iter().take(20) {
            println!("[{:>5}] {}", process.0, process.1.useful_cmdline());
        }
        if matches.len() > 20 {
            println!("And {} more...", matches.len() - 20)
        }
    }
    status.exit();
}

#[cfg(test)]
mod unit {
    use super::{Args, USAGE};

    use docopt::Docopt;

    #[test]
    fn validate_docstring() {
        let args: Args = Docopt::new(USAGE)
            .and_then(|d| d
                      .argv(vec!["c-p", "some.*proc", "--crit-under=1"].into_iter())
                      .decode())
            .unwrap();
    }
}
<|endoftext|>


<commit_before><commit_msg>Added basic Item to put on map.<commit_after>use tcod::colors::{Color};

use traits::{Renderable, Movable, Position};
use point::Point;

#[derive(Debug)]
pub struct Item {
    name: String,
    glyph: char,
    color: Color,
    position: Point<i16>,
}

impl Item {
    pub fn new(name: &str, glyph: char, colour: Color, pos: Point<i16>) -> Item {
        Item {
            name: name,
            glyph: glyph,
            color: color,
            position: pos,
        }
    }
}

impl Position for Unit {
    fn get_x(&self) -> i16 {
        self.position.x
    }

    fn get_y(&self) -> i16 {
        self.position.y
    }
}

impl Renderable for Unit {
    fn get_color(&self) -> Color {
        self.color
    }

    fn get_glyph(&self) -> char {
        self.glyph
    }
}<|endoftext|>


<commit_before><commit_msg>Add a example<commit_after>#[macro_use]
extern crate log;
#[macro_use]
extern crate s_structured_log;
extern crate serde_json;

use s_structured_log::{JsonLogger, LoggerOutput, q};

fn main() {
    JsonLogger::init(LoggerOutput::Stderr, log::LogLevelFilter::Info);

    // use json_object!
    s_info!(json_object! {
        "Fruits" => json_object! {
            "on_the_table" => json_object! {
                "Apple" => 1,
                "Orange" => "two",
                "Grape" => 1.0
            },
            "in_the_basket" => ["Banana", "Strawberry"]
        },
        "Pets" => [
            json_object! {
                "name" => "Tama",
                "kind" => "cat",
                "age" => 3
            },
            json_object! {
                "name" => "Pochi",
                "kind" => "dog",
                "age" => 5
            }
        ]
    });

    // use json_format! and target with `json:` prefix.
    info!(target: &format!("json:{}", module_path!()),
          "{}",
          json_format! {
        "Fruits" => json_format! {
            "on_the_table" => json_format! {
                "Apple" => 1,
                "Orange" => q("two"),
                "Grape" => 1.0
            },
            "in_the_basket" => json_format![q("Banana"), q("Strawberry")]
        },
        "Pets" => json_format![
            json_format! {
                "name" => q("Tama"),
                "kind" => q("cat"),
                "age" => 3
            },
            json_format! {
                "name" => q("Pochi"),
                "kind" => q("dog"),
                "age" => 5
            }
        ]
    });

    // use json_format! and default target.
    info!("{}",
          json_format! {
        "Fruits" => json_format! {
            "on_the_table" => json_format! {
                "Apple" => 1,
                "Orange" => 2,
                "Grape" => 1
            },
            "in_the_basket" => json_format![q("Banana"), q("Strawberry")]
        },
        "Pets" => json_format![
            json_format! {
                "name" => q("Tama"),
                "kind" => q("cat")
            },
            json_format! {
                "name" => q("Pochi"),
                "kind" => q("dog")
            }
        ]
    });
}
<|endoftext|>


<commit_before>#[doc = "Utilities for manipulating the char type"];

/*
    Lu  Uppercase_Letter    an uppercase letter
    Ll  Lowercase_Letter    a lowercase letter
    Lt  Titlecase_Letter    a digraphic character, with first part uppercase
    Lm  Modifier_Letter     a modifier letter
    Lo  Other_Letter    other letters, including syllables and ideographs
    Mn  Nonspacing_Mark     a nonspacing combining mark (zero advance width)
    Mc  Spacing_Mark    a spacing combining mark (positive advance width)
    Me  Enclosing_Mark  an enclosing combining mark
    Nd  Decimal_Number  a decimal digit
    Nl  Letter_Number   a letterlike numeric character
    No  Other_Number    a numeric character of other type
    Pc  Connector_Punctuation   a connecting punctuation mark, like a tie
    Pd  Dash_Punctuation    a dash or hyphen punctuation mark
    Ps  Open_Punctuation    an opening punctuation mark (of a pair)
    Pe  Close_Punctuation   a closing punctuation mark (of a pair)
    Pi  Initial_Punctuation     an initial quotation mark
    Pf  Final_Punctuation   a final quotation mark
    Po  Other_Punctuation   a punctuation mark of other type
    Sm  Math_Symbol     a symbol of primarily mathematical use
    Sc  Currency_Symbol     a currency sign
    Sk  Modifier_Symbol     a non-letterlike modifier symbol
    So  Other_Symbol    a symbol of other type
    Zs  Space_Separator     a space character (of various non-zero widths)
    Zl  Line_Separator  U+2028 LINE SEPARATOR only
    Zp  Paragraph_Separator     U+2029 PARAGRAPH SEPARATOR only
    Cc  Control     a C0 or C1 control code
    Cf  Format  a format control character
    Cs  Surrogate   a surrogate code point
    Co  Private_Use     a private-use character
    Cn  Unassigned  a reserved unassigned code point or a noncharacter
*/

export is_alphabetic,
       is_XID_start, is_XID_continue,
       is_lowercase, is_uppercase,
       is_whitespace, is_alphanumeric,
       is_ascii,
       to_digit, to_lower, to_upper, maybe_digit, cmp;

import is_alphabetic = unicode::derived_property::Alphabetic;
import is_XID_start = unicode::derived_property::XID_Start;
import is_XID_continue = unicode::derived_property::XID_Continue;

#[doc(
  brief = "Indicates whether a character is in lower case, defined \
           in terms of the Unicode General Category 'Ll'."
)]
pure fn is_lowercase(c: char) -> bool {
    ret unicode::general_category::Ll(c);
}

#[doc(
  brief = "Indicates whether a character is in upper case, defined \
           in terms of the Unicode General Category 'Lu'."
)]
pure fn is_uppercase(c: char) -> bool {
    ret unicode::general_category::Lu(c);
}

#[doc(
  brief = "Indicates whether a character is whitespace, defined in \
           terms of the Unicode General Categories 'Zs', 'Zl', 'Zp' \
           additional 'Cc'-category control codes in the range [0x09, 0x0d]"
)]
pure fn is_whitespace(c: char) -> bool {
    ret ('\x09' <= c && c <= '\x0d')
        || unicode::general_category::Zs(c)
        || unicode::general_category::Zl(c)
        || unicode::general_category::Zp(c);
}

#[doc(
  brief = "Indicates whether a character is alphanumeric, defined \
            in terms of the Unicode General Categories 'Nd', \
            'Nl', 'No' and the Derived Core Property 'Alphabetic'."
)]
pure fn is_alphanumeric(c: char) -> bool {
    ret unicode::derived_property::Alphabetic(c) ||
        unicode::general_category::Nd(c) ||
        unicode::general_category::Nl(c) ||
        unicode::general_category::No(c);
}

#[doc( brief = "Indicates whether the character is an ASCII character" )]
pure fn is_ascii(c: char) -> bool {
   c - ('\x7F' & c) == '\x00'
}

#[doc( brief = "Indicates whether the character is numeric (Nd, Nl, or No)" )]
pure fn is_digit(c: char) -> bool {
    ret unicode::general_category::Nd(c) ||
        unicode::general_category::Nl(c) ||
        unicode::general_category::No(c);
}

#[doc(
  brief = "Convert a char to the corresponding digit. \
           Safety note: This function fails if `c` is not a valid char",
  return = "If `c` is between '0' and '9', the corresponding value \
            between 0 and 9. If `c` is 'a' or 'A', 10. If `c` is \
            'b' or 'B', 11, etc."
)]
pure fn to_digit(c: char) -> u8 unsafe {
    alt maybe_digit(c) {
      option::some(x) { x }
      option::none { fail; }
    }
}

#[doc(
  brief = "Convert a char to the corresponding digit. Returns none when \
           character is not a valid hexadecimal digit."
)]
pure fn maybe_digit(c: char) -> option<u8> {
    alt c {
      '0' to '9' { option::some(c as u8 - ('0' as u8)) }
      'a' to 'z' { option::some(c as u8 + 10u8 - ('a' as u8)) }
      'A' to 'Z' { option::some(c as u8 + 10u8 - ('A' as u8)) }
      _ { option::none }
    }
}

/*
 FIXME: works only on ASCII
*/
#[doc(
  brief = "Convert a char to the corresponding lower case."
)]
pure fn to_lower(c: char) -> char {
    alt c {
      'A' to 'Z' { ((c as u8) + 32u8) as char }
      _ { c }
    }
}

/*
 FIXME: works only on ASCII
*/
#[doc(
  brief = "Convert a char to the corresponding upper case."
)]
pure fn to_upper(c: char) -> char {
    alt c {
      'a' to 'z' { ((c as u8) - 32u8) as char }
      _ { c }
    }
}

#[doc(
  brief =  "Compare two chars.",
  return = "-1 if a<b, 0 if a==b, +1 if a>b"
)]
pure fn cmp(a: char, b: char) -> int {
    ret  if b > a { -1 }
    else if b < a { 1 }
    else { 0 }
}

#[test]
fn test_is_lowercase() {
    assert is_lowercase('a');
    assert is_lowercase('ö');
    assert is_lowercase('ß');
    assert !is_lowercase('Ü');
    assert !is_lowercase('P');
}

#[test]
fn test_is_uppercase() {
    assert !is_uppercase('h');
    assert !is_uppercase('ä');
    assert !is_uppercase('ß');
    assert is_uppercase('Ö');
    assert is_uppercase('T');
}

#[test]
fn test_is_whitespace() {
    assert is_whitespace(' ');
    assert is_whitespace('\u2007');
    assert is_whitespace('\t');
    assert is_whitespace('\n');

    assert !is_whitespace('a');
    assert !is_whitespace('_');
    assert !is_whitespace('\u0000');
}

#[test]
fn test_to_digit() {
    assert (to_digit('0') == 0u8);
    assert (to_digit('1') == 1u8);
    assert (to_digit('2') == 2u8);
    assert (to_digit('9') == 9u8);
    assert (to_digit('a') == 10u8);
    assert (to_digit('A') == 10u8);
    assert (to_digit('b') == 11u8);
    assert (to_digit('B') == 11u8);
    assert (to_digit('z') == 35u8);
    assert (to_digit('Z') == 35u8);
}

#[test]
#[should_fail]
#[ignore(cfg(target_os = "win32"))]
fn test_to_digit_fail_1() {
    to_digit(' ');
}

#[test]
#[should_fail]
#[ignore(cfg(target_os = "win32"))]
fn test_to_digit_fail_2() {
    to_digit('$');
}

#[test]
fn test_to_lower() {
    assert (to_lower('H') == 'h');
    assert (to_lower('e') == 'e');
    //assert (to_lower('Ö') == 'ö');
    assert (to_lower('ß') == 'ß');
}

#[test]
fn test_to_upper() {
    assert (to_upper('l') == 'L');
    assert (to_upper('Q') == 'Q');
    //assert (to_upper('ü') == 'Ü');
    assert (to_upper('ß') == 'ß');
}

#[test]
fn test_is_ascii() unsafe {
   assert str::all("banana", char::is_ascii);
   assert ! str::all("ประเทศไทย中华Việt Nam", char::is_ascii);
}

#[test]
fn test_is_digit() {
   assert is_digit('2');
   assert is_digit('7');
   assert ! is_digit('c');
   assert ! is_digit('i');
   assert ! is_digit('z');
   assert ! is_digit('Q');
}

<commit_msg>(core::char) export is_digit<commit_after>#[doc = "Utilities for manipulating the char type"];

/*
    Lu  Uppercase_Letter    an uppercase letter
    Ll  Lowercase_Letter    a lowercase letter
    Lt  Titlecase_Letter    a digraphic character, with first part uppercase
    Lm  Modifier_Letter     a modifier letter
    Lo  Other_Letter    other letters, including syllables and ideographs
    Mn  Nonspacing_Mark     a nonspacing combining mark (zero advance width)
    Mc  Spacing_Mark    a spacing combining mark (positive advance width)
    Me  Enclosing_Mark  an enclosing combining mark
    Nd  Decimal_Number  a decimal digit
    Nl  Letter_Number   a letterlike numeric character
    No  Other_Number    a numeric character of other type
    Pc  Connector_Punctuation   a connecting punctuation mark, like a tie
    Pd  Dash_Punctuation    a dash or hyphen punctuation mark
    Ps  Open_Punctuation    an opening punctuation mark (of a pair)
    Pe  Close_Punctuation   a closing punctuation mark (of a pair)
    Pi  Initial_Punctuation     an initial quotation mark
    Pf  Final_Punctuation   a final quotation mark
    Po  Other_Punctuation   a punctuation mark of other type
    Sm  Math_Symbol     a symbol of primarily mathematical use
    Sc  Currency_Symbol     a currency sign
    Sk  Modifier_Symbol     a non-letterlike modifier symbol
    So  Other_Symbol    a symbol of other type
    Zs  Space_Separator     a space character (of various non-zero widths)
    Zl  Line_Separator  U+2028 LINE SEPARATOR only
    Zp  Paragraph_Separator     U+2029 PARAGRAPH SEPARATOR only
    Cc  Control     a C0 or C1 control code
    Cf  Format  a format control character
    Cs  Surrogate   a surrogate code point
    Co  Private_Use     a private-use character
    Cn  Unassigned  a reserved unassigned code point or a noncharacter
*/

export is_alphabetic,
       is_XID_start, is_XID_continue,
       is_lowercase, is_uppercase,
       is_whitespace, is_alphanumeric,
       is_ascii, is_digit,
       to_digit, to_lower, to_upper, maybe_digit, cmp;

import is_alphabetic = unicode::derived_property::Alphabetic;
import is_XID_start = unicode::derived_property::XID_Start;
import is_XID_continue = unicode::derived_property::XID_Continue;

#[doc(
  brief = "Indicates whether a character is in lower case, defined \
           in terms of the Unicode General Category 'Ll'."
)]
pure fn is_lowercase(c: char) -> bool {
    ret unicode::general_category::Ll(c);
}

#[doc(
  brief = "Indicates whether a character is in upper case, defined \
           in terms of the Unicode General Category 'Lu'."
)]
pure fn is_uppercase(c: char) -> bool {
    ret unicode::general_category::Lu(c);
}

#[doc(
  brief = "Indicates whether a character is whitespace, defined in \
           terms of the Unicode General Categories 'Zs', 'Zl', 'Zp' \
           additional 'Cc'-category control codes in the range [0x09, 0x0d]"
)]
pure fn is_whitespace(c: char) -> bool {
    ret ('\x09' <= c && c <= '\x0d')
        || unicode::general_category::Zs(c)
        || unicode::general_category::Zl(c)
        || unicode::general_category::Zp(c);
}

#[doc(
  brief = "Indicates whether a character is alphanumeric, defined \
            in terms of the Unicode General Categories 'Nd', \
            'Nl', 'No' and the Derived Core Property 'Alphabetic'."
)]
pure fn is_alphanumeric(c: char) -> bool {
    ret unicode::derived_property::Alphabetic(c) ||
        unicode::general_category::Nd(c) ||
        unicode::general_category::Nl(c) ||
        unicode::general_category::No(c);
}

#[doc( brief = "Indicates whether the character is an ASCII character" )]
pure fn is_ascii(c: char) -> bool {
   c - ('\x7F' & c) == '\x00'
}

#[doc( brief = "Indicates whether the character is numeric (Nd, Nl, or No)" )]
pure fn is_digit(c: char) -> bool {
    ret unicode::general_category::Nd(c) ||
        unicode::general_category::Nl(c) ||
        unicode::general_category::No(c);
}

#[doc(
  brief = "Convert a char to the corresponding digit. \
           Safety note: This function fails if `c` is not a valid char",
  return = "If `c` is between '0' and '9', the corresponding value \
            between 0 and 9. If `c` is 'a' or 'A', 10. If `c` is \
            'b' or 'B', 11, etc."
)]
pure fn to_digit(c: char) -> u8 unsafe {
    alt maybe_digit(c) {
      option::some(x) { x }
      option::none { fail; }
    }
}

#[doc(
  brief = "Convert a char to the corresponding digit. Returns none when \
           character is not a valid hexadecimal digit."
)]
pure fn maybe_digit(c: char) -> option<u8> {
    alt c {
      '0' to '9' { option::some(c as u8 - ('0' as u8)) }
      'a' to 'z' { option::some(c as u8 + 10u8 - ('a' as u8)) }
      'A' to 'Z' { option::some(c as u8 + 10u8 - ('A' as u8)) }
      _ { option::none }
    }
}

/*
 FIXME: works only on ASCII
*/
#[doc(
  brief = "Convert a char to the corresponding lower case."
)]
pure fn to_lower(c: char) -> char {
    alt c {
      'A' to 'Z' { ((c as u8) + 32u8) as char }
      _ { c }
    }
}

/*
 FIXME: works only on ASCII
*/
#[doc(
  brief = "Convert a char to the corresponding upper case."
)]
pure fn to_upper(c: char) -> char {
    alt c {
      'a' to 'z' { ((c as u8) - 32u8) as char }
      _ { c }
    }
}

#[doc(
  brief =  "Compare two chars.",
  return = "-1 if a<b, 0 if a==b, +1 if a>b"
)]
pure fn cmp(a: char, b: char) -> int {
    ret  if b > a { -1 }
    else if b < a { 1 }
    else { 0 }
}

#[test]
fn test_is_lowercase() {
    assert is_lowercase('a');
    assert is_lowercase('ö');
    assert is_lowercase('ß');
    assert !is_lowercase('Ü');
    assert !is_lowercase('P');
}

#[test]
fn test_is_uppercase() {
    assert !is_uppercase('h');
    assert !is_uppercase('ä');
    assert !is_uppercase('ß');
    assert is_uppercase('Ö');
    assert is_uppercase('T');
}

#[test]
fn test_is_whitespace() {
    assert is_whitespace(' ');
    assert is_whitespace('\u2007');
    assert is_whitespace('\t');
    assert is_whitespace('\n');

    assert !is_whitespace('a');
    assert !is_whitespace('_');
    assert !is_whitespace('\u0000');
}

#[test]
fn test_to_digit() {
    assert (to_digit('0') == 0u8);
    assert (to_digit('1') == 1u8);
    assert (to_digit('2') == 2u8);
    assert (to_digit('9') == 9u8);
    assert (to_digit('a') == 10u8);
    assert (to_digit('A') == 10u8);
    assert (to_digit('b') == 11u8);
    assert (to_digit('B') == 11u8);
    assert (to_digit('z') == 35u8);
    assert (to_digit('Z') == 35u8);
}

#[test]
#[should_fail]
#[ignore(cfg(target_os = "win32"))]
fn test_to_digit_fail_1() {
    to_digit(' ');
}

#[test]
#[should_fail]
#[ignore(cfg(target_os = "win32"))]
fn test_to_digit_fail_2() {
    to_digit('$');
}

#[test]
fn test_to_lower() {
    assert (to_lower('H') == 'h');
    assert (to_lower('e') == 'e');
    //assert (to_lower('Ö') == 'ö');
    assert (to_lower('ß') == 'ß');
}

#[test]
fn test_to_upper() {
    assert (to_upper('l') == 'L');
    assert (to_upper('Q') == 'Q');
    //assert (to_upper('ü') == 'Ü');
    assert (to_upper('ß') == 'ß');
}

#[test]
fn test_is_ascii() unsafe {
   assert str::all("banana", char::is_ascii);
   assert ! str::all("ประเทศไทย中华Việt Nam", char::is_ascii);
}

#[test]
fn test_is_digit() {
   assert is_digit('2');
   assert is_digit('7');
   assert ! is_digit('c');
   assert ! is_digit('i');
   assert ! is_digit('z');
   assert ! is_digit('Q');
}

<|endoftext|>