<commit_before>#[doc = "Generic pass for performing an operation on all descriptions"];

export mk_pass;

fn mk_pass(op: fn~(str) -> str) -> pass {
    fn~(srv: astsrv::srv, doc: doc::cratedoc) -> doc::cratedoc {
        run(srv, doc, op)
    }
}

type op = fn~(str) -> str;

fn run(
    _srv: astsrv::srv,
    doc: doc::cratedoc,
    op: op
) -> doc::cratedoc {
    let fold = fold::fold({
        fold_mod: fold_mod,
        fold_const: fold_const,
        fold_fn: fold_fn,
        fold_enum: fold_enum,
        fold_res: fold_res,
        fold_iface: fold_iface
        with *fold::default_seq_fold(op)
    });
    fold.fold_crate(fold, doc)
}

fn maybe_apply_op(op: op, s: option<str>) -> option<str> {
    option::map(s) {|s| op(s) }
}

fn fold_mod(fold: fold::fold<op>, doc: doc::moddoc) -> doc::moddoc {
    let doc = fold::default_seq_fold_mod(fold, doc);

    {
        brief: maybe_apply_op(fold.ctxt, doc.brief),
        desc: maybe_apply_op(fold.ctxt, doc.desc)
        with doc
    }
}

fn fold_const(fold: fold::fold<op>, doc: doc::constdoc) -> doc::constdoc {
    let doc = fold::default_seq_fold_const(fold, doc);

    {
        brief: maybe_apply_op(fold.ctxt, doc.brief),
        desc: maybe_apply_op(fold.ctxt, doc.desc)
        with doc
    }
}

fn fold_fn(fold: fold::fold<op>, doc: doc::fndoc) -> doc::fndoc {
    let doc = fold::default_seq_fold_fn(fold, doc);

    {
        brief: maybe_apply_op(fold.ctxt, doc.brief),
        desc: maybe_apply_op(fold.ctxt, doc.desc),
        args: vec::map(doc.args) {|doc|
            {
                desc: maybe_apply_op(fold.ctxt, doc.desc)
                with doc
            }
        },
        return: {
            desc: maybe_apply_op(fold.ctxt, doc.return.desc)
            with doc.return
        },
        failure: maybe_apply_op(fold.ctxt, doc.failure)
        with doc
    }
}

fn fold_enum(fold: fold::fold<op>, doc: doc::enumdoc) -> doc::enumdoc {
    {
        brief: maybe_apply_op(fold.ctxt, doc.brief),
        desc: maybe_apply_op(fold.ctxt, doc.desc),
        variants: vec::map(doc.variants) {|variant|
            {
                desc: maybe_apply_op(fold.ctxt, variant.desc)
                with variant
            }
        }
        with doc
    }
}

fn fold_res(fold: fold::fold<op>, doc: doc::resdoc) -> doc::resdoc {
    {
        brief: maybe_apply_op(fold.ctxt, doc.brief),
        desc: maybe_apply_op(fold.ctxt, doc.desc),
        args: vec::map(doc.args) {|arg|
            {
                desc: maybe_apply_op(fold.ctxt, arg.desc)
                with arg
            }
        }
        with doc
    }
}

fn fold_iface(fold: fold::fold<op>, doc: doc::ifacedoc) -> doc::ifacedoc {
    {
        brief: maybe_apply_op(fold.ctxt, doc.brief),
        desc: maybe_apply_op(fold.ctxt, doc.desc),
        methods: vec::map(doc.methods) {|doc|
            {
                brief: maybe_apply_op(fold.ctxt, doc.brief),
                desc: maybe_apply_op(fold.ctxt, doc.desc),
                args: vec::map(doc.args) {|doc|
                    {
                        desc: maybe_apply_op(fold.ctxt, doc.desc)
                        with doc
                    }
                },
                return: {
                    desc: maybe_apply_op(fold.ctxt, doc.return.desc)
                    with doc.return
                },
                failure: maybe_apply_op(fold.ctxt, doc.failure)
                with doc
            }
        }
        with doc
    }
}

#[test]
fn should_execute_op_on_enum_brief() {
    let doc = test::mk_doc("#[doc(brief = \" a \")] enum a { b }");
    assert doc.topmod.enums()[0].brief == some("a");
}

#[test]
fn should_execute_op_on_enum_desc() {
    let doc = test::mk_doc("#[doc(desc = \" a \")] enum a { b }");
    assert doc.topmod.enums()[0].desc == some("a");
}

#[test]
fn should_execute_op_on_variant_desc() {
    let doc = test::mk_doc("enum a { #[doc = \" a \"] b }");
    assert doc.topmod.enums()[0].variants[0].desc == some("a");
}

#[test]
fn should_execute_op_on_resource_brief() {
    let doc = test::mk_doc("#[doc(brief = \" a \")] resource r(a: bool) { }");
    assert doc.topmod.resources()[0].brief == some("a");
}

#[test]
fn should_execute_op_on_resource_desc() {
    let doc = test::mk_doc("#[doc(desc = \" a \")] resource r(a: bool) { }");
    assert doc.topmod.resources()[0].desc == some("a");
}

#[test]
fn should_execute_op_on_resource_args() {
    let doc = test::mk_doc(
        "#[doc(args(a = \" a \"))] resource r(a: bool) { }");
    assert doc.topmod.resources()[0].args[0].desc == some("a");
}

#[test]
fn should_execute_op_on_iface_brief() {
    let doc = test::mk_doc(
        "#[doc(brief = \" a \")] iface i { fn a(); }");
    assert doc.topmod.ifaces()[0].brief == some("a");
}

#[test]
fn should_execute_op_on_iface_desc() {
    let doc = test::mk_doc(
        "#[doc(desc = \" a \")] iface i { fn a(); }");
    assert doc.topmod.ifaces()[0].desc == some("a");
}

#[test]
fn should_execute_op_on_iface_method_brief() {
    let doc = test::mk_doc(
        "iface i { #[doc(brief = \" a \")] fn a(); }");
    assert doc.topmod.ifaces()[0].methods[0].brief == some("a");
}

#[test]
fn should_execute_op_on_iface_method_desc() {
    let doc = test::mk_doc(
        "iface i { #[doc(desc = \" a \")] fn a(); }");
    assert doc.topmod.ifaces()[0].methods[0].desc == some("a");
}

#[test]
fn should_execute_op_on_iface_method_args() {
    let doc = test::mk_doc(
        "iface i { #[doc(args(a = \" a \"))] fn a(a: bool); }");
    assert doc.topmod.ifaces()[0].methods[0].args[0].desc == some("a");
}

#[test]
fn should_execute_op_on_iface_method_return() {
    let doc = test::mk_doc(
        "iface i { #[doc(return = \" a \")] fn a() -> int; }");
    assert doc.topmod.ifaces()[0].methods[0].return.desc == some("a");
}

#[test]
fn should_execute_op_on_iface_method_failure_condition() {
    let doc = test::mk_doc("iface i { #[doc(failure = \" a \")] fn a(); }");
    assert doc.topmod.ifaces()[0].methods[0].failure == some("a");
}

#[cfg(test)]
mod test {
    fn mk_doc(source: str) -> doc::cratedoc {
        let srv = astsrv::mk_srv_from_str(source);
        let doc = extract::from_srv(srv, "");
        let doc = attr_pass::mk_pass()(srv, doc);
        mk_pass(str::trim)(srv, doc)
    }
}<commit_msg>rustdoc: Apply string ops to impl docs<commit_after>#[doc = "Generic pass for performing an operation on all descriptions"];

export mk_pass;

fn mk_pass(op: fn~(str) -> str) -> pass {
    fn~(srv: astsrv::srv, doc: doc::cratedoc) -> doc::cratedoc {
        run(srv, doc, op)
    }
}

type op = fn~(str) -> str;

fn run(
    _srv: astsrv::srv,
    doc: doc::cratedoc,
    op: op
) -> doc::cratedoc {
    let fold = fold::fold({
        fold_mod: fold_mod,
        fold_const: fold_const,
        fold_fn: fold_fn,
        fold_enum: fold_enum,
        fold_res: fold_res,
        fold_iface: fold_iface,
        fold_impl: fold_impl
        with *fold::default_seq_fold(op)
    });
    fold.fold_crate(fold, doc)
}

fn maybe_apply_op(op: op, s: option<str>) -> option<str> {
    option::map(s) {|s| op(s) }
}

fn fold_mod(fold: fold::fold<op>, doc: doc::moddoc) -> doc::moddoc {
    let doc = fold::default_seq_fold_mod(fold, doc);

    {
        brief: maybe_apply_op(fold.ctxt, doc.brief),
        desc: maybe_apply_op(fold.ctxt, doc.desc)
        with doc
    }
}

fn fold_const(fold: fold::fold<op>, doc: doc::constdoc) -> doc::constdoc {
    let doc = fold::default_seq_fold_const(fold, doc);

    {
        brief: maybe_apply_op(fold.ctxt, doc.brief),
        desc: maybe_apply_op(fold.ctxt, doc.desc)
        with doc
    }
}

fn fold_fn(fold: fold::fold<op>, doc: doc::fndoc) -> doc::fndoc {
    let doc = fold::default_seq_fold_fn(fold, doc);

    {
        brief: maybe_apply_op(fold.ctxt, doc.brief),
        desc: maybe_apply_op(fold.ctxt, doc.desc),
        args: vec::map(doc.args) {|doc|
            {
                desc: maybe_apply_op(fold.ctxt, doc.desc)
                with doc
            }
        },
        return: {
            desc: maybe_apply_op(fold.ctxt, doc.return.desc)
            with doc.return
        },
        failure: maybe_apply_op(fold.ctxt, doc.failure)
        with doc
    }
}

fn fold_enum(fold: fold::fold<op>, doc: doc::enumdoc) -> doc::enumdoc {
    {
        brief: maybe_apply_op(fold.ctxt, doc.brief),
        desc: maybe_apply_op(fold.ctxt, doc.desc),
        variants: vec::map(doc.variants) {|variant|
            {
                desc: maybe_apply_op(fold.ctxt, variant.desc)
                with variant
            }
        }
        with doc
    }
}

fn fold_res(fold: fold::fold<op>, doc: doc::resdoc) -> doc::resdoc {
    {
        brief: maybe_apply_op(fold.ctxt, doc.brief),
        desc: maybe_apply_op(fold.ctxt, doc.desc),
        args: vec::map(doc.args) {|arg|
            {
                desc: maybe_apply_op(fold.ctxt, arg.desc)
                with arg
            }
        }
        with doc
    }
}

fn fold_iface(fold: fold::fold<op>, doc: doc::ifacedoc) -> doc::ifacedoc {
    {
        brief: maybe_apply_op(fold.ctxt, doc.brief),
        desc: maybe_apply_op(fold.ctxt, doc.desc),
        methods: apply_to_methods(fold.ctxt, doc.methods)
        with doc
    }
}

fn apply_to_methods(op: op, docs: [doc::methoddoc]) -> [doc::methoddoc] {
    vec::map(docs) {|doc|
        {
            brief: maybe_apply_op(op, doc.brief),
            desc: maybe_apply_op(op, doc.desc),
            args: vec::map(doc.args) {|doc|
                {
                    desc: maybe_apply_op(op, doc.desc)
                    with doc
                }
            },
            return: {
                desc: maybe_apply_op(op, doc.return.desc)
                with doc.return
            },
            failure: maybe_apply_op(op, doc.failure)
            with doc
        }
    }
}

fn fold_impl(fold: fold::fold<op>, doc: doc::impldoc) -> doc::impldoc {
    {
        brief: maybe_apply_op(fold.ctxt, doc.brief),
        desc: maybe_apply_op(fold.ctxt, doc.desc),
        methods: apply_to_methods(fold.ctxt, doc.methods)
        with doc
    }
}

#[test]
fn should_execute_op_on_enum_brief() {
    let doc = test::mk_doc("#[doc(brief = \" a \")] enum a { b }");
    assert doc.topmod.enums()[0].brief == some("a");
}

#[test]
fn should_execute_op_on_enum_desc() {
    let doc = test::mk_doc("#[doc(desc = \" a \")] enum a { b }");
    assert doc.topmod.enums()[0].desc == some("a");
}

#[test]
fn should_execute_op_on_variant_desc() {
    let doc = test::mk_doc("enum a { #[doc = \" a \"] b }");
    assert doc.topmod.enums()[0].variants[0].desc == some("a");
}

#[test]
fn should_execute_op_on_resource_brief() {
    let doc = test::mk_doc("#[doc(brief = \" a \")] resource r(a: bool) { }");
    assert doc.topmod.resources()[0].brief == some("a");
}

#[test]
fn should_execute_op_on_resource_desc() {
    let doc = test::mk_doc("#[doc(desc = \" a \")] resource r(a: bool) { }");
    assert doc.topmod.resources()[0].desc == some("a");
}

#[test]
fn should_execute_op_on_resource_args() {
    let doc = test::mk_doc(
        "#[doc(args(a = \" a \"))] resource r(a: bool) { }");
    assert doc.topmod.resources()[0].args[0].desc == some("a");
}

#[test]
fn should_execute_op_on_iface_brief() {
    let doc = test::mk_doc(
        "#[doc(brief = \" a \")] iface i { fn a(); }");
    assert doc.topmod.ifaces()[0].brief == some("a");
}

#[test]
fn should_execute_op_on_iface_desc() {
    let doc = test::mk_doc(
        "#[doc(desc = \" a \")] iface i { fn a(); }");
    assert doc.topmod.ifaces()[0].desc == some("a");
}

#[test]
fn should_execute_op_on_iface_method_brief() {
    let doc = test::mk_doc(
        "iface i { #[doc(brief = \" a \")] fn a(); }");
    assert doc.topmod.ifaces()[0].methods[0].brief == some("a");
}

#[test]
fn should_execute_op_on_iface_method_desc() {
    let doc = test::mk_doc(
        "iface i { #[doc(desc = \" a \")] fn a(); }");
    assert doc.topmod.ifaces()[0].methods[0].desc == some("a");
}

#[test]
fn should_execute_op_on_iface_method_args() {
    let doc = test::mk_doc(
        "iface i { #[doc(args(a = \" a \"))] fn a(a: bool); }");
    assert doc.topmod.ifaces()[0].methods[0].args[0].desc == some("a");
}

#[test]
fn should_execute_op_on_iface_method_return() {
    let doc = test::mk_doc(
        "iface i { #[doc(return = \" a \")] fn a() -> int; }");
    assert doc.topmod.ifaces()[0].methods[0].return.desc == some("a");
}

#[test]
fn should_execute_op_on_iface_method_failure_condition() {
    let doc = test::mk_doc("iface i { #[doc(failure = \" a \")] fn a(); }");
    assert doc.topmod.ifaces()[0].methods[0].failure == some("a");
}

#[test]
fn should_execute_op_on_impl_brief() {
    let doc = test::mk_doc(
        "#[doc(brief = \" a \")] impl i for int { fn a() { } }");
    assert doc.topmod.impls()[0].brief == some("a");
}

#[test]
fn should_execute_op_on_impl_desc() {
    let doc = test::mk_doc(
        "#[doc(desc = \" a \")] impl i for int { fn a() { } }");
    assert doc.topmod.impls()[0].desc == some("a");
}

#[test]
fn should_execute_op_on_impl_method_brief() {
    let doc = test::mk_doc(
        "impl i for int { #[doc(brief = \" a \")] fn a() { } }");
    assert doc.topmod.impls()[0].methods[0].brief == some("a");
}

#[test]
fn should_execute_op_on_impl_method_desc() {
    let doc = test::mk_doc(
        "impl i for int { #[doc(desc = \" a \")] fn a() { } }");
    assert doc.topmod.impls()[0].methods[0].desc == some("a");
}

#[test]
fn should_execute_op_on_impl_method_args() {
    let doc = test::mk_doc(
        "impl i for int { #[doc(args(a = \" a \"))] fn a(a: bool) { } }");
    assert doc.topmod.impls()[0].methods[0].args[0].desc == some("a");
}

#[test]
fn should_execute_op_on_impl_method_return() {
    let doc = test::mk_doc(
        "impl i for int { #[doc(return = \" a \")] fn a() -> int { fail } }");
    assert doc.topmod.impls()[0].methods[0].return.desc == some("a");
}

#[test]
fn should_execute_op_on_impl_method_failure_condition() {
    let doc = test::mk_doc(
        "impl i for int { #[doc(failure = \" a \")] fn a() { } }");
    assert doc.topmod.impls()[0].methods[0].failure == some("a");
}

#[cfg(test)]
mod test {
    fn mk_doc(source: str) -> doc::cratedoc {
        let srv = astsrv::mk_srv_from_str(source);
        let doc = extract::from_srv(srv, "");
        let doc = attr_pass::mk_pass()(srv, doc);
        mk_pass(str::trim)(srv, doc)
    }
}<|endoftext|>


<commit_before><commit_msg>Update short_number_info.rs<commit_after><|endoftext|>


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

extern crate std;
extern crate getopts;
extern crate test;

use test::{TestOpts, run_tests_console, TestDesc, TestDescAndFn, DynTestFn, DynTestName};
use getopts::{getopts, reqopt};
use std::{os, str};
use std::io::fs;
use std::io::Reader;
use std::io::process::{Process, ProcessConfig, Ignored, CreatePipe, InheritFd, ExitStatus};

#[deriving(Clone)]
struct Config {
    source_dir: ~str,
    filter: Option<~str>
}

fn main() {
    let args = os::args();
    let config = parse_config(args);
    let opts = test_options(config.clone());
    let tests = find_tests(config);
    match run_tests_console(&opts, tests) {
        Ok(false) => os::set_exit_status(1), // tests failed
        Err(_) => os::set_exit_status(2),    // I/O-related failure
        _ => (),
    }
}

fn parse_config(args: ~[~str]) -> Config {
    let args = args.tail();
    let opts = ~[reqopt("s", "source-dir", "source-dir", "source-dir")];
    let matches = match getopts(args, opts) {
      Ok(m) => m,
      Err(f) => fail!(f.to_err_msg())
    };

    Config {
        source_dir: matches.opt_str("source-dir").unwrap(),
        filter: if matches.free.is_empty() {
            None
        } else {
            Some(matches.free.as_slice().head().unwrap().clone())
        }
    }
}

fn test_options(config: Config) -> TestOpts {
    TestOpts {
        filter: config.filter,
        run_ignored: false,
        run_tests: true,
        run_benchmarks: false,
        ratchet_metrics: None,
        ratchet_noise_percent: None,
        save_metrics: None,
        test_shard: None,
        logfile: None
    }
}

fn find_tests(config: Config) -> Vec<TestDescAndFn> {
    let files_res = fs::readdir(&Path::new(config.source_dir));
    let mut files = match files_res {
        Ok(files) => files,
        _ => fail!("Error reading directory."),
    };
    files.retain(|file| file.extension_str() == Some("html") );
    return files.iter().map(|file| make_test(file.display().to_str()) ).collect();
}

fn make_test(file: ~str) -> TestDescAndFn {
    TestDescAndFn {
        desc: TestDesc {
            name: DynTestName(file.clone()),
            ignore: false,
            should_fail: false
        },
        testfn: DynTestFn(proc() { run_test(file) })
    }
}

fn run_test(file: ~str) {
    let path = os::make_absolute(&Path::new(file));
    // FIXME (#1094): not the right way to transform a path
    let infile = "file://".to_owned() + path.display().to_str();
    let stdout = CreatePipe(false, true);
    let stderr = InheritFd(2);

    let config = ProcessConfig {
        program: "./servo",
        args: &["-z".to_owned(), "-f".to_owned(), infile.clone()],
        stdin: Ignored,
        stdout: stdout,
        stderr: stderr,
        .. ProcessConfig::new()
    };
    let mut prc = match Process::configure(config) {
        Ok(p) => p,
        _ => fail!("Unable to configure process."),
    };
    let mut output = Vec::new();
    loop {
        let byte = prc.stdout.get_mut_ref().read_byte();
        match byte {
            Ok(byte) => {
                print!("{}", byte as char);
                output.push(byte);
            }
            _ => break
        }
    }

    let out = str::from_utf8(output.as_slice());
    let lines: ~[&str] = out.unwrap().split('\n').collect();
    for &line in lines.iter() {
        if line.contains("TEST-UNEXPECTED-FAIL") {
            fail!(line.to_owned());
        }
    }

    let retval = prc.wait();
    if retval != ExitStatus(0) {
        fail!("Servo exited with non-zero status {}", retval);
    }
}
<commit_msg>Use Vec in contenttest.rs.<commit_after>// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

extern crate std;
extern crate getopts;
extern crate test;

use test::{TestOpts, run_tests_console, TestDesc, TestDescAndFn, DynTestFn, DynTestName};
use getopts::{getopts, reqopt};
use std::{os, str};
use std::io::fs;
use std::io::Reader;
use std::io::process::{Process, ProcessConfig, Ignored, CreatePipe, InheritFd, ExitStatus};

#[deriving(Clone)]
struct Config {
    source_dir: ~str,
    filter: Option<~str>
}

fn main() {
    let args = os::args();
    let config = parse_config(args.move_iter().collect());
    let opts = test_options(config.clone());
    let tests = find_tests(config);
    match run_tests_console(&opts, tests) {
        Ok(false) => os::set_exit_status(1), // tests failed
        Err(_) => os::set_exit_status(2),    // I/O-related failure
        _ => (),
    }
}

fn parse_config(args: Vec<~str>) -> Config {
    let args = args.tail();
    let opts = vec!(reqopt("s", "source-dir", "source-dir", "source-dir"));
    let matches = match getopts(args, opts.as_slice()) {
      Ok(m) => m,
      Err(f) => fail!(f.to_err_msg())
    };

    Config {
        source_dir: matches.opt_str("source-dir").unwrap(),
        filter: if matches.free.is_empty() {
            None
        } else {
            Some(matches.free.as_slice().head().unwrap().clone())
        }
    }
}

fn test_options(config: Config) -> TestOpts {
    TestOpts {
        filter: config.filter,
        run_ignored: false,
        run_tests: true,
        run_benchmarks: false,
        ratchet_metrics: None,
        ratchet_noise_percent: None,
        save_metrics: None,
        test_shard: None,
        logfile: None
    }
}

fn find_tests(config: Config) -> Vec<TestDescAndFn> {
    let files_res = fs::readdir(&Path::new(config.source_dir));
    let mut files = match files_res {
        Ok(files) => files,
        _ => fail!("Error reading directory."),
    };
    files.retain(|file| file.extension_str() == Some("html") );
    return files.iter().map(|file| make_test(file.display().to_str()) ).collect();
}

fn make_test(file: ~str) -> TestDescAndFn {
    TestDescAndFn {
        desc: TestDesc {
            name: DynTestName(file.clone()),
            ignore: false,
            should_fail: false
        },
        testfn: DynTestFn(proc() { run_test(file) })
    }
}

fn run_test(file: ~str) {
    let path = os::make_absolute(&Path::new(file));
    // FIXME (#1094): not the right way to transform a path
    let infile = "file://".to_owned() + path.display().to_str();
    let stdout = CreatePipe(false, true);
    let stderr = InheritFd(2);

    let config = ProcessConfig {
        program: "./servo",
        args: &["-z".to_owned(), "-f".to_owned(), infile.clone()],
        stdin: Ignored,
        stdout: stdout,
        stderr: stderr,
        .. ProcessConfig::new()
    };
    let mut prc = match Process::configure(config) {
        Ok(p) => p,
        _ => fail!("Unable to configure process."),
    };
    let mut output = Vec::new();
    loop {
        let byte = prc.stdout.get_mut_ref().read_byte();
        match byte {
            Ok(byte) => {
                print!("{}", byte as char);
                output.push(byte);
            }
            _ => break
        }
    }

    let out = str::from_utf8(output.as_slice());
    let lines: Vec<&str> = out.unwrap().split('\n').collect();
    for &line in lines.iter() {
        if line.contains("TEST-UNEXPECTED-FAIL") {
            fail!(line.to_owned());
        }
    }

    let retval = prc.wait();
    if retval != ExitStatus(0) {
        fail!("Servo exited with non-zero status {}", retval);
    }
}
<|endoftext|>


<commit_before><commit_msg>qcow: Add raw file struct<commit_after><|endoftext|>


<commit_before><commit_msg>missed a piece of logging<commit_after><|endoftext|>


<commit_before><commit_msg>Add test with deprecated variant<commit_after>#![deny(deprecated)]

use thiserror::Error;

#[derive(Error, Debug)]
pub enum Error {
    #[deprecated]
    #[error("...")]
    Deprecated,
}
<|endoftext|>


<commit_before>use std::marker::{PhantomFn};

/// Types able to be transferred across thread boundaries.
///
/// If possible you should implement `std::marker::Send` instead of this trait. This trait
/// exists because `Send` cannot be implemented for `*mut T` and `*const T`.
pub unsafe trait Sendable: PhantomFn<Self> { }

unsafe impl<T: Send+?Sized> Sendable for T { }
<commit_msg>update rust<commit_after>/// Types able to be transferred across thread boundaries.
///
/// If possible you should implement `std::marker::Send` instead of this trait. This trait
/// exists because `Send` cannot be implemented for `*mut T` and `*const T`.
pub unsafe trait Sendable { }

unsafe impl<T: Send+?Sized> Sendable for T { }
<|endoftext|>


<commit_before><commit_msg>Scrolling, changed functions to take advantage of memset<commit_after><|endoftext|>


<commit_before><commit_msg>Renames Vector::one/zero to Vector::ones/zeros<commit_after><|endoftext|>


<commit_before><commit_msg>thread<commit_after>use std::thread;

fn main() {
    thread::spawn(move || {
        println!("Hello from the goblin in the spawned thread!");
    });
    thread::sleep_ms(50);
}<|endoftext|>


<commit_before><commit_msg>First Rust program!<commit_after>fn main(){
    println!("Hello, world!");
}
<|endoftext|>


<commit_before><commit_msg>Support expression parsing. Extend pattern parsing in `let` statement. Fix bug: assume `(ty)` as single-element-tuple.<commit_after><|endoftext|>


<commit_before><commit_msg>docs(examples): add event-listener example code<commit_after>use rocks::listener::*;
use rocks::prelude::*;
use rocks::sst_file_writer::SstFileWriter;

#[derive(Default)]
struct MyEventListener {
    flush_completed_called: usize,
    flush_begin_called: usize,
    table_file_deleted_called: usize,
    compaction_completed_called: usize,
    table_file_created_called: usize,
    table_file_creation_started_called: usize,
    on_memtable_sealed_called: usize,
    on_external_file_ingested_called: usize,
    on_column_family_handle_deletion_started_called: usize,
}

impl Drop for MyEventListener {
    fn drop(&mut self) {
        assert!(self.flush_begin_called > 0);
        assert!(self.flush_completed_called > 0);
        assert!(self.table_file_deleted_called > 0);
        assert!(self.compaction_completed_called > 0);
        assert!(self.table_file_created_called > 0);
        assert!(self.table_file_creation_started_called > 0);
        assert!(self.on_memtable_sealed_called > 0);
        assert!(self.on_external_file_ingested_called > 0);

        // FIXME: seems default cf is deleted twice
        assert!(self.on_column_family_handle_deletion_started_called > 0);

        // assert!(false);
        // FIXME: must assert drop is called
    }
}

impl EventListener for MyEventListener {
    fn on_flush_completed(&mut self, db: &DBRef, flush_job_info: &FlushJobInfo) {
        assert!(db.name().len() > 0, "DB name is accessible");
        println!(
            "! flush completed: cf={:?} path={:?}",
            flush_job_info.cf_name, flush_job_info.file_path
        );
        self.flush_completed_called += 1;
    }

    fn on_flush_begin(&mut self, _db: &DBRef, flush_job_info: &FlushJobInfo) {
        println!(
            "! flush begin: cf={:?} path={:?}",
            flush_job_info.cf_name, flush_job_info.file_path
        );
        self.flush_begin_called += 1;
    }

    fn on_table_file_deleted(&mut self, info: &TableFileDeletionInfo) {
        assert!(info.status.is_ok());
        println!("! table file deleted: path={:?}", info.file_path);
        self.table_file_deleted_called += 1;
    }

    fn on_compaction_completed(&mut self, _db: &DBRef, ci: &CompactionJobInfo) {
        assert!(ci.status().is_ok());
        assert!(ci.stats().num_input_files() > 0);
        println!(
            "! compaction completed: {:?} => {:?}",
            ci.input_files(),
            ci.output_files()
        );
        self.compaction_completed_called += 1;
    }

    fn on_table_file_created(&mut self, info: &TableFileCreationInfo) {
        // maybe: Err(ShutdownInProgress(None, "Database shutdown or Column family drop during compaction"))
        // so `db.pause_background_work()` is needed
        assert!(info.status().is_ok());
        assert!(info.file_size() > 0);
        assert!(info.table_properties().num_entries() > 0);
        assert!(info.reason() != TableFileCreationReason::Recovery);
        println!("! table file created: path={:?}", info.file_path());
        self.table_file_created_called += 1;
    }

    fn on_table_file_creation_started(&mut self, info: &TableFileCreationBriefInfo) {
        assert!(info.reason() != TableFileCreationReason::Recovery);
        println!("! table file creation started");
        self.table_file_creation_started_called += 1;
    }

    fn on_memtable_sealed(&mut self, info: &MemTableInfo) {
        assert!(info.num_entries() > 0);
        println!("! memtable sealed");
        self.on_memtable_sealed_called += 1;
    }

    fn on_column_family_handle_deletion_started(&mut self, handle: &ColumnFamilyHandle) {
        assert_eq!(handle.id(), 0); // default cf
        println!("! colum family handle deletion started, id={}", handle.id());
        self.on_column_family_handle_deletion_started_called += 1;
    }

    fn on_external_file_ingested(&mut self, _db: &DBRef, info: &ExternalFileIngestionInfo) {
        assert_eq!(info.table_properties().num_entries(), 9);
        println!(
            "! external file ingested, entries={}",
            info.table_properties().num_entries()
        );
        self.on_external_file_ingested_called += 1;
    }

    // TODO: how to test this?
    fn on_background_error(&mut self, reason: BackgroundErrorReason, bg_error: Error) -> Result<()> {
        println!("! background error: reason={:?}", reason);
        Err(bg_error)
    }

    fn get_compaction_event_listener(&mut self) -> Option<&mut dyn CompactionEventListener> {
        static mut FUNC: &'static dyn Fn(CompactionEvent) = &|event| {
            assert!(event.is_new);
            // print here will suppress rust test's capture
            // since it'll be called from C++
            // println!("listen compaction event: got => {:?} {:?}", event.sn, event);
            println!("! got compaction event");
        };
        unsafe { Some(&mut FUNC) }
    }
}

fn main() {
    let tmp_dir = ::tempdir::TempDir::new_in(".", "rocks").unwrap();
    let db = DB::open(
        Options::default().map_db_options(|db| db.create_if_missing(true).add_listener(MyEventListener::default())),
        &tmp_dir,
    )
    .unwrap();

    for i in 0..100 {
        let key = format!("test2-key-{}", i);
        let val = format!("rocksdb-value-{}", i * 10);

        db.put(&WriteOptions::default(), key.as_bytes(), val.as_bytes())
            .unwrap();

        if i % 6 == 0 {
            db.flush(&FlushOptions::default().wait(true)).unwrap();
        }
        if i % 36 == 0 {
            db.compact_range(&CompactRangeOptions::default(), ..).unwrap();
        }
    }

    assert!(db.flush(&Default::default()).is_ok());

    // ingest an sst file
    let sst_dir = ::tempdir::TempDir::new_in(".", "rocks.sst").unwrap();
    let writer = SstFileWriter::builder().build();
    writer.open(sst_dir.path().join("2333.sst")).unwrap();
    for i in 0..9 {
        let key = format!("B{:05}", i);
        let value = format!("ABCDEFGH{:03}IJKLMN", i);
        writer.put(key.as_bytes(), value.as_bytes()).unwrap();
    }
    let info = writer.finish().unwrap();
    assert_eq!(info.num_entries(), 9);

    let ret = db.ingest_external_file(
        &[sst_dir.path().join("2333.sst")],
        &IngestExternalFileOptions::default(),
    );
    assert!(ret.is_ok(), "ingest external file fails: {:?}", ret);

    // must have bg threads
    assert!(Env::default_instance().get_thread_list().len() > 0);

    // safe shutdown
    assert!(db.pause_background_work().is_ok());
}
<|endoftext|>


<commit_before><commit_msg>Some corrections for EWMA and tests<commit_after><|endoftext|>


<commit_before><commit_msg>Add resizing support for gfx_window_sdl (#1263)<commit_after><|endoftext|>


<commit_before><commit_msg>ADD MOAR THINGS<commit_after><|endoftext|>


<commit_before><commit_msg>Experiment: QWERTY key distances<commit_after><|endoftext|>


<commit_before><commit_msg>Adding current work.<commit_after>extern crate getopts;
extern crate recital;

use getopts::{Matches, Options};
use recital::prelude::*;
use std::{env, io, process};
use std::io::Write;

/// The current version of this program.
const VERSION: &'static str = "0.1.0";

/// Processes the command line arguments.
fn main() {
    let args: Vec<String> = env::args().collect();

    let mut rules = Options::new();

    rules.optflag("1", "major",
                  "Increment the major version number.");

    rules.optflag("2", "minor",
                  "Increment the minor version number.");

    rules.optflag("3", "patch",
                  "Increment the patch version number.");

    rules.optflag("e", "equal-to",
                  "Confirm VERSION is equal to VERSION.");

    rules.optflag("g", "greater-than",
                  "Confirm VERSION is greater than VERSION.");

    rules.optflag("h", "help",
                  "Displays this help mssage.");

    rules.optflag("l", "less-than",
                  "Confirm VERSION is less than VERSION.");

    rules.optflag("v", "version",
                  "Displays the version of this program.");

    let options = match rules.parse(&args[1..]) {
        Ok(result) => result,
        Err(error) => exit(1, &error.to_string()),
    };

    if options.opt_present("h") {
        usage(&args[0], &rules);
    }

    if options.opt_present("v") {
        println!("{} v{}", &args[0], &VERSION);

        process::exit(0);
    }

    match options.free.len() {
        0 => usage(&args[0], &rules),
        1 => modify(&options),
        2 => compare(&options),
        _ => exit(1, "Too many arguments provided."),
    }
}

/// Compares the given version numbers.
fn compare(options: &Matches) {
    let left = parse(&options.free[0]);
    let right = parse(&options.free[1]);

    if options.opt_present("g") && options.opt_present("l") {
        exit(1, "Cannot combine --greater-than and --less-than.");
    }

    if options.opt_present("e") {
        if left == right {
            return;
        }
    }

    if options.opt_present("g") {
        if left > right {
            return;
        }
    }

    if options.opt_present("l") {
        if left < right {
            return;
        }
    }

    process::exit(1);
}

/// Exits the program early with a message.
fn exit(code: i32, message: &str) -> ! {
    let _ = writeln!(io::stderr(), "{}", message);

    process::exit(code);
}

/// Modifies the given version number.
fn modify(options: &Matches) {
    let mut version = parse(&options.free[0]);

    if options.opt_present("1") {
        version.increment_major();
    }

    if options.opt_present("2") {
        version.increment_minor();
    }

    if options.opt_present("3") {
        version.increment_patch();
    }

    println!("{}", version);
}

/// Parses a version number.
fn parse(version: &str) -> Version {
    match version.parse() {
        Ok(result) => result,
        Err(_) => exit(1, &format!("Invalid version number: {}", version)),
    }
}

/// Displays the usage message.
fn usage(program: &str, options: &Options) {
    let b = format!("Usage: {} [OPTIONS] VERSION [VERSION]", program);
    let _ = writeln!(io::stderr(), "{}", options.usage(&b));

    process::exit(0);
}
<|endoftext|>


<commit_before><commit_msg>Daemon spawn<commit_after><|endoftext|>


<commit_before><commit_msg>safety<commit_after><|endoftext|>


<commit_before><commit_msg>	modified:   src/scan.rs<commit_after><|endoftext|>


<commit_before><commit_msg>bug in gap closing<commit_after><|endoftext|>


<commit_before><commit_msg>sprite animations are off center, but working<commit_after><|endoftext|>


<commit_before>use super::{Region, RegionIndex};
use std::mem;
use rustc::infer::InferCtxt;
use rustc::mir::{Location, Mir};
use rustc_data_structures::indexed_vec::{Idx, IndexVec};
use rustc_data_structures::fx::FxHashSet;

pub struct InferenceContext {
    definitions: IndexVec<RegionIndex, VarDefinition>,
    constraints: IndexVec<ConstraintIndex, Constraint>,
    errors: IndexVec<InferenceErrorIndex, InferenceError>,
}

pub struct InferenceError {
    pub constraint_point: Location,
    pub name: (), // TODO(nashenas88) RegionName
}

newtype_index!(InferenceErrorIndex);

struct VarDefinition {
    name: (), // TODO(nashenas88) RegionName
    value: Region,
    capped: bool,
}

impl VarDefinition {
    pub fn new(value: Region) -> Self {
        Self {
            name: (),
            value,
            capped: false,
        }
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct Constraint {
    sub: RegionIndex,
    sup: RegionIndex,
    point: Location,
}

newtype_index!(ConstraintIndex);

impl InferenceContext {
    pub fn new(values: IndexVec<RegionIndex, Region>) -> Self {
        Self {
            definitions: values.into_iter().map(VarDefinition::new).collect(),
            constraints: IndexVec::new(),
            errors: IndexVec::new(),
        }
    }

    pub fn cap_var(&mut self, v: RegionIndex) {
        self.definitions[v].capped = true;
    }

    pub fn add_live_point(&mut self, v: RegionIndex, point: Location) {
        debug!("add_live_point({:?}, {:?})", v, point);
        let definition = &mut self.definitions[v];
        if definition.value.add_point(point) {
            if definition.capped {
                self.errors.push(InferenceError {
                    constraint_point: point,
                    name: definition.name,
                });
            }
        }
    }

    pub fn add_outlives(&mut self, sup: RegionIndex, sub: RegionIndex, point: Location) {
        debug!("add_outlives({:?}: {:?} @ {:?}", sup, sub, point);
        self.constraints.push(Constraint { sup, sub, point });
    }

    pub fn region(&self, v: RegionIndex) -> &Region {
        &self.definitions[v].value
    }

    pub fn solve<'a, 'gcx, 'tcx>(
        &mut self,
        infcx: InferCtxt<'a, 'gcx, 'tcx>,
        mir: &'a Mir<'tcx>,
    ) -> IndexVec<InferenceErrorIndex, InferenceError>
    where
        'gcx: 'tcx + 'a,
        'tcx: 'a,
    {
        let mut changed = true;
        let mut dfs = Dfs::new(infcx, mir);
        while changed {
            changed = false;
            for constraint in &self.constraints {
                let sub = &self.definitions[constraint.sub].value.clone();
                let sup_def = &mut self.definitions[constraint.sup];
                debug!("constraint: {:?}", constraint);
                debug!("    sub (before): {:?}", sub);
                debug!("    sup (before): {:?}", sup_def.value);

                if dfs.copy(sub, &mut sup_def.value, constraint.point) {
                    changed = true;
                    if sup_def.capped {
                        // This is kind of a hack, but when we add a
                        // constraint, the "point" is always the point
                        // AFTER the action that induced the
                        // constraint. So report the error on the
                        // action BEFORE that.
                        assert!(constraint.point.statement_index > 0);
                        let p = Location {
                            block: constraint.point.block,
                            statement_index: constraint.point.statement_index - 1,
                        };

                        self.errors.push(InferenceError {
                            constraint_point: p,
                            name: sup_def.name,
                        });
                    }
                }

                debug!("    sup (after) : {:?}", sup_def.value);
                debug!("    changed     : {:?}", changed);
            }
            debug!("\n");
        }

        mem::replace(&mut self.errors, IndexVec::new())
    }
}

struct Dfs<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> {
    infcx: InferCtxt<'a, 'gcx, 'tcx>,
    mir: &'a Mir<'tcx>,
}

impl<'a, 'gcx: 'tcx, 'tcx: 'a> Dfs<'a, 'gcx, 'tcx> {
    fn new(infcx: InferCtxt<'a, 'gcx, 'tcx>, mir: &'a Mir<'tcx>) -> Self {
        Self { infcx, mir }
    }

    fn copy(
        &mut self,
        from_region: &Region,
        to_region: &mut Region,
        start_point: Location,
    ) -> bool {
        let mut changed = false;

        let mut stack = vec![];
        let mut visited = FxHashSet();

        stack.push(start_point);
        while let Some(p) = stack.pop() {
            debug!("        dfs: p={:?}", p);

            if !from_region.may_contain(p) {
                debug!("            not in from-region");
                continue;
            }

            if !visited.insert(p) {
                debug!("            already visited");
                continue;
            }

            changed |= to_region.add_point(p);

            let block_data = self.mir[p.block];
            let successor_points = if p.statement_index < block_data.statements.len() {
                vec![Location {
                    statement_index: p.statement_index + 1,
                    ..p
                }]
            } else {
                block_data.terminator()
                    .successors()
                    .iter()
                    .map(|&basic_block| Location {
                        statement_index: 0,
                        block: basic_block,
                    })
                    .collect::<Vec<_>>()
            };

            if successor_points.is_empty() {
                // TODO handle free regions
                // If we reach the END point in the graph, then copy
                // over any skolemized end points in the `from_region`
                // and make sure they are included in the `to_region`.
                // for region_decl in self.infcx.tcx.tables.borrow().free_region_map() {
                //     // TODO(nashenas88) figure out skolemized_end points
                //     let block = self.env.graph.skolemized_end(region_decl.name);
                //     let skolemized_end_point = Location {
                //         block,
                //         statement_index: 0,
                //     };
                //     changed |= to_region.add_point(skolemized_end_point);
                // }
            } else {
                stack.extend(successor_points);
            }
        }

        changed
    }
}
<commit_msg>borrow block_data instead of moving it<commit_after>use super::{Region, RegionIndex};
use std::mem;
use rustc::infer::InferCtxt;
use rustc::mir::{Location, Mir};
use rustc_data_structures::indexed_vec::{Idx, IndexVec};
use rustc_data_structures::fx::FxHashSet;

pub struct InferenceContext {
    definitions: IndexVec<RegionIndex, VarDefinition>,
    constraints: IndexVec<ConstraintIndex, Constraint>,
    errors: IndexVec<InferenceErrorIndex, InferenceError>,
}

pub struct InferenceError {
    pub constraint_point: Location,
    pub name: (), // TODO(nashenas88) RegionName
}

newtype_index!(InferenceErrorIndex);

struct VarDefinition {
    name: (), // TODO(nashenas88) RegionName
    value: Region,
    capped: bool,
}

impl VarDefinition {
    pub fn new(value: Region) -> Self {
        Self {
            name: (),
            value,
            capped: false,
        }
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct Constraint {
    sub: RegionIndex,
    sup: RegionIndex,
    point: Location,
}

newtype_index!(ConstraintIndex);

impl InferenceContext {
    pub fn new(values: IndexVec<RegionIndex, Region>) -> Self {
        Self {
            definitions: values.into_iter().map(VarDefinition::new).collect(),
            constraints: IndexVec::new(),
            errors: IndexVec::new(),
        }
    }

    pub fn cap_var(&mut self, v: RegionIndex) {
        self.definitions[v].capped = true;
    }

    pub fn add_live_point(&mut self, v: RegionIndex, point: Location) {
        debug!("add_live_point({:?}, {:?})", v, point);
        let definition = &mut self.definitions[v];
        if definition.value.add_point(point) {
            if definition.capped {
                self.errors.push(InferenceError {
                    constraint_point: point,
                    name: definition.name,
                });
            }
        }
    }

    pub fn add_outlives(&mut self, sup: RegionIndex, sub: RegionIndex, point: Location) {
        debug!("add_outlives({:?}: {:?} @ {:?}", sup, sub, point);
        self.constraints.push(Constraint { sup, sub, point });
    }

    pub fn region(&self, v: RegionIndex) -> &Region {
        &self.definitions[v].value
    }

    pub fn solve<'a, 'gcx, 'tcx>(
        &mut self,
        infcx: InferCtxt<'a, 'gcx, 'tcx>,
        mir: &'a Mir<'tcx>,
    ) -> IndexVec<InferenceErrorIndex, InferenceError>
    where
        'gcx: 'tcx + 'a,
        'tcx: 'a,
    {
        let mut changed = true;
        let mut dfs = Dfs::new(infcx, mir);
        while changed {
            changed = false;
            for constraint in &self.constraints {
                let sub = &self.definitions[constraint.sub].value.clone();
                let sup_def = &mut self.definitions[constraint.sup];
                debug!("constraint: {:?}", constraint);
                debug!("    sub (before): {:?}", sub);
                debug!("    sup (before): {:?}", sup_def.value);

                if dfs.copy(sub, &mut sup_def.value, constraint.point) {
                    changed = true;
                    if sup_def.capped {
                        // This is kind of a hack, but when we add a
                        // constraint, the "point" is always the point
                        // AFTER the action that induced the
                        // constraint. So report the error on the
                        // action BEFORE that.
                        assert!(constraint.point.statement_index > 0);
                        let p = Location {
                            block: constraint.point.block,
                            statement_index: constraint.point.statement_index - 1,
                        };

                        self.errors.push(InferenceError {
                            constraint_point: p,
                            name: sup_def.name,
                        });
                    }
                }

                debug!("    sup (after) : {:?}", sup_def.value);
                debug!("    changed     : {:?}", changed);
            }
            debug!("\n");
        }

        mem::replace(&mut self.errors, IndexVec::new())
    }
}

struct Dfs<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> {
    infcx: InferCtxt<'a, 'gcx, 'tcx>,
    mir: &'a Mir<'tcx>,
}

impl<'a, 'gcx: 'tcx, 'tcx: 'a> Dfs<'a, 'gcx, 'tcx> {
    fn new(infcx: InferCtxt<'a, 'gcx, 'tcx>, mir: &'a Mir<'tcx>) -> Self {
        Self { infcx, mir }
    }

    fn copy(
        &mut self,
        from_region: &Region,
        to_region: &mut Region,
        start_point: Location,
    ) -> bool {
        let mut changed = false;

        let mut stack = vec![];
        let mut visited = FxHashSet();

        stack.push(start_point);
        while let Some(p) = stack.pop() {
            debug!("        dfs: p={:?}", p);

            if !from_region.may_contain(p) {
                debug!("            not in from-region");
                continue;
            }

            if !visited.insert(p) {
                debug!("            already visited");
                continue;
            }

            changed |= to_region.add_point(p);

            let block_data = &self.mir[p.block];
            let successor_points = if p.statement_index < block_data.statements.len() {
                vec![Location {
                    statement_index: p.statement_index + 1,
                    ..p
                }]
            } else {
                block_data.terminator()
                    .successors()
                    .iter()
                    .map(|&basic_block| Location {
                        statement_index: 0,
                        block: basic_block,
                    })
                    .collect::<Vec<_>>()
            };

            if successor_points.is_empty() {
                // TODO handle free regions
                // If we reach the END point in the graph, then copy
                // over any skolemized end points in the `from_region`
                // and make sure they are included in the `to_region`.
                // for region_decl in self.infcx.tcx.tables.borrow().free_region_map() {
                //     // TODO(nashenas88) figure out skolemized_end points
                //     let block = self.env.graph.skolemized_end(region_decl.name);
                //     let skolemized_end_point = Location {
                //         block,
                //         statement_index: 0,
                //     };
                //     changed |= to_region.add_point(skolemized_end_point);
                // }
            } else {
                stack.extend(successor_points);
            }
        }

        changed
    }
}
<|endoftext|>


<commit_before><commit_msg>remove RefCell::get and RefCell::set<commit_after><|endoftext|>


<commit_before><commit_msg> boilerplate net:connection<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/.
*/
<|endoftext|>


<commit_before><commit_msg>impl eq and copy for audio some requests<commit_after><|endoftext|>


<commit_before><commit_msg>added drain instead of waiting for stabilization<commit_after>use std::slice;
use std::ptr;

pub trait DrainExt<T> {
    fn drain_temp(&mut self) -> Drain<T>;
}

impl<T> DrainExt<T> for Vec<T> {
    fn drain_temp(&mut self) -> Drain<T> {
        // Memory safety
        //
        // When the Drain is first created, it shortens the length of
        // the source vector to make sure no uninitalized or moved-from elements
        // are accessible at all if the Drain's destructor never gets to run.
        //
        // Drain will ptr::read out the values to remove.
        // When finished, remaining tail of the vec is copied back to cover
        // the hole, and the vector length is restored to the new length.
        //
        let len = self.len();
        let start = 0;
        let end = len;
        assert!(start <= end);
        assert!(end <= len);

        unsafe {
            // set self.vec length's to start, to be safe in case Drain is leaked
            self.set_len(start);
            // Use the borrow in the IterMut to indicate borrowing behavior of the
            // whole Drain iterator (like &mut T).
            let range_slice = slice::from_raw_parts_mut(
                                        self.as_mut_ptr().offset(start as isize),
                                        end - start);
            Drain {
                tail_start: end,
                tail_len: len - end,
                iter: range_slice.iter_mut(),
                vec: self as *mut _,
            }
        }
    }
}

pub struct Drain<'a, T: 'a> {
    /// Index of tail to preserve
    tail_start: usize,
    /// Length of tail
    tail_len: usize,
    /// Current remaining range to remove
    iter: slice::IterMut<'a, T>,
    vec: *mut Vec<T>,
}

impl<'a, T> Iterator for Drain<'a, T> {
    type Item = T;

    #[inline]
    fn next(&mut self) -> Option<T> {
        self.iter.next().map(|elt|
            unsafe {
                ptr::read(elt as *const _)
            }
        )
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl<'a, T> Drop for Drain<'a, T> {
    fn drop(&mut self) {
        // exhaust self first
        while let Some(_) = self.next() { }

        if self.tail_len > 0 {
            unsafe {
                let source_vec = &mut *self.vec;
                // memmove back untouched tail, update to new length
                let start = source_vec.len();
                let tail = self.tail_start;
                let src = source_vec.as_ptr().offset(tail as isize);
                let dst = source_vec.as_mut_ptr().offset(start as isize);
                ptr::copy(src, dst, self.tail_len);
                source_vec.set_len(start + self.tail_len);
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Start on lexer<commit_after>mod lexer {
    extern mod core;

    enum TokenType {
        COMMAND,
        EXIT,
        PIPE,
        EOF,
    }

    pub struct Token {
        text: ~str,
        ttype: TokenType,
    }

    pub struct Lexer {
        input: ~str,
        mut currentChar: char,
        mut index: int,
    }
}
<|endoftext|>


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

// compile-flags: -Z unstable-options --enable-index-page

#![crate_name = "foo"]

// @has foo/../index.html
// @has - '//span[@class="in-band"]' 'List of all crates'
// @has - '//ul[@class="mod"]//a[@href="foo/index.html"]' 'foo'
pub struct Foo;
<|endoftext|>


<commit_before>use std::mem;
use std::ptr;
use std::cell::RefCell;
use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex};
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;

use CursorState;
use Event;
use super::event;

use user32;
use shell32;
use winapi;

/// There's no parameters passed to the callback function, so it needs to get
/// its context (the HWND, the Sender for events, etc.) stashed in
/// a thread-local variable.
thread_local!(pub static CONTEXT_STASH: RefCell<Option<ThreadLocalData>> = RefCell::new(None));

pub struct ThreadLocalData {
    pub win: winapi::HWND,
    pub sender: Sender<Event>,
    pub cursor_state: Arc<Mutex<CursorState>>
}

/// Checks that the window is the good one, and if so send the event to it.
fn send_event(input_window: winapi::HWND, event: Event) {
    CONTEXT_STASH.with(|context_stash| {
        let context_stash = context_stash.borrow();
        let stored = match *context_stash {
            None => return,
            Some(ref v) => v
        };

        let &ThreadLocalData { ref win, ref sender, .. } = stored;

        if win != &input_window {
            return;
        }

        sender.send(event).ok();  // ignoring if closed
    });
}

/// This is the callback that is called by `DispatchMessage` in the events loop.
///
/// Returning 0 tells the Win32 API that the message has been processed.
// FIXME: detect WM_DWMCOMPOSITIONCHANGED and call DwmEnableBlurBehindWindow if necessary
pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
                                       wparam: winapi::WPARAM, lparam: winapi::LPARAM)
                                       -> winapi::LRESULT
{
    match msg {
        winapi::WM_DESTROY => {
            use events::Event::Closed;

            CONTEXT_STASH.with(|context_stash| {
                let context_stash = context_stash.borrow();
                let stored = match *context_stash {
                    None => return,
                    Some(ref v) => v
                };

                let &ThreadLocalData { ref win, .. } = stored;

                if win == &window {
                    user32::PostQuitMessage(0);
                }
            });

            send_event(window, Closed);
            0
        },

        winapi::WM_ERASEBKGND => {
            1
        },

        winapi::WM_SIZE => {
            use events::Event::Resized;
            let w = winapi::LOWORD(lparam as winapi::DWORD) as u32;
            let h = winapi::HIWORD(lparam as winapi::DWORD) as u32;
            send_event(window, Resized(w, h));
            0
        },

        winapi::WM_MOVE => {
            use events::Event::Moved;
            let x = winapi::LOWORD(lparam as winapi::DWORD) as i32;
            let y = winapi::HIWORD(lparam as winapi::DWORD) as i32;
            send_event(window, Moved(x, y));
            0
        },

        winapi::WM_CHAR => {
            use std::mem;
            use events::Event::ReceivedCharacter;
            let chr: char = mem::transmute(wparam as u32);
            send_event(window, ReceivedCharacter(chr));
            0
        },

        winapi::WM_MOUSEMOVE => {
            use events::Event::MouseMoved;

            let x = winapi::GET_X_LPARAM(lparam) as i32;
            let y = winapi::GET_Y_LPARAM(lparam) as i32;

            send_event(window, MouseMoved((x, y)));

            0
        },

        winapi::WM_MOUSEWHEEL => {
            use events::Event::MouseWheel;
            use events::MouseScrollDelta::LineDelta;

            let value = (wparam >> 16) as i16;
            let value = value as i32;
            let value = value as f32 / winapi::WHEEL_DELTA as f32;

            send_event(window, MouseWheel(LineDelta(0.0, value)));

            0
        },

        winapi::WM_KEYDOWN => {
            use events::Event::KeyboardInput;
            use events::ElementState::Pressed;
            let (scancode, vkey) = event::vkeycode_to_element(wparam, lparam);
            send_event(window, KeyboardInput(Pressed, scancode, vkey));
            0
        },

        winapi::WM_KEYUP => {
            use events::Event::KeyboardInput;
            use events::ElementState::Released;
            let (scancode, vkey) = event::vkeycode_to_element(wparam, lparam);
            send_event(window, KeyboardInput(Released, scancode, vkey));
            0
        },

        winapi::WM_LBUTTONDOWN => {
            use events::Event::MouseInput;
            use events::MouseButton::Left;
            use events::ElementState::Pressed;
            send_event(window, MouseInput(Pressed, Left));
            0
        },

        winapi::WM_LBUTTONUP => {
            use events::Event::MouseInput;
            use events::MouseButton::Left;
            use events::ElementState::Released;
            send_event(window, MouseInput(Released, Left));
            0
        },

        winapi::WM_RBUTTONDOWN => {
            use events::Event::MouseInput;
            use events::MouseButton::Right;
            use events::ElementState::Pressed;
            send_event(window, MouseInput(Pressed, Right));
            0
        },

        winapi::WM_RBUTTONUP => {
            use events::Event::MouseInput;
            use events::MouseButton::Right;
            use events::ElementState::Released;
            send_event(window, MouseInput(Released, Right));
            0
        },

        winapi::WM_MBUTTONDOWN => {
            use events::Event::MouseInput;
            use events::MouseButton::Middle;
            use events::ElementState::Pressed;
            send_event(window, MouseInput(Pressed, Middle));
            0
        },

        winapi::WM_MBUTTONUP => {
            use events::Event::MouseInput;
            use events::MouseButton::Middle;
            use events::ElementState::Released;
            send_event(window, MouseInput(Released, Middle));
            0
        },

        winapi::WM_INPUT => {
            let mut data: winapi::RAWINPUT = mem::uninitialized();
            let mut data_size = mem::size_of::<winapi::RAWINPUT>() as winapi::UINT;
            user32::GetRawInputData(mem::transmute(lparam), winapi::RID_INPUT,
                                    mem::transmute(&mut data), &mut data_size,
                                    mem::size_of::<winapi::RAWINPUTHEADER>() as winapi::UINT);

            if data.header.dwType == winapi::RIM_TYPEMOUSE {
                let _x = data.mouse.lLastX;  // FIXME: this is not always the relative movement
                let _y = data.mouse.lLastY;
                // TODO:
                //send_event(window, Event::MouseRawMovement { x: x, y: y });

                0

            } else {
                user32::DefWindowProcW(window, msg, wparam, lparam)
            }
        },

        winapi::WM_SETFOCUS => {
            use events::Event::Focused;
            send_event(window, Focused(true));
            0
        },

        winapi::WM_KILLFOCUS => {
            use events::Event::Focused;
            send_event(window, Focused(false));
            0
        },

        winapi::WM_SETCURSOR => {
            CONTEXT_STASH.with(|context_stash| {
                let cstash = context_stash.borrow();
                let cstash = cstash.as_ref();
                // there's a very bizarre borrow checker bug
                // possibly related to rust-lang/rust/#23338
                let _cursor_state = if let Some(cstash) = cstash {
                    if let Ok(cursor_state) = cstash.cursor_state.lock() {
                        match *cursor_state {
                            CursorState::Normal => {
                                user32::SetCursor(user32::LoadCursorW(
                                        ptr::null_mut(),
                                        winapi::IDC_ARROW));
                            },
                            CursorState::Grab | CursorState::Hide => {
                                user32::SetCursor(ptr::null_mut());
                            }
                        }
                    }
                } else {
                    return
                };

//                let &ThreadLocalData { ref cursor_state, .. } = stored;
            });
            0
        },

        winapi::WM_DROPFILES => {
            use events::Event::DroppedFile;

            let hdrop = wparam as winapi::HDROP;
            let mut pathbuf: [u16; winapi::MAX_PATH] = mem::uninitialized();
            let num_drops = shell32::DragQueryFileW(hdrop, 0xFFFFFFFF, ptr::null_mut(), 0);

            for i in 0..num_drops {
                let nch = shell32::DragQueryFileW(hdrop, i, pathbuf.as_mut_ptr(),
                                                  winapi::MAX_PATH as u32) as usize;
                if nch > 0 {
                    send_event(window, DroppedFile(OsString::from_wide(&pathbuf[0..nch]).into()));
                }
            }

            shell32::DragFinish(hdrop);
            0
        },

        _ => {
            user32::DefWindowProcW(window, msg, wparam, lparam)
        }
    }
}
<commit_msg>Handle events for Alt-<Key> and F10 presses in windows<commit_after>use std::mem;
use std::ptr;
use std::cell::RefCell;
use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex};
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;

use CursorState;
use Event;
use super::event;

use user32;
use shell32;
use winapi;

/// There's no parameters passed to the callback function, so it needs to get
/// its context (the HWND, the Sender for events, etc.) stashed in
/// a thread-local variable.
thread_local!(pub static CONTEXT_STASH: RefCell<Option<ThreadLocalData>> = RefCell::new(None));

pub struct ThreadLocalData {
    pub win: winapi::HWND,
    pub sender: Sender<Event>,
    pub cursor_state: Arc<Mutex<CursorState>>
}

/// Checks that the window is the good one, and if so send the event to it.
fn send_event(input_window: winapi::HWND, event: Event) {
    CONTEXT_STASH.with(|context_stash| {
        let context_stash = context_stash.borrow();
        let stored = match *context_stash {
            None => return,
            Some(ref v) => v
        };

        let &ThreadLocalData { ref win, ref sender, .. } = stored;

        if win != &input_window {
            return;
        }

        sender.send(event).ok();  // ignoring if closed
    });
}

/// This is the callback that is called by `DispatchMessage` in the events loop.
///
/// Returning 0 tells the Win32 API that the message has been processed.
// FIXME: detect WM_DWMCOMPOSITIONCHANGED and call DwmEnableBlurBehindWindow if necessary
pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
                                       wparam: winapi::WPARAM, lparam: winapi::LPARAM)
                                       -> winapi::LRESULT
{
    match msg {
        winapi::WM_DESTROY => {
            use events::Event::Closed;

            CONTEXT_STASH.with(|context_stash| {
                let context_stash = context_stash.borrow();
                let stored = match *context_stash {
                    None => return,
                    Some(ref v) => v
                };

                let &ThreadLocalData { ref win, .. } = stored;

                if win == &window {
                    user32::PostQuitMessage(0);
                }
            });

            send_event(window, Closed);
            0
        },

        winapi::WM_ERASEBKGND => {
            1
        },

        winapi::WM_SIZE => {
            use events::Event::Resized;
            let w = winapi::LOWORD(lparam as winapi::DWORD) as u32;
            let h = winapi::HIWORD(lparam as winapi::DWORD) as u32;
            send_event(window, Resized(w, h));
            0
        },

        winapi::WM_MOVE => {
            use events::Event::Moved;
            let x = winapi::LOWORD(lparam as winapi::DWORD) as i32;
            let y = winapi::HIWORD(lparam as winapi::DWORD) as i32;
            send_event(window, Moved(x, y));
            0
        },

        winapi::WM_CHAR => {
            use std::mem;
            use events::Event::ReceivedCharacter;
            let chr: char = mem::transmute(wparam as u32);
            send_event(window, ReceivedCharacter(chr));
            0
        },

        // Prevents default windows menu hotkeys playing unwanted
        // "ding" sounds. Alternatively could check for WM_SYSCOMMAND
        // with wparam being SC_KEYMENU, but this may prevent some
        // other unwanted default hotkeys as well.
        winapi::WM_SYSCHAR => {
            0
        }

        winapi::WM_MOUSEMOVE => {
            use events::Event::MouseMoved;

            let x = winapi::GET_X_LPARAM(lparam) as i32;
            let y = winapi::GET_Y_LPARAM(lparam) as i32;

            send_event(window, MouseMoved((x, y)));

            0
        },

        winapi::WM_MOUSEWHEEL => {
            use events::Event::MouseWheel;
            use events::MouseScrollDelta::LineDelta;

            let value = (wparam >> 16) as i16;
            let value = value as i32;
            let value = value as f32 / winapi::WHEEL_DELTA as f32;

            send_event(window, MouseWheel(LineDelta(0.0, value)));

            0
        },

        winapi::WM_KEYDOWN | winapi::WM_SYSKEYDOWN => {
            use events::Event::KeyboardInput;
            use events::ElementState::Pressed;
            if msg == winapi::WM_SYSKEYDOWN && wparam as i32 == winapi::VK_F4 {
                user32::DefWindowProcW(window, msg, wparam, lparam)
            } else {
                let (scancode, vkey) = event::vkeycode_to_element(wparam, lparam);
                send_event(window, KeyboardInput(Pressed, scancode, vkey));
                0
            }
        },

        winapi::WM_KEYUP | winapi::WM_SYSKEYUP => {
            use events::Event::KeyboardInput;
            use events::ElementState::Released;
            let (scancode, vkey) = event::vkeycode_to_element(wparam, lparam);
            send_event(window, KeyboardInput(Released, scancode, vkey));
            0
        },

        winapi::WM_LBUTTONDOWN => {
            use events::Event::MouseInput;
            use events::MouseButton::Left;
            use events::ElementState::Pressed;
            send_event(window, MouseInput(Pressed, Left));
            0
        },

        winapi::WM_LBUTTONUP => {
            use events::Event::MouseInput;
            use events::MouseButton::Left;
            use events::ElementState::Released;
            send_event(window, MouseInput(Released, Left));
            0
        },

        winapi::WM_RBUTTONDOWN => {
            use events::Event::MouseInput;
            use events::MouseButton::Right;
            use events::ElementState::Pressed;
            send_event(window, MouseInput(Pressed, Right));
            0
        },

        winapi::WM_RBUTTONUP => {
            use events::Event::MouseInput;
            use events::MouseButton::Right;
            use events::ElementState::Released;
            send_event(window, MouseInput(Released, Right));
            0
        },

        winapi::WM_MBUTTONDOWN => {
            use events::Event::MouseInput;
            use events::MouseButton::Middle;
            use events::ElementState::Pressed;
            send_event(window, MouseInput(Pressed, Middle));
            0
        },

        winapi::WM_MBUTTONUP => {
            use events::Event::MouseInput;
            use events::MouseButton::Middle;
            use events::ElementState::Released;
            send_event(window, MouseInput(Released, Middle));
            0
        },

        winapi::WM_INPUT => {
            let mut data: winapi::RAWINPUT = mem::uninitialized();
            let mut data_size = mem::size_of::<winapi::RAWINPUT>() as winapi::UINT;
            user32::GetRawInputData(mem::transmute(lparam), winapi::RID_INPUT,
                                    mem::transmute(&mut data), &mut data_size,
                                    mem::size_of::<winapi::RAWINPUTHEADER>() as winapi::UINT);

            if data.header.dwType == winapi::RIM_TYPEMOUSE {
                let _x = data.mouse.lLastX;  // FIXME: this is not always the relative movement
                let _y = data.mouse.lLastY;
                // TODO:
                //send_event(window, Event::MouseRawMovement { x: x, y: y });

                0

            } else {
                user32::DefWindowProcW(window, msg, wparam, lparam)
            }
        },

        winapi::WM_SETFOCUS => {
            use events::Event::Focused;
            send_event(window, Focused(true));
            0
        },

        winapi::WM_KILLFOCUS => {
            use events::Event::Focused;
            send_event(window, Focused(false));
            0
        },

        winapi::WM_SETCURSOR => {
            CONTEXT_STASH.with(|context_stash| {
                let cstash = context_stash.borrow();
                let cstash = cstash.as_ref();
                // there's a very bizarre borrow checker bug
                // possibly related to rust-lang/rust/#23338
                let _cursor_state = if let Some(cstash) = cstash {
                    if let Ok(cursor_state) = cstash.cursor_state.lock() {
                        match *cursor_state {
                            CursorState::Normal => {
                                user32::SetCursor(user32::LoadCursorW(
                                        ptr::null_mut(),
                                        winapi::IDC_ARROW));
                            },
                            CursorState::Grab | CursorState::Hide => {
                                user32::SetCursor(ptr::null_mut());
                            }
                        }
                    }
                } else {
                    return
                };

//                let &ThreadLocalData { ref cursor_state, .. } = stored;
            });
            0
        },

        winapi::WM_DROPFILES => {
            use events::Event::DroppedFile;

            let hdrop = wparam as winapi::HDROP;
            let mut pathbuf: [u16; winapi::MAX_PATH] = mem::uninitialized();
            let num_drops = shell32::DragQueryFileW(hdrop, 0xFFFFFFFF, ptr::null_mut(), 0);

            for i in 0..num_drops {
                let nch = shell32::DragQueryFileW(hdrop, i, pathbuf.as_mut_ptr(),
                                                  winapi::MAX_PATH as u32) as usize;
                if nch > 0 {
                    send_event(window, DroppedFile(OsString::from_wide(&pathbuf[0..nch]).into()));
                }
            }

            shell32::DragFinish(hdrop);
            0
        },

        _ => {
            user32::DefWindowProcW(window, msg, wparam, lparam)
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Removed Name<commit_after><|endoftext|>


<commit_before><commit_msg>probably not an awesome implementation of some filesystem functions.<commit_after>/* kernel::fs.rs */

use core::*;
use core::str::*;
use core::option::{Some, Option, None}; // Match statement
use core::iter::Iterator;
use core::vec::Vec;
use super::super::platform::*;

pub fn open(node: *tree_node, file: cstr) -> (*tree_node, bool, bool)
{
    if dir.isLeaf() || file == ""
    {
	return (node, dir.isLeaf(), file == "");
    }
    let mut children: uint = (*node).child_count;
    let mut i: uint = 0;
    let mut split = file.before('/');
    while i < children
    {
	if (*node).children[i].name == k
	{
	    return open((*node).children[i], file.remainder('/'));
	} else
	{
	    i += 1;
	}
    }
    return cstr::new();
}

pub fn append(node: *tree_node, file: cstr, content: cstr) -> bool
{
    let (mut f, _, _) = open(node, file);
    if f == cstr::new()
    {
	return false;
    }
    let mut x = 0;
    let mut f_contents = (*f).contents;
    while x < content.len()
    {
	let b = f_contents.push_char(content.char_at(x));
	if !b
	{
	    return false;
	}
    }
    let (*f).contents = f_contents;
    return true;
}

pub fn new(node: *tree_node, dir: cstr, name: cstr) -> bool
{
    let (mut n, _, _) = open(node, file);
    if !n.isLeaf()
    {
	n.insert(name);
    }
    return false;

}
<|endoftext|>


<commit_before><commit_msg>Add Entry type for store<commit_after>use std::path::PathBuf;

use header::EntryHeader;
use content::EntryContent;

pub struct Entry {
    location: PathBuf,
    header: EntryHeader,
    content: EntryContent,
}

<|endoftext|>


<commit_before><commit_msg>Update valid_items and deleted_items.<commit_after><|endoftext|>


<commit_before><commit_msg>Add `from_map` and `from_vec` to `Table`<commit_after><|endoftext|>


<commit_before><commit_msg>Add ui test of handwritten Drop for shared struct<commit_after>#[cxx::bridge]
mod ffi {
    struct Shared {
        fd: i32,
    }
}

impl Drop for ffi::Shared {
    fn drop(&mut self) {
        println!("close({})", self.fd);
    }
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Added missing file.<commit_after>
use std::ptr;
use std::ffi;
use std::path::Path;

/// Copies data from `src` to `dst`
/// TODO remove once stable in standard library.
///
/// Panics if the length of `dst` is less than the length of `src`.
#[inline]
pub fn copy_memory(src: &[u8], dst: &mut [u8]) {
    let len_src = src.len();
    assert!(dst.len() >= len_src);
    // `dst` is unaliasable, so we know statically it doesn't overlap
    // with `src`.
    unsafe {
        ptr::copy_nonoverlapping(src.as_ptr(),
                                 dst.as_mut_ptr(),
                                 len_src);
    }
}

pub fn path_to_cstring<P: AsRef<Path>>(path: &P) -> Option<ffi::CString> {
    path.as_ref().to_str().and_then(|p| ffi::CString::new(p).ok())
}
<|endoftext|>


<commit_before>use std;

fn f() {
}

import std::io::println;    //~ ERROR view items must be declared at the top

fn main() {
}

<commit_msg>test: Use a mod that exists in view-item-at-top<commit_after>use std;

fn f() {
}

import std::net;    //~ ERROR view items must be declared at the top

fn main() {
}

<|endoftext|>


<commit_before><commit_msg>Add editor mod<commit_after>#[cfg(feature = "editor")]
pub mod gfx_editor;
#[cfg(feature = "editor")]
pub mod music_editor;
#[cfg(feature = "editor")]
pub mod text_editor;<|endoftext|>


<commit_before><commit_msg>Add test: store is empty after creation<commit_after><|endoftext|>


<commit_before><commit_msg>Tests file<commit_after>extern crate kennitala;

use kennitala::is_valid;

#[test]
fn valid_kennitala(){
	assert_eq!(is_valid("091280-5079"), true);
    assert_eq!(is_valid("0902862349"), true);
    assert_eq!(is_valid("140543-3229"), true);

}
#[test]
fn invalid_kennitala(){
	assert_eq!(is_valid("091280-079"), false);
    assert_eq!(is_valid("091280-B079"), false);
}
<|endoftext|>


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

fn foo<T>(t: T) -> impl Into<[T; { const FOO: usize = 1; FOO }]> {
    [t]
}

fn bar() -> impl Into<[u8; { const FOO: usize = 1; FOO }]> {
    [99]
}

fn main() {
    println!("{:?}", foo(42).into());
    println!("{:?}", bar().into());
}
<|endoftext|>


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

pub trait LineFormatter<'a> {
    type Iter: Iterator<Item=&'a str> + 'a;
    fn iter(&'a self, line: &'a str) -> Self::Iter;

    fn dimensions(&'a self, line: &'a str) {
        let iter: Self::Iter = self.iter(line);
        <_ as IntoIterator>::into_iter(iter);
    }
}

fn main() {}<|endoftext|>


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

pub fn main() {
    let x = (0, 2);

    match x {
        (0, ref y) => {}
        (y, 0) => {}
        _ => (),
    }
}
<|endoftext|>


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

#![feature(specialization)]

fn main() {}

pub trait Alpha<T> { }

pub trait Beta {
    type Event;
}

pub trait Delta {
    type Handle;
    fn process(&self);
}

pub struct Parent<A, T>(A, T);

impl<A, T> Delta for Parent<A, T>
where A: Alpha<T::Handle>,
      T: Delta,
      T::Handle: Beta<Event = <Handle as Beta>::Event> {
    type Handle = Handle;
    default fn process(&self) {
        unimplemented!()
    }
}

impl<A, T> Delta for Parent<A, T>
where A: Alpha<T::Handle> + Alpha<Handle>,
      T: Delta,
      T::Handle: Beta<Event = <Handle as Beta>::Event> {
      fn process(&self) {
        unimplemented!()
      }
}

pub struct Handle;

impl Beta for Handle {
    type Event = ();
}<|endoftext|>


<commit_before><commit_msg>Add regression test for issue 770<commit_after>fn main() {
    if false {
        if false {
        } else {
            // A let binding here seems necessary to trigger it.
            let _ = ();
        }
    } else if let false = false {
    }
}
<|endoftext|>


<commit_before><commit_msg>added new notify battery test<commit_after>use mio::*;
use mio::net::*;
use mio::net::tcp::*;
use mio::buf::{ByteBuf, SliceBuf};
use mio::util::Slab;
use super::localhost;
use mio::event as evt;
use collections::DList;
use std::thread::Thread;

type TestEventLoop = EventLoop<usize, String>;

const SERVER: Token = Token(0);
const CLIENT: Token = Token(1);

struct EchoConn {
    sock: TcpSocket,
    token: Token,
    count: u32,
    buf: ByteBuf
}

impl EchoConn {
    fn new(sock: TcpSocket) -> EchoConn {
        EchoConn {
            sock: sock,
            token: Token(-1),
            buf: ByteBuf::new(10000),
            count: 0
        }
    }

    fn writable(&mut self, event_loop: &mut TestEventLoop) -> MioResult<()> {

        event_loop.reregister(&self.sock, self.token, evt::READABLE, evt::PollOpt::edge())
    }

    fn readable(&mut self, event_loop: &mut TestEventLoop) -> MioResult<()> {
        match self.sock.read(&mut self.buf) {
            Ok(NonBlock::WouldBlock) => {
                panic!("We just got readable, but were unable to read from the socket?");
            }
            Ok(NonBlock::Ready(r)) => {
                debug!("CONN : we read {} bytes!", r);
                self.buf.clear();
                self.count += 1;
                if self.count % 10000 == 0 {
                    println!("Received {} messages", self.count);
                }
            }
            Err(e) => {
                debug!("not implemented; client err={:?}", e);
            }

        };

        event_loop.reregister(&self.sock, self.token, evt::READABLE, evt::PollOpt::edge())
    }
}

struct EchoServer {
    sock: TcpAcceptor,
    conns: Slab<EchoConn>
}

impl EchoServer {
    fn accept(&mut self, event_loop: &mut TestEventLoop) -> MioResult<()> {
        debug!("server accepting socket");

        let sock = self.sock.accept().unwrap().unwrap();
        let conn = EchoConn::new(sock,);
        let tok = self.conns.insert(conn)
            .ok().expect("could not add connection to slab");

        // Register the connection
        self.conns[tok].token = tok;
        event_loop.register_opt(&self.conns[tok].sock, tok, evt::READABLE, evt::PollOpt::edge())
            .ok().expect("could not register socket with event loop");

        Ok(())
    }

    fn conn_readable(&mut self, event_loop: &mut TestEventLoop, tok: Token) -> MioResult<()> {
        debug!("server conn readable; tok={:?}", tok);
        self.conn(tok).readable(event_loop)
    }

    fn conn_writable(&mut self, event_loop: &mut TestEventLoop, tok: Token) -> MioResult<()> {
        debug!("server conn writable; tok={:?}", tok);
        self.conn(tok).writable(event_loop)
    }

    fn conn<'a>(&'a mut self, tok: Token) -> &'a mut EchoConn {
        &mut self.conns[tok]
    }
}

struct EchoClient {
    sock: TcpSocket,
    backlog: DList<String>,
    token: Token,
    count: u32
}

// Sends a message and expects to receive the same exact message, one at a time
impl EchoClient {
    fn new(sock: TcpSocket, tok: Token) -> EchoClient {

        EchoClient {
            sock: sock,
            backlog: DList::new(),
            token: tok,
            count: 0
        }
    }

    fn readable(&mut self, event_loop: &mut TestEventLoop) -> MioResult<()> {
        Ok(())
    }

    fn writable(&mut self, event_loop: &mut TestEventLoop) -> MioResult<()> {
        debug!("client socket writable");

        while self.backlog.len() > 0 {
            match self.sock.write_slice(self.backlog.front().unwrap().as_bytes()) {
                Ok(NonBlock::WouldBlock) => {
                    break;
                }
                Ok(NonBlock::Ready(r)) => {
                    self.backlog.pop_front();
                    self.count += 1;
                }
                Err(e) => { debug!("not implemented; client err={:?}", e); break; }
            }
        }
        if self.backlog.len() > 0 {
            event_loop.reregister(&self.sock, self.token, evt::WRITABLE, evt::PollOpt::edge());
        }

        Ok(())
    }
}

struct EchoHandler {
    server: EchoServer,
    client: EchoClient,
    count: u32
}

impl EchoHandler {
    fn new(srv: TcpAcceptor, client: TcpSocket) -> EchoHandler {
        EchoHandler {
            server: EchoServer {
                sock: srv,
                conns: Slab::new_starting_at(Token(2), 128),
            },
            client: EchoClient::new(client, CLIENT),
            count: 0
        }
    }
}

impl Handler<usize, String> for EchoHandler {
    fn readable(&mut self, event_loop: &mut TestEventLoop, token: Token, hint: evt::ReadHint) {
        assert_eq!(hint, evt::DATAHINT);

        match token {
            SERVER => self.server.accept(event_loop).unwrap(),
            CLIENT => self.client.readable(event_loop).unwrap(),
            i => self.server.conn_readable(event_loop, i).unwrap()
        };
    }

    fn writable(&mut self, event_loop: &mut TestEventLoop, token: Token) {
        match token {
            SERVER => panic!("received writable for token 0"),
            CLIENT => self.client.writable(event_loop).unwrap(),
            _ => self.server.conn_writable(event_loop, token).unwrap()
        };
    }

    fn notify(&mut self, event_loop: &mut TestEventLoop, msg: String) {
        match self.client.sock.write_slice(msg.as_bytes()) {
            Ok(n) => self.count += 1,
            Err(_) => {
                self.client.backlog.push_back(msg);
                event_loop.reregister(&self.client.sock, self.client.token, evt::WRITABLE, evt::PollOpt::edge());
            }
        }
    }
}

#[test]
pub fn test_echo_server() {
    debug!("Starting TEST_ECHO_SERVER");
    let config =
        EventLoopConfig {
            io_poll_timeout_ms: 1_000,
            notify_capacity: 1_048_576,
            messages_per_tick: 64,
            timer_tick_ms: 100,
            timer_wheel_size: 1_024,
            timer_capacity: 65_536,
        };
    let mut event_loop = EventLoop::configured(config).unwrap();

    let addr = SockAddr::parse(localhost().as_slice())
        .expect("could not parse InetAddr");

    let srv = TcpSocket::v4().unwrap();

    info!("setting re-use addr");
    srv.set_reuseaddr(true).unwrap();

    let srv = srv.bind(&addr).unwrap()
        .listen(256).unwrap();

    info!("listen for connections");
    event_loop.register_opt(&srv, SERVER, evt::READABLE, evt::PollOpt::edge()).unwrap();

    let sock = TcpSocket::v4().unwrap();

    // Connect to the server
    event_loop.register_opt(&sock, CLIENT, evt::WRITABLE, evt::PollOpt::edge()).unwrap();
    sock.connect(&addr).unwrap();
    let chan = event_loop.channel();

    let go = move|:| {
        let mut i = 1_000_000;

        let message = String::from_str("THIS IS A TEST MESSAGE");
        while i > 0 {
            chan.send(message.clone());
            i -= 1;
            if i % 10000 == 0 {
                println!("Sent {} messages", 1_000_000 - i);
            }
        }
    };

    let guard = Thread::spawn(go);

    // Start the event loop
    event_loop.run(EchoHandler::new(srv, sock))
        .ok().expect("failed to execute event loop");

}
<|endoftext|>