<commit_before>
import front::ast;
import front::codemap;
import util::common::span;
import util::common::ty_mach;
import std::uint;
import std::term;
import std::io;
import std::map;
import std::option;
import std::option::some;
import std::option::none;

tag os { os_win32; os_macos; os_linux; }

tag arch { arch_x86; arch_x64; arch_arm; }

type config =
    rec(os os,
        arch arch,
        ty_mach int_type,
        ty_mach uint_type,
        ty_mach float_type);

type options =
    rec(bool shared,
        uint optimize,
        bool debuginfo,
        bool verify,
        bool run_typestate,
        bool save_temps,
        bool stats,
        bool time_passes,
        bool time_llvm_passes,
        back::link::output_type output_type,
        vec[str] library_search_paths,
        str sysroot);

type crate_metadata = rec(str name, vec[u8] data);

fn span_to_str(span sp, codemap::codemap cm) -> str {
    auto lo = codemap::lookup_pos(cm, sp.lo);
    auto hi = codemap::lookup_pos(cm, sp.hi);
    ret #fmt("%s:%u:%u:%u:%u", lo.filename, lo.line, lo.col, hi.line, hi.col);
}

fn emit_diagnostic(option::t[span] sp, str msg, str kind, u8 color,
                   codemap::codemap cm) {
    auto ss = "<input>:0:0:0:0";
    alt (sp) {
        case (some(?ssp)) { ss = span_to_str(ssp, cm); }
        case (none) { }
    }
    io::stdout().write_str(ss + ": ");
    if (term::color_supported()) {
        term::fg(io::stdout().get_buf_writer(), color);
    }
    io::stdout().write_str(#fmt("%s:", kind));
    if (term::color_supported()) {
        term::reset(io::stdout().get_buf_writer());
    }
    io::stdout().write_str(#fmt(" %s\n", msg));
}

obj session(ast::crate_num cnum,
            @config targ_cfg,
            @options opts,
            map::hashmap[int, crate_metadata] crates,
            mutable vec[str] used_crate_files,
            mutable vec[str] used_libraries,
            codemap::codemap cm,
            mutable uint err_count) {
    fn get_targ_cfg() -> @config { ret targ_cfg; }
    fn get_opts() -> @options { ret opts; }
    fn get_targ_crate_num() -> ast::crate_num { ret cnum; }
    fn span_fatal(span sp, str msg) -> ! {
        // FIXME: Use constants, but rustboot doesn't know how to export them.

        emit_diagnostic(some(sp), msg, "error", 9u8, cm);
        fail;
    }
    fn fatal(str msg) -> ! {
        emit_diagnostic(none[span], msg, "error", 9u8, cm);
        fail;
    }
    fn span_err(span sp, str msg) {
        emit_diagnostic(some(sp), msg, "error", 9u8, cm);
        err_count += 1u;
    }
    fn err(span sp, str msg) {
        emit_diagnostic(some(sp), msg, "error", 9u8, cm);
        err_count += 1u;
    }
    fn abort_if_errors() {
        if (err_count > 0u) {
            self.fatal("aborting due to previous errors");
        }
    }
    fn span_warn(span sp, str msg) {
        // FIXME: Use constants, but rustboot doesn't know how to export them.

        emit_diagnostic(some(sp), msg, "warning", 11u8, cm);
    }
    fn warn(str msg) {
        emit_diagnostic(none[span], msg, "warning", 11u8, cm);
    }
    fn span_note(span sp, str msg) {
        // FIXME: Use constants, but rustboot doesn't know how to export them.

        emit_diagnostic(some(sp), msg, "note", 10u8, cm);
    }
    fn span_bug(span sp, str msg) -> ! {
        self.span_fatal(sp, #fmt("internal compiler error %s", msg));
    }
    fn bug(str msg) -> ! {
        self.fatal(#fmt("internal compiler error %s", msg));
    }
    fn span_unimpl(span sp, str msg) -> ! {
        self.span_bug(sp, "unimplemented " + msg);
    }
    fn unimpl(str msg) -> ! { self.bug("unimplemented " + msg); }
    fn get_external_crate(int num) -> crate_metadata { ret crates.get(num); }
    fn set_external_crate(int num, &crate_metadata metadata) {
        crates.insert(num, metadata);
    }
    fn has_external_crate(int num) -> bool { ret crates.contains_key(num); }
    fn add_used_library(&str lib) {
        if (lib == "") {
            ret;
        }
        // A program has a small number of libraries, so a vector is probably
        // a good data structure in here.
        for (str l in used_libraries) {
            if (l == lib) {
                ret;
            }
        }
        used_libraries += [lib];
    }
    fn get_used_libraries() -> vec[str] {
       ret used_libraries;
    }
    fn add_used_crate_file(&str lib) {
        // A program has a small number of crates, so a vector is probably
        // a good data structure in here.
        for (str l in used_crate_files) {
            if (l == lib) {
                ret;
            }
        }
        used_crate_files += [lib];
    }
    fn get_used_crate_files() -> vec[str] {
       ret used_crate_files;
    }
    fn get_codemap() -> codemap::codemap { ret cm; }
    fn lookup_pos(uint pos) -> codemap::loc {
        ret codemap::lookup_pos(cm, pos);
    }
    fn span_str(span sp) -> str { ret span_to_str(sp, self.get_codemap()); }
}
// Local Variables:
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<commit_msg>session.err shouldn't take a span<commit_after>
import front::ast;
import front::codemap;
import util::common::span;
import util::common::ty_mach;
import std::uint;
import std::term;
import std::io;
import std::map;
import std::option;
import std::option::some;
import std::option::none;

tag os { os_win32; os_macos; os_linux; }

tag arch { arch_x86; arch_x64; arch_arm; }

type config =
    rec(os os,
        arch arch,
        ty_mach int_type,
        ty_mach uint_type,
        ty_mach float_type);

type options =
    rec(bool shared,
        uint optimize,
        bool debuginfo,
        bool verify,
        bool run_typestate,
        bool save_temps,
        bool stats,
        bool time_passes,
        bool time_llvm_passes,
        back::link::output_type output_type,
        vec[str] library_search_paths,
        str sysroot);

type crate_metadata = rec(str name, vec[u8] data);

fn span_to_str(span sp, codemap::codemap cm) -> str {
    auto lo = codemap::lookup_pos(cm, sp.lo);
    auto hi = codemap::lookup_pos(cm, sp.hi);
    ret #fmt("%s:%u:%u:%u:%u", lo.filename, lo.line, lo.col, hi.line, hi.col);
}

fn emit_diagnostic(option::t[span] sp, str msg, str kind, u8 color,
                   codemap::codemap cm) {
    auto ss = "<input>:0:0:0:0";
    alt (sp) {
        case (some(?ssp)) { ss = span_to_str(ssp, cm); }
        case (none) { }
    }
    io::stdout().write_str(ss + ": ");
    if (term::color_supported()) {
        term::fg(io::stdout().get_buf_writer(), color);
    }
    io::stdout().write_str(#fmt("%s:", kind));
    if (term::color_supported()) {
        term::reset(io::stdout().get_buf_writer());
    }
    io::stdout().write_str(#fmt(" %s\n", msg));
}

obj session(ast::crate_num cnum,
            @config targ_cfg,
            @options opts,
            map::hashmap[int, crate_metadata] crates,
            mutable vec[str] used_crate_files,
            mutable vec[str] used_libraries,
            codemap::codemap cm,
            mutable uint err_count) {
    fn get_targ_cfg() -> @config { ret targ_cfg; }
    fn get_opts() -> @options { ret opts; }
    fn get_targ_crate_num() -> ast::crate_num { ret cnum; }
    fn span_fatal(span sp, str msg) -> ! {
        // FIXME: Use constants, but rustboot doesn't know how to export them.

        emit_diagnostic(some(sp), msg, "error", 9u8, cm);
        fail;
    }
    fn fatal(str msg) -> ! {
        emit_diagnostic(none[span], msg, "error", 9u8, cm);
        fail;
    }
    fn span_err(span sp, str msg) {
        emit_diagnostic(some(sp), msg, "error", 9u8, cm);
        err_count += 1u;
    }
    fn err(str msg) {
        emit_diagnostic(none, msg, "error", 9u8, cm);
        err_count += 1u;
    }
    fn abort_if_errors() {
        if (err_count > 0u) {
            self.fatal("aborting due to previous errors");
        }
    }
    fn span_warn(span sp, str msg) {
        // FIXME: Use constants, but rustboot doesn't know how to export them.

        emit_diagnostic(some(sp), msg, "warning", 11u8, cm);
    }
    fn warn(str msg) {
        emit_diagnostic(none[span], msg, "warning", 11u8, cm);
    }
    fn span_note(span sp, str msg) {
        // FIXME: Use constants, but rustboot doesn't know how to export them.

        emit_diagnostic(some(sp), msg, "note", 10u8, cm);
    }
    fn span_bug(span sp, str msg) -> ! {
        self.span_fatal(sp, #fmt("internal compiler error %s", msg));
    }
    fn bug(str msg) -> ! {
        self.fatal(#fmt("internal compiler error %s", msg));
    }
    fn span_unimpl(span sp, str msg) -> ! {
        self.span_bug(sp, "unimplemented " + msg);
    }
    fn unimpl(str msg) -> ! { self.bug("unimplemented " + msg); }
    fn get_external_crate(int num) -> crate_metadata { ret crates.get(num); }
    fn set_external_crate(int num, &crate_metadata metadata) {
        crates.insert(num, metadata);
    }
    fn has_external_crate(int num) -> bool { ret crates.contains_key(num); }
    fn add_used_library(&str lib) {
        if (lib == "") {
            ret;
        }
        // A program has a small number of libraries, so a vector is probably
        // a good data structure in here.
        for (str l in used_libraries) {
            if (l == lib) {
                ret;
            }
        }
        used_libraries += [lib];
    }
    fn get_used_libraries() -> vec[str] {
       ret used_libraries;
    }
    fn add_used_crate_file(&str lib) {
        // A program has a small number of crates, so a vector is probably
        // a good data structure in here.
        for (str l in used_crate_files) {
            if (l == lib) {
                ret;
            }
        }
        used_crate_files += [lib];
    }
    fn get_used_crate_files() -> vec[str] {
       ret used_crate_files;
    }
    fn get_codemap() -> codemap::codemap { ret cm; }
    fn lookup_pos(uint pos) -> codemap::loc {
        ret codemap::lookup_pos(cm, pos);
    }
    fn span_str(span sp) -> str { ret span_to_str(sp, self.get_codemap()); }
}
// Local Variables:
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<|endoftext|>


<commit_before><commit_msg>add response module<commit_after>pub mod response;
pub use self::response::Response;
<|endoftext|>


<commit_before><commit_msg>Fix test count tracking<commit_after><|endoftext|>


<commit_before><commit_msg>Add note about using Windows-31J instead of Shift JIS<commit_after><|endoftext|>


<commit_before>use registry::{Registry, StdRegistry};
use std::time::Duration;
use std::thread;
use std::sync::Arc;
use reporter::base::Reporter;
use metrics::counter::StdCounter;
use metrics::gauge::StdGauge;
use metrics::meter::MeterSnapshot;
use histogram::Histogram;
use time;
use time::Timespec;
use std::net::TcpStream;
use std::io::Write;

pub struct CarbonStream {
    graphite_stream: Option<TcpStream>,
    host_and_port: String,
}

pub struct CarbonReporter {
    host_and_port: String,
    prefix: &'static str,
    registry: Arc<StdRegistry<'static>>,
    reporter_name: &'static str,
}

impl CarbonStream {
    pub fn new(host_and_port: String) -> CarbonStream {
        CarbonStream {
            host_and_port: host_and_port,
            graphite_stream: None,
        }
    }

    pub fn connect(&mut self) {
        let host_and_port = &*self.host_and_port;
        match TcpStream::connect(host_and_port) {
            Ok(x) => self.graphite_stream = Some(x),
            Err(e) => panic!("Unable to connect to {} because {}", host_and_port, e),
        }

    }

    pub fn write(&mut self, metric_path: String, value: String, timespec: Timespec) {
        let seconds_in_ms = (timespec.sec * 1000) as u32;
        let nseconds_in_ms = (timespec.nsec / 1000) as u32;
        let timestamp = seconds_in_ms + nseconds_in_ms;
        match self.graphite_stream {
            Some(ref mut stream) => {
                let carbon_command = format!("{} {} {}\n", metric_path, value, timestamp)
                    .into_bytes();
                match stream.write_all(&carbon_command) {
                    Ok(_) => {}
                    Err(x) => println!("Failed to Send {:?}", x),
                }
            }
            None => {
                self.reconnect_stream();
                self.write(metric_path, value, timespec);
            }
        }
    }
    fn reconnect_stream(&mut self) {
        println!("Waiting 123ms and then reconnecting");
        thread::sleep(Duration::from_millis(123));
        self.connect();
    }
}

impl Reporter for CarbonReporter {
    fn get_unique_reporter_name(&self) -> &'static str {
        self.reporter_name
    }
}

fn prefix(metric_line: String, prefix_str: &'static str) -> String {
    format!("{}.{}", prefix_str, metric_line)
}

fn send_meter_metric(metric_name: String,
                     meter: MeterSnapshot,
                     carbon: &mut CarbonStream,
                     prefix_str: &'static str,
                     ts: Timespec) {

    let count = meter.count.to_string();
    let m1_rate = meter.rates[0].to_string();
    let m5_rate = meter.rates[1].to_string();
    let m15_rate = meter.rates[2].to_string();
    let mean_rate = meter.mean.to_string();
    carbon.write(prefix(format!("{}.count", metric_name), prefix_str),
                 count,
                 ts);
    carbon.write(prefix(format!("{}.m1", metric_name), prefix_str),
                 m1_rate,
                 ts);
    carbon.write(prefix(format!("{}.m5", metric_name), prefix_str),
                 m5_rate,
                 ts);
    carbon.write(prefix(format!("{}.m15", metric_name), prefix_str),
                 m15_rate,
                 ts);
    carbon.write(prefix(format!("{}.mean", metric_name), prefix_str),
                 mean_rate,
                 ts);
}

fn send_gauge_metric(metric_name: String,
                     gauge: StdGauge,
                     carbon: &mut CarbonStream,
                     prefix_str: &'static str,
                     ts: Timespec) {
    carbon.write(prefix(format!("{}", metric_name), prefix_str),
                 gauge.value.to_string(),
                 ts);
}

fn send_counter_metric(metric_name: String,
                       counter: StdCounter,
                       carbon: &mut CarbonStream,
                       prefix_str: &'static str,
                       ts: Timespec) {
    carbon.write(prefix(format!("{}", metric_name), prefix_str),
                 counter.value.to_string(),
                 ts);
}
fn send_histogram_metric(metric_name: String,
                         histogram: &mut Histogram,
                         carbon: &mut CarbonStream,
                         prefix_str: &'static str,
                         ts: Timespec) {
    let count = histogram.count();
    // let sum = histogram.sum();
    // let mean = sum / count;
    let max = histogram.percentile(100.0).unwrap();
    let min = histogram.percentile(0.0).unwrap();

    let p50 = histogram.percentile(50.0).unwrap();
    let p75 = histogram.percentile(75.0).unwrap();
    let p95 = histogram.percentile(95.0).unwrap();
    let p98 = histogram.percentile(98.0).unwrap();
    let p99 = histogram.percentile(99.0).unwrap();
    let p999 = histogram.percentile(99.9).unwrap();
    let p9999 = histogram.percentile(99.99).unwrap();
    let p99999 = histogram.percentile(99.999).unwrap();

    carbon.write(prefix(format!("{}.count", metric_name), prefix_str),
                 count.to_string(),
                 ts);

    carbon.write(prefix(format!("{}.max", metric_name), prefix_str),
                 max.to_string(),
                 ts);

    // carbon
    // .write(prefix(format!("{}.mean", metric_name), prefix_str),
    // mean.into_string(),
    // ts);

    carbon.write(prefix(format!("{}.min", metric_name), prefix_str),
                 min.to_string(),
                 ts);

    carbon.write(prefix(format!("{}.p50", metric_name), prefix_str),
                 p50.to_string(),
                 ts);

    carbon.write(prefix(format!("{}.p75", metric_name), prefix_str),
                 p75.to_string(),
                 ts);

    carbon.write(prefix(format!("{}.p95", metric_name), prefix_str),
                 p95.to_string(),
                 ts);

    carbon.write(prefix(format!("{}.p98", metric_name), prefix_str),
                 p98.to_string(),
                 ts);

    carbon.write(prefix(format!("{}.p99", metric_name), prefix_str),
                 p99.to_string(),
                 ts);

    carbon.write(prefix(format!("{}.p999", metric_name), prefix_str),
                 p999.to_string(),
                 ts);

    carbon.write(prefix(format!("{}.p9999", metric_name), prefix_str),
                 p9999.to_string(),
                 ts);

    carbon.write(prefix(format!("{}.p99999", metric_name), prefix_str),
                 p99999.to_string(),
                 ts);
}

impl CarbonReporter {
    pub fn new(registry: Arc<StdRegistry<'static>>,
               reporter_name: &'static str,
               host_and_port: String,
               prefix: &'static str)
               -> CarbonReporter {
        CarbonReporter {
            host_and_port: host_and_port,
            prefix: prefix,
            registry: registry,
            reporter_name: reporter_name,
        }
    }

    fn report_to_carbon_continuously(self, delay_ms: u32) -> thread::JoinHandle<()> {
        use metrics::metric::MetricValue::{Counter, Gauge, Histogram, Meter};

        let prefix = self.prefix;
        let host_and_port = self.host_and_port.clone();
        let mut carbon = CarbonStream::new(host_and_port);
        let registry = self.registry.clone();
        thread::spawn(move || {
            loop {
                let ts = time::now().to_timespec();
                for metric_name in &registry.get_metrics_names() {
                    let metric = registry.get(metric_name);
                    let mnas = metric_name.to_string(); // Metric name as string
                    match metric.export_metric() {
                        Meter(x) => send_meter_metric(mnas, x, &mut carbon, prefix, ts),
                        Gauge(x) => send_gauge_metric(mnas, x, &mut carbon, prefix, ts),
                        Counter(x) => send_counter_metric(mnas, x, &mut carbon, prefix, ts),
                        Histogram(mut x) => {
                            send_histogram_metric(mnas, &mut x, &mut carbon, prefix, ts)
                        }
                    }
                }
                thread::sleep(Duration::from_millis(delay_ms as u64));
            }
        })
    }

    pub fn start(self, delay_ms: u32) {
        self.report_to_carbon_continuously(delay_ms);
    }
}

#[cfg(test)]
mod test {
    use metrics::meter::{Meter, StdMeter};
    use metrics::counter::{Counter, StdCounter};
    use metrics::gauge::{Gauge, StdGauge};
    use registry::{Registry, StdRegistry};
    use reporter::carbon::CarbonReporter;
    use std::sync::Arc;
    use std::thread;
    use histogram::*;

    #[test]
    fn meter() {
        let m = StdMeter::new();
        m.mark(100);

        let mut c: StdCounter = StdCounter::new();
        c.inc();

        let mut g: StdGauge = StdGauge { value: 0f64 };
        g.set(1.2);

        let mut hc = HistogramConfig::new();
        hc.max_value(100).precision(1);
        let mut h = Histogram::configured(hc).unwrap();

        h.record(1, 1);

        let mut r = StdRegistry::new();
        r.insert("meter1", m);
        r.insert("counter1", c);
        r.insert("gauge1", g);
        r.insert("histogram", h);

        let arc_registry = Arc::new(r);
        CarbonReporter::new(arc_registry.clone(),
                            "test",
                            "localhost:0".to_string(),
                            "asd.asdf");
    }
}
<commit_msg>Update carbon.rs<commit_after>// CarbonReporter sends a message to a carbon end point at a regular basis.
use registry::{Registry, StdRegistry};
use std::time::Duration;
use std::thread;
use std::sync::Arc;
use reporter::base::Reporter;
use metrics::counter::StdCounter;
use metrics::gauge::StdGauge;
use metrics::meter::MeterSnapshot;
use histogram::Histogram;
use time;
use time::Timespec;
use std::net::TcpStream;
use std::io::Write;

pub struct CarbonStream {
    graphite_stream: Option<TcpStream>,
    host_and_port: String,
}

pub struct CarbonReporter {
    host_and_port: String,
    prefix: &'static str,
    registry: Arc<StdRegistry<'static>>,
    reporter_name: &'static str,
}

impl CarbonStream {
    pub fn new(host_and_port: String) -> CarbonStream {
        CarbonStream {
            host_and_port: host_and_port,
            graphite_stream: None,
        }
    }

    pub fn connect(&mut self) {
        let host_and_port = &*self.host_and_port;
        match TcpStream::connect(host_and_port) {
            Ok(x) => self.graphite_stream = Some(x),
            Err(e) => panic!("Unable to connect to {} because {}", host_and_port, e),
        }

    }

    pub fn write(&mut self, metric_path: String, value: String, timespec: Timespec) {
        let seconds_in_ms = (timespec.sec * 1000) as u32;
        let nseconds_in_ms = (timespec.nsec / 1000) as u32;
        let timestamp = seconds_in_ms + nseconds_in_ms;
        match self.graphite_stream {
            Some(ref mut stream) => {
                let carbon_command = format!("{} {} {}\n", metric_path, value, timestamp)
                    .into_bytes();
                match stream.write_all(&carbon_command) {
                    Ok(_) => {}
                    Err(x) => println!("Failed to Send {:?}", x),
                }
            }
            None => {
                self.reconnect_stream();
                self.write(metric_path, value, timespec);
            }
        }
    }
    fn reconnect_stream(&mut self) {
        println!("Waiting 123ms and then reconnecting");
        thread::sleep(Duration::from_millis(123));
        self.connect();
    }
}

impl Reporter for CarbonReporter {
    fn get_unique_reporter_name(&self) -> &'static str {
        self.reporter_name
    }
}

fn prefix(metric_line: String, prefix_str: &'static str) -> String {
    format!("{}.{}", prefix_str, metric_line)
}

fn send_meter_metric(metric_name: String,
                     meter: MeterSnapshot,
                     carbon: &mut CarbonStream,
                     prefix_str: &'static str,
                     ts: Timespec) {

    let count = meter.count.to_string();
    let m1_rate = meter.rates[0].to_string();
    let m5_rate = meter.rates[1].to_string();
    let m15_rate = meter.rates[2].to_string();
    let mean_rate = meter.mean.to_string();
    carbon.write(prefix(format!("{}.count", metric_name), prefix_str),
                 count,
                 ts);
    carbon.write(prefix(format!("{}.m1", metric_name), prefix_str),
                 m1_rate,
                 ts);
    carbon.write(prefix(format!("{}.m5", metric_name), prefix_str),
                 m5_rate,
                 ts);
    carbon.write(prefix(format!("{}.m15", metric_name), prefix_str),
                 m15_rate,
                 ts);
    carbon.write(prefix(format!("{}.mean", metric_name), prefix_str),
                 mean_rate,
                 ts);
}

fn send_gauge_metric(metric_name: String,
                     gauge: StdGauge,
                     carbon: &mut CarbonStream,
                     prefix_str: &'static str,
                     ts: Timespec) {
    carbon.write(prefix(format!("{}", metric_name), prefix_str),
                 gauge.value.to_string(),
                 ts);
}

fn send_counter_metric(metric_name: String,
                       counter: StdCounter,
                       carbon: &mut CarbonStream,
                       prefix_str: &'static str,
                       ts: Timespec) {
    carbon.write(prefix(format!("{}", metric_name), prefix_str),
                 counter.value.to_string(),
                 ts);
}
fn send_histogram_metric(metric_name: String,
                         histogram: &mut Histogram,
                         carbon: &mut CarbonStream,
                         prefix_str: &'static str,
                         ts: Timespec) {
    let count = histogram.count();
    // let sum = histogram.sum();
    // let mean = sum / count;
    let max = histogram.percentile(100.0).unwrap();
    let min = histogram.percentile(0.0).unwrap();

    let p50 = histogram.percentile(50.0).unwrap();
    let p75 = histogram.percentile(75.0).unwrap();
    let p95 = histogram.percentile(95.0).unwrap();
    let p98 = histogram.percentile(98.0).unwrap();
    let p99 = histogram.percentile(99.0).unwrap();
    let p999 = histogram.percentile(99.9).unwrap();
    let p9999 = histogram.percentile(99.99).unwrap();
    let p99999 = histogram.percentile(99.999).unwrap();

    carbon.write(prefix(format!("{}.count", metric_name), prefix_str),
                 count.to_string(),
                 ts);

    carbon.write(prefix(format!("{}.max", metric_name), prefix_str),
                 max.to_string(),
                 ts);

    // carbon
    // .write(prefix(format!("{}.mean", metric_name), prefix_str),
    // mean.into_string(),
    // ts);

    carbon.write(prefix(format!("{}.min", metric_name), prefix_str),
                 min.to_string(),
                 ts);

    carbon.write(prefix(format!("{}.p50", metric_name), prefix_str),
                 p50.to_string(),
                 ts);

    carbon.write(prefix(format!("{}.p75", metric_name), prefix_str),
                 p75.to_string(),
                 ts);

    carbon.write(prefix(format!("{}.p95", metric_name), prefix_str),
                 p95.to_string(),
                 ts);

    carbon.write(prefix(format!("{}.p98", metric_name), prefix_str),
                 p98.to_string(),
                 ts);

    carbon.write(prefix(format!("{}.p99", metric_name), prefix_str),
                 p99.to_string(),
                 ts);

    carbon.write(prefix(format!("{}.p999", metric_name), prefix_str),
                 p999.to_string(),
                 ts);

    carbon.write(prefix(format!("{}.p9999", metric_name), prefix_str),
                 p9999.to_string(),
                 ts);

    carbon.write(prefix(format!("{}.p99999", metric_name), prefix_str),
                 p99999.to_string(),
                 ts);
}

impl CarbonReporter {
    pub fn new(registry: Arc<StdRegistry<'static>>,
               reporter_name: &'static str,
               host_and_port: String,
               prefix: &'static str)
               -> CarbonReporter {
        CarbonReporter {
            host_and_port: host_and_port,
            prefix: prefix,
            registry: registry,
            reporter_name: reporter_name,
        }
    }

    fn report_to_carbon_continuously(self, delay_ms: u32) -> thread::JoinHandle<()> {
        use metrics::metric::MetricValue::{Counter, Gauge, Histogram, Meter};

        let prefix = self.prefix;
        let host_and_port = self.host_and_port.clone();
        let mut carbon = CarbonStream::new(host_and_port);
        let registry = self.registry.clone();
        thread::spawn(move || {
            loop {
                let ts = time::now().to_timespec();
                for metric_name in &registry.get_metrics_names() {
                    let metric = registry.get(metric_name);
                    let mnas = metric_name.to_string(); // Metric name as string
                    match metric.export_metric() {
                        Meter(x) => send_meter_metric(mnas, x, &mut carbon, prefix, ts),
                        Gauge(x) => send_gauge_metric(mnas, x, &mut carbon, prefix, ts),
                        Counter(x) => send_counter_metric(mnas, x, &mut carbon, prefix, ts),
                        Histogram(mut x) => {
                            send_histogram_metric(mnas, &mut x, &mut carbon, prefix, ts)
                        }
                    }
                }
                thread::sleep(Duration::from_millis(delay_ms as u64));
            }
        })
    }

    pub fn start(self, delay_ms: u32) {
        self.report_to_carbon_continuously(delay_ms);
    }
}

#[cfg(test)]
mod test {
    use metrics::meter::{Meter, StdMeter};
    use metrics::counter::{Counter, StdCounter};
    use metrics::gauge::{Gauge, StdGauge};
    use registry::{Registry, StdRegistry};
    use reporter::carbon::CarbonReporter;
    use std::sync::Arc;
    use std::thread;
    use histogram::*;

    #[test]
    fn meter() {
        let m = StdMeter::new();
        m.mark(100);

        let mut c: StdCounter = StdCounter::new();
        c.inc();

        let mut g: StdGauge = StdGauge { value: 0f64 };
        g.set(1.2);

        let mut hc = HistogramConfig::new();
        hc.max_value(100).precision(1);
        let mut h = Histogram::configured(hc).unwrap();

        h.record(1, 1);

        let mut r = StdRegistry::new();
        r.insert("meter1", m);
        r.insert("counter1", c);
        r.insert("gauge1", g);
        r.insert("histogram", h);

        let arc_registry = Arc::new(r);
        CarbonReporter::new(arc_registry.clone(),
                            "test",
                            "localhost:0".to_string(),
                            "asd.asdf");
    }
}
<|endoftext|>


<commit_before><commit_msg>Add raw pointer variant of #90752 with incorrect behavior<commit_after>// run-pass

use std::cell::RefCell;

struct S<'a>(i32, &'a RefCell<Vec<i32>>);

impl<'a> Drop for S<'a> {
    fn drop(&mut self) {
        self.1.borrow_mut().push(self.0);
    }
}

fn test(drops: &RefCell<Vec<i32>>) {
    let mut foo = None;
    let pfoo: *mut _ = &mut foo;

    match foo {
        None => (),
        _ => return,
    }

    // Both S(0) and S(1) should be dropped, but aren't.
    unsafe { *pfoo = Some((S(0, drops), S(1, drops))); }

    match foo {
        Some((_x, _)) => {}
        _ => {}
    }
}

fn main() {
    let drops = RefCell::new(Vec::new());
    test(&drops);

    // Ideally, we want this...
    //assert_eq!(*drops.borrow(), &[0, 1]);

    // But the delayed access through the raw pointer confuses drop elaboration,
    // causing S(1) to be leaked.
    assert_eq!(*drops.borrow(), &[0]);
}
<|endoftext|>


<commit_before>

fn add(uint x, uint y) -> uint { ret x + y; }

fn sub(uint x, uint y) -> uint { ret x - y; }

fn mul(uint x, uint y) -> uint { ret x * y; }

fn div(uint x, uint y) -> uint { ret x / y; }

fn rem(uint x, uint y) -> uint { ret x % y; }

pred lt(uint x, uint y) -> bool { ret x < y; }

pred le(uint x, uint y) -> bool { ret x <= y; }

pred eq(uint x, uint y) -> bool { ret x == y; }

pred ne(uint x, uint y) -> bool { ret x != y; }

pred ge(uint x, uint y) -> bool { ret x >= y; }

pred gt(uint x, uint y) -> bool { ret x > y; }

fn max(uint x, uint y) -> uint { if (x > y) { ret x; } ret y; }

iter range(uint lo, uint hi) -> uint {
    auto lo_ = lo;
    while (lo_ < hi) { put lo_; lo_ += 1u; }
}

fn next_power_of_two(uint n) -> uint {
    // FIXME change |* uint(4)| below to |* uint(8) / uint(2)| and watch the
    // world explode.

    let uint halfbits = sys::rustrt::size_of[uint]() * 4u;
    let uint tmp = n - 1u;
    let uint shift = 1u;
    while (shift <= halfbits) { tmp |= tmp >> shift; shift <<= 1u; }
    ret tmp + 1u;
}

fn parse_buf(vec[u8] buf, uint radix) -> uint {
    if (vec::len[u8](buf) == 0u) {
        log_err "parse_buf(): buf is empty";
        fail;
    }
    auto i = vec::len[u8](buf) - 1u;
    auto power = 1u;
    auto n = 0u;
    while (true) {
        n += (buf.(i) - ('0' as u8) as uint) * power;
        power *= radix;
        if (i == 0u) { ret n; }
        i -= 1u;
    }
    fail;
}

fn to_str(uint num, uint radix) -> str {
    auto n = num;
    assert (0u < radix && radix <= 16u);
    fn digit(uint n) -> char {
        ret alt (n) {
                case (0u) { '0' }
                case (1u) { '1' }
                case (2u) { '2' }
                case (3u) { '3' }
                case (4u) { '4' }
                case (5u) { '5' }
                case (6u) { '6' }
                case (7u) { '7' }
                case (8u) { '8' }
                case (9u) { '9' }
                case (10u) { 'a' }
                case (11u) { 'b' }
                case (12u) { 'c' }
                case (13u) { 'd' }
                case (14u) { 'e' }
                case (15u) { 'f' }
                case (_) { fail }
            };
    }
    if (n == 0u) { ret "0"; }
    let str s = "";
    while (n != 0u) {
        s += str::unsafe_from_byte(digit(n % radix) as u8);
        n /= radix;
    }
    let str s1 = "";
    let uint len = str::byte_len(s);
    while (len != 0u) { len -= 1u; s1 += str::unsafe_from_byte(s.(len)); }
    ret s1;
}
fn str(uint i) -> str { ret to_str(i, 10u); }

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

fn add(uint x, uint y) -> uint { ret x + y; }

fn sub(uint x, uint y) -> uint { ret x - y; }

fn mul(uint x, uint y) -> uint { ret x * y; }

fn div(uint x, uint y) -> uint { ret x / y; }

fn rem(uint x, uint y) -> uint { ret x % y; }

pred lt(uint x, uint y) -> bool { ret x < y; }

pred le(uint x, uint y) -> bool { ret x <= y; }

pred eq(uint x, uint y) -> bool { ret x == y; }

pred ne(uint x, uint y) -> bool { ret x != y; }

pred ge(uint x, uint y) -> bool { ret x >= y; }

pred gt(uint x, uint y) -> bool { ret x > y; }

fn max(uint x, uint y) -> uint { if (x > y) { ret x; } ret y; }

fn min(uint x, uint y) -> uint { if (x > y) { ret y; } ret x; }

iter range(uint lo, uint hi) -> uint {
    auto lo_ = lo;
    while (lo_ < hi) { put lo_; lo_ += 1u; }
}

fn next_power_of_two(uint n) -> uint {
    // FIXME change |* uint(4)| below to |* uint(8) / uint(2)| and watch the
    // world explode.

    let uint halfbits = sys::rustrt::size_of[uint]() * 4u;
    let uint tmp = n - 1u;
    let uint shift = 1u;
    while (shift <= halfbits) { tmp |= tmp >> shift; shift <<= 1u; }
    ret tmp + 1u;
}

fn parse_buf(vec[u8] buf, uint radix) -> uint {
    if (vec::len[u8](buf) == 0u) {
        log_err "parse_buf(): buf is empty";
        fail;
    }
    auto i = vec::len[u8](buf) - 1u;
    auto power = 1u;
    auto n = 0u;
    while (true) {
        n += (buf.(i) - ('0' as u8) as uint) * power;
        power *= radix;
        if (i == 0u) { ret n; }
        i -= 1u;
    }
    fail;
}

fn to_str(uint num, uint radix) -> str {
    auto n = num;
    assert (0u < radix && radix <= 16u);
    fn digit(uint n) -> char {
        ret alt (n) {
                case (0u) { '0' }
                case (1u) { '1' }
                case (2u) { '2' }
                case (3u) { '3' }
                case (4u) { '4' }
                case (5u) { '5' }
                case (6u) { '6' }
                case (7u) { '7' }
                case (8u) { '8' }
                case (9u) { '9' }
                case (10u) { 'a' }
                case (11u) { 'b' }
                case (12u) { 'c' }
                case (13u) { 'd' }
                case (14u) { 'e' }
                case (15u) { 'f' }
                case (_) { fail }
            };
    }
    if (n == 0u) { ret "0"; }
    let str s = "";
    while (n != 0u) {
        s += str::unsafe_from_byte(digit(n % radix) as u8);
        n /= radix;
    }
    let str s1 = "";
    let uint len = str::byte_len(s);
    while (len != 0u) { len -= 1u; s1 += str::unsafe_from_byte(s.(len)); }
    ret s1;
}
fn str(uint i) -> str { ret to_str(i, 10u); }

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


<commit_before><commit_msg>euler: add problem 10 in rust<commit_after>#[allow(dead_code)]
fn is_prime(num: int) -> bool {
    let sqrt_num = (num as f64).sqrt() as int;
    for divisor in range(2i, sqrt_num + 1) {
        if num % divisor == 0 {
            return false;
        }
    }
    return true;
}

#[allow(dead_code)]
fn is_prime2(num: int) -> bool {
    let sqrt_num = (num as f64).sqrt() as int;
    if num % 2 == 0 {
        return num == 2;
    }
    for divisor in std::iter::count(3i, 2).take_while(|x| *x <= sqrt_num) {
        if num % divisor == 0 {
            return false;
        }
    }
    return true;
}

#[allow(dead_code)]
fn is_prime3(num: int) -> bool {
    let sqrt_num = (num as f64).sqrt() as int;
    if num % 2 == 0 {
        return num == 2;
    }
    if num % 3 == 0 {
        return num == 3;
    }
    for k in std::iter::count(6i, 6).take_while(|x| *x - 1 <= sqrt_num) {
        if num % (k - 1) == 0 {
            return num == k - 1;
        }
        if num % (k + 1) == 0 {
            return num == k + 1;
        }
    }
    return true;
}

#[allow(dead_code)]
fn is_prime4(num: int) -> bool {
    let sqrt_num = (num as f64).sqrt() as int;
    let first_primes = [2i, 3, 5, 7, 11, 13, 17, 19, 23];
    for prime in first_primes.iter() {
        if num % *prime == 0 {
            return num == *prime;
        }
    }
    for divisor in std::iter::count(3i, 2).take_while(|x| *x <= sqrt_num) {
        if num % divisor == 0 {
            return false;
        }
    }
    return true;
}

fn is_prime_(num: int) -> bool {
    return is_prime3(num);
}

#[allow(dead_code)]
fn sum_of_primes_below(limit: int) -> int {
    let mut sum = 0i;
    for n in range(2i, limit) {
        if is_prime_(n) {
            sum += n;
        }
    }
    return sum;
}

#[allow(dead_code)]
fn sum_of_primes_below2(limit: int) -> int {
    let mut prime_sum = 0i;
    if limit > 2 {
        prime_sum += 2
    }
    if limit > 3 {
        prime_sum += 3
    }
    for k in std::iter::count(6i, 6).take_while(|k| *k - 1 < limit) {
        if is_prime_(k - 1) {
            prime_sum += k - 1
        }
        if k + 1 < limit && is_prime_(k + 1) {
            prime_sum += k + 1
        }
    }
    return prime_sum;
}

fn sum_of_primes_below_(limit: int) -> int {
    return sum_of_primes_below2(limit);
}

pub fn main() {
    println!("answer = {}", sum_of_primes_below_(2000000));
}

#[cfg(test)]
mod test {
    use super::{is_prime_, sum_of_primes_below};

    #[test]
    fn test_is_prime() {
        assert_eq!(is_prime_(2), true);
        assert_eq!(is_prime_(3), true);
        assert_eq!(is_prime_(4), false);
        assert_eq!(is_prime_(5), true);
        assert_eq!(is_prime_(6), false);
        assert_eq!(is_prime_(7), true);
        assert_eq!(is_prime_(8), false);
        assert_eq!(is_prime_(9), false);
        assert_eq!(is_prime_(10), false);
        assert_eq!(is_prime_(11), true);
        assert_eq!(is_prime_(12), false);
        assert_eq!(is_prime_(13), true);
        assert_eq!(is_prime_(14), false);
        assert_eq!(is_prime_(15), false);
        assert_eq!(is_prime_(16), false);
        assert_eq!(is_prime_(17), true);
        assert_eq!(is_prime_(18), false);
        assert_eq!(is_prime_(19), true);
        assert_eq!(is_prime_(20), false);
        assert_eq!(is_prime_(21), false);
        assert_eq!(is_prime_(22), false);
        assert_eq!(is_prime_(23), true);
        assert_eq!(is_prime_(24), false);
        assert_eq!(is_prime_(25), false);
        assert_eq!(is_prime_(26), false);
        assert_eq!(is_prime_(27), false);
        assert_eq!(is_prime_(28), false);
        assert_eq!(is_prime_(29), true);
        assert_eq!(is_prime_(101), true);
        assert_eq!(is_prime_(3581), true);
        assert_eq!(is_prime_(3583), true);
    }

    #[test]
    fn correct_example() {
        assert_eq!(sum_of_primes_below(10), 17);
    }

    #[test]
    fn correct_answer() {
        assert_eq!(sum_of_primes_below(2000000), 142913828922);
    }

    // wget -q -O - http://primes.utm.edu/lists/small/1000.txt | cut-first-n-lines 4 | cut-last-n-lines 1 | tr -s  ' ' | cut -c2- | trim-trailing-whitespace | sed 's/ /, /g' | sed 's/$/,/'
    static first_1000_primes : [int, ..1000] = [2i, 3, 5, 7, 11, 13, 17, 19, 23, 29,
        31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
        73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
        127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
        179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
        233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
        283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
        353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
        419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
        467, 479, 487, 491, 499, 503, 509, 521, 523, 541,
        547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
        607, 613, 617, 619, 631, 641, 643, 647, 653, 659,
        661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
        739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
        811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
        877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
        947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013,
        1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069,
        1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,
        1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223,
        1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291,
        1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373,
        1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,
        1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511,
        1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583,
        1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657,
        1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,
        1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811,
        1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889,
        1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987,
        1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053,
        2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129,
        2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213,
        2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287,
        2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,
        2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423,
        2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531,
        2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617,
        2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687,
        2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741,
        2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819,
        2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903,
        2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,
        3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079,
        3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181,
        3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257,
        3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,
        3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413,
        3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511,
        3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571,
        3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643,
        3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727,
        3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821,
        3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907,
        3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989,
        4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057,
        4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139,
        4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231,
        4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297,
        4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409,
        4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493,
        4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583,
        4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657,
        4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751,
        4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831,
        4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937,
        4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 5003,
        5009, 5011, 5021, 5023, 5039, 5051, 5059, 5077, 5081, 5087,
        5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167, 5171, 5179,
        5189, 5197, 5209, 5227, 5231, 5233, 5237, 5261, 5273, 5279,
        5281, 5297, 5303, 5309, 5323, 5333, 5347, 5351, 5381, 5387,
        5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443,
        5449, 5471, 5477, 5479, 5483, 5501, 5503, 5507, 5519, 5521,
        5527, 5531, 5557, 5563, 5569, 5573, 5581, 5591, 5623, 5639,
        5641, 5647, 5651, 5653, 5657, 5659, 5669, 5683, 5689, 5693,
        5701, 5711, 5717, 5737, 5741, 5743, 5749, 5779, 5783, 5791,
        5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, 5851, 5857,
        5861, 5867, 5869, 5879, 5881, 5897, 5903, 5923, 5927, 5939,
        5953, 5981, 5987, 6007, 6011, 6029, 6037, 6043, 6047, 6053,
        6067, 6073, 6079, 6089, 6091, 6101, 6113, 6121, 6131, 6133,
        6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211, 6217, 6221,
        6229, 6247, 6257, 6263, 6269, 6271, 6277, 6287, 6299, 6301,
        6311, 6317, 6323, 6329, 6337, 6343, 6353, 6359, 6361, 6367,
        6373, 6379, 6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473,
        6481, 6491, 6521, 6529, 6547, 6551, 6553, 6563, 6569, 6571,
        6577, 6581, 6599, 6607, 6619, 6637, 6653, 6659, 6661, 6673,
        6679, 6689, 6691, 6701, 6703, 6709, 6719, 6733, 6737, 6761,
        6763, 6779, 6781, 6791, 6793, 6803, 6823, 6827, 6829, 6833,
        6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907, 6911, 6917,
        6947, 6949, 6959, 6961, 6967, 6971, 6977, 6983, 6991, 6997,
        7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103,
        7109, 7121, 7127, 7129, 7151, 7159, 7177, 7187, 7193, 7207,
        7211, 7213, 7219, 7229, 7237, 7243, 7247, 7253, 7283, 7297,
        7307, 7309, 7321, 7331, 7333, 7349, 7351, 7369, 7393, 7411,
        7417, 7433, 7451, 7457, 7459, 7477, 7481, 7487, 7489, 7499,
        7507, 7517, 7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561,
        7573, 7577, 7583, 7589, 7591, 7603, 7607, 7621, 7639, 7643,
        7649, 7669, 7673, 7681, 7687, 7691, 7699, 7703, 7717, 7723,
        7727, 7741, 7753, 7757, 7759, 7789, 7793, 7817, 7823, 7829,
        7841, 7853, 7867, 7873, 7877, 7879, 7883, 7901, 7907, 7919];

    #[test]
    fn check_first_1000_primes() {
        for prime in first_1000_primes.iter() {
            assert_eq!(is_prime_(*prime), true);
            if *prime > 2 {
                assert_eq!(is_prime_(*prime+1), false);
            }
            if *prime > 3 {
                assert_eq!(is_prime_(*prime-1), false);
            }
        }
    }

}
<|endoftext|>


<commit_before><commit_msg>Add problem #118<commit_after>#[crate_type = "rlib"];

extern mod math;

use std::{iter, util, vec};
use math::numconv;
use math::prime::Prime;

pub static EXPECTED_ANSWER: &'static str = "44680";

pub trait ImmutableCloneableVector<T> {
    fn groups(&self, n: uint) -> Groups<T>;
}

impl<'a, T: Clone> ImmutableCloneableVector<T> for &'a [T] {
    #[inline]
    fn groups(&self, n: uint) -> Groups<T> { Groups::new(n, self.to_owned()) }
}

struct ElementIndex {
    num_elem: uint,
    idx: Option<~[uint]>
}

impl ElementIndex {
    #[inline]
    fn new(num_select_elem: uint, num_all_elem: uint) -> ElementIndex {
        ElementIndex {
            num_elem: num_all_elem,
            idx: if num_select_elem > num_all_elem {
                None
            } else {
                Some(vec::from_fn(num_select_elem, |i| i))
            }
        }
    }
}

impl Iterator<~[uint]> for ElementIndex {
    #[inline]
    fn next(&mut self) -> Option<~[uint]> {
        let next = self.idx
            .as_ref()
            .and_then(|idx| {
                let max_num = self.num_elem - 1;
                let max_idx = idx.len() - 1;
                range(0, idx.len())
                    .invert()
                    .find(|&i| idx[i] < max_num - (max_idx - i))
                    .map(|incr_idx| (idx, incr_idx))
            }).map(|(idx, incr_idx)| {
                let mut next = idx.clone();
                next[incr_idx] += 1;
                for j in range(incr_idx + 1, idx.len()) {
                    next[j] = next[incr_idx] + (j - incr_idx);
                }
                next
            });
        util::replace(&mut self.idx, next)
    }
}

pub struct Groups<T> {
    idx: ElementIndex,
    vec: ~[T]
}

impl<T: Clone> Groups<T> {
    fn new(num_select_elem: uint, v: ~[T]) -> Groups<T> {
        Groups { idx: ElementIndex::new(num_select_elem, v.len()), vec: v }
    }
}

impl<T: Clone> Iterator<(~[T], ~[T])> for Groups<T> {
    #[inline]
    fn next(&mut self) -> Option<(~[T], ~[T])> {
        self.idx
            .next()
            .map(|idx| {
                let left = vec::from_fn(idx.len(), |i| self.vec[idx[i]].clone());
                let mut offset = 0;
                let right = vec::from_fn(self.vec.len() - idx.len(), |i| {
                        while offset < idx.len() && offset + i == idx[offset] { offset += 1; }
                        self.vec[offset + i].clone()
                    });
                (left, right)
            })
    }
}

fn count_primes(prime: &Prime, digits: &[uint]) -> uint {
    if digits.len() == 0 { return 1 }

    let mut cnt = 0;
    for n in iter::range_inclusive(1, digits.len()) {
        for (ds, rest) in digits.groups(n) {
            if ds[0] != digits[0] { break }
            if rest.len() == 1 && !prime.contains(rest[0]) { continue }

            let num_prime = if ds.len() == 1 {
                if prime.contains(ds[0]) { 1 } else { 0 }
            } else {
                if ds.iter().fold(0, |x, &y| x + y) % 3 != 0 {
                    ds.permutations()
                        .filter(|perm| perm[0].is_odd() && perm[0] != 5)
                        .filter(|perm| prime.contains(numconv::from_digits(*perm, 10)))
                        .len()
                } else {
                    0
                }
            };

            if num_prime != 0 {
                let rest_primes = count_primes(prime, rest);
                cnt += num_prime * rest_primes;
            }
        }
    }
    cnt
}

pub fn solve() -> ~str {
    let digits = iter::range_inclusive(1u, 9).to_owned_vec();
    let prime = Prime::new();
    count_primes(&prime, digits).to_str()
}

#[cfg(test)]
mod test {
    use super::ElementIndex;

    #[test]
    fn element_index() {
        let mut it = ElementIndex::new(0, 0);
        assert_eq!(Some(~[]), it.next());
        assert_eq!(None, it.next());

        let mut it = ElementIndex::new(3, 3);
        assert_eq!(Some(~[0, 1, 2]), it.next());
        assert_eq!(None, it.next());

        let mut it = ElementIndex::new(2, 3);
        assert_eq!(Some(~[0, 1]), it.next());
        assert_eq!(Some(~[0, 2]), it.next());
        assert_eq!(Some(~[1, 2]), it.next());
        assert_eq!(None, it.next());

        let mut it = ElementIndex::new(1, 3);
        assert_eq!(Some(~[0]), it.next());
        assert_eq!(Some(~[1]), it.next());
        assert_eq!(Some(~[2]), it.next());
        assert_eq!(None, it.next());

        let mut it = ElementIndex::new(4, 3);
        assert_eq!(None, it.next());

        let mut it = ElementIndex::new(3, 6);
        assert_eq!(Some(~[0, 1, 2]), it.next());
        assert_eq!(Some(~[0, 1, 3]), it.next());
        assert_eq!(Some(~[0, 1, 4]), it.next());
        assert_eq!(Some(~[0, 1, 5]), it.next());
        assert_eq!(Some(~[0, 2, 3]), it.next());
        assert_eq!(Some(~[0, 2, 4]), it.next());
        assert_eq!(Some(~[0, 2, 5]), it.next());
        assert_eq!(Some(~[0, 3, 4]), it.next());
        assert_eq!(Some(~[0, 3, 5]), it.next());
        assert_eq!(Some(~[0, 4, 5]), it.next());
        assert_eq!(Some(~[1, 2, 3]), it.next());
        assert_eq!(Some(~[1, 2, 4]), it.next());
        assert_eq!(Some(~[1, 2, 5]), it.next());
        assert_eq!(Some(~[1, 3, 4]), it.next());
        assert_eq!(Some(~[1, 3, 5]), it.next());
        assert_eq!(Some(~[1, 4, 5]), it.next());
        assert_eq!(Some(~[2, 3, 4]), it.next());
        assert_eq!(Some(~[2, 3, 5]), it.next());
        assert_eq!(Some(~[2, 4, 5]), it.next());
        assert_eq!(Some(~[3, 4, 5]), it.next());
        assert_eq!(None, it.next());
    }

    #[test]
    fn groups() {
        let v = ~[1, 2, 3];
        let mut it = v.groups(0);
        assert_eq!(Some((~[], ~[1, 2, 3])), it.next());
        assert_eq!(None, it.next());

        let mut it = v.groups(1);
        assert_eq!(Some((~[1], ~[2, 3])), it.next());
        assert_eq!(Some((~[2], ~[1, 3])), it.next());
        assert_eq!(Some((~[3], ~[1, 2])), it.next());
        assert_eq!(None, it.next());

        let mut it = v.groups(2);
        assert_eq!(Some((~[1, 2], ~[3])), it.next());
        assert_eq!(Some((~[1, 3], ~[2])), it.next());
        assert_eq!(Some((~[2, 3], ~[1])), it.next());
        assert_eq!(None, it.next());

        let mut it = v.groups(3);
        assert_eq!(Some((~[1, 2, 3], ~[])), it.next());
        assert_eq!(None, it.next());

        let mut it = v.groups(4);
        assert_eq!(None, it.next());
    }
}
<|endoftext|>


<commit_before><commit_msg>languages/rust/rust-book/3-chapter/25-code/multiple_phrases/src/chinese/farewells.rs<commit_after><|endoftext|>


<commit_before>#![feature(box_syntax)]

extern crate orbital;

extern crate system;

use std::url::Url;
use std::{cmp, mem, ptr, slice};
use std::fs::File;
use std::io::{Result, Read, Write, Seek, SeekFrom};
use std::mem::size_of;
use std::ops::DerefMut;
use std::to_num::ToNum;
use std::thread;

use system::error::{Error, ENOENT};
use system::scheme::{Packet, Scheme};

use orbital::Color;
use orbital::event::Event;
use orbital::Point;
use orbital::Size;

use self::display::Display;

pub mod display;
/*
use self::session::Session;
use self::window::Window;

pub mod session;
pub mod window;

pub static mut session_ptr: *mut Session = 0 as *mut Session;

/// A window resource
pub struct Resource {
    /// The window
    pub window: Box<Window>,
    /// Seek point
    pub seek: usize,
}

impl Resource {
    pub fn dup(&self) -> Result<Box<Resource>> {
        Ok(box Resource {
            window: Window::new(self.window.point,
                                self.window.size,
                                self.window.title.clone()),
            seek: self.seek,
        })
    }

    /// Return the url of this resource
    pub fn path(&self) -> Result<String> {
        Ok(format!("orbital:///{}/{}/{}/{}/{}",
                   self.window.point.x,
                   self.window.point.y,
                   self.window.size.width,
                   self.window.size.height,
                   self.window.title))
    }

    /// Read data to buffer
    pub fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        // Read events from window
        let mut i = 0;
        while buf.len() - i >= mem::size_of::<Event>() {
            match self.window.poll() {
                Some(event) => {
                    unsafe { ptr::write(buf.as_ptr().offset(i as isize) as *mut Event, event) };
                    i += mem::size_of::<Event>();
                }
                None => break,
            }
        }

        Ok(i)
    }

    /// Write to resource
    pub fn write(&mut self, buf: &[u8]) -> Result<usize> {
        let content = &mut self.window.content;

        let size = cmp::min(content.size - self.seek, buf.len());
        unsafe {
            Display::copy_run(buf.as_ptr() as usize, content.offscreen + self.seek, size);
        }
        self.seek += size;

        Ok(size)
    }

    /// Seek
    pub fn seek(&mut self, pos: SeekFrom) -> Result<u64> {
        let end = self.window.content.size;

        self.seek = match pos {
            SeekFrom::Start(offset) => cmp::min(end as u64, cmp::max(0, offset)) as usize,
            SeekFrom::Current(offset) => {
                cmp::min(end as i64, cmp::max(0, self.seek as i64 + offset)) as usize
            }
            SeekFrom::End(offset) => {
                cmp::min(end as i64, cmp::max(0, end as i64 + offset)) as usize
            }
        };

        Ok(self.seek as u64)
    }

    /// Sync the resource, should flip
    pub fn sync(&mut self) -> Result<()> {
        self.window.redraw();
        Ok(())
    }
}

/// A window scheme
pub struct Scheme {
    pub session: Option<Box<Session>>,
    pub next_x: isize,
    pub next_y: isize,
}

impl Scheme {
    pub fn new() -> Box<Scheme> {
        let mut ret = box Scheme {
            session: None,
            next_x: 0,
            next_y: 0,
        };
        if let Some(mut session) = Session::new() {
            println!("- Orbital: Found Display {}x{}", session.display.width, session.display.height);
            println!("    Console: Press F1");
            println!("    Desktop: Press F2");

            unsafe { session_ptr = session.deref_mut() };
            ret.session = Some(session);
        } else {
            println!("- Orbital: No Display Found");
        }
        ret
    }

    pub fn open(&mut self, url_str: &str, _: usize) -> Result<Box<Resource>> {
        if let Some(ref session) = self.session {
            // window://host/path/path/path is the path type we're working with.
            let url = Url::from_str(url_str);

            let host = url.host();
            if host.is_empty() {
                let path = url.path_parts();
                let mut pointx = match path.get(0) {
                    Some(x) => x.to_num_signed(),
                    None => 0,
                };
                let mut pointy = match path.get(1) {
                    Some(y) => y.to_num_signed(),
                    None => 0,
                };
                let size_width = match path.get(2) {
                    Some(w) => w.to_num(),
                    None => 100,
                };
                let size_height = match path.get(3) {
                    Some(h) => h.to_num(),
                    None => 100,
                };

                let mut title = match path.get(4) {
                    Some(t) => t.clone(),
                    None => String::new(),
                };
                for i in 5..path.len() {
                    if let Some(t) = path.get(i) {
                        title = title + "/" + t;
                    }
                }

                if pointx <= 0 || pointy <= 0 {
                    if self.next_x > session.display.width as isize - size_width as isize {
                        self.next_x = 0;
                    }
                    self.next_x += 32;
                    pointx = self.next_x as i32;

                    if self.next_y > session.display.height as isize - size_height as isize {
                        self.next_y = 0;
                    }
                    self.next_y += 32;
                    pointy = self.next_y as i32;
                }

                Ok(box Resource {
                    window: Window::new(Point::new(pointx, pointy),
                                        Size::new(size_width, size_height),
                                        title),
                    seek: 0,
                })
            } else {
                Err(Error::new(ENOENT))
            }
        }else{
            Err(Error::new(ENOENT))
        }
    }

    pub fn event(&mut self, event: &Event) {
        if let Some(ref mut session) = self.session {
            session.event(event);

            unsafe { session.redraw() };
        }
    }
}
*/

struct OrbitalScheme;

impl OrbitalScheme {
    fn new() -> OrbitalScheme {
        OrbitalScheme
    }
}

impl Scheme for OrbitalScheme {}

fn main() {
    match Display::new() {
        Ok(mut display) => {
            println!("- Orbital: Found Display {}x{}", display.width(), display.height());
            println!("    Console: Press F1");
            println!("    Desktop: Press F2");

            let mut x = 0;
            let mut y = 0;
            let w = 50;
            let h = 50;
            let mut dx = 1;
            let mut dy = 1;
            let fg = Color::rgb(224, 224, 224);
            let bg = Color::rgb(75, 163, 253);

            display.set(bg);
            loop {
                display.rect(x, y, w, h, fg);
                display.flip();

                display.rect(x, y, w, h, bg);

                x += dx;
                if x < 0 {
                    dx = 1;
                }
                if x + w >= display.width() {
                    dx = -1;
                }

                y += dy;
                if y < 0 {
                    dy = 1;
                }
                if y + h >= display.height() {
                    dy = -1;
                }

                thread::yield_now();
            }

            /*
            let mut scheme = OrbitalScheme::new();
            let mut socket = File::create(":orbital").unwrap();
            loop {
                let mut packet = Packet::default();
                if socket.read(&mut packet).unwrap() == 0 {
                    panic!("Unexpected EOF");
                }
                //println!("Recv {:?}", packet);

                scheme.handle(&mut packet);

                socket.write(&packet).unwrap();
                //println!("Sent {:?}", packet);
            }
            */
        },
        Err(err) => println!("- Orbital: No Display Found: {}", err)
    }
}
<commit_msg>Improve throughput<commit_after>#![feature(box_syntax)]

extern crate orbital;

extern crate system;

use std::url::Url;
use std::{cmp, mem, ptr, slice};
use std::fs::File;
use std::io::{Result, Read, Write, Seek, SeekFrom};
use std::mem::size_of;
use std::ops::DerefMut;
use std::to_num::ToNum;
use std::thread;

use system::error::{Error, ENOENT};
use system::scheme::{Packet, Scheme};

use orbital::Color;
use orbital::event::Event;
use orbital::Point;
use orbital::Size;

use self::display::Display;

pub mod display;
/*
use self::session::Session;
use self::window::Window;

pub mod session;
pub mod window;

pub static mut session_ptr: *mut Session = 0 as *mut Session;

/// A window resource
pub struct Resource {
    /// The window
    pub window: Box<Window>,
    /// Seek point
    pub seek: usize,
}

impl Resource {
    pub fn dup(&self) -> Result<Box<Resource>> {
        Ok(box Resource {
            window: Window::new(self.window.point,
                                self.window.size,
                                self.window.title.clone()),
            seek: self.seek,
        })
    }

    /// Return the url of this resource
    pub fn path(&self) -> Result<String> {
        Ok(format!("orbital:///{}/{}/{}/{}/{}",
                   self.window.point.x,
                   self.window.point.y,
                   self.window.size.width,
                   self.window.size.height,
                   self.window.title))
    }

    /// Read data to buffer
    pub fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        // Read events from window
        let mut i = 0;
        while buf.len() - i >= mem::size_of::<Event>() {
            match self.window.poll() {
                Some(event) => {
                    unsafe { ptr::write(buf.as_ptr().offset(i as isize) as *mut Event, event) };
                    i += mem::size_of::<Event>();
                }
                None => break,
            }
        }

        Ok(i)
    }

    /// Write to resource
    pub fn write(&mut self, buf: &[u8]) -> Result<usize> {
        let content = &mut self.window.content;

        let size = cmp::min(content.size - self.seek, buf.len());
        unsafe {
            Display::copy_run(buf.as_ptr() as usize, content.offscreen + self.seek, size);
        }
        self.seek += size;

        Ok(size)
    }

    /// Seek
    pub fn seek(&mut self, pos: SeekFrom) -> Result<u64> {
        let end = self.window.content.size;

        self.seek = match pos {
            SeekFrom::Start(offset) => cmp::min(end as u64, cmp::max(0, offset)) as usize,
            SeekFrom::Current(offset) => {
                cmp::min(end as i64, cmp::max(0, self.seek as i64 + offset)) as usize
            }
            SeekFrom::End(offset) => {
                cmp::min(end as i64, cmp::max(0, end as i64 + offset)) as usize
            }
        };

        Ok(self.seek as u64)
    }

    /// Sync the resource, should flip
    pub fn sync(&mut self) -> Result<()> {
        self.window.redraw();
        Ok(())
    }
}

/// A window scheme
pub struct Scheme {
    pub session: Option<Box<Session>>,
    pub next_x: isize,
    pub next_y: isize,
}

impl Scheme {
    pub fn new() -> Box<Scheme> {
        let mut ret = box Scheme {
            session: None,
            next_x: 0,
            next_y: 0,
        };
        if let Some(mut session) = Session::new() {
            println!("- Orbital: Found Display {}x{}", session.display.width, session.display.height);
            println!("    Console: Press F1");
            println!("    Desktop: Press F2");

            unsafe { session_ptr = session.deref_mut() };
            ret.session = Some(session);
        } else {
            println!("- Orbital: No Display Found");
        }
        ret
    }

    pub fn open(&mut self, url_str: &str, _: usize) -> Result<Box<Resource>> {
        if let Some(ref session) = self.session {
            // window://host/path/path/path is the path type we're working with.
            let url = Url::from_str(url_str);

            let host = url.host();
            if host.is_empty() {
                let path = url.path_parts();
                let mut pointx = match path.get(0) {
                    Some(x) => x.to_num_signed(),
                    None => 0,
                };
                let mut pointy = match path.get(1) {
                    Some(y) => y.to_num_signed(),
                    None => 0,
                };
                let size_width = match path.get(2) {
                    Some(w) => w.to_num(),
                    None => 100,
                };
                let size_height = match path.get(3) {
                    Some(h) => h.to_num(),
                    None => 100,
                };

                let mut title = match path.get(4) {
                    Some(t) => t.clone(),
                    None => String::new(),
                };
                for i in 5..path.len() {
                    if let Some(t) = path.get(i) {
                        title = title + "/" + t;
                    }
                }

                if pointx <= 0 || pointy <= 0 {
                    if self.next_x > session.display.width as isize - size_width as isize {
                        self.next_x = 0;
                    }
                    self.next_x += 32;
                    pointx = self.next_x as i32;

                    if self.next_y > session.display.height as isize - size_height as isize {
                        self.next_y = 0;
                    }
                    self.next_y += 32;
                    pointy = self.next_y as i32;
                }

                Ok(box Resource {
                    window: Window::new(Point::new(pointx, pointy),
                                        Size::new(size_width, size_height),
                                        title),
                    seek: 0,
                })
            } else {
                Err(Error::new(ENOENT))
            }
        }else{
            Err(Error::new(ENOENT))
        }
    }

    pub fn event(&mut self, event: &Event) {
        if let Some(ref mut session) = self.session {
            session.event(event);

            unsafe { session.redraw() };
        }
    }
}
*/

struct OrbitalScheme;

impl OrbitalScheme {
    fn new() -> OrbitalScheme {
        OrbitalScheme
    }
}

impl Scheme for OrbitalScheme {}

struct Window {
    x: i32,
    y: i32,
    w: i32,
    h: i32,
    dx: i32,
    dy: i32,
    color: Color,
}

impl Window {
    fn draw(&self, display: &mut Display) {
        display.rect(self.x, self.y, self.w, self.h, self.color);
    }

    fn clear(&self, display: &mut Display, color: Color) {
        display.rect(self.x, self.y, self.w, self.h, color);
    }

    fn update(&mut self, display: &Display) {
        self.x += self.dx;
        if self.x < 0 {
            self.dx = 1;
        }
        if self.x + self.w >= display.width() {
            self.dx = -1;
        }

        self.y += self.dy;
        if self.y < 0 {
            self.dy = 1;
        }
        if self.y + self.h >= display.height() {
            self.dy = -1;
        }
    }
}

fn main() {
    match Display::new() {
        Ok(mut display) => {
            println!("- Orbital: Found Display {}x{}", display.width(), display.height());
            println!("    Console: Press F1");
            println!("    Desktop: Press F2");

            let mut windows = Vec::new();

            windows.push(Window {
                x: 0,
                y: 0,
                w: 50,
                h: 50,
                dx: 1,
                dy: 1,
                color: Color::rgb(224, 0, 0)
            });

            windows.push(Window {
                x: 100,
                y: 0,
                w: 50,
                h: 50,
                dx: -1,
                dy: 1,
                color: Color::rgb(0, 224, 0)
            });

            windows.push(Window {
                x: 0,
                y: 100,
                w: 50,
                h: 50,
                dx: 1,
                dy: -1,
                color: Color::rgb(0, 0, 224)
            });

            windows.push(Window {
                x: 100,
                y: 100,
                w: 50,
                h: 50,
                dx: -1,
                dy: -1,
                color: Color::rgb(224, 224, 224)
            });

            let bg = Color::rgb(32, 32, 32); //Color::rgb(75, 163, 253);

            display.set(bg);
            loop {
                for window in windows.iter() {
                    window.draw(&mut display);
                }
                display.flip();
                for window in windows.iter() {
                    window.clear(&mut display, bg);
                }
                for window in windows.iter_mut() {
                    window.update(&display);
                }

                thread::yield_now();
            }

            /*
            let mut scheme = OrbitalScheme::new();
            let mut socket = File::create(":orbital").unwrap();
            loop {
                let mut packet = Packet::default();
                if socket.read(&mut packet).unwrap() == 0 {
                    panic!("Unexpected EOF");
                }
                //println!("Recv {:?}", packet);

                scheme.handle(&mut packet);

                socket.write(&packet).unwrap();
                //println!("Sent {:?}", packet);
            }
            */
        },
        Err(err) => println!("- Orbital: No Display Found: {}", err)
    }
}
<|endoftext|>


<commit_before>use super::SDTHeader;

#[repr(packed)]
#[derive(Clone, Copy, Debug, Default)]
pub struct DSDT {
    pub header: SDTHeader,
    pub data: &'static [u8]

}

impl DSDT {
    pub fn new(header: *const SDTHeader) -> Option<Self> {
        if unsafe { (*header).valid("DSDT") } {
            Some(DSDT {
                header: unsafe { *header },
                data: unsafe { (*header).data() }
            })
        } else {
            None
        }
    }
}
<commit_msg>Simplify `DSDT::new()` with fewer `unsafe` blocks<commit_after>use super::SDTHeader;

#[repr(packed)]
#[derive(Clone, Copy, Debug, Default)]
pub struct DSDT {
    pub header: SDTHeader,
    pub data: &'static [u8]

}

impl DSDT {
    pub fn new(header: *const SDTHeader) -> Option<Self> {
        let header = unsafe { *header };
        if header.valid("DSDT") {
            Some(DSDT {
                header: header,
                data: header.data(),
            })
        } else {
            None
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Added tests for reload with glob<commit_after>extern crate tera;

use tera::Tera;

#[test]
fn test_full_reload_with_glob() {
    let mut tera = Tera::new("tests/templates/**/*").unwrap();
    tera.full_reload().unwrap();

    assert!(tera.get_template("basic.html").is_ok());
}

#[test]
fn test_full_reload_with_glob_after_extending() {
    let mut tera = Tera::new("tests/templates/**/*").unwrap();
    let mut framework_tera = Tera::default();
    framework_tera.add_raw_templates(vec![
        ("one", "FRAMEWORK"),
        ("four", "Framework X"),
    ]).unwrap();
    tera.extend(&framework_tera).unwrap();
    tera.full_reload().unwrap();

    assert!(tera.get_template("basic.html").is_ok());
    assert!(tera.get_template("one").is_ok());
}
<|endoftext|>


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

use dom::bindings::codegen::BindingDeclarations::HTMLParagraphElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLParagraphElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::error::ErrorResult;
use dom::document::Document;
use dom::element::HTMLParagraphElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;

#[deriving(Encodable)]
pub struct HTMLParagraphElement {
    pub htmlelement: HTMLElement
}

impl HTMLParagraphElementDerived for EventTarget {
    fn is_htmlparagraphelement(&self) -> bool {
        self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLParagraphElementTypeId))
    }
}

impl HTMLParagraphElement {
    pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLParagraphElement {
        HTMLParagraphElement {
            htmlelement: HTMLElement::new_inherited(HTMLParagraphElementTypeId, localName, document)
        }
    }

    pub fn new(localName: DOMString, document: &JSRef<Document>) -> Temporary<HTMLParagraphElement> {
        let element = HTMLParagraphElement::new_inherited(localName, document);
        Node::reflect_node(box element, document, HTMLParagraphElementBinding::Wrap)
    }
}

pub trait HTMLParagraphElementMethods {
    fn Align(&self) -> DOMString;
    fn SetAlign(&mut self, _align: DOMString) -> ErrorResult;
}

impl<'a> HTMLParagraphElementMethods for JSRef<'a, HTMLParagraphElement> {
    fn Align(&self) -> DOMString {
        "".to_owned()
    }

    fn SetAlign(&mut self, _align: DOMString) -> ErrorResult {
        Ok(())
    }
}
<commit_msg>Remove needless '&mut self' from HTMLParagraphElementMethods.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use dom::bindings::codegen::BindingDeclarations::HTMLParagraphElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLParagraphElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::error::ErrorResult;
use dom::document::Document;
use dom::element::HTMLParagraphElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;

#[deriving(Encodable)]
pub struct HTMLParagraphElement {
    pub htmlelement: HTMLElement
}

impl HTMLParagraphElementDerived for EventTarget {
    fn is_htmlparagraphelement(&self) -> bool {
        self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLParagraphElementTypeId))
    }
}

impl HTMLParagraphElement {
    pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLParagraphElement {
        HTMLParagraphElement {
            htmlelement: HTMLElement::new_inherited(HTMLParagraphElementTypeId, localName, document)
        }
    }

    pub fn new(localName: DOMString, document: &JSRef<Document>) -> Temporary<HTMLParagraphElement> {
        let element = HTMLParagraphElement::new_inherited(localName, document);
        Node::reflect_node(box element, document, HTMLParagraphElementBinding::Wrap)
    }
}

pub trait HTMLParagraphElementMethods {
    fn Align(&self) -> DOMString;
    fn SetAlign(&self, _align: DOMString) -> ErrorResult;
}

impl<'a> HTMLParagraphElementMethods for JSRef<'a, HTMLParagraphElement> {
    fn Align(&self) -> DOMString {
        "".to_owned()
    }

    fn SetAlign(&self, _align: DOMString) -> ErrorResult {
        Ok(())
    }
}
<|endoftext|>


<commit_before><commit_msg>implement `Hash` for ()<commit_after><|endoftext|>


<commit_before>extern mod std;

use libc::c_char;
use libc::c_int;
use libc::size_t;
use libc::c_ulong;
use libc::c_void;
use ptr::null;
use ptr::addr_of;
use ptr::mut_addr_of;
use str::as_c_str;

struct mpz_struct {
  _mp_alloc: c_int,
  _mp_size: c_int,
  _mp_d: *c_void
}

type mpz_srcptr = *const mpz_struct;
type mpz_ptr = *mut mpz_struct;

extern mod gmp {
  fn __gmpz_init(x: mpz_ptr);
  fn __gmpz_init_set_str(rop: mpz_ptr, str: *c_char, base: c_int) -> c_int;
  fn __gmpz_clear(x: mpz_ptr);
  fn __gmpz_set_str(rop: mpz_ptr, str: *c_char, base: c_int) -> c_int;
  fn __gmpz_get_str(str: *c_char, base: c_int, op: mpz_srcptr) -> *c_char;
  pure fn __gmpz_sizeinbase(op: mpz_srcptr, base: c_int) -> size_t;
  pure fn __gmpz_cmp(op: mpz_srcptr, op2: mpz_srcptr) -> c_int;
  pure fn __gmpz_cmp_ui(op1: mpz_srcptr, op2: c_ulong) -> c_int;
  fn __gmpz_add(rop: mpz_ptr, op1: mpz_srcptr, op2: mpz_srcptr);
  fn __gmpz_sub(rop: mpz_ptr, op1: mpz_srcptr, op2: mpz_srcptr);
  fn __gmpz_mul(rop: mpz_ptr, op1: mpz_srcptr, op2: mpz_srcptr);
  fn __gmpz_neg(rop: mpz_ptr, op: mpz_srcptr);
  fn __gmpz_tdiv_q(r: mpz_ptr, n: mpz_srcptr, d: mpz_srcptr);
  fn __gmpz_mod(r: mpz_ptr, n: mpz_srcptr, d: mpz_srcptr);
}

use gmp::*;

pub struct Mpz {
  priv mpz: mpz_struct,

  drop {
    __gmpz_clear(mut_addr_of(&self.mpz));
  }
}

impl Mpz {
  fn set_str(&self, s: &str, base: int) -> bool {
    let mpz = mut_addr_of(&self.mpz);
    let r = as_c_str(s, { |s| __gmpz_set_str(mpz, s, base as c_int) });
    r == 0
  }

  pure fn size_in_base(&self, base: int) -> uint {
    __gmpz_sizeinbase(addr_of(&self.mpz), base as c_int) as uint
  }
}

impl Mpz: cmp::Eq {
  pure fn eq(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) == 0
  }
  pure fn ne(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) != 0
  }
}

impl Mpz: cmp::Ord {
  pure fn lt(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) < 0
  }
  pure fn le(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) <= 0
  }
  pure fn gt(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) > 0
  }
  pure fn ge(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) >= 0
  }
}

impl Mpz: num::Num {
  pure fn add(other: &Mpz) -> Mpz unsafe {
    let res = init();
    __gmpz_add(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn sub(other: &Mpz) -> Mpz unsafe {
    let res = init();
    __gmpz_sub(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn mul(other: &Mpz) -> Mpz unsafe {
    let res = init();
    __gmpz_mul(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn div(other: &Mpz) -> Mpz unsafe {
    if __gmpz_cmp_ui(addr_of(&self.mpz), 0) == 0 {
      fail ~"divide by zero";
    }

    let res = init();
    __gmpz_tdiv_q(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn modulo(other: &Mpz) -> Mpz unsafe {
    if __gmpz_cmp_ui(addr_of(&self.mpz), 0) == 0 {
      fail ~"divide by zero";
    }

    let res = init();
    __gmpz_mod(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn neg() -> Mpz unsafe {
    let res = init();
    __gmpz_neg(mut_addr_of(&res.mpz), addr_of(&self.mpz));
    res
  }
  pure fn to_int() -> int {
    fail ~"not implemented";
  }
  static pure fn from_int(other: int) -> Mpz unsafe {
    let res = init();
    // the gmp functions dealing with longs aren't usable here - long is only
    // guaranteed to be at least 32-bit
    assert(res.set_str(other.to_str(), 10));
    res
  }
}

pub fn from_str(s: &str) -> Option<Mpz> {
  init_set_str(s, 10)
}

impl Mpz : from_str::FromStr {
  static fn from_str(s: &str) -> Option<Mpz> {
    from_str(s)
  }
}

impl Mpz : to_str::ToStr {
  pure fn to_str() -> ~str unsafe {
    let length = self.size_in_base(10) + 2;
    let dst = vec::to_mut(vec::from_elem(length, '0'));
    let pdst = vec::raw::to_ptr(dst);

    str::raw::from_c_str(__gmpz_get_str(pdst as *c_char, 10, addr_of(&self.mpz)))
  }
}

pub fn init() -> Mpz {
  let mpz = mpz_struct { _mp_alloc: 0, _mp_size: 0, _mp_d: null() };
  __gmpz_init(mut_addr_of(&mpz));
  Mpz { mpz: mpz }
}

pub fn init_set_str(s: &str, base: int) -> Option<Mpz> {
  let mpz = mpz_struct { _mp_alloc: 0, _mp_size: 0, _mp_d: null() };
  let mpz_ptr = mut_addr_of(&mpz);
  let r = as_c_str(s, { |s| __gmpz_init_set_str(mpz_ptr, s, base as c_int) });
  if r == 0 {
    Some(Mpz { mpz: mpz })
  } else {
    __gmpz_clear(mpz_ptr);
    None
  }
}

#[cfg(test)]
mod tests {
  #[test]
  fn size_in_base() {
    let x = init();
    x.set_str("150000", 10);
    assert(x.size_in_base(10) == 6);
  }

  #[test]
  fn eq() {
    let x = option::unwrap(from_str("4242142195"));
    let y = option::unwrap(from_str("4242142195"));
    let z = option::unwrap(from_str("4242142196"));

    assert(x == y);
    assert(x != z);
    assert(y != z);
  }

  #[test]
  fn ord() {
    let x = option::unwrap(from_str("40000000000000000000000"));
    let y = option::unwrap(from_str("45000000000000000000000"));
    let z = option::unwrap(from_str("50000000000000000000000"));

    assert(x < y && x < z && y < z);
    assert(x <= x && x <= y && x <= z && y <= z);
    assert(z > y && z > x && y > x);
    assert(z >= z && z >= y && z >= x && y >= x);
  }

  #[test]
  #[should_fail]
  fn div_zero() {
    let x = init();
    x / x;
  }

  #[test]
  #[should_fail]
  fn modulo_zero() {
    let x = init();
    x % x;
  }

  #[test]
  fn test_div_round() {
    let x = init();
    let y = init();
    let mut z: Mpz;

    x.set_str("2", 10);
    y.set_str("3", 10);
    z = x / y;
    assert(__gmpz_cmp_ui(addr_of(&z.mpz), 2 / 3) == 0);

    x.set_str("2", 10);
    y.set_str("-3", 10);
    z = x / y;
    assert(__gmpz_cmp_ui(addr_of(&z.mpz), 2 / -3) == 0);
  }

  #[test]
  fn to_str() {
    let x = option::unwrap(from_str("1234567890"));
    assert(x.to_str() == ~"1234567890");
  }

  #[test]
  fn invalid_str() {
    assert(from_str("foobar").is_none());
  }
}
<commit_msg>from_str, init and init_set_str should be pure<commit_after>extern mod std;

use libc::c_char;
use libc::c_int;
use libc::size_t;
use libc::c_ulong;
use libc::c_void;
use ptr::null;
use ptr::addr_of;
use ptr::mut_addr_of;
use str::as_c_str;

struct mpz_struct {
  _mp_alloc: c_int,
  _mp_size: c_int,
  _mp_d: *c_void
}

type mpz_srcptr = *const mpz_struct;
type mpz_ptr = *mut mpz_struct;

extern mod gmp {
  fn __gmpz_init(x: mpz_ptr);
  fn __gmpz_init_set_str(rop: mpz_ptr, str: *c_char, base: c_int) -> c_int;
  fn __gmpz_clear(x: mpz_ptr);
  fn __gmpz_set_str(rop: mpz_ptr, str: *c_char, base: c_int) -> c_int;
  fn __gmpz_get_str(str: *c_char, base: c_int, op: mpz_srcptr) -> *c_char;
  pure fn __gmpz_sizeinbase(op: mpz_srcptr, base: c_int) -> size_t;
  pure fn __gmpz_cmp(op: mpz_srcptr, op2: mpz_srcptr) -> c_int;
  pure fn __gmpz_cmp_ui(op1: mpz_srcptr, op2: c_ulong) -> c_int;
  fn __gmpz_add(rop: mpz_ptr, op1: mpz_srcptr, op2: mpz_srcptr);
  fn __gmpz_sub(rop: mpz_ptr, op1: mpz_srcptr, op2: mpz_srcptr);
  fn __gmpz_mul(rop: mpz_ptr, op1: mpz_srcptr, op2: mpz_srcptr);
  fn __gmpz_neg(rop: mpz_ptr, op: mpz_srcptr);
  fn __gmpz_tdiv_q(r: mpz_ptr, n: mpz_srcptr, d: mpz_srcptr);
  fn __gmpz_mod(r: mpz_ptr, n: mpz_srcptr, d: mpz_srcptr);
}

use gmp::*;

pub struct Mpz {
  priv mpz: mpz_struct,

  drop {
    __gmpz_clear(mut_addr_of(&self.mpz));
  }
}

impl Mpz {
  fn set_str(&self, s: &str, base: int) -> bool {
    let mpz = mut_addr_of(&self.mpz);
    let r = as_c_str(s, { |s| __gmpz_set_str(mpz, s, base as c_int) });
    r == 0
  }

  pure fn size_in_base(&self, base: int) -> uint {
    __gmpz_sizeinbase(addr_of(&self.mpz), base as c_int) as uint
  }
}

impl Mpz: cmp::Eq {
  pure fn eq(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) == 0
  }
  pure fn ne(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) != 0
  }
}

impl Mpz: cmp::Ord {
  pure fn lt(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) < 0
  }
  pure fn le(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) <= 0
  }
  pure fn gt(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) > 0
  }
  pure fn ge(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) >= 0
  }
}

impl Mpz: num::Num {
  pure fn add(other: &Mpz) -> Mpz unsafe {
    let res = init();
    __gmpz_add(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn sub(other: &Mpz) -> Mpz unsafe {
    let res = init();
    __gmpz_sub(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn mul(other: &Mpz) -> Mpz unsafe {
    let res = init();
    __gmpz_mul(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn div(other: &Mpz) -> Mpz unsafe {
    if __gmpz_cmp_ui(addr_of(&self.mpz), 0) == 0 {
      fail ~"divide by zero";
    }

    let res = init();
    __gmpz_tdiv_q(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn modulo(other: &Mpz) -> Mpz unsafe {
    if __gmpz_cmp_ui(addr_of(&self.mpz), 0) == 0 {
      fail ~"divide by zero";
    }

    let res = init();
    __gmpz_mod(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn neg() -> Mpz unsafe {
    let res = init();
    __gmpz_neg(mut_addr_of(&res.mpz), addr_of(&self.mpz));
    res
  }
  pure fn to_int() -> int {
    fail ~"not implemented";
  }
  static pure fn from_int(other: int) -> Mpz unsafe {
    let res = init();
    // the gmp functions dealing with longs aren't usable here - long is only
    // guaranteed to be at least 32-bit
    assert(res.set_str(other.to_str(), 10));
    res
  }
}

pub pure fn from_str(s: &str) -> Option<Mpz> {
  init_set_str(s, 10)
}

impl Mpz : from_str::FromStr {
  static fn from_str(s: &str) -> Option<Mpz> {
    from_str(s)
  }
}

impl Mpz : to_str::ToStr {
  pure fn to_str() -> ~str unsafe {
    let length = self.size_in_base(10) + 2;
    let dst = vec::to_mut(vec::from_elem(length, '0'));
    let pdst = vec::raw::to_ptr(dst);

    str::raw::from_c_str(__gmpz_get_str(pdst as *c_char, 10, addr_of(&self.mpz)))
  }
}

pub pure fn init() -> Mpz unsafe {
  let mpz = mpz_struct { _mp_alloc: 0, _mp_size: 0, _mp_d: null() };
  __gmpz_init(mut_addr_of(&mpz));
  Mpz { mpz: mpz }
}

pub pure fn init_set_str(s: &str, base: int) -> Option<Mpz> unsafe {
  let mpz = mpz_struct { _mp_alloc: 0, _mp_size: 0, _mp_d: null() };
  let mpz_ptr = mut_addr_of(&mpz);
  let r = as_c_str(s, { |s| __gmpz_init_set_str(mpz_ptr, s, base as c_int) });
  if r == 0 {
    Some(Mpz { mpz: mpz })
  } else {
    __gmpz_clear(mpz_ptr);
    None
  }
}

#[cfg(test)]
mod tests {
  #[test]
  fn size_in_base() {
    let x = init();
    x.set_str("150000", 10);
    assert(x.size_in_base(10) == 6);
  }

  #[test]
  fn eq() {
    let x = option::unwrap(from_str("4242142195"));
    let y = option::unwrap(from_str("4242142195"));
    let z = option::unwrap(from_str("4242142196"));

    assert(x == y);
    assert(x != z);
    assert(y != z);
  }

  #[test]
  fn ord() {
    let x = option::unwrap(from_str("40000000000000000000000"));
    let y = option::unwrap(from_str("45000000000000000000000"));
    let z = option::unwrap(from_str("50000000000000000000000"));

    assert(x < y && x < z && y < z);
    assert(x <= x && x <= y && x <= z && y <= z);
    assert(z > y && z > x && y > x);
    assert(z >= z && z >= y && z >= x && y >= x);
  }

  #[test]
  #[should_fail]
  fn div_zero() {
    let x = init();
    x / x;
  }

  #[test]
  #[should_fail]
  fn modulo_zero() {
    let x = init();
    x % x;
  }

  #[test]
  fn test_div_round() {
    let x = init();
    let y = init();
    let mut z: Mpz;

    x.set_str("2", 10);
    y.set_str("3", 10);
    z = x / y;
    assert(__gmpz_cmp_ui(addr_of(&z.mpz), 2 / 3) == 0);

    x.set_str("2", 10);
    y.set_str("-3", 10);
    z = x / y;
    assert(__gmpz_cmp_ui(addr_of(&z.mpz), 2 / -3) == 0);
  }

  #[test]
  fn to_str() {
    let x = option::unwrap(from_str("1234567890"));
    assert(x.to_str() == ~"1234567890");
  }

  #[test]
  fn invalid_str() {
    assert(from_str("foobar").is_none());
  }
}
<|endoftext|>


<commit_before>#![cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd"))]

use {Api, ContextError, CreationError, GlAttributes, PixelFormat, PixelFormatRequirements};

use api::osmesa::OsMesaContext;
use wayland_client;
use winit;

mod wayland;
mod x11;

pub enum Context {
    X(x11::Context),
    Wayland(wayland::Context)
}

impl Context {

    #[inline]
    pub fn new(
        window: &winit::Window,
        pf_reqs: &PixelFormatRequirements,
        gl_attr: &GlAttributes<&Context>,
    ) -> Result<Self, CreationError>
    {

        if wayland_client::default_connect().is_ok() {
            if let Some(&Context::X(_)) = gl_attr.sharing {
                let msg = "Cannot share a wayland context with an X11 context";
                return Err(CreationError::PlatformSpecific(msg.into()));
            }
            let gl_attr = gl_attr.clone().map_sharing(|ctxt| match ctxt {
                &Context::X(_) => unreachable!(),
                &Context::Wayland(ref ctxt) => ctxt,
            });
            Ok(Context::Wayland(try!(wayland::Context::new(window, pf_reqs, &gl_attr))))

        } else {
            if let Some(&Context::Wayland(_)) = gl_attr.sharing {
                let msg = "Cannot share a X11 context with an wayland context";
                return Err(CreationError::PlatformSpecific(msg.into()));
            }
            let gl_attr = gl_attr.clone().map_sharing(|ctxt| match ctxt {
                &Context::Wayland(_) => unreachable!(),
                &Context::X(ref ctxt) => ctxt,
            });
            Ok(Context::X(try!(x11::Context::new(window, pf_reqs, &gl_attr))))
        }
    }

    pub fn resize(&self, width: u32, height: u32) {
        match *self {
            Context::X(ref _ctxt) => (),
            Context::Wayland(ref ctxt) => ctxt.resize(width, height),
        }
    }

    #[inline]
    pub unsafe fn make_current(&self) -> Result<(), ContextError> {
        match *self {
            Context::X(ref ctxt) => ctxt.make_current(),
            Context::Wayland(ref ctxt) => ctxt.make_current()
        }
    }

    #[inline]
    pub fn is_current(&self) -> bool {
        match *self {
            Context::X(ref ctxt) => ctxt.is_current(),
            Context::Wayland(ref ctxt) => ctxt.is_current()
        }
    }

    #[inline]
    pub fn get_proc_address(&self, addr: &str) -> *const () {
        match *self {
            Context::X(ref ctxt) => ctxt.get_proc_address(addr),
            Context::Wayland(ref ctxt) => ctxt.get_proc_address(addr)
        }
    }

    #[inline]
    pub fn swap_buffers(&self) -> Result<(), ContextError> {
        match *self {
            Context::X(ref ctxt) => ctxt.swap_buffers(),
            Context::Wayland(ref ctxt) => ctxt.swap_buffers()
        }
    }

    #[inline]
    pub fn get_api(&self) -> ::Api {
        match *self {
            Context::X(ref ctxt) => ctxt.get_api(),
            Context::Wayland(ref ctxt) => ctxt.get_api()
        }
    }

    #[inline]
    pub fn get_pixel_format(&self) -> PixelFormat {
        match *self {
            Context::X(ref ctxt) => ctxt.get_pixel_format(),
            Context::Wayland(ref ctxt) => ctxt.get_pixel_format()
        }
    }
}

#[derive(Clone, Default)]
pub struct PlatformSpecificHeadlessBuilderAttributes;

pub struct HeadlessContext(OsMesaContext);

impl HeadlessContext {
    fn from(mesa: OsMesaContext) -> Self {
        HeadlessContext(mesa)
    }
}

impl HeadlessContext {
    pub fn new(dimensions: (u32, u32), pf_reqs: &PixelFormatRequirements,
               opengl: &GlAttributes<&HeadlessContext>,
               _: &PlatformSpecificHeadlessBuilderAttributes)
               -> Result<HeadlessContext, CreationError>
    {
        let opengl = opengl.clone().map_sharing(|c| &c.0);

        OsMesaContext::new(dimensions, pf_reqs, &opengl).map(HeadlessContext::from)
    }

    #[inline]
    pub unsafe fn make_current(&self) -> Result<(), ContextError> {
        self.0.make_current()
    }

    #[inline]
    pub fn is_current(&self) -> bool {
        self.0.is_current()
    }

    #[inline]
    pub fn get_proc_address(&self, addr: &str) -> *const () {
        self.0.get_proc_address(addr)
    }

    #[inline]
    pub fn swap_buffers(&self) -> Result<(), ContextError> {
        self.0.swap_buffers()
    }

    #[inline]
    pub fn get_api(&self) -> Api {
        self.0.get_api()
    }

    #[inline]
    pub fn get_pixel_format(&self) -> PixelFormat {
        self.0.get_pixel_format()
    }
}
<commit_msg>Change if else to use match in linux backend (kvark nit)<commit_after>#![cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd"))]

use {Api, ContextError, CreationError, GlAttributes, PixelFormat, PixelFormatRequirements};

use api::osmesa::OsMesaContext;
use wayland_client;
use winit;

mod wayland;
mod x11;

pub enum Context {
    X(x11::Context),
    Wayland(wayland::Context)
}

impl Context {
    #[inline]
    pub fn new(
        window: &winit::Window,
        pf_reqs: &PixelFormatRequirements,
        gl_attr: &GlAttributes<&Context>,
    ) -> Result<Self, CreationError>
    {
        match wayland_client::default_connect() {
            Ok(_) => {
                if let Some(&Context::X(_)) = gl_attr.sharing {
                    let msg = "Cannot share a wayland context with an X11 context";
                    return Err(CreationError::PlatformSpecific(msg.into()));
                }
                let gl_attr = gl_attr.clone().map_sharing(|ctxt| match ctxt {
                    &Context::X(_) => unreachable!(),
                    &Context::Wayland(ref ctxt) => ctxt,
                });
                Ok(Context::Wayland(try!(wayland::Context::new(window, pf_reqs, &gl_attr))))
            },
            Err(_) => {
                if let Some(&Context::Wayland(_)) = gl_attr.sharing {
                    let msg = "Cannot share a X11 context with an wayland context";
                    return Err(CreationError::PlatformSpecific(msg.into()));
                }
                let gl_attr = gl_attr.clone().map_sharing(|ctxt| match ctxt {
                    &Context::Wayland(_) => unreachable!(),
                    &Context::X(ref ctxt) => ctxt,
                });
                Ok(Context::X(try!(x11::Context::new(window, pf_reqs, &gl_attr))))
            }
        }
    }

    pub fn resize(&self, width: u32, height: u32) {
        match *self {
            Context::X(ref _ctxt) => (),
            Context::Wayland(ref ctxt) => ctxt.resize(width, height),
        }
    }

    #[inline]
    pub unsafe fn make_current(&self) -> Result<(), ContextError> {
        match *self {
            Context::X(ref ctxt) => ctxt.make_current(),
            Context::Wayland(ref ctxt) => ctxt.make_current()
        }
    }

    #[inline]
    pub fn is_current(&self) -> bool {
        match *self {
            Context::X(ref ctxt) => ctxt.is_current(),
            Context::Wayland(ref ctxt) => ctxt.is_current()
        }
    }

    #[inline]
    pub fn get_proc_address(&self, addr: &str) -> *const () {
        match *self {
            Context::X(ref ctxt) => ctxt.get_proc_address(addr),
            Context::Wayland(ref ctxt) => ctxt.get_proc_address(addr)
        }
    }

    #[inline]
    pub fn swap_buffers(&self) -> Result<(), ContextError> {
        match *self {
            Context::X(ref ctxt) => ctxt.swap_buffers(),
            Context::Wayland(ref ctxt) => ctxt.swap_buffers()
        }
    }

    #[inline]
    pub fn get_api(&self) -> ::Api {
        match *self {
            Context::X(ref ctxt) => ctxt.get_api(),
            Context::Wayland(ref ctxt) => ctxt.get_api()
        }
    }

    #[inline]
    pub fn get_pixel_format(&self) -> PixelFormat {
        match *self {
            Context::X(ref ctxt) => ctxt.get_pixel_format(),
            Context::Wayland(ref ctxt) => ctxt.get_pixel_format()
        }
    }
}

#[derive(Clone, Default)]
pub struct PlatformSpecificHeadlessBuilderAttributes;

pub struct HeadlessContext(OsMesaContext);

impl HeadlessContext {
    fn from(mesa: OsMesaContext) -> Self {
        HeadlessContext(mesa)
    }
}

impl HeadlessContext {
    pub fn new(dimensions: (u32, u32), pf_reqs: &PixelFormatRequirements,
               opengl: &GlAttributes<&HeadlessContext>,
               _: &PlatformSpecificHeadlessBuilderAttributes)
               -> Result<HeadlessContext, CreationError>
    {
        let opengl = opengl.clone().map_sharing(|c| &c.0);

        OsMesaContext::new(dimensions, pf_reqs, &opengl).map(HeadlessContext::from)
    }

    #[inline]
    pub unsafe fn make_current(&self) -> Result<(), ContextError> {
        self.0.make_current()
    }

    #[inline]
    pub fn is_current(&self) -> bool {
        self.0.is_current()
    }

    #[inline]
    pub fn get_proc_address(&self, addr: &str) -> *const () {
        self.0.get_proc_address(addr)
    }

    #[inline]
    pub fn swap_buffers(&self) -> Result<(), ContextError> {
        self.0.swap_buffers()
    }

    #[inline]
    pub fn get_api(&self) -> Api {
        self.0.get_api()
    }

    #[inline]
    pub fn get_pixel_format(&self) -> PixelFormat {
        self.0.get_pixel_format()
    }
}
<|endoftext|>