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

#[doc(keyword = "fn")]
//
/// The `fn` keyword.
///
/// The `fn` keyword is used to declare a function.
///
/// Example:
///
/// ```rust
/// fn some_function() {
///     // code goes in here
/// }
/// ```
///
/// For more information about functions, take a look at the [Rust Book][book].
///
/// [book]: https://doc.rust-lang.org/book/second-edition/ch03-03-how-functions-work.html
mod fn_keyword { }
<commit_msg>Rollup merge of #53231 - GuillaumeGomez:let-keyword, r=QuietMisdreavus<commit_after>// Copyright 2018 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.

#[doc(keyword = "fn")]
//
/// The `fn` keyword.
///
/// The `fn` keyword is used to declare a function.
///
/// Example:
///
/// ```rust
/// fn some_function() {
///     // code goes in here
/// }
/// ```
///
/// For more information about functions, take a look at the [Rust Book][book].
///
/// [book]: https://doc.rust-lang.org/book/second-edition/ch03-03-how-functions-work.html
mod fn_keyword { }

#[doc(keyword = "let")]
//
/// The `let` keyword.
///
/// The `let` keyword is used to declare a variable.
///
/// Example:
///
/// ```rust
/// # #![allow(unused_assignments)]
/// let x = 3; // We create a variable named `x` with the value `3`.
/// ```
///
/// By default, all variables are **not** mutable. If you want a mutable variable,
/// you'll have to use the `mut` keyword.
///
/// Example:
///
/// ```rust
/// # #![allow(unused_assignments)]
/// let mut x = 3; // We create a mutable variable named `x` with the value `3`.
///
/// x += 4; // `x` is now equal to `7`.
/// ```
///
/// For more information about the `let` keyword, take a look at the [Rust Book][book].
///
/// [book]: https://doc.rust-lang.org/book/second-edition/ch03-01-variables-and-mutability.html
mod let_keyword { }
<|endoftext|>


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

#[cfg(target_os = "linux")]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "linux";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".so";
    pub const DLL_EXTENSION: &'static str = "so";
    pub const EXE_SUFFIX: &'static str = "";
    pub const EXE_EXTENSION: &'static str = "";
}

#[cfg(target_os = "macos")]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "macos";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".dylib";
    pub const DLL_EXTENSION: &'static str = "dylib";
    pub const EXE_SUFFIX: &'static str = "";
    pub const EXE_EXTENSION: &'static str = "";
}

#[cfg(target_os = "ios")]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "ios";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".dylib";
    pub const DLL_EXTENSION: &'static str = "dylib";
    pub const EXE_SUFFIX: &'static str = "";
    pub const EXE_EXTENSION: &'static str = "";
}

#[cfg(target_os = "freebsd")]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "freebsd";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".so";
    pub const DLL_EXTENSION: &'static str = "so";
    pub const EXE_SUFFIX: &'static str = "";
    pub const EXE_EXTENSION: &'static str = "";
}

#[cfg(target_os = "dragonfly")]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "dragonfly";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".so";
    pub const DLL_EXTENSION: &'static str = "so";
    pub const EXE_SUFFIX: &'static str = "";
    pub const EXE_EXTENSION: &'static str = "";
}

#[cfg(target_os = "bitrig")]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "bitrig";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".so";
    pub const DLL_EXTENSION: &'static str = "so";
    pub const EXE_SUFFIX: &'static str = "";
    pub const EXE_EXTENSION: &'static str = "";
}

#[cfg(target_os = "netbsd")]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "netbsd";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".so";
    pub const DLL_EXTENSION: &'static str = "so";
    pub const EXE_SUFFIX: &'static str = "";
    pub const EXE_EXTENSION: &'static str = "";
}

#[cfg(target_os = "openbsd")]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "openbsd";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".so";
    pub const DLL_EXTENSION: &'static str = "so";
    pub const EXE_SUFFIX: &'static str = "";
    pub const EXE_EXTENSION: &'static str = "";
}

#[cfg(target_os = "android")]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "android";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".so";
    pub const DLL_EXTENSION: &'static str = "so";
    pub const EXE_SUFFIX: &'static str = "";
    pub const EXE_EXTENSION: &'static str = "";
}

#[cfg(target_os = "solaris")]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "solaris";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".so";
    pub const DLL_EXTENSION: &'static str = "so";
    pub const EXE_SUFFIX: &'static str = "";
    pub const EXE_EXTENSION: &'static str = "";
}

#[cfg(all(target_os = "nacl", not(target_arch = "le32")))]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "nacl";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".so";
    pub const DLL_EXTENSION: &'static str = "so";
    pub const EXE_SUFFIX: &'static str = ".nexe";
    pub const EXE_EXTENSION: &'static str = "nexe";
}
#[cfg(all(target_os = "nacl", target_arch = "le32"))]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "pnacl";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".pso";
    pub const DLL_EXTENSION: &'static str = "pso";
    pub const EXE_SUFFIX: &'static str = ".pexe";
    pub const EXE_EXTENSION: &'static str = "pexe";
}

#[cfg(target_os = "haiku")]
mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "haiku";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".so";
    pub const DLL_EXTENSION: &'static str = "so";
    pub const EXE_SUFFIX: &'static str = "";
    pub const EXE_EXTENSION: &'static str = "";
}

#[cfg(all(target_os = "emscripten", target_arch = "asmjs"))]
mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "emscripten";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".so";
    pub const DLL_EXTENSION: &'static str = "so";
    pub const EXE_SUFFIX: &'static str = ".js";
    pub const EXE_EXTENSION: &'static str = "js";
}

#[cfg(all(target_os = "emscripten", target_arch = "wasm32"))]
mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "emscripten";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".so";
    pub const DLL_EXTENSION: &'static str = "so";
    pub const EXE_SUFFIX: &'static str = ".js";
    pub const EXE_EXTENSION: &'static str = "js";
}
<commit_msg>Auto merge of #36944 - brson:modos, r=alexcrichton<commit_after>// Copyright 2012-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.

#[cfg(target_os = "linux")]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "linux";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".so";
    pub const DLL_EXTENSION: &'static str = "so";
    pub const EXE_SUFFIX: &'static str = "";
    pub const EXE_EXTENSION: &'static str = "";
}

#[cfg(target_os = "macos")]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "macos";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".dylib";
    pub const DLL_EXTENSION: &'static str = "dylib";
    pub const EXE_SUFFIX: &'static str = "";
    pub const EXE_EXTENSION: &'static str = "";
}

#[cfg(target_os = "ios")]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "ios";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".dylib";
    pub const DLL_EXTENSION: &'static str = "dylib";
    pub const EXE_SUFFIX: &'static str = "";
    pub const EXE_EXTENSION: &'static str = "";
}

#[cfg(target_os = "freebsd")]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "freebsd";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".so";
    pub const DLL_EXTENSION: &'static str = "so";
    pub const EXE_SUFFIX: &'static str = "";
    pub const EXE_EXTENSION: &'static str = "";
}

#[cfg(target_os = "dragonfly")]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "dragonfly";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".so";
    pub const DLL_EXTENSION: &'static str = "so";
    pub const EXE_SUFFIX: &'static str = "";
    pub const EXE_EXTENSION: &'static str = "";
}

#[cfg(target_os = "bitrig")]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "bitrig";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".so";
    pub const DLL_EXTENSION: &'static str = "so";
    pub const EXE_SUFFIX: &'static str = "";
    pub const EXE_EXTENSION: &'static str = "";
}

#[cfg(target_os = "netbsd")]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "netbsd";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".so";
    pub const DLL_EXTENSION: &'static str = "so";
    pub const EXE_SUFFIX: &'static str = "";
    pub const EXE_EXTENSION: &'static str = "";
}

#[cfg(target_os = "openbsd")]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "openbsd";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".so";
    pub const DLL_EXTENSION: &'static str = "so";
    pub const EXE_SUFFIX: &'static str = "";
    pub const EXE_EXTENSION: &'static str = "";
}

#[cfg(target_os = "android")]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "android";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".so";
    pub const DLL_EXTENSION: &'static str = "so";
    pub const EXE_SUFFIX: &'static str = "";
    pub const EXE_EXTENSION: &'static str = "";
}

#[cfg(target_os = "solaris")]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "solaris";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".so";
    pub const DLL_EXTENSION: &'static str = "so";
    pub const EXE_SUFFIX: &'static str = "";
    pub const EXE_EXTENSION: &'static str = "";
}

#[cfg(all(target_os = "nacl", not(target_arch = "le32")))]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "nacl";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".so";
    pub const DLL_EXTENSION: &'static str = "so";
    pub const EXE_SUFFIX: &'static str = ".nexe";
    pub const EXE_EXTENSION: &'static str = "nexe";
}
#[cfg(all(target_os = "nacl", target_arch = "le32"))]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "pnacl";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".pso";
    pub const DLL_EXTENSION: &'static str = "pso";
    pub const EXE_SUFFIX: &'static str = ".pexe";
    pub const EXE_EXTENSION: &'static str = "pexe";
}

#[cfg(target_os = "haiku")]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "haiku";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".so";
    pub const DLL_EXTENSION: &'static str = "so";
    pub const EXE_SUFFIX: &'static str = "";
    pub const EXE_EXTENSION: &'static str = "";
}

#[cfg(all(target_os = "emscripten", target_arch = "asmjs"))]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "emscripten";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".so";
    pub const DLL_EXTENSION: &'static str = "so";
    pub const EXE_SUFFIX: &'static str = ".js";
    pub const EXE_EXTENSION: &'static str = "js";
}

#[cfg(all(target_os = "emscripten", target_arch = "wasm32"))]
pub mod os {
    pub const FAMILY: &'static str = "unix";
    pub const OS: &'static str = "emscripten";
    pub const DLL_PREFIX: &'static str = "lib";
    pub const DLL_SUFFIX: &'static str = ".so";
    pub const DLL_EXTENSION: &'static str = "so";
    pub const EXE_SUFFIX: &'static str = ".js";
    pub const EXE_EXTENSION: &'static str = "js";
}
<|endoftext|>


<commit_before><commit_msg>Cleaned up some some warnings in StringWatch.<commit_after><|endoftext|>


<commit_before><commit_msg>client<commit_after><|endoftext|>


<commit_before><commit_msg>Added an example file using table slicing for #10<commit_after>#[macro_use] extern crate prettytable;

use prettytable::Slice;

fn main() {
    let mut table = table![[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4], [5, 5, 5]];
    table.set_titles(row![cell!("t1"), cell!("t2"), cell!("t3")]);

    let slice = table.slice(..);
    let slice = slice.slice(2..);
    let slice = slice.slice(..3);

    /*
        Will print
        +----+----+----+
        | t1 | t2 | t3 |
        +====+====+====+
        | 2  | 2  | 2  |
        +----+----+----+
        | 3  | 3  | 3  |
        +----+----+----+
    */
    slice.printstd();

    // This is equivalent to
    let slice = table.slice(2..3);
    slice.printstd();
}
<|endoftext|>


<commit_before><commit_msg>Add long example program<commit_after>//! Counts the number of codepoints of each UTF-8 length in files

use std::env::args_os;
use std::fs::File;
use std::io::{self, Read, stdin};
use std::borrow::Cow;
extern crate encode_unicode;
use encode_unicode::U8UtfExt;

#[derive(Default)]
struct Distribution {
    bytes: usize,
    utf8: [usize; 4],
}

fn read(file: &mut Read) -> (Distribution, Option<io::Error>) {
    let mut r = Distribution::default();
    let mut buf = [0u8; 4096];
    loop {
        let read = match file.read(&mut buf) {
            Ok(0) => return (r, None),
            Ok(n) => n,
            Err(e) => return (r, Some(e)),
        };
        r.bytes += read;
        for (o, &b) in buf[..read].iter().enumerate() {
            match b.extra_utf8_bytes() {
                Ok(i) => {
                    r.utf8[i] += 1;
                    if i == 3 {
                        let min = o.saturating_sub(20);
                        let max = if o+23 <= read {o+23} else {read};
                        println!("{}", String::from_utf8_lossy(&buf[min..max]));
                    }
                },
                Err(_) => {}
            }
        }
    }
}

fn display(name_pad: usize,  name: Cow<str>,
           r: Distribution,  err: Option<io::Error>) {
    let c = r.utf8;
    let characters = c[0]+c[1]+c[2]+c[3];
    let s = [c[0], c[1]*2, c[2]*3, c[3]*4];
    let p = [
        (s[0]*100) as f32 / r.bytes as f32,
        (s[1]*100) as f32 / r.bytes as f32,
        (s[2]*100) as f32 / r.bytes as f32,
        (s[3]*100) as f32 / r.bytes as f32,
    ];
    println!("{:>6$}: bytes: {:7}, UTF-8 distribution: [{:7}, {:6}, {:6}, {:6}]",
        name, r.bytes, s[0], s[1], s[2], s[3], name_pad
    );
    println!("{5:6$}  chars: {:7}, UTF-8 percentages:  [{:>6.2}%, {:>5.2}%, {:>5.2}%, {:>5.2}%]",
        characters, p[0], p[1], p[2], p[3], "", name_pad
    );
    if let Some(err) = err {
        println!("{1:2$}  {}", err, "", name_pad);
    }
}

fn main() {
    let name_length = args_os().skip(1)
        .map(|path| path.to_string_lossy().chars().count() )
        .max();
    for path in args_os().skip(1) {
        let name = path.to_string_lossy();
        let (r,err) = match File::open(&path) {
            Ok(mut file) => read(&mut file),
            Err(err) => {
                eprintln!("{}:\t{}", name, err);
                continue;
            }
        };
        display(name_length.unwrap(), name, r, err);
    }
    if name_length.is_none() {
        let stdin = stdin();
        let (r,err) = read(&mut stdin.lock());
        display(0, Cow::Borrowed("stdin"), r, err);
    }
}
<|endoftext|>


<commit_before>use rocket::request::{FromParam, Request};
use rocket::response::{self, Redirect, Responder, NamedFile};
use rocket;
use rocket::http::RawStr;
use scheduled_executor::ThreadPoolExecutor;

use error::*;
use web_server::pages;
use web_server::api;
use cache::Cache;
use config::Config;
use metadata::ClusterId;
use live_consumer::{self, LiveConsumerStore};
use utils::{GZip, RequestLogger};

use std::path::{Path, PathBuf};
use std;

#[get("/")]
fn index() -> Redirect {
    Redirect::to("/clusters")
}

// Make ClusterId a valid parameter
impl<'a> FromParam<'a> for ClusterId {
    type Error = ();

    fn from_param(param: &'a RawStr) -> std::result::Result<Self, Self::Error> {
        Ok(param.as_str().into())
    }
}

#[get("/public/<file..>")]
fn files(file: PathBuf) -> Option<CachedFile> {
    NamedFile::open(Path::new("resources/web_server/public/").join(file))
        .map(CachedFile::from)
        .ok()
}

#[get("/public/<file..>?<version>")]
fn files_v(file: PathBuf, version: &str) -> Option<CachedFile> {
    let _ = version;  // just ignore version
    NamedFile::open(Path::new("resources/web_server/public/").join(file))
        .map(CachedFile::from)
        .ok()
}

pub struct CachedFile {
    ttl: usize,
    file: NamedFile,
}

impl CachedFile {
    pub fn from(file: NamedFile) -> CachedFile {
        CachedFile::with_ttl(1800, file)
    }

    pub fn with_ttl(ttl: usize, file: NamedFile) -> CachedFile {
        CachedFile { ttl, file }
    }
}

impl<'a> Responder<'a> for CachedFile {
    fn respond_to(self, request: &Request) -> response::Result<'a> {
        let inner_response = self.file.respond_to(request).unwrap(); // fixme
        response::Response::build_from(inner_response)
            .raw_header("Cache-Control", format!("max-age={}, must-revalidate", self.ttl))
            .ok()
    }
}

pub fn run_server(executor: &ThreadPoolExecutor, cache: Cache, config: &Config) -> Result<()> {
    let version = option_env!("CARGO_PKG_VERSION").unwrap_or("?");
    info!("Starting kafka-view v{}, listening on {}:{}.", version, config.listen_host, config.listen_port);

    let rocket_config = rocket::config::Config::build(rocket::config::Environment::Development)
        .address(config.listen_host.to_owned())
        .port(config.listen_port)
        .workers(4)
        .log_level(rocket::logger::LoggingLevel::Critical)
        .finalize()
        .chain_err(|| "Invalid rocket configuration")?;

    rocket::custom(rocket_config, false)
        .attach(GZip)
        .attach(RequestLogger)
        .manage(cache)
        .manage(config.clone())
        .manage(LiveConsumerStore::new(executor.clone()))
        .mount("/", routes![
            index,
            files,
            files_v,
            pages::cluster::cluster_page,
            pages::cluster::broker_page,
            pages::clusters::clusters_page,
            pages::group::group_page,
            pages::internals::caches_page,
            pages::internals::live_consumers_page,
            pages::omnisearch::consumer_search,
            pages::omnisearch::consumer_search_p,
            pages::omnisearch::omnisearch,
            pages::omnisearch::omnisearch_p,
            pages::omnisearch::topic_search,
            pages::omnisearch::topic_search_p,
            pages::topic::topic_page,
            api::brokers,
            api::cache_brokers,
            api::cache_metrics,
            api::cache_offsets,
            api::live_consumers,
            api::cluster_groups,
            api::cluster_topics,
            api::consumer_search,
            api::group_members,
            api::group_offsets,
            api::topic_groups,
            api::topic_search,
            api::topic_topology,
            live_consumer::test_live_consumer_api,
        ])
        .launch();

    Ok(())
}

<commit_msg>Respect ROCKET_ENV<commit_after>use rocket::request::{FromParam, Request};
use rocket::response::{self, Redirect, Responder, NamedFile};
use rocket;
use rocket::http::RawStr;
use scheduled_executor::ThreadPoolExecutor;

use error::*;
use web_server::pages;
use web_server::api;
use cache::Cache;
use config::Config;
use metadata::ClusterId;
use live_consumer::{self, LiveConsumerStore};
use utils::{GZip, RequestLogger};

use std::path::{Path, PathBuf};
use std;

#[get("/")]
fn index() -> Redirect {
    Redirect::to("/clusters")
}

// Make ClusterId a valid parameter
impl<'a> FromParam<'a> for ClusterId {
    type Error = ();

    fn from_param(param: &'a RawStr) -> std::result::Result<Self, Self::Error> {
        Ok(param.as_str().into())
    }
}

#[get("/public/<file..>")]
fn files(file: PathBuf) -> Option<CachedFile> {
    NamedFile::open(Path::new("resources/web_server/public/").join(file))
        .map(CachedFile::from)
        .ok()
}

#[get("/public/<file..>?<version>")]
fn files_v(file: PathBuf, version: &str) -> Option<CachedFile> {
    let _ = version;  // just ignore version
    NamedFile::open(Path::new("resources/web_server/public/").join(file))
        .map(CachedFile::from)
        .ok()
}

pub struct CachedFile {
    ttl: usize,
    file: NamedFile,
}

impl CachedFile {
    pub fn from(file: NamedFile) -> CachedFile {
        CachedFile::with_ttl(1800, file)
    }

    pub fn with_ttl(ttl: usize, file: NamedFile) -> CachedFile {
        CachedFile { ttl, file }
    }
}

impl<'a> Responder<'a> for CachedFile {
    fn respond_to(self, request: &Request) -> response::Result<'a> {
        let inner_response = self.file.respond_to(request).unwrap(); // fixme
        response::Response::build_from(inner_response)
            .raw_header("Cache-Control", format!("max-age={}, must-revalidate", self.ttl))
            .ok()
    }
}

pub fn run_server(executor: &ThreadPoolExecutor, cache: Cache, config: &Config) -> Result<()> {
    let version = option_env!("CARGO_PKG_VERSION").unwrap_or("?");
    info!("Starting kafka-view v{}, listening on {}:{}.", version, config.listen_host, config.listen_port);

    let rocket_env = rocket::config::Environment::active()
        .chain_err(|| "Invalid ROCKET_ENV environment variable")?;
    let rocket_config = rocket::config::Config::build(rocket_env)
        .address(config.listen_host.to_owned())
        .port(config.listen_port)
        .workers(4)
        .log_level(rocket::logger::LoggingLevel::Critical)
        .finalize()
        .chain_err(|| "Invalid rocket configuration")?;

    rocket::custom(rocket_config, false)
        .attach(GZip)
        .attach(RequestLogger)
        .manage(cache)
        .manage(config.clone())
        .manage(LiveConsumerStore::new(executor.clone()))
        .mount("/", routes![
            index,
            files,
            files_v,
            pages::cluster::cluster_page,
            pages::cluster::broker_page,
            pages::clusters::clusters_page,
            pages::group::group_page,
            pages::internals::caches_page,
            pages::internals::live_consumers_page,
            pages::omnisearch::consumer_search,
            pages::omnisearch::consumer_search_p,
            pages::omnisearch::omnisearch,
            pages::omnisearch::omnisearch_p,
            pages::omnisearch::topic_search,
            pages::omnisearch::topic_search_p,
            pages::topic::topic_page,
            api::brokers,
            api::cache_brokers,
            api::cache_metrics,
            api::cache_offsets,
            api::live_consumers,
            api::cluster_groups,
            api::cluster_topics,
            api::consumer_search,
            api::group_members,
            api::group_offsets,
            api::topic_groups,
            api::topic_search,
            api::topic_topology,
            live_consumer::test_live_consumer_api,
        ])
        .launch();

    Ok(())
}

<|endoftext|>


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

#![crate_name = "foo"]

// @has foo/fn.tuple0.html //pre 'pub fn tuple0(x: ())'
pub fn tuple0(x: ()) -> () { x }
// @has foo/fn.tuple1.html //pre 'pub fn tuple1(x: (i32,)) -> (i32,)'
pub fn tuple1(x: (i32,)) -> (i32,) { x }
// @has foo/fn.tuple2.html //pre 'pub fn tuple2(x: (i32, i32)) -> (i32, i32)'
pub fn tuple2(x: (i32, i32)) -> (i32, i32) { x }
<|endoftext|>


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

use core::prelude::*;

use driver::session::Session;
use middle::resolve;
use middle::ty;
use middle::typeck;
use util::ppaux;

use syntax::ast::*;
use syntax::codemap;
use syntax::{visit, ast_util, ast_map};

pub fn check_crate(sess: Session,
                   crate: @crate,
                   ast_map: ast_map::map,
                   def_map: resolve::DefMap,
                   method_map: typeck::method_map,
                   tcx: ty::ctxt) {
    visit::visit_crate(*crate, false, visit::mk_vt(@visit::Visitor {
        visit_item: |a,b,c| check_item(sess, ast_map, def_map, a, b, c),
        visit_pat: check_pat,
        visit_expr: |a,b,c|
            check_expr(sess, def_map, method_map, tcx, a, b, c),
        .. *visit::default_visitor()
    }));
    sess.abort_if_errors();
}

pub fn check_item(sess: Session,
                  ast_map: ast_map::map,
                  def_map: resolve::DefMap,
                  it: @item,
                  &&_is_const: bool,
                  v: visit::vt<bool>) {
    match it.node {
      item_const(_, ex) => {
        (v.visit_expr)(ex, true, v);
        check_item_recursion(sess, ast_map, def_map, it);
      }
      item_enum(ref enum_definition, _) => {
        for (*enum_definition).variants.each |var| {
            for var.node.disr_expr.each |ex| {
                (v.visit_expr)(*ex, true, v);
            }
        }
      }
      _ => visit::visit_item(it, false, v)
    }
}

pub fn check_pat(p: @pat, &&_is_const: bool, v: visit::vt<bool>) {
    fn is_str(e: @expr) -> bool {
        match e.node {
            expr_vstore(
                @expr { node: expr_lit(@codemap::spanned {
                    node: lit_str(_),
                    _}),
                       _ },
                expr_vstore_uniq
            ) => true,
            _ => false
        }
    }
    match p.node {
      // Let through plain ~-string literals here
      pat_lit(a) => if !is_str(a) { (v.visit_expr)(a, true, v); },
      pat_range(a, b) => {
        if !is_str(a) { (v.visit_expr)(a, true, v); }
        if !is_str(b) { (v.visit_expr)(b, true, v); }
      }
      _ => visit::visit_pat(p, false, v)
    }
}

pub fn check_expr(sess: Session,
                  def_map: resolve::DefMap,
                  method_map: typeck::method_map,
                  tcx: ty::ctxt,
                  e: @expr,
                  &&is_const: bool,
                  v: visit::vt<bool>) {
    if is_const {
        match e.node {
          expr_unary(box(_), _) | expr_unary(uniq(_), _) |
          expr_unary(deref, _) => {
            sess.span_err(e.span,
                          ~"disallowed operator in constant expression");
            return;
          }
          expr_lit(@codemap::spanned {node: lit_str(_), _}) => { }
          expr_binary(_, _, _) | expr_unary(_, _) => {
            if method_map.contains_key(&e.id) {
                sess.span_err(e.span, ~"user-defined operators are not \
                                       allowed in constant expressions");
            }
          }
          expr_lit(_) => (),
          expr_cast(_, _) => {
            let ety = ty::expr_ty(tcx, e);
            if !ty::type_is_numeric(ety) {
                sess.span_err(e.span, ~"can not cast to `" +
                              ppaux::ty_to_str(tcx, ety) +
                              ~"` in a constant expression");
            }
          }
          expr_path(pth) => {
            // NB: In the future you might wish to relax this slightly
            // to handle on-demand instantiation of functions via
            // foo::<bar> in a const. Currently that is only done on
            // a path in trans::callee that only works in block contexts.
            if pth.types.len() != 0 {
                sess.span_err(
                    e.span, ~"paths in constants may only refer to \
                              items without type parameters");
            }
            match def_map.find(&e.id) {
                Some(def_variant(_, _)) |
                Some(def_struct(_)) => { }

                Some(def_const(def_id)) |
                Some(def_fn(def_id, _)) => {
                if !ast_util::is_local(def_id) {
                    sess.span_err(
                        e.span, ~"paths in constants may only refer to \
                                 crate-local constants or functions");
                }
              }
              Some(def) => {
                debug!("(checking const) found bad def: %?", def);
                sess.span_err(
                    e.span,
                    fmt!("paths in constants may only refer to \
                          constants or functions"));
              }
              None => {
                sess.span_bug(e.span, ~"unbound path in const?!");
              }
            }
          }
          expr_call(callee, _, NoSugar) => {
            match def_map.find(&callee.id) {
                Some(def_struct(*)) => {}    // OK.
                Some(def_variant(*)) => {}    // OK.
                _ => {
                    sess.span_err(
                        e.span,
                        ~"function calls in constants are limited to \
                          struct and enum constructors");
                }
            }
          }
          expr_paren(e) => { check_expr(sess, def_map, method_map,
                                         tcx, e, is_const, v); }
          expr_vstore(_, expr_vstore_slice) |
          expr_vstore(_, expr_vstore_fixed(_)) |
          expr_vec(_, m_imm) |
          expr_addr_of(m_imm, _) |
          expr_field(*) |
          expr_index(*) |
          expr_tup(*) |
          expr_struct(*) |
          expr_rec(*) => { }
          expr_addr_of(*) => {
                sess.span_err(
                    e.span,
                    ~"borrowed pointers in constants may only refer to \
                      immutable values");
          }
          _ => {
            sess.span_err(e.span,
                          ~"constant contains unimplemented expression type");
            return;
          }
        }
    }
    match e.node {
      expr_lit(@codemap::spanned {node: lit_int(v, t), _}) => {
        if t != ty_char {
            if (v as u64) > ast_util::int_ty_max(
                if t == ty_i { sess.targ_cfg.int_type } else { t }) {
                sess.span_err(e.span, ~"literal out of range for its type");
            }
        }
      }
      expr_lit(@codemap::spanned {node: lit_uint(v, t), _}) => {
        if v > ast_util::uint_ty_max(
            if t == ty_u { sess.targ_cfg.uint_type } else { t }) {
            sess.span_err(e.span, ~"literal out of range for its type");
        }
      }
      _ => ()
    }
    visit::visit_expr(e, is_const, v);
}

// Make sure a const item doesn't recursively refer to itself
// FIXME: Should use the dependency graph when it's available (#1356)
pub fn check_item_recursion(sess: Session,
                            ast_map: ast_map::map,
                            def_map: resolve::DefMap,
                            it: @item) {
    struct env {
        root_it: @item,
        sess: Session,
        ast_map: ast_map::map,
        def_map: resolve::DefMap,
        idstack: @mut ~[node_id]
    }

    let env = env {
        root_it: it,
        sess: sess,
        ast_map: ast_map,
        def_map: def_map,
        idstack: @mut ~[]
    };

    let visitor = visit::mk_vt(@visit::Visitor {
        visit_item: visit_item,
        visit_expr: visit_expr,
        .. *visit::default_visitor()
    });
    (visitor.visit_item)(it, env, visitor);

    fn visit_item(it: @item, &&env: env, v: visit::vt<env>) {
        if env.idstack.contains(&(it.id)) {
            env.sess.span_fatal(env.root_it.span, ~"recursive constant");
        }
        env.idstack.push(it.id);
        visit::visit_item(it, env, v);
        env.idstack.pop();
    }

    fn visit_expr(e: @expr, &&env: env, v: visit::vt<env>) {
        match e.node {
          expr_path(*) => {
            match env.def_map.find(&e.id) {
              Some(def_const(def_id)) => {
                match env.ast_map.get(&def_id.node) {
                  ast_map::node_item(it, _) => {
                    (v.visit_item)(it, env, v);
                  }
                  _ => fail!(~"const not bound to an item")
                }
              }
              _ => ()
            }
          }
          _ => ()
        }
        visit::visit_expr(e, env, v);
    }
}

// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
<commit_msg>Make functional-update struct consts not an ICE<commit_after>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use core::prelude::*;

use driver::session::Session;
use middle::resolve;
use middle::ty;
use middle::typeck;
use util::ppaux;

use syntax::ast::*;
use syntax::codemap;
use syntax::{visit, ast_util, ast_map};

pub fn check_crate(sess: Session,
                   crate: @crate,
                   ast_map: ast_map::map,
                   def_map: resolve::DefMap,
                   method_map: typeck::method_map,
                   tcx: ty::ctxt) {
    visit::visit_crate(*crate, false, visit::mk_vt(@visit::Visitor {
        visit_item: |a,b,c| check_item(sess, ast_map, def_map, a, b, c),
        visit_pat: check_pat,
        visit_expr: |a,b,c|
            check_expr(sess, def_map, method_map, tcx, a, b, c),
        .. *visit::default_visitor()
    }));
    sess.abort_if_errors();
}

pub fn check_item(sess: Session,
                  ast_map: ast_map::map,
                  def_map: resolve::DefMap,
                  it: @item,
                  &&_is_const: bool,
                  v: visit::vt<bool>) {
    match it.node {
      item_const(_, ex) => {
        (v.visit_expr)(ex, true, v);
        check_item_recursion(sess, ast_map, def_map, it);
      }
      item_enum(ref enum_definition, _) => {
        for (*enum_definition).variants.each |var| {
            for var.node.disr_expr.each |ex| {
                (v.visit_expr)(*ex, true, v);
            }
        }
      }
      _ => visit::visit_item(it, false, v)
    }
}

pub fn check_pat(p: @pat, &&_is_const: bool, v: visit::vt<bool>) {
    fn is_str(e: @expr) -> bool {
        match e.node {
            expr_vstore(
                @expr { node: expr_lit(@codemap::spanned {
                    node: lit_str(_),
                    _}),
                       _ },
                expr_vstore_uniq
            ) => true,
            _ => false
        }
    }
    match p.node {
      // Let through plain ~-string literals here
      pat_lit(a) => if !is_str(a) { (v.visit_expr)(a, true, v); },
      pat_range(a, b) => {
        if !is_str(a) { (v.visit_expr)(a, true, v); }
        if !is_str(b) { (v.visit_expr)(b, true, v); }
      }
      _ => visit::visit_pat(p, false, v)
    }
}

pub fn check_expr(sess: Session,
                  def_map: resolve::DefMap,
                  method_map: typeck::method_map,
                  tcx: ty::ctxt,
                  e: @expr,
                  &&is_const: bool,
                  v: visit::vt<bool>) {
    if is_const {
        match e.node {
          expr_unary(box(_), _) | expr_unary(uniq(_), _) |
          expr_unary(deref, _) => {
            sess.span_err(e.span,
                          ~"disallowed operator in constant expression");
            return;
          }
          expr_lit(@codemap::spanned {node: lit_str(_), _}) => { }
          expr_binary(_, _, _) | expr_unary(_, _) => {
            if method_map.contains_key(&e.id) {
                sess.span_err(e.span, ~"user-defined operators are not \
                                       allowed in constant expressions");
            }
          }
          expr_lit(_) => (),
          expr_cast(_, _) => {
            let ety = ty::expr_ty(tcx, e);
            if !ty::type_is_numeric(ety) {
                sess.span_err(e.span, ~"can not cast to `" +
                              ppaux::ty_to_str(tcx, ety) +
                              ~"` in a constant expression");
            }
          }
          expr_path(pth) => {
            // NB: In the future you might wish to relax this slightly
            // to handle on-demand instantiation of functions via
            // foo::<bar> in a const. Currently that is only done on
            // a path in trans::callee that only works in block contexts.
            if pth.types.len() != 0 {
                sess.span_err(
                    e.span, ~"paths in constants may only refer to \
                              items without type parameters");
            }
            match def_map.find(&e.id) {
                Some(def_variant(_, _)) |
                Some(def_struct(_)) => { }

                Some(def_const(def_id)) |
                Some(def_fn(def_id, _)) => {
                if !ast_util::is_local(def_id) {
                    sess.span_err(
                        e.span, ~"paths in constants may only refer to \
                                 crate-local constants or functions");
                }
              }
              Some(def) => {
                debug!("(checking const) found bad def: %?", def);
                sess.span_err(
                    e.span,
                    fmt!("paths in constants may only refer to \
                          constants or functions"));
              }
              None => {
                sess.span_bug(e.span, ~"unbound path in const?!");
              }
            }
          }
          expr_call(callee, _, NoSugar) => {
            match def_map.find(&callee.id) {
                Some(def_struct(*)) => {}    // OK.
                Some(def_variant(*)) => {}    // OK.
                _ => {
                    sess.span_err(
                        e.span,
                        ~"function calls in constants are limited to \
                          struct and enum constructors");
                }
            }
          }
          expr_paren(e) => { check_expr(sess, def_map, method_map,
                                         tcx, e, is_const, v); }
          expr_vstore(_, expr_vstore_slice) |
          expr_vstore(_, expr_vstore_fixed(_)) |
          expr_vec(_, m_imm) |
          expr_addr_of(m_imm, _) |
          expr_field(*) |
          expr_index(*) |
          expr_tup(*) |
          expr_struct(_, _, None) |
          expr_rec(_, None) => { }
          expr_addr_of(*) => {
                sess.span_err(
                    e.span,
                    ~"borrowed pointers in constants may only refer to \
                      immutable values");
          }
          _ => {
            sess.span_err(e.span,
                          ~"constant contains unimplemented expression type");
            return;
          }
        }
    }
    match e.node {
      expr_lit(@codemap::spanned {node: lit_int(v, t), _}) => {
        if t != ty_char {
            if (v as u64) > ast_util::int_ty_max(
                if t == ty_i { sess.targ_cfg.int_type } else { t }) {
                sess.span_err(e.span, ~"literal out of range for its type");
            }
        }
      }
      expr_lit(@codemap::spanned {node: lit_uint(v, t), _}) => {
        if v > ast_util::uint_ty_max(
            if t == ty_u { sess.targ_cfg.uint_type } else { t }) {
            sess.span_err(e.span, ~"literal out of range for its type");
        }
      }
      _ => ()
    }
    visit::visit_expr(e, is_const, v);
}

// Make sure a const item doesn't recursively refer to itself
// FIXME: Should use the dependency graph when it's available (#1356)
pub fn check_item_recursion(sess: Session,
                            ast_map: ast_map::map,
                            def_map: resolve::DefMap,
                            it: @item) {
    struct env {
        root_it: @item,
        sess: Session,
        ast_map: ast_map::map,
        def_map: resolve::DefMap,
        idstack: @mut ~[node_id]
    }

    let env = env {
        root_it: it,
        sess: sess,
        ast_map: ast_map,
        def_map: def_map,
        idstack: @mut ~[]
    };

    let visitor = visit::mk_vt(@visit::Visitor {
        visit_item: visit_item,
        visit_expr: visit_expr,
        .. *visit::default_visitor()
    });
    (visitor.visit_item)(it, env, visitor);

    fn visit_item(it: @item, &&env: env, v: visit::vt<env>) {
        if env.idstack.contains(&(it.id)) {
            env.sess.span_fatal(env.root_it.span, ~"recursive constant");
        }
        env.idstack.push(it.id);
        visit::visit_item(it, env, v);
        env.idstack.pop();
    }

    fn visit_expr(e: @expr, &&env: env, v: visit::vt<env>) {
        match e.node {
          expr_path(*) => {
            match env.def_map.find(&e.id) {
              Some(def_const(def_id)) => {
                match env.ast_map.get(&def_id.node) {
                  ast_map::node_item(it, _) => {
                    (v.visit_item)(it, env, v);
                  }
                  _ => fail!(~"const not bound to an item")
                }
              }
              _ => ()
            }
          }
          _ => ()
        }
        visit::visit_expr(e, env, v);
    }
}

// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
<|endoftext|>


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

#![allow(non_snake_case)]

register_long_diagnostics! {

E0046: r##"
When trying to make some type implement a trait `Foo`, you must, at minimum,
provide implementations for all of `Foo`'s required methods (meaning the
methods that do not have default implementations), as well as any required
trait items like associated types or constants.
"##,

E0054: r##"
It is not allowed to cast to a bool. If you are trying to cast a numeric type
to a bool, you can compare it with zero instead:

```
let x = 5;

// Ok
let x_is_nonzero = x != 0;

// Not allowed, won't compile
let x_is_nonzero = x as bool;
```
"##,

E0062: r##"
This error indicates that during an attempt to build a struct or struct-like
enum variant, one of the fields was specified more than once. Each field should
be specified exactly one time.
"##,

E0063: r##"
This error indicates that during an attempt to build a struct or struct-like
enum variant, one of the fields was not provided. Each field should be specified
exactly once.
"##,

E0067: r##"
The left-hand side of an assignment operator must be an lvalue expression. An
lvalue expression represents a memory location and includes item paths (ie,
namespaced variables), dereferences, indexing expressions, and field references.

```
use std::collections::LinkedList;

// Good
let mut list = LinkedList::new();

// Bad: assignment to non-lvalue expression
LinkedList::new() += 1;
```
"##,

E0081: r##"
Enum discriminants are used to differentiate enum variants stored in memory.
This error indicates that the same value was used for two or more variants,
making them impossible to tell apart.

```
// Good.
enum Enum {
    P,
    X = 3,
    Y = 5
}

// Bad.
enum Enum {
    P = 3,
    X = 3,
    Y = 5
}
```

Note that variants without a manually specified discriminant are numbered from
top to bottom starting from 0, so clashes can occur with seemingly unrelated
variants.

```
enum Bad {
    X,
    Y = 0
}
```

Here `X` will have already been assigned the discriminant 0 by the time `Y` is
encountered, so a conflict occurs.
"##,

E0082: r##"
The default type for enum discriminants is `isize`, but it can be adjusted by
adding the `repr` attribute to the enum declaration. This error indicates that
an integer literal given as a discriminant is not a member of the discriminant
type. For example:

```
#[repr(u8)]
enum Thing {
    A = 1024,
    B = 5
}
```

Here, 1024 lies outside the valid range for `u8`, so the discriminant for `A` is
invalid. You may want to change representation types to fix this, or else change
invalid discriminant values so that they fit within the existing type.

Note also that without a representation manually defined, the compiler will
optimize by using the smallest integer type possible.
"##,

E0083: r##"
At present, it's not possible to define a custom representation for an enum with
a single variant. As a workaround you can add a `Dummy` variant.

See: https://github.com/rust-lang/rust/issues/10292
"##,

E0084: r##"
It is impossible to define an integer type to be used to represent zero-variant
enum values because there are no zero-variant enum values. There is no way to
construct an instance of the following type using only safe code:

```
enum Empty {}
```
"##,

E0131: r##"
It is not possible to define `main` with type parameters, or even with function
parameters. When `main` is present, it must take no arguments and return `()`.
"##,

E0132: r##"
It is not possible to declare type parameters on a function that has the `start`
attribute. Such a function must have the following type signature:

```
fn(isize, *const *const u8) -> isize
```
"##

}

register_diagnostics! {
    E0023,
    E0024,
    E0025,
    E0026,
    E0027,
    E0029,
    E0030,
    E0031,
    E0033,
    E0034,
    E0035,
    E0036,
    E0038,
    E0040, // explicit use of destructor method
    E0044,
    E0045,
    E0049,
    E0050,
    E0053,
    E0055,
    E0057,
    E0059,
    E0060,
    E0061,
    E0066,
    E0068,
    E0069,
    E0070,
    E0071,
    E0072,
    E0073,
    E0074,
    E0075,
    E0076,
    E0077,
    E0085,
    E0086,
    E0087,
    E0088,
    E0089,
    E0090,
    E0091,
    E0092,
    E0093,
    E0094,
    E0101,
    E0102,
    E0103,
    E0104,
    E0106,
    E0107,
    E0116,
    E0117,
    E0118,
    E0119,
    E0120,
    E0121,
    E0122,
    E0123,
    E0124,
    E0127,
    E0128,
    E0129,
    E0130,
    E0141,
    E0159,
    E0163,
    E0164,
    E0166,
    E0167,
    E0168,
    E0172,
    E0173, // manual implementations of unboxed closure traits are experimental
    E0174, // explicit use of unboxed closure methods are experimental
    E0178,
    E0182,
    E0183,
    E0184,
    E0185,
    E0186,
    E0187, // can't infer the kind of the closure
    E0188, // types differ in mutability
    E0189, // can only cast a boxed pointer to a boxed object
    E0190, // can only cast a &-pointer to an &-object
    E0191, // value of the associated type must be specified
    E0192, // negative imples are allowed just for `Send` and `Sync`
    E0193, // cannot bound type where clause bounds may only be attached to types
           // involving type parameters
    E0194,
    E0195, // lifetime parameters or bounds on method do not match the trait declaration
    E0196, // cannot determine a type for this closure
    E0197, // inherent impls cannot be declared as unsafe
    E0198, // negative implementations are not unsafe
    E0199, // implementing trait is not unsafe
    E0200, // trait requires an `unsafe impl` declaration
    E0201, // duplicate method in trait impl
    E0202, // associated items are not allowed in inherent impls
    E0203, // type parameter has more than one relaxed default bound,
           // and only one is supported
    E0204, // trait `Copy` may not be implemented for this type; field
           // does not implement `Copy`
    E0205, // trait `Copy` may not be implemented for this type; variant
           // does not implement `copy`
    E0206, // trait `Copy` may not be implemented for this type; type is
           // not a structure or enumeration
    E0207, // type parameter is not constrained by the impl trait, self type, or predicate
    E0208,
    E0209, // builtin traits can only be implemented on structs or enums
    E0210, // type parameter is not constrained by any local type
    E0211,
    E0212, // cannot extract an associated type from a higher-ranked trait bound
    E0213, // associated types are not accepted in this context
    E0214, // parenthesized parameters may only be used with a trait
    E0215, // angle-bracket notation is not stable with `Fn`
    E0216, // parenthetical notation is only stable with `Fn`
    E0217, // ambiguous associated type, defined in multiple supertraits
    E0218, // no associated type defined
    E0219, // associated type defined in higher-ranked supertrait
    E0220, // associated type not found for type parameter
    E0221, // ambiguous associated type in bounds
    E0222, // variadic function must have C calling convention
    E0223, // ambiguous associated type
    E0224, // at least one non-builtin train is required for an object type
    E0225, // only the builtin traits can be used as closure or object bounds
    E0226, // only a single explicit lifetime bound is permitted
    E0227, // ambiguous lifetime bound, explicit lifetime bound required
    E0228, // explicit lifetime bound required
    E0229, // associated type bindings are not allowed here
    E0230, // there is no type parameter on trait
    E0231, // only named substitution parameters are allowed
    E0232, // this attribute must have a value
    E0233,
    E0234, // `for` loop expression has type which does not implement the `Iterator` trait
    E0235, // structure constructor specifies a structure of type but
    E0236, // no lang item for range syntax
    E0237, // no lang item for range syntax
    E0238, // parenthesized parameters may only be used with a trait
    E0239, // `next` method of `Iterator` trait has unexpected type
    E0240,
    E0241,
    E0242, // internal error looking up a definition
    E0243, // wrong number of type arguments
    E0244, // wrong number of type arguments
    E0245, // not a trait
    E0246, // illegal recursive type
    E0247, // found module name used as a type
    E0248, // found value name used as a type
    E0249, // expected constant expr for array length
    E0250, // expected constant expr for array length
    E0318, // can't create default impls for traits outside their crates
    E0319, // trait impls for defaulted traits allowed just for structs/enums
    E0320, // recursive overflow during dropck
    E0321, // extended coherence rules for defaulted traits violated
    E0322, // cannot implement Sized explicitly
    E0323, // implemented an associated const when another trait item expected
    E0324, // implemented a method when another trait item expected
    E0325, // implemented an associated type when another trait item expected
    E0326, // associated const implemented with different type from trait
    E0327, // referred to method instead of constant in match pattern
    E0366, // dropck forbid specialization to concrete type or region
    E0367, // dropck forbid specialization to predicate not in struct/enum
    E0368, // binary operation `<op>=` cannot be applied to types
    E0369, // binary operation `<op>` cannot be applied to types
    E0371, // impl Trait for Trait is illegal
    E0372  // impl Trait for Trait where Trait is not object safe
}
<commit_msg>Add some comments for error codes in librustc_typeck/diagnostics<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![allow(non_snake_case)]

register_long_diagnostics! {

E0046: r##"
When trying to make some type implement a trait `Foo`, you must, at minimum,
provide implementations for all of `Foo`'s required methods (meaning the
methods that do not have default implementations), as well as any required
trait items like associated types or constants.
"##,

E0054: r##"
It is not allowed to cast to a bool. If you are trying to cast a numeric type
to a bool, you can compare it with zero instead:

```
let x = 5;

// Ok
let x_is_nonzero = x != 0;

// Not allowed, won't compile
let x_is_nonzero = x as bool;
```
"##,

E0062: r##"
This error indicates that during an attempt to build a struct or struct-like
enum variant, one of the fields was specified more than once. Each field should
be specified exactly one time.
"##,

E0063: r##"
This error indicates that during an attempt to build a struct or struct-like
enum variant, one of the fields was not provided. Each field should be specified
exactly once.
"##,

E0067: r##"
The left-hand side of an assignment operator must be an lvalue expression. An
lvalue expression represents a memory location and includes item paths (ie,
namespaced variables), dereferences, indexing expressions, and field references.

```
use std::collections::LinkedList;

// Good
let mut list = LinkedList::new();

// Bad: assignment to non-lvalue expression
LinkedList::new() += 1;
```
"##,

E0081: r##"
Enum discriminants are used to differentiate enum variants stored in memory.
This error indicates that the same value was used for two or more variants,
making them impossible to tell apart.

```
// Good.
enum Enum {
    P,
    X = 3,
    Y = 5
}

// Bad.
enum Enum {
    P = 3,
    X = 3,
    Y = 5
}
```

Note that variants without a manually specified discriminant are numbered from
top to bottom starting from 0, so clashes can occur with seemingly unrelated
variants.

```
enum Bad {
    X,
    Y = 0
}
```

Here `X` will have already been assigned the discriminant 0 by the time `Y` is
encountered, so a conflict occurs.
"##,

E0082: r##"
The default type for enum discriminants is `isize`, but it can be adjusted by
adding the `repr` attribute to the enum declaration. This error indicates that
an integer literal given as a discriminant is not a member of the discriminant
type. For example:

```
#[repr(u8)]
enum Thing {
    A = 1024,
    B = 5
}
```

Here, 1024 lies outside the valid range for `u8`, so the discriminant for `A` is
invalid. You may want to change representation types to fix this, or else change
invalid discriminant values so that they fit within the existing type.

Note also that without a representation manually defined, the compiler will
optimize by using the smallest integer type possible.
"##,

E0083: r##"
At present, it's not possible to define a custom representation for an enum with
a single variant. As a workaround you can add a `Dummy` variant.

See: https://github.com/rust-lang/rust/issues/10292
"##,

E0084: r##"
It is impossible to define an integer type to be used to represent zero-variant
enum values because there are no zero-variant enum values. There is no way to
construct an instance of the following type using only safe code:

```
enum Empty {}
```
"##,

E0131: r##"
It is not possible to define `main` with type parameters, or even with function
parameters. When `main` is present, it must take no arguments and return `()`.
"##,

E0132: r##"
It is not possible to declare type parameters on a function that has the `start`
attribute. Such a function must have the following type signature:

```
fn(isize, *const *const u8) -> isize
```
"##

}

register_diagnostics! {
    E0023,
    E0024,
    E0025,
    E0026,
    E0027,
    E0029,
    E0030,
    E0031,
    E0033,
    E0034, // multiple applicable methods in scope
    E0035, // does not take type parameters
    E0036, // incorrect number of type parameters given for this method
    E0038, // cannot convert to a trait object because trait is not object-safe
    E0040, // explicit use of destructor method
    E0044, // foreign items may not have type parameters
    E0045, // variadic function must have C calling convention
    E0049,
    E0050,
    E0053,
    E0055, // method has an incompatible type for trait
    E0057, // method has an incompatible type for trait
    E0059,
    E0060,
    E0061,
    E0066,
    E0068,
    E0069,
    E0070,
    E0071,
    E0072,
    E0073,
    E0074,
    E0075,
    E0076,
    E0077,
    E0085,
    E0086,
    E0087,
    E0088,
    E0089,
    E0090,
    E0091,
    E0092,
    E0093,
    E0094,
    E0101,
    E0102,
    E0103,
    E0104,
    E0106,
    E0107,
    E0116,
    E0117,
    E0118,
    E0119,
    E0120,
    E0121,
    E0122,
    E0123,
    E0124,
    E0127,
    E0128,
    E0129,
    E0130,
    E0141,
    E0159,
    E0163,
    E0164,
    E0166,
    E0167,
    E0168,
    E0172,
    E0173, // manual implementations of unboxed closure traits are experimental
    E0174, // explicit use of unboxed closure methods are experimental
    E0178,
    E0182,
    E0183,
    E0184,
    E0185,
    E0186,
    E0187, // can't infer the kind of the closure
    E0188, // types differ in mutability
    E0189, // can only cast a boxed pointer to a boxed object
    E0190, // can only cast a &-pointer to an &-object
    E0191, // value of the associated type must be specified
    E0192, // negative imples are allowed just for `Send` and `Sync`
    E0193, // cannot bound type where clause bounds may only be attached to types
           // involving type parameters
    E0194,
    E0195, // lifetime parameters or bounds on method do not match the trait declaration
    E0196, // cannot determine a type for this closure
    E0197, // inherent impls cannot be declared as unsafe
    E0198, // negative implementations are not unsafe
    E0199, // implementing trait is not unsafe
    E0200, // trait requires an `unsafe impl` declaration
    E0201, // duplicate method in trait impl
    E0202, // associated items are not allowed in inherent impls
    E0203, // type parameter has more than one relaxed default bound,
           // and only one is supported
    E0204, // trait `Copy` may not be implemented for this type; field
           // does not implement `Copy`
    E0205, // trait `Copy` may not be implemented for this type; variant
           // does not implement `copy`
    E0206, // trait `Copy` may not be implemented for this type; type is
           // not a structure or enumeration
    E0207, // type parameter is not constrained by the impl trait, self type, or predicate
    E0208,
    E0209, // builtin traits can only be implemented on structs or enums
    E0210, // type parameter is not constrained by any local type
    E0211,
    E0212, // cannot extract an associated type from a higher-ranked trait bound
    E0213, // associated types are not accepted in this context
    E0214, // parenthesized parameters may only be used with a trait
    E0215, // angle-bracket notation is not stable with `Fn`
    E0216, // parenthetical notation is only stable with `Fn`
    E0217, // ambiguous associated type, defined in multiple supertraits
    E0218, // no associated type defined
    E0219, // associated type defined in higher-ranked supertrait
    E0220, // associated type not found for type parameter
    E0221, // ambiguous associated type in bounds
    E0222, // variadic function must have C calling convention
    E0223, // ambiguous associated type
    E0224, // at least one non-builtin train is required for an object type
    E0225, // only the builtin traits can be used as closure or object bounds
    E0226, // only a single explicit lifetime bound is permitted
    E0227, // ambiguous lifetime bound, explicit lifetime bound required
    E0228, // explicit lifetime bound required
    E0229, // associated type bindings are not allowed here
    E0230, // there is no type parameter on trait
    E0231, // only named substitution parameters are allowed
    E0232, // this attribute must have a value
    E0233,
    E0234, // `for` loop expression has type which does not implement the `Iterator` trait
    E0235, // structure constructor specifies a structure of type but
    E0236, // no lang item for range syntax
    E0237, // no lang item for range syntax
    E0238, // parenthesized parameters may only be used with a trait
    E0239, // `next` method of `Iterator` trait has unexpected type
    E0240,
    E0241,
    E0242, // internal error looking up a definition
    E0243, // wrong number of type arguments
    E0244, // wrong number of type arguments
    E0245, // not a trait
    E0246, // illegal recursive type
    E0247, // found module name used as a type
    E0248, // found value name used as a type
    E0249, // expected constant expr for array length
    E0250, // expected constant expr for array length
    E0318, // can't create default impls for traits outside their crates
    E0319, // trait impls for defaulted traits allowed just for structs/enums
    E0320, // recursive overflow during dropck
    E0321, // extended coherence rules for defaulted traits violated
    E0322, // cannot implement Sized explicitly
    E0323, // implemented an associated const when another trait item expected
    E0324, // implemented a method when another trait item expected
    E0325, // implemented an associated type when another trait item expected
    E0326, // associated const implemented with different type from trait
    E0327, // referred to method instead of constant in match pattern
    E0366, // dropck forbid specialization to concrete type or region
    E0367, // dropck forbid specialization to predicate not in struct/enum
    E0368, // binary operation `<op>=` cannot be applied to types
    E0369, // binary operation `<op>` cannot be applied to types
    E0371, // impl Trait for Trait is illegal
    E0372  // impl Trait for Trait where Trait is not object safe
}
<|endoftext|>


<commit_before><commit_msg>added to<commit_after>// Half precision float

pub struct Half(u16);

// conversions

pub trait ToHalf {
	fn to_half(&self)->Half;
}

impl ToHalf for f32 {
	fn to_half(&self)->Half{ fail!();Half(0)}
}

impl ToPrimitive for Half {
	fn to_f32(&self)->Option<f32> {fail!(); None}
	fn to_f64(&self)->Option<f64> {fail!(); None}

	fn to_u8(&self)->Option<u8> {fail!(); self.to_uint().unwrap().to_u8()}
	fn to_u16(&self)->Option<u16> {fail!(); self.to_uint().unwrap().to_u16()}
	fn to_u32(&self)->Option<u32> {fail!(); self.to_uint().unwrap().to_u32()}
	fn to_u64(&self)->Option<u64> {fail!(); None}
	fn to_uint(&self)->Option<uint> {fail!(); None}

	fn to_i8(&self)->Option<i8> {fail!(); self.to_int().unwrap().to_i8()}
	fn to_i16(&self)->Option<i16> {fail!(); self.to_int().unwrap().to_i16()}
	fn to_i32(&self)->Option<i32> {fail!(); self.to_int().unwrap().to_i32()}
	fn to_i64(&self)->Option<i64> {fail!(); None}
	fn to_int(&self)->Option<int> {fail!(); None}
}

// Dont bother with arithmetic, its a storage format only.
<|endoftext|>


<commit_before><commit_msg>Fix failed test cases of rotate_bytes_right<commit_after><|endoftext|>


<commit_before><commit_msg>Add ARM decode for branching instructions<commit_after><|endoftext|>


<commit_before><commit_msg>Moved stuff to lib.rs<commit_after>#![deny(missing_docs)]

//! A Gfx texture representation that works nicely with Piston libraries.

extern crate gfx;
extern crate texture;
extern crate image;

pub use texture::*;

use std::path::Path;
use image::{
    DynamicImage,
    GenericImage,
    RgbaImage,
};
use gfx::traits::*;

/// Represents a texture.
#[derive(Clone, Debug, PartialEq)]
pub struct Texture<R> where R: gfx::Resources {
    handle: gfx::handle::Texture<R>
}

impl<R: gfx::Resources> Texture<R> {
    /// Gets a handle to the Gfx texture.
    pub fn handle(&self) -> gfx::handle::Texture<R> {
        self.handle.clone()
    }

    /// Returns empty texture.
    pub fn empty<F>(factory: &mut F) -> Result<Self, gfx::tex::TextureError>
        where F: gfx::Factory<R>
    {
        let tex_handle = try!(factory.create_texture_rgba8(1, 1));
        let ref image_info = tex_handle.get_info().clone().into();
        try!(factory.update_texture(
            &tex_handle,
            &image_info,
            &[0u8; 4],
            Some(gfx::tex::Kind::D2)
        ));
        Ok(Texture {
            handle: tex_handle
        })
    }

    /// Creates a texture from path.
    pub fn from_path<F, P>(
        factory: &mut F,
        path: P,
        settings: &TextureSettings,
    ) -> Result<Self, String>
        where F: gfx::Factory<R>,
              P: AsRef<Path>
    {
        let img = try!(image::open(path).map_err(|e| e.to_string()));

        let img = match img {
            DynamicImage::ImageRgba8(img) => img,
            img => img.to_rgba()
        };

        Ok(Texture::from_image(factory, &img, settings))
    }

    /// Creates a texture from image.
    pub fn from_image<F>(
        factory: &mut F,
        img: &RgbaImage,
        settings: &TextureSettings
    ) -> Self
        where F: gfx::Factory<R>
    {
        let (width, height) = img.dimensions();
        let tex_info = gfx::tex::TextureInfo {
            width: width as u16,
            height: height as u16,
            depth: 1,
            levels: 1,
            kind: gfx::tex::Kind::D2,
            format: if settings.get_convert_gamma() {
                        gfx::tex::Format::SRGB8_A8
                    } else { gfx::tex::RGBA8 }
        };
        let tex_handle = factory.create_texture_static(tex_info, &img).unwrap();
        if settings.get_generate_mipmap() {
            factory.generate_mipmap(&tex_handle);
        }
        Texture {
            handle: tex_handle
        }
    }

    /// Creates texture from memory alpha.
    pub fn from_memory_alpha<F>(
        factory: &mut F,
        buffer: &[u8],
        width: u32,
        height: u32,
    ) -> Self
        where F: gfx::Factory<R>
    {
        let width = if width == 0 { 1 } else { width as u16 };
        let height = if height == 0 { 1 } else { height as u16 };

        let mut pixels = vec![];
        for alpha in buffer {
            pixels.extend(vec![255; 3]);
            pixels.push(*alpha);
        }

        let tex_handle = factory.create_texture_rgba8(width, height).unwrap();
        let ref image_info = tex_handle.get_info().clone().into();
        factory.update_texture(
            &tex_handle,
            &image_info,
            &pixels,
            Some(gfx::tex::Kind::D2)
        ).unwrap();

        Texture {
            handle: tex_handle
        }
    }

    /// Updates the texture with an image.
    pub fn update<F>(&mut self, factory: &mut F, image: &RgbaImage)
        where F: gfx::Factory<R>
    {
        factory.update_texture(&self.handle,
            &self.handle.get_info().clone().into(),
            &image,
            Some(gfx::tex::Kind::D2)
        ).unwrap();
    }
}

impl<F, R> Rgba8Texture<F> for Texture<R>
    where F: gfx::Factory<R>,
          R: gfx::Resources
{
    fn from_memory<S: Into<[u32; 2]>>(
        factory: &mut F,
        memory: &[u8],
        size: S,
        settings: &TextureSettings
    ) -> TextureResult<Self> {
        let size = size.into();
        let (width, height) = (size[0] as u16, size[1] as u16);
        let tex_info = gfx::tex::TextureInfo {
            width: width,
            height: height,
            depth: 1,
            levels: 1,
            kind: gfx::tex::Kind::D2,
            format: if settings.get_convert_gamma() {
                        gfx::tex::Format::SRGB8_A8
                    } else { gfx::tex::RGBA8 }
        };
        let tex_handle = match factory.create_texture_static(tex_info, &memory) {
            Ok(x) => x,
            Err(err) => {
                return Err(TextureError::FactoryError(format!("{:?}", err)));
            }
        };
        if settings.get_generate_mipmap() {
            factory.generate_mipmap(&tex_handle);
        }
        Ok(Texture { handle: tex_handle })
    }

    fn update<S: Into<[u32; 2]>>(
        &mut self,
        factory: &mut F,
        memory: &[u8],
        _size: S,
    ) -> TextureResult<()> {
        match factory.update_texture(&self.handle,
            &self.handle.get_info().clone().into(),
            &memory,
            Some(gfx::tex::Kind::D2)
        ) {
            Ok(()) => Ok(()),
            Err(err) => Err(TextureError::FactoryError(format!("{:?}", err)))
        }
    }
}

impl<R> ImageSize for Texture<R> where R: gfx::Resources {
    #[inline(always)]
    fn get_size(&self) -> (u32, u32) {
        let info = self.handle.get_info();
        (info.width as u32, info.height as u32)
    }
}
<|endoftext|>


<commit_before><commit_msg>cleanup<commit_after><|endoftext|>


<commit_before><commit_msg>Make fields public (blegh)<commit_after><|endoftext|>


<commit_before><commit_msg>Refactor<commit_after><|endoftext|>


<commit_before><commit_msg>Forgot to commit this file. It is important for tests.<commit_after>pub mod syntax;
<|endoftext|>


<commit_before><commit_msg>Add heapsort<commit_after><|endoftext|>


<commit_before><commit_msg>Oops forgot to git add<commit_after>#[macro_use] extern crate log;
extern crate byteorder;
extern crate bytes;
extern crate mio;
extern crate uuid;
pub mod packet;
pub mod worker;
pub mod queues;
pub mod server;
pub mod constants;
pub mod job;
<|endoftext|>


<commit_before><commit_msg>Add documentation for readline and add_history<commit_after><|endoftext|>


<commit_before><commit_msg>Added RenderContext Added Return Type Parsing<commit_after><|endoftext|>


<commit_before><commit_msg>add Machine Learning integration tests<commit_after>#![cfg(feature = "machinelearning")]

extern crate rusoto;

use rusoto::machinelearning::{MachineLearningClient, DescribeDataSourcesInput, DescribeBatchPredictionsInput, DescribeEvaluationsInput};
use rusoto::{DefaultCredentialsProvider, Region};

#[test]
fn should_describe_batch_predictions() {
    let credentials = DefaultCredentialsProvider::new().unwrap();
    let client = MachineLearningClient::new(credentials, Region::UsEast1);

    let request = DescribeBatchPredictionsInput::default();

    match client.describe_batch_predictions(&request) {
        Ok(response) => {
            println!("{:#?}", response);
            assert!(true)
        },
        Err(err) => panic!("Expected OK response, got {:#?}", err)
    };
}
#[test]
fn should_describe_data_sources() {
    let credentials = DefaultCredentialsProvider::new().unwrap();
    let client = MachineLearningClient::new(credentials, Region::UsEast1);

    let request = DescribeDataSourcesInput::default();

    match client.describe_data_sources(&request) {
        Ok(response) => {
            println!("{:#?}", response);
            assert!(true)
        },
        Err(err) => panic!("Expected OK response, got {:#?}", err)
    };
}
#[test]
fn should_describe_evaluations() {
    let credentials = DefaultCredentialsProvider::new().unwrap();
    let client = MachineLearningClient::new(credentials, Region::UsEast1);

    let request = DescribeEvaluationsInput::default();

    match client.describe_evaluations(&request) {
        Ok(response) => {
            println!("{:#?}", response);
            assert!(true)
        },
        Err(err) => panic!("Expected OK response, got {:#?}", err)
    };
}
<|endoftext|>


<commit_before><commit_msg>within example<commit_after>use ipnetwork::IpNetwork;

use maxminddb::geoip2;
use maxminddb::Within;

fn main() -> Result<(), String> {
    let mut args = std::env::args().skip(1);
    let reader = maxminddb::Reader::open_readfile(
        args.next()
            .ok_or("First argument must be the path to the IP database")?,
    )
    .unwrap();
    let cidr: String = args
        .next()
        .ok_or("Second argument must be the IP address and mask in CIDR notation")?
        .parse()
        .unwrap();
    let ip_net = if cidr.contains(":") {
        IpNetwork::V6(cidr.parse().unwrap())
    } else {
        IpNetwork::V4(cidr.parse().unwrap())
    };
    let within: Within<_, geoip2::City> = reader.within(ip_net).unwrap();
    for item in within {
        println!("item={:#?}", item);
    }
    Ok(())
}
<|endoftext|>


<commit_before>// aux-build:issue_2723_a.rs

use issue_2723_a;
import issue_2723_a::*;

fn main() unsafe {
  f(~[2]);
}<commit_msg>add xfail-fast directive due to aux-build<commit_after>// xfail-fast: aux-build not compatible with fast
// aux-build:issue_2723_a.rs

use issue_2723_a;
import issue_2723_a::*;

fn main() unsafe {
  f(~[2]);
}<|endoftext|>


<commit_before><commit_msg>added rust code for figure 5.5<commit_after>extern crate libc;
extern crate apue;

static MAXLINE:libc::c_int = 10;

fn main() {
	unsafe {
		let stdin = libc::fdopen(libc::STDIN_FILENO, &('r' as libc::c_char));
		let stdout = libc::fdopen(libc::STDOUT_FILENO, &('w' as libc::c_char));
		let mut buf = Vec::with_capacity(MAXLINE as usize);
		let ptr = buf.as_mut_ptr() as *mut libc::c_char;
	    while !libc::fgets(ptr, MAXLINE, stdin).is_null() {
	    	if libc::fputs(ptr, stdout) == libc::EOF {
				panic!("output error");
	    	}
	    }
	    if libc::ferror(stdin) != 0 {
	    	panic!("input error");
	    }
	}
}<|endoftext|>


<commit_before><commit_msg>New functionality for clear command<commit_after><|endoftext|>


<commit_before><commit_msg>Reexport more specs types<commit_after><|endoftext|>


<commit_before><commit_msg>Fixing bugs<commit_after><|endoftext|>


<commit_before><commit_msg>Add _mut version of accessors. Fix #7.<commit_after><|endoftext|>


<commit_before><commit_msg>Use `append_raw` to ensure all headers are set.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix test file<commit_after>#![feature(macro_rules)]
extern crate opencl = "OpenCL#0.2";

use opencl::hl;

macro_rules! expect (
    ($test: expr, $expected: expr) => ({
            let test     = $test;
            let expected = $expected;
            if test != expected {
                fail!(format!("Test failure in {:s}: expected {:?}, got {:?}",
                              stringify!($test),
                              expected, test))
            }
        })
        )

fn main () {
    /*let src = "__kernel void test(__global int *i, long int k) {
                   *i += k;
                   }";
    let prog = ctx.create_program_from_source(src);
    prog.build(&device).unwrap();

    let k = prog.create_kernel("test");
    let v = ctx.create_buffer_from(&[1], CL_MEM_READ_WRITE);
    k.set_arg(0, &v);
    k.set_arg(1, &42);
    queue.enqueue_async_kernel(&k, 1, None, ()).wait();
    let v: ~[int] = queue.get(&v, ());

    expect!(v[0], 43);*/

    let platforms = hl::get_platforms();
    for p in platforms.iter() {
        let devices = p.get_devices();
        for d in devices.iter() {
            let context = d.create_context();
            let queue = context.create_command_queue(d);
            let name = d.name();
            println!("device found");
        }
    }

}
<|endoftext|>


<commit_before><commit_msg>Add for grammar<commit_after><|endoftext|>


<commit_before><commit_msg>Rewrite some match {} statements as Option::map() and Option::and_then()<commit_after><|endoftext|>


<commit_before><commit_msg>util: require full feature in tokio-util tests (#3636)<commit_after>#![cfg(not(feature = "full"))]
compile_error!("run tokio-util tests with `--features full`");
<|endoftext|>


<commit_before>//! The `game` module contains traits and structs to actually run your game mainloop
//! and handle top-level state.

use context::Context;
use GameResult;
use timer;

use std::time::Duration;

use super::event as gevent;

use sdl2::event::Event::*;
use sdl2::event;
use sdl2::mouse;
use sdl2::keyboard;

/// A trait defining event callbacks.
///
/// The default event handlers do nothing, apart from `key_down_event()`,
/// which *should* by default exit the game if escape is pressed.
/// (Once we work around some event bugs in rust-sdl2.)
pub trait EventHandler {
    /// Called upon each physics update to the game.
    /// This should be where the game's logic takes place.
    fn update(&mut self, ctx: &mut Context, dt: Duration) -> GameResult<()>;

    /// Called to do the drawing of your game.
    /// You probably want to start this with
    /// `graphics::clear()` and end it with
    /// `graphics::present()` and `timer::sleep_until_next_frame()`
    fn draw(&mut self, ctx: &mut Context) -> GameResult<()>;

    // You don't have to override these if you don't want to; the defaults
    // do nothing.
    // It might be nice to be able to have custom event types and a map or
    // such of handlers?  Hmm, maybe later.
    fn mouse_button_down_event(&mut self, _button: mouse::MouseButton, _x: i32, _y: i32) {}

    fn mouse_button_up_event(&mut self, _button: mouse::MouseButton, _x: i32, _y: i32) {}

    fn mouse_motion_event(&mut self,
                          _state: mouse::MouseState,
                          _x: i32,
                          _y: i32,
                          _xrel: i32,
                          _yrel: i32) {
    }

    fn mouse_wheel_event(&mut self, _x: i32, _y: i32) {}

    fn key_down_event(&mut self, _keycode: gevent::Keycode, _keymod: gevent::Mod, _repeat: bool) {}

    fn key_up_event(&mut self, _keycode: gevent::Keycode, _keymod: gevent::Mod, _repeat: bool) {}

    fn controller_button_down_event(&mut self, _btn: gevent::Button) {}
    fn controller_button_up_event(&mut self, _btn: gevent::Button) {}
    fn controller_axis_event(&mut self, _axis: gevent::Axis, _value: i16) {}

    fn focus_event(&mut self, _gained: bool) {}

    /// Called upon a quit event.  If it returns true,
    /// the game does not exit.
    fn quit_event(&mut self) -> bool {
        println!("Quitting game");
        false
    }
}

/// Runs the game's main loop, calling event
/// callbacks on the given state object as events
/// occur.
pub fn run<S>(ctx: &mut Context, state: &mut S) -> GameResult<()>
    where S: EventHandler
{
    {
        let mut event_pump = ctx.sdl_context.event_pump()?;

        let mut continuing = true;
        let mut residual_update_dt = Duration::new(0, 0);
        let mut residual_draw_dt = Duration::new(0, 0);
        while continuing {
            ctx.timer_context.tick();

            for event in event_pump.poll_iter() {
                match event {
                    Quit { .. } => {
                        continuing = state.quit_event();
                        // println!("Quit event: {:?}", t);
                    }
                    // TODO: We need a good way to have
                    // a default like this, while still allowing
                    // it to be overridden.
                    // Bah, just put it in the GameState trait
                    // as the default function.
                    // But it doesn't have access to the context
                    // to call quit!  Bah.
                    KeyDown { keycode, keymod, repeat, .. } => {
                        if let Some(key) = keycode {
                            if key == keyboard::Keycode::Escape {
                                ctx.quit()?;
                            } else {
                                state.key_down_event(key, keymod, repeat)
                            }
                        }
                    }
                    KeyUp { keycode, keymod, repeat, .. } => {
                        if let Some(key) = keycode {
                            state.key_up_event(key, keymod, repeat)
                        }
                    }
                    MouseButtonDown { mouse_btn, x, y, .. } => {
                        state.mouse_button_down_event(mouse_btn, x, y)
                    }
                    MouseButtonUp { mouse_btn, x, y, .. } => {
                        state.mouse_button_up_event(mouse_btn, x, y)
                    }
                    MouseMotion { mousestate, x, y, xrel, yrel, .. } => {
                        state.mouse_motion_event(mousestate, x, y, xrel, yrel)
                    }
                    MouseWheel { x, y, .. } => state.mouse_wheel_event(x, y),
                    ControllerButtonDown { button, .. } => {
                        state.controller_button_down_event(button)
                    }
                    ControllerButtonUp { button, .. } => state.controller_button_up_event(button),
                    ControllerAxisMotion { axis, value, .. } => {
                        state.controller_axis_event(axis, value)
                    }
                    Window { win_event: event::WindowEvent::FocusGained, .. } => {
                        state.focus_event(true)
                    }
                    Window { win_event: event::WindowEvent::FocusLost, .. } => {
                        state.focus_event(false)
                    }
                    _ => {}
                }
            }

            // BUGGO: These should be gotten from
            // the config file!
            // Draw should be as-fast-as-possible tho
            let update_dt = Duration::from_millis(10);
            let draw_dt = Duration::new(0, 16_666_666);
            let dt = timer::get_delta(ctx);
            {
                let mut current_dt = dt + residual_update_dt;
                while current_dt > update_dt {
                    state.update(ctx, update_dt)?;
                    current_dt -= update_dt;
                }
                residual_update_dt = current_dt;
            }

            {
                let mut current_dt = dt + residual_draw_dt;
                while current_dt > draw_dt {
                    state.draw(ctx)?;
                    current_dt -= draw_dt;
                }
                residual_draw_dt = draw_dt;
            }
            timer::sleep(Duration::new(0, 0));
        }
    }

    Ok(())
}
<commit_msg>Resolve issue #42<commit_after>//! The `game` module contains traits and structs to actually run your game mainloop
//! and handle top-level state.

use context::Context;
use GameResult;
use timer;

use std::time::Duration;

use super::event as gevent;

use sdl2::event::Event::*;
use sdl2::event;
use sdl2::mouse;
use sdl2::keyboard;

/// A trait defining event callbacks.
///
/// The default event handlers do nothing, apart from `key_down_event()`,
/// which *should* by default exit the game if escape is pressed.
/// (Once we work around some event bugs in rust-sdl2.)
pub trait EventHandler {
    /// Called upon each physics update to the game.
    /// This should be where the game's logic takes place.
    fn update(&mut self, ctx: &mut Context, dt: Duration) -> GameResult<()>;

    /// Called to do the drawing of your game.
    /// You probably want to start this with
    /// `graphics::clear()` and end it with
    /// `graphics::present()` and `timer::sleep_until_next_frame()`
    fn draw(&mut self, ctx: &mut Context) -> GameResult<()>;

    // You don't have to override these if you don't want to; the defaults
    // do nothing.
    // It might be nice to be able to have custom event types and a map or
    // such of handlers?  Hmm, maybe later.
    fn mouse_button_down_event(&mut self, _button: mouse::MouseButton, _x: i32, _y: i32) {}

    fn mouse_button_up_event(&mut self, _button: mouse::MouseButton, _x: i32, _y: i32) {}

    fn mouse_motion_event(&mut self,
                          _state: mouse::MouseState,
                          _x: i32,
                          _y: i32,
                          _xrel: i32,
                          _yrel: i32) {
    }

    fn mouse_wheel_event(&mut self, _x: i32, _y: i32) {}

    fn key_down_event(&mut self, _keycode: gevent::Keycode, _keymod: gevent::Mod, _repeat: bool) {}

    fn key_up_event(&mut self, _keycode: gevent::Keycode, _keymod: gevent::Mod, _repeat: bool) {}

    fn controller_button_down_event(&mut self, _btn: gevent::Button) {}
    fn controller_button_up_event(&mut self, _btn: gevent::Button) {}
    fn controller_axis_event(&mut self, _axis: gevent::Axis, _value: i16) {}

    fn focus_event(&mut self, _gained: bool) {}

    /// Called upon a quit event.  If it returns true,
    /// the game does not exit.
    fn quit_event(&mut self) -> bool {
        println!("Quitting game");
        false
    }
}

/// Runs the game's main loop, calling event
/// callbacks on the given state object as events
/// occur.
pub fn run<S>(ctx: &mut Context, state: &mut S) -> GameResult<()>
    where S: EventHandler
{
    {
        let mut event_pump = ctx.sdl_context.event_pump()?;

        let mut continuing = true;
        let mut residual_update_dt = Duration::new(0, 0);
        let mut residual_draw_dt = Duration::new(0, 0);
        while continuing {
            ctx.timer_context.tick();

            for event in event_pump.poll_iter() {
                match event {
                    Quit { .. } => {
                        continuing = state.quit_event();
                        // println!("Quit event: {:?}", t);
                    }
                    // TODO: We need a good way to have
                    // a default like this, while still allowing
                    // it to be overridden.
                    // Bah, just put it in the GameState trait
                    // as the default function.
                    // But it doesn't have access to the context
                    // to call quit!  Bah.
                    KeyDown { keycode, keymod, repeat, .. } => {
                        if let Some(key) = keycode {
                            if key == keyboard::Keycode::Escape {
                                ctx.quit()?;
                            } else {
                                state.key_down_event(key, keymod, repeat)
                            }
                        }
                    }
                    KeyUp { keycode, keymod, repeat, .. } => {
                        if let Some(key) = keycode {
                            state.key_up_event(key, keymod, repeat)
                        }
                    }
                    MouseButtonDown { mouse_btn, x, y, .. } => {
                        state.mouse_button_down_event(mouse_btn, x, y)
                    }
                    MouseButtonUp { mouse_btn, x, y, .. } => {
                        state.mouse_button_up_event(mouse_btn, x, y)
                    }
                    MouseMotion { mousestate, x, y, xrel, yrel, .. } => {
                        state.mouse_motion_event(mousestate, x, y, xrel, yrel)
                    }
                    MouseWheel { x, y, .. } => state.mouse_wheel_event(x, y),
                    ControllerButtonDown { button, .. } => {
                        state.controller_button_down_event(button)
                    }
                    ControllerButtonUp { button, .. } => state.controller_button_up_event(button),
                    ControllerAxisMotion { axis, value, .. } => {
                        state.controller_axis_event(axis, value)
                    }
                    Window { win_event: event::WindowEvent::FocusGained, .. } => {
                        state.focus_event(true)
                    }
                    Window { win_event: event::WindowEvent::FocusLost, .. } => {
                        state.focus_event(false)
                    }
                    _ => {}
                }
            }

            // BUGGO: These should be gotten from
            // the config file!
            // Draw should be as-fast-as-possible tho
            // TODO: The catchup_frames is a bit hacky too;
            // this whole section is sound in principle but
            // just needs cleanup.
            let update_dt = Duration::from_millis(10);
            let draw_dt = Duration::new(0, 16_666_666);
            let dt = timer::get_delta(ctx);
            let mut catchup_frames = 10;
            {
                let mut current_dt = dt + residual_update_dt;
                while current_dt > update_dt {
                    state.update(ctx, update_dt)?;
                    current_dt -= update_dt;
                    catchup_frames -= 1;
                    if catchup_frames <= 0 {
                        break;
                    }
                }
                residual_update_dt = current_dt;
            }

            {
                let mut current_dt = dt + residual_draw_dt;
                while current_dt > draw_dt {
                    state.draw(ctx)?;
                    current_dt -= draw_dt;
                }
                residual_draw_dt = draw_dt;
            }
            timer::sleep(Duration::new(0, 0));
        }
    }

    Ok(())
}
<|endoftext|>