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

#![allow(dead_code)] // runtime init functions not used during testing

use os::windows::prelude::*;
use sys::windows::os::current_exe;
use sys::c;
use ffi::OsString;
use fmt;
use collections::VecDeque;
use core::iter;
use slice;
use path::PathBuf;

pub unsafe fn init(_argc: isize, _argv: *const *const u8) { }

pub unsafe fn cleanup() { }

pub fn args() -> Args {
    unsafe {
        let lp_cmd_line = c::GetCommandLineW();
        let parsed_args_list = parse_lp_cmd_line(
            lp_cmd_line as *const u16,
            || current_exe().map(PathBuf::into_os_string).unwrap_or_else(|_| OsString::new()));

        Args { parsed_args_list: parsed_args_list }
    }
}

/// Implements the Windows command-line argument parsing algorithm, described at
/// <https://docs.microsoft.com/en-us/previous-versions//17w5ykft(v=vs.85)>.
///
/// Windows includes a function to do this in shell32.dll,
/// but linking with that DLL causes the process to be registered as a GUI application.
/// GUI applications add a bunch of overhead, even if no windows are drawn. See
/// <https://randomascii.wordpress.com/2018/12/03/a-not-called-function-can-cause-a-5x-slowdown/>.
unsafe fn parse_lp_cmd_line<F: Fn() -> OsString>(lp_cmd_line: *const u16, exe_name: F)
                                                 -> VecDeque<OsString> {
    const BACKSLASH: u16 = '\\' as u16;
    const QUOTE: u16 = '"' as u16;
    const TAB: u16 = '\t' as u16;
    const SPACE: u16 = ' ' as u16;
    let mut in_quotes = false;
    let mut was_in_quotes = false;
    let mut backslash_count: usize = 0;
    let mut ret_val = VecDeque::new();
    let mut cur = Vec::new();
    if lp_cmd_line.is_null() || *lp_cmd_line == 0 {
        ret_val.push_back(exe_name());
        return ret_val;
    }
    let mut i = 0;
    // The executable name at the beginning is special.
    match *lp_cmd_line {
        // The executable name ends at the next quote mark,
        // no matter what.
        QUOTE => {
            loop {
                i += 1;
                if *lp_cmd_line.offset(i) == 0 {
                    ret_val.push_back(OsString::from_wide(
                        slice::from_raw_parts(lp_cmd_line.offset(1), i as usize - 1)
                    ));
                    return ret_val;
                }
                if *lp_cmd_line.offset(i) == QUOTE {
                    break;
                }
            }
            ret_val.push_back(OsString::from_wide(
                slice::from_raw_parts(lp_cmd_line.offset(1), i as usize - 1)
            ));
            i += 1;
        }
        // Implement quirk: when they say whitespace here,
        // they include the entire ASCII control plane:
        // "However, if lpCmdLine starts with any amount of whitespace, CommandLineToArgvW
        // will consider the first argument to be an empty string. Excess whitespace at the
        // end of lpCmdLine is ignored."
        0...SPACE => {
            ret_val.push_back(OsString::new());
            i += 1;
        },
        // The executable name ends at the next quote mark,
        // no matter what.
        _ => {
            loop {
                i += 1;
                if *lp_cmd_line.offset(i) == 0 {
                    ret_val.push_back(OsString::from_wide(
                        slice::from_raw_parts(lp_cmd_line, i as usize)
                    ));
                    return ret_val;
                }
                if let 0...SPACE = *lp_cmd_line.offset(i) {
                    break;
                }
            }
            ret_val.push_back(OsString::from_wide(
                slice::from_raw_parts(lp_cmd_line, i as usize)
            ));
            i += 1;
        }
    }
    loop {
        let c = *lp_cmd_line.offset(i);
        match c {
            // backslash
            BACKSLASH => {
                backslash_count += 1;
                was_in_quotes = false;
            },
            QUOTE if backslash_count % 2 == 0 => {
                cur.extend(iter::repeat(b'\\' as u16).take(backslash_count / 2));
                backslash_count = 0;
                if was_in_quotes {
                    cur.push('"' as u16);
                    was_in_quotes = false;
                } else {
                    was_in_quotes = in_quotes;
                    in_quotes = !in_quotes;
                }
            }
            QUOTE if backslash_count % 2 != 0 => {
                cur.extend(iter::repeat(b'\\' as u16).take(backslash_count / 2));
                backslash_count = 0;
                was_in_quotes = false;
                cur.push(b'"' as u16);
            }
            SPACE | TAB if !in_quotes => {
                cur.extend(iter::repeat(b'\\' as u16).take(backslash_count));
                if !cur.is_empty() || was_in_quotes {
                    ret_val.push_back(OsString::from_wide(&cur[..]));
                    cur.truncate(0);
                }
                backslash_count = 0;
                was_in_quotes = false;
            }
            0x00 => {
                cur.extend(iter::repeat(b'\\' as u16).take(backslash_count));
                // include empty quoted strings at the end of the arguments list
                if !cur.is_empty() || was_in_quotes || in_quotes {
                    ret_val.push_back(OsString::from_wide(&cur[..]));
                }
                break;
            }
            _ => {
                cur.extend(iter::repeat(b'\\' as u16).take(backslash_count));
                backslash_count = 0;
                was_in_quotes = false;
                cur.push(c);
            }
        }
        i += 1;
    }
    ret_val
}

pub struct Args {
    parsed_args_list: VecDeque<OsString>,
}

pub struct ArgsInnerDebug<'a> {
    args: &'a Args,
}

impl<'a> fmt::Debug for ArgsInnerDebug<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("[")?;
        let mut first = true;
        for i in &self.args.parsed_args_list {
            if !first {
                f.write_str(", ")?;
            }
            first = false;

            fmt::Debug::fmt(i, f)?;
        }
        f.write_str("]")?;
        Ok(())
    }
}

impl Args {
    pub fn inner_debug(&self) -> ArgsInnerDebug {
        ArgsInnerDebug {
            args: self
        }
    }
}

impl Iterator for Args {
    type Item = OsString;
    fn next(&mut self) -> Option<OsString> { self.parsed_args_list.pop_front() }
    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.parsed_args_list.len(), Some(self.parsed_args_list.len()))
    }
}

impl DoubleEndedIterator for Args {
    fn next_back(&mut self) -> Option<OsString> { self.parsed_args_list.pop_back() }
}

impl ExactSizeIterator for Args {
    fn len(&self) -> usize { self.parsed_args_list.len() }
}

#[cfg(test)]
mod tests {
    use sys::windows::args::*;
    use ffi::OsString;

    fn chk(string: &str, parts: &[&str]) {
        let mut wide: Vec<u16> = OsString::from(string).encode_wide().collect();
        wide.push(0);
        let parsed = unsafe {
            parse_lp_cmd_line(wide.as_ptr() as *const u16, || OsString::from("TEST.EXE"))
        };
        let expected: Vec<OsString> = parts.iter().map(|k| OsString::from(k)).collect();
        assert_eq!(parsed, expected);
    }

    #[test]
    fn empty() {
        chk("", &["TEST.EXE"]);
        chk("\0", &["TEST.EXE"]);
    }

    #[test]
    fn single_words() {
        chk("EXE one_word", &["EXE", "one_word"]);
        chk("EXE a", &["EXE", "a"]);
        chk("EXE 😅", &["EXE", "😅"]);
        chk("EXE 😅🤦", &["EXE", "😅🤦"]);
    }

    #[test]
    fn official_examples() {
        chk(r#"EXE "abc" d e"#, &["EXE", "abc", "d", "e"]);
        chk(r#"EXE a\\\b d"e f"g h"#, &["EXE", r#"a\\\b"#, "de fg", "h"]);
        chk(r#"EXE a\\\"b c d"#, &["EXE", r#"a\"b"#, "c", "d"]);
        chk(r#"EXE a\\\\"b c" d e"#, &["EXE", r#"a\\b c"#, "d", "e"]);
    }

    #[test]
    fn whitespace_behavior() {
        chk(r#" test"#, &["", "test"]);
        chk(r#"  test"#, &["", "test"]);
        chk(r#" test test2"#, &["", "test", "test2"]);
        chk(r#" test  test2"#, &["", "test", "test2"]);
        chk(r#"test test2 "#, &["test", "test2"]);
        chk(r#"test  test2 "#, &["test", "test2"]);
        chk(r#"test "#, &["test"]);
    }

    #[test]
    fn genius_quotes() {
        chk(r#"EXE "" """#, &["EXE", "", ""]);
        chk(r#"EXE "" """"#, &["EXE", "", "\""]);
        chk(
            r#"EXE "this is """all""" in the same argument""#,
            &["EXE", "this is \"all\" in the same argument"]
        );
        chk(r#"EXE "\u{1}"""#, &["EXE", "\u{1}\""]);
        chk(r#"EXE "a"" a"#, &["EXE", "a\"", "a"]);
    }
}
<commit_msg>Fix nitpicks<commit_after>// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![allow(dead_code)] // runtime init functions not used during testing

use os::windows::prelude::*;
use sys::windows::os::current_exe;
use sys::c;
use ffi::OsString;
use fmt;
use vec;
use core::iter;
use slice;
use path::PathBuf;

pub unsafe fn init(_argc: isize, _argv: *const *const u8) { }

pub unsafe fn cleanup() { }

pub fn args() -> Args {
    unsafe {
        let lp_cmd_line = c::GetCommandLineW();
        let parsed_args_list = parse_lp_cmd_line(
            lp_cmd_line as *const u16,
            || current_exe().map(PathBuf::into_os_string).unwrap_or_else(|_| OsString::new()));

        Args { parsed_args_list: parsed_args_list }
    }
}

/// Implements the Windows command-line argument parsing algorithm, described at
/// <https://docs.microsoft.com/en-us/previous-versions//17w5ykft(v=vs.85)>.
///
/// Windows includes a function to do this in shell32.dll,
/// but linking with that DLL causes the process to be registered as a GUI application.
/// GUI applications add a bunch of overhead, even if no windows are drawn. See
/// <https://randomascii.wordpress.com/2018/12/03/a-not-called-function-can-cause-a-5x-slowdown/>.
unsafe fn parse_lp_cmd_line<F: Fn() -> OsString>(lp_cmd_line: *const u16, exe_name: F)
                                                 -> vec::IntoIter<OsString> {
    const BACKSLASH: u16 = '\\' as u16;
    const QUOTE: u16 = '"' as u16;
    const TAB: u16 = '\t' as u16;
    const SPACE: u16 = ' ' as u16;
    let mut in_quotes = false;
    let mut was_in_quotes = false;
    let mut backslash_count: usize = 0;
    let mut ret_val = Vec::new();
    let mut cur = Vec::new();
    if lp_cmd_line.is_null() || *lp_cmd_line == 0 {
        ret_val.push(exe_name());
        return ret_val.into_iter();
    }
    let mut i = 0;
    // The executable name at the beginning is special.
    match *lp_cmd_line {
        // The executable name ends at the next quote mark,
        // no matter what.
        QUOTE => {
            loop {
                i += 1;
                if *lp_cmd_line.offset(i) == 0 {
                    ret_val.push(OsString::from_wide(
                        slice::from_raw_parts(lp_cmd_line.offset(1), i as usize - 1)
                    ));
                    return ret_val.into_iter();
                }
                if *lp_cmd_line.offset(i) == QUOTE {
                    break;
                }
            }
            ret_val.push(OsString::from_wide(
                slice::from_raw_parts(lp_cmd_line.offset(1), i as usize - 1)
            ));
            i += 1;
        }
        // Implement quirk: when they say whitespace here,
        // they include the entire ASCII control plane:
        // "However, if lpCmdLine starts with any amount of whitespace, CommandLineToArgvW
        // will consider the first argument to be an empty string. Excess whitespace at the
        // end of lpCmdLine is ignored."
        0...SPACE => {
            ret_val.push(OsString::new());
            i += 1;
        },
        // The executable name ends at the next whitespace,
        // no matter what.
        _ => {
            loop {
                i += 1;
                if *lp_cmd_line.offset(i) == 0 {
                    ret_val.push(OsString::from_wide(
                        slice::from_raw_parts(lp_cmd_line, i as usize)
                    ));
                    return ret_val.into_iter();
                }
                if let 0...SPACE = *lp_cmd_line.offset(i) {
                    break;
                }
            }
            ret_val.push(OsString::from_wide(
                slice::from_raw_parts(lp_cmd_line, i as usize)
            ));
            i += 1;
        }
    }
    loop {
        let c = *lp_cmd_line.offset(i);
        match c {
            // backslash
            BACKSLASH => {
                backslash_count += 1;
                was_in_quotes = false;
            },
            QUOTE if backslash_count % 2 == 0 => {
                cur.extend(iter::repeat(b'\\' as u16).take(backslash_count / 2));
                backslash_count = 0;
                if was_in_quotes {
                    cur.push('"' as u16);
                    was_in_quotes = false;
                } else {
                    was_in_quotes = in_quotes;
                    in_quotes = !in_quotes;
                }
            }
            QUOTE if backslash_count % 2 != 0 => {
                cur.extend(iter::repeat(b'\\' as u16).take(backslash_count / 2));
                backslash_count = 0;
                was_in_quotes = false;
                cur.push(b'"' as u16);
            }
            SPACE | TAB if !in_quotes => {
                cur.extend(iter::repeat(b'\\' as u16).take(backslash_count));
                if !cur.is_empty() || was_in_quotes {
                    ret_val.push(OsString::from_wide(&cur[..]));
                    cur.truncate(0);
                }
                backslash_count = 0;
                was_in_quotes = false;
            }
            0x00 => {
                cur.extend(iter::repeat(b'\\' as u16).take(backslash_count));
                // include empty quoted strings at the end of the arguments list
                if !cur.is_empty() || was_in_quotes || in_quotes {
                    ret_val.push(OsString::from_wide(&cur[..]));
                }
                break;
            }
            _ => {
                cur.extend(iter::repeat(b'\\' as u16).take(backslash_count));
                backslash_count = 0;
                was_in_quotes = false;
                cur.push(c);
            }
        }
        i += 1;
    }
    ret_val.into_iter()
}

pub struct Args {
    parsed_args_list: vec::IntoIter<OsString>,
}

pub struct ArgsInnerDebug<'a> {
    args: &'a Args,
}

impl<'a> fmt::Debug for ArgsInnerDebug<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("[")?;
        let mut first = true;
        for i in self.args.parsed_args_list.clone() {
            if !first {
                f.write_str(", ")?;
            }
            first = false;

            fmt::Debug::fmt(i, f)?;
        }
        f.write_str("]")?;
        Ok(())
    }
}

impl Args {
    pub fn inner_debug(&self) -> ArgsInnerDebug {
        ArgsInnerDebug {
            args: self
        }
    }
}

impl Iterator for Args {
    type Item = OsString;
    fn next(&mut self) -> Option<OsString> { self.parsed_args_list.next() }
    fn size_hint(&self) -> (usize, Option<usize>) { self.parsed_args_list.size_hint() }
}

impl DoubleEndedIterator for Args {
    fn next_back(&mut self) -> Option<OsString> { self.parsed_args_list.next_back() }
}

impl ExactSizeIterator for Args {
    fn len(&self) -> usize { self.parsed_args_list.len() }
}

#[cfg(test)]
mod tests {
    use sys::windows::args::*;
    use ffi::OsString;

    fn chk(string: &str, parts: &[&str]) {
        let mut wide: Vec<u16> = OsString::from(string).encode_wide().collect();
        wide.push(0);
        let parsed = unsafe {
            parse_lp_cmd_line(wide.as_ptr() as *const u16, || OsString::from("TEST.EXE"))
        };
        let expected: Vec<OsString> = parts.iter().map(|k| OsString::from(k)).collect();
        assert_eq!(parsed, expected);
    }

    #[test]
    fn empty() {
        chk("", &["TEST.EXE"]);
        chk("\0", &["TEST.EXE"]);
    }

    #[test]
    fn single_words() {
        chk("EXE one_word", &["EXE", "one_word"]);
        chk("EXE a", &["EXE", "a"]);
        chk("EXE 😅", &["EXE", "😅"]);
        chk("EXE 😅🤦", &["EXE", "😅🤦"]);
    }

    #[test]
    fn official_examples() {
        chk(r#"EXE "abc" d e"#, &["EXE", "abc", "d", "e"]);
        chk(r#"EXE a\\\b d"e f"g h"#, &["EXE", r#"a\\\b"#, "de fg", "h"]);
        chk(r#"EXE a\\\"b c d"#, &["EXE", r#"a\"b"#, "c", "d"]);
        chk(r#"EXE a\\\\"b c" d e"#, &["EXE", r#"a\\b c"#, "d", "e"]);
    }

    #[test]
    fn whitespace_behavior() {
        chk(r#" test"#, &["", "test"]);
        chk(r#"  test"#, &["", "test"]);
        chk(r#" test test2"#, &["", "test", "test2"]);
        chk(r#" test  test2"#, &["", "test", "test2"]);
        chk(r#"test test2 "#, &["test", "test2"]);
        chk(r#"test  test2 "#, &["test", "test2"]);
        chk(r#"test "#, &["test"]);
    }

    #[test]
    fn genius_quotes() {
        chk(r#"EXE "" """#, &["EXE", "", ""]);
        chk(r#"EXE "" """"#, &["EXE", "", "\""]);
        chk(
            r#"EXE "this is """all""" in the same argument""#,
            &["EXE", "this is \"all\" in the same argument"]
        );
        chk(r#"EXE "\u{1}"""#, &["EXE", "\u{1}\""]);
        chk(r#"EXE "a"" a"#, &["EXE", "a\"", "a"]);
    }
}
<|endoftext|>


<commit_before><commit_msg>Add runtime feature: Ignore id reporting<commit_after><|endoftext|>


<commit_before><commit_msg>added test for checking that ICEs are not hidden<commit_after>// revisions: cfail1 cfail2
// should-ice
// error-pattern: compilation successful

#![feature(rustc_attrs)]

#[rustc_error(delay_span_bug_from_inside_query)]
fn main() {}
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #37799 - michaelwoerister:ich-type-def-tests, r=nikomatsakis<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.

// This test case tests the incremental compilation hash (ICH) implementation
// for `type` definitions.

// The general pattern followed here is: Change one thing between rev1 and rev2
// and make sure that the hash has changed, then change nothing between rev2 and
// rev3 and make sure that the hash has not changed.

// We also test the ICH for `type` definitions exported in metadata. Same as
// above, we want to make sure that the change between rev1 and rev2 also
// results in a change of the ICH for the enum's metadata, and that it stays
// the same between rev2 and rev3.

// must-compile-successfully
// revisions: cfail1 cfail2 cfail3
// compile-flags: -Z query-dep-graph

#![allow(warnings)]
#![feature(rustc_attrs)]
#![crate_type="rlib"]

// Change type (primitive) -----------------------------------------------------
#[cfg(cfail1)]
type ChangePrimitiveType = i32;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type ChangePrimitiveType = i64;

// Change mutability -----------------------------------------------------------
#[cfg(cfail1)]
type ChangeMutability = &'static i32;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type ChangeMutability = &'static mut i32;

// Change mutability -----------------------------------------------------------
#[cfg(cfail1)]
type ChangeLifetime<'a> = (&'static i32, &'a i32);

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type ChangeLifetime<'a> = (&'a i32, &'a i32);

// Change type (struct) -----------------------------------------------------------
struct Struct1;
struct Struct2;

#[cfg(cfail1)]
type ChangeTypeStruct = Struct1;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type ChangeTypeStruct = Struct2;

// Change type (tuple) ---------------------------------------------------------
#[cfg(cfail1)]
type ChangeTypeTuple = (u32, u64);

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type ChangeTypeTuple = (u32, i64);

// Change type (enum) ----------------------------------------------------------
enum Enum1 {
    Var1,
    Var2,
}
enum Enum2 {
    Var1,
    Var2,
}

#[cfg(cfail1)]
type ChangeTypeEnum = Enum1;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type ChangeTypeEnum = Enum2;

// Add tuple field -------------------------------------------------------------
#[cfg(cfail1)]
type AddTupleField = (i32, i64);

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type AddTupleField = (i32, i64, i16);

// Change nested tuple field ---------------------------------------------------
#[cfg(cfail1)]
type ChangeNestedTupleField = (i32, (i64, i16));

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type ChangeNestedTupleField = (i32, (i64, i8));

// Add type param --------------------------------------------------------------
#[cfg(cfail1)]
type AddTypeParam<T1> = (T1, T1);

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type AddTypeParam<T1, T2> = (T1, T2);

// Add type param bound --------------------------------------------------------
#[cfg(cfail1)]
type AddTypeParamBound<T1> = (T1, u32);

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type AddTypeParamBound<T1: Clone> = (T1, u32);

// Add type param bound in where clause ----------------------------------------
#[cfg(cfail1)]
type AddTypeParamBoundWhereClause<T1> where T1: Clone = (T1, u32);

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type AddTypeParamBoundWhereClause<T1> where T1: Clone+Copy = (T1, u32);

// Add lifetime param ----------------------------------------------------------
#[cfg(cfail1)]
type AddLifetimeParam<'a> = (&'a u32, &'a u32);

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type AddLifetimeParam<'a, 'b> = (&'a u32, &'b u32);

// Add lifetime param bound ----------------------------------------------------
#[cfg(cfail1)]
type AddLifetimeParamBound<'a, 'b> = (&'a u32, &'b u32);

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type AddLifetimeParamBound<'a, 'b: 'a> = (&'a u32, &'b u32);

// Add lifetime param bound in where clause ------------------------------------
#[cfg(cfail1)]
type AddLifetimeParamBoundWhereClause<'a, 'b, 'c>
where 'b: 'a
    = (&'a u32, &'b u32, &'c u32);

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type AddLifetimeParamBoundWhereClause<'a, 'b, 'c>
where 'b: 'a,
      'c: 'a
    = (&'a u32, &'b u32, &'c u32);

// Change Trait Bound Indirectly -----------------------------------------------
trait ReferencedTrait1 {}
trait ReferencedTrait2 {}

mod change_trait_bound_indirectly {
    #[cfg(cfail1)]
    use super::ReferencedTrait1 as Trait;
    #[cfg(not(cfail1))]
    use super::ReferencedTrait2 as Trait;

    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    type ChangeTraitBoundIndirectly<T: Trait> = (T, u32);
}

// Change Trait Bound Indirectly In Where Clause -------------------------------
mod change_trait_bound_indirectly_in_where_clause {
    #[cfg(cfail1)]
    use super::ReferencedTrait1 as Trait;
    #[cfg(not(cfail1))]
    use super::ReferencedTrait2 as Trait;

    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    type ChangeTraitBoundIndirectly<T> where T : Trait = (T, u32);
}
<|endoftext|>


<commit_before><commit_msg>Clean up code.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix a syntax error when converting the string "success" to JSON<commit_after><|endoftext|>


<commit_before><commit_msg>Regression test for #63154.<commit_after>// Regression test for rust-lang/rust#63154
//
// Before, we would ICE after faiing to normalize the destination type
// when checking call destinations and also when checking MIR
// assignment statements.

// check-pass

trait HasAssocType {
    type Inner;
}

impl HasAssocType for () {
    type Inner = ();
}

trait Tr<I, T>: Fn(I) -> Option<T> {}
impl<I, T, Q: Fn(I) -> Option<T>> Tr<I, T> for Q {}

fn f<T: HasAssocType>() -> impl Tr<T, T::Inner> {
    |_| None
}

fn g<T, Y>(f: impl Tr<T, Y>) -> impl Tr<T, Y> {
    f
}

fn h() {
    g(f())(());
}

fn main() {
    h();
}
<|endoftext|>


<commit_before><commit_msg>Skeleton out the main compilation function.<commit_after><|endoftext|>


<commit_before><commit_msg>Make api, diff, gradebook modules public<commit_after><|endoftext|>


<commit_before><commit_msg>added todo<commit_after><|endoftext|>


<commit_before><commit_msg>deprecation is stable; no feature(deprecated)<commit_after><|endoftext|>


<commit_before><commit_msg>fix formating<commit_after><|endoftext|>


<commit_before><commit_msg>minor fix<commit_after><|endoftext|>


<commit_before>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use std::path::PathBuf;
use std::process::Command;
use std::env;
use std::io::stderr;
use std::io::Write;

pub use clap::App;

use clap::{Arg, ArgMatches};
use log;
use log::LogLevelFilter;

use configuration::Configuration;
use error::RuntimeError;
use error::RuntimeErrorKind;
use error::MapErrInto;
use logger::ImagLogger;

use libimagstore::store::Store;

/// The Runtime object
///
/// This object contains the complete runtime environment of the imag application running.
#[derive(Debug)]
pub struct Runtime<'a> {
    rtp: PathBuf,
    configuration: Option<Configuration>,
    cli_matches: ArgMatches<'a>,
    store: Store,
}

impl<'a> Runtime<'a> {

    /// Gets the CLI spec for the program and retreives the config file path (or uses the default on
    /// in $HOME/.imag/config, $XDG_CONFIG_DIR/imag/config or from env("$IMAG_CONFIG")
    /// and builds the Runtime object with it.
    ///
    /// The cli_spec object should be initially build with the ::get_default_cli_builder() function.
    pub fn new(mut cli_spec: App<'a, 'a>) -> Result<Runtime<'a>, RuntimeError> {
        use std::env;
        use std::io::stdout;

        use clap::Shell;

        use libimagerror::trace::trace_error;
        use libimagerror::into::IntoError;

        use configuration::error::ConfigErrorKind;

        let matches = cli_spec.clone().get_matches();

        let is_debugging = matches.is_present("debugging");
        let is_verbose   = matches.is_present("verbosity");
        let colored      = !matches.is_present("no-color-output");

        Runtime::init_logger(is_debugging, is_verbose, colored);

        match matches.value_of(Runtime::arg_generate_compl()) {
            Some(shell) => {
                debug!("Generating shell completion script, writing to stdout");
                let shell   = shell.parse::<Shell>().unwrap(); // clap has our back here.
                let appname = String::from(cli_spec.get_name());
                cli_spec.gen_completions_to(appname, shell, &mut stdout());
            },
            _ => debug!("Not generating shell completion script"),
        }

        let rtp : PathBuf = matches.value_of("runtimepath")
            .map_or_else(|| {
                env::var("HOME")
                    .map(PathBuf::from)
                    .map(|mut p| { p.push(".imag"); p})
                    .unwrap_or_else(|_| {
                        panic!("You seem to be $HOME-less. Please get a $HOME before using this software. We are sorry for you and hope you have some accommodation anyways.");
                    })
            }, PathBuf::from);
        let storepath = matches.value_of("storepath")
                                .map_or_else(|| {
                                    let mut spath = rtp.clone();
                                    spath.push("store");
                                    spath
                                }, PathBuf::from);

        let configpath = matches.value_of("config")
                                .map_or_else(|| rtp.clone(), PathBuf::from);

        debug!("RTP path    = {:?}", rtp);
        debug!("Store path  = {:?}", storepath);
        debug!("Config path = {:?}", configpath);

        let cfg = match Configuration::new(&configpath) {
            Err(e) => if e.err_type() != ConfigErrorKind::NoConfigFileFound {
                return Err(RuntimeErrorKind::Instantiate.into_error_with_cause(Box::new(e)));
            } else {
                warn!("No config file found.");
                warn!("Continuing without configuration file");
                None
            },

            Ok(mut cfg) => {
                if let Err(e) = cfg.override_config(get_override_specs(&matches)) {
                    error!("Could not apply config overrides");
                    trace_error(&e);

                    // TODO: continue question (interactive)
                }

                Some(cfg)
            }
        };

        let store_config = match cfg {
            Some(ref c) => c.store_config().cloned(),
            None        => None,
        };

        if is_debugging {
            write!(stderr(), "Config: {:?}\n", cfg).ok();
            write!(stderr(), "Store-config: {:?}\n", store_config).ok();
        }

        Store::new(storepath.clone(), store_config).map(|store| {
            Runtime {
                cli_matches: matches,
                configuration: cfg,
                rtp: rtp,
                store: store,
            }
        })
        .map_err_into(RuntimeErrorKind::Instantiate)
    }

    ///
    /// Get a commandline-interface builder object from `clap`
    ///
    /// This commandline interface builder object already contains some predefined interface flags:
    ///   * -v | --verbose for verbosity
    ///   * --debug for debugging
    ///   * -c <file> | --config <file> for alternative configuration file
    ///   * -r <path> | --rtp <path> for alternative runtimepath
    ///   * --store <path> for alternative store path
    /// Each has the appropriate help text included.
    ///
    /// The `appname` shall be "imag-<command>".
    ///
    pub fn get_default_cli_builder(appname: &'a str,
                                   version: &'a str,
                                   about: &'a str)
        -> App<'a, 'a>
    {
        App::new(appname)
            .version(version)
            .author("Matthias Beyer <mail@beyermatthias.de>")
            .about(about)
            .arg(Arg::with_name(Runtime::arg_verbosity_name())
                .short("v")
                .long("verbose")
                .help("Enables verbosity")
                .required(false)
                .takes_value(false))

            .arg(Arg::with_name(Runtime::arg_debugging_name())
                .long("debug")
                .help("Enables debugging output")
                .required(false)
                .takes_value(false))

            .arg(Arg::with_name(Runtime::arg_no_color_output_name())
                .long("no-color")
                .help("Disable color output")
                .required(false)
                .takes_value(false))

            .arg(Arg::with_name(Runtime::arg_config_name())
                .long("config")
                .help("Path to alternative config file")
                .required(false)
                .takes_value(true))

            .arg(Arg::with_name(Runtime::arg_config_override_name())
                 .long("override-config")
                 .help("Override a configuration settings. Use 'key=value' pairs, where the key is a path in the TOML configuration. The value must be present in the configuration and be convertible to the type of the configuration setting. If the argument does not contain a '=', it gets ignored. Setting Arrays and Tables is not yet supported.")
                 .required(false)
                 .takes_value(true))

            .arg(Arg::with_name(Runtime::arg_runtimepath_name())
                .long("rtp")
                .help("Alternative runtimepath")
                .required(false)
                .takes_value(true))

            .arg(Arg::with_name(Runtime::arg_storepath_name())
                .long("store")
                .help("Alternative storepath. Must be specified as full path, can be outside of the RTP")
                .required(false)
                .takes_value(true))

            .arg(Arg::with_name(Runtime::arg_editor_name())
                .long("editor")
                .help("Set editor")
                .required(false)
                .takes_value(true))

            .arg(Arg::with_name(Runtime::arg_generate_compl())
                .long("generate-commandline-completion")
                .help("Generate the commandline completion for bash or zsh or fish")
                .required(false)
                .takes_value(true)
                .value_name("SHELL")
                .possible_values(&["bash", "fish", "zsh"]))

    }

    /// Get the argument names of the Runtime which are available
    pub fn arg_names() -> Vec<&'static str> {
        vec![
            Runtime::arg_verbosity_name(),
            Runtime::arg_debugging_name(),
            Runtime::arg_no_color_output_name(),
            Runtime::arg_config_name(),
            Runtime::arg_config_override_name(),
            Runtime::arg_runtimepath_name(),
            Runtime::arg_storepath_name(),
            Runtime::arg_editor_name(),
        ]
    }

    /// Get the verbosity argument name for the Runtime
    pub fn arg_verbosity_name() -> &'static str {
        "verbosity"
    }

    /// Get the debugging argument name for the Runtime
    pub fn arg_debugging_name() -> &'static str {
        "debugging"
    }

    /// Get the argument name for no color output of the Runtime
    pub fn arg_no_color_output_name() -> &'static str {
        "no-color-output"
    }

    /// Get the config argument name for the Runtime
    pub fn arg_config_name() -> &'static str {
        "config"
    }

    /// Get the config-override argument name for the Runtime
    pub fn arg_config_override_name() -> &'static str {
        "config-override"
    }

    /// Get the runtime argument name for the Runtime
    pub fn arg_runtimepath_name() -> &'static str {
        "runtimepath"
    }

    /// Get the storepath argument name for the Runtime
    pub fn arg_storepath_name() -> &'static str {
        "storepath"
    }

    /// Get the editor argument name for the Runtime
    pub fn arg_editor_name() -> &'static str {
        "editor"
    }

    /// Get the argument name for generating the completion
    pub fn arg_generate_compl() -> &'static str {
        "generate-completion"
    }

    /// Initialize the internal logger
    fn init_logger(is_debugging: bool, is_verbose: bool, colored: bool) {
        use std::env::var as env_var;
        use env_logger;

        if env_var("IMAG_LOG_ENV").is_ok() {
            env_logger::init().unwrap();
        } else {
            let lvl = if is_debugging {
                LogLevelFilter::Debug
            } else if is_verbose {
                LogLevelFilter::Info
            } else {
                LogLevelFilter::Warn
            };

            log::set_logger(|max_log_lvl| {
                max_log_lvl.set(lvl);
                debug!("Init logger with {}", lvl);
                Box::new(ImagLogger::new(lvl.to_log_level().unwrap()).with_color(colored))
            })
            .map_err(|e| panic!("Could not setup logger: {:?}", e))
            .ok();
        }
    }

    /// Get the verbosity flag value
    pub fn is_verbose(&self) -> bool {
        self.cli_matches.is_present("verbosity")
    }

    /// Get the debugging flag value
    pub fn is_debugging(&self) -> bool {
        self.cli_matches.is_present("debugging")
    }

    /// Get the runtimepath
    pub fn rtp(&self) -> &PathBuf {
        &self.rtp
    }

    /// Get the commandline interface matches
    pub fn cli(&self) -> &ArgMatches {
        &self.cli_matches
    }

    /// Get the configuration object
    pub fn config(&self) -> Option<&Configuration> {
        self.configuration.as_ref()
    }

    /// Get the store object
    pub fn store(&self) -> &Store {
        &self.store
    }

    /// Change the store backend to stdout
    ///
    /// For the documentation on purpose and cavecats, have a look at the documentation of the
    /// `Store::reset_backend()` function.
    ///
    pub fn store_backend_to_stdio(&mut self) -> Result<(), RuntimeError> {
        use libimagstore::file_abstraction::stdio::*;
        use libimagstore::file_abstraction::stdio::mapper::json::JsonMapper;
        use std::rc::Rc;
        use std::cell::RefCell;

        let mut input = ::std::io::stdin();
        let output    = ::std::io::stdout();
        let output    = Rc::new(RefCell::new(output));
        let mapper    = JsonMapper::new();

        StdIoFileAbstraction::new(&mut input, output, mapper)
            .map_err_into(RuntimeErrorKind::Instantiate)
            .and_then(|backend| {
                self.store
                    .reset_backend(Box::new(backend))
                    .map_err_into(RuntimeErrorKind::Instantiate)
            })
    }

    pub fn store_backend_to_stdout(&mut self) -> Result<(), RuntimeError> {
        use libimagstore::file_abstraction::stdio::mapper::json::JsonMapper;
        use libimagstore::file_abstraction::stdio::out::StdoutFileAbstraction;
        use std::rc::Rc;
        use std::cell::RefCell;

        let output    = ::std::io::stdout();
        let output    = Rc::new(RefCell::new(output));
        let mapper    = JsonMapper::new();

        StdoutFileAbstraction::new(output, mapper)
            .map_err_into(RuntimeErrorKind::Instantiate)
            .and_then(|backend| {
                self.store
                    .reset_backend(Box::new(backend))
                    .map_err_into(RuntimeErrorKind::Instantiate)
            })
    }

    /// Get a editor command object which can be called to open the $EDITOR
    pub fn editor(&self) -> Option<Command> {
        self.cli()
            .value_of("editor")
            .map(String::from)
            .or({
                match self.configuration {
                    Some(ref c) => c.editor().cloned(),
                    _ => None,
                }
            })
            .or(env::var("EDITOR").ok())
            .map(Command::new)
    }
}

fn get_override_specs(matches: &ArgMatches) -> Vec<String> {
    matches
        .values_of("config-override")
        .map(|values| {
             values
             .filter(|s| {
                 let b = s.contains("=");
                 if !b { warn!("override '{}' does not contain '=' - will be ignored!", s); }
                 b
             })
             .map(String::from)
             .collect()
        })
        .unwrap_or(vec![])
}

<commit_msg>Minify match<commit_after>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use std::path::PathBuf;
use std::process::Command;
use std::env;
use std::io::stderr;
use std::io::Write;

pub use clap::App;

use clap::{Arg, ArgMatches};
use log;
use log::LogLevelFilter;

use configuration::Configuration;
use error::RuntimeError;
use error::RuntimeErrorKind;
use error::MapErrInto;
use logger::ImagLogger;

use libimagstore::store::Store;

/// The Runtime object
///
/// This object contains the complete runtime environment of the imag application running.
#[derive(Debug)]
pub struct Runtime<'a> {
    rtp: PathBuf,
    configuration: Option<Configuration>,
    cli_matches: ArgMatches<'a>,
    store: Store,
}

impl<'a> Runtime<'a> {

    /// Gets the CLI spec for the program and retreives the config file path (or uses the default on
    /// in $HOME/.imag/config, $XDG_CONFIG_DIR/imag/config or from env("$IMAG_CONFIG")
    /// and builds the Runtime object with it.
    ///
    /// The cli_spec object should be initially build with the ::get_default_cli_builder() function.
    pub fn new(mut cli_spec: App<'a, 'a>) -> Result<Runtime<'a>, RuntimeError> {
        use std::env;
        use std::io::stdout;

        use clap::Shell;

        use libimagerror::trace::trace_error;
        use libimagerror::into::IntoError;

        use configuration::error::ConfigErrorKind;

        let matches = cli_spec.clone().get_matches();

        let is_debugging = matches.is_present("debugging");
        let is_verbose   = matches.is_present("verbosity");
        let colored      = !matches.is_present("no-color-output");

        Runtime::init_logger(is_debugging, is_verbose, colored);

        match matches.value_of(Runtime::arg_generate_compl()) {
            Some(shell) => {
                debug!("Generating shell completion script, writing to stdout");
                let shell   = shell.parse::<Shell>().unwrap(); // clap has our back here.
                let appname = String::from(cli_spec.get_name());
                cli_spec.gen_completions_to(appname, shell, &mut stdout());
            },
            _ => debug!("Not generating shell completion script"),
        }

        let rtp : PathBuf = matches.value_of("runtimepath")
            .map_or_else(|| {
                env::var("HOME")
                    .map(PathBuf::from)
                    .map(|mut p| { p.push(".imag"); p})
                    .unwrap_or_else(|_| {
                        panic!("You seem to be $HOME-less. Please get a $HOME before using this software. We are sorry for you and hope you have some accommodation anyways.");
                    })
            }, PathBuf::from);
        let storepath = matches.value_of("storepath")
                                .map_or_else(|| {
                                    let mut spath = rtp.clone();
                                    spath.push("store");
                                    spath
                                }, PathBuf::from);

        let configpath = matches.value_of("config")
                                .map_or_else(|| rtp.clone(), PathBuf::from);

        debug!("RTP path    = {:?}", rtp);
        debug!("Store path  = {:?}", storepath);
        debug!("Config path = {:?}", configpath);

        let cfg = match Configuration::new(&configpath) {
            Err(e) => if e.err_type() != ConfigErrorKind::NoConfigFileFound {
                return Err(RuntimeErrorKind::Instantiate.into_error_with_cause(Box::new(e)));
            } else {
                warn!("No config file found.");
                warn!("Continuing without configuration file");
                None
            },

            Ok(mut cfg) => {
                if let Err(e) = cfg.override_config(get_override_specs(&matches)) {
                    error!("Could not apply config overrides");
                    trace_error(&e);

                    // TODO: continue question (interactive)
                }

                Some(cfg)
            }
        };

        let store_config = match cfg {
            Some(ref c) => c.store_config().cloned(),
            None        => None,
        };

        if is_debugging {
            write!(stderr(), "Config: {:?}\n", cfg).ok();
            write!(stderr(), "Store-config: {:?}\n", store_config).ok();
        }

        Store::new(storepath.clone(), store_config).map(|store| {
            Runtime {
                cli_matches: matches,
                configuration: cfg,
                rtp: rtp,
                store: store,
            }
        })
        .map_err_into(RuntimeErrorKind::Instantiate)
    }

    ///
    /// Get a commandline-interface builder object from `clap`
    ///
    /// This commandline interface builder object already contains some predefined interface flags:
    ///   * -v | --verbose for verbosity
    ///   * --debug for debugging
    ///   * -c <file> | --config <file> for alternative configuration file
    ///   * -r <path> | --rtp <path> for alternative runtimepath
    ///   * --store <path> for alternative store path
    /// Each has the appropriate help text included.
    ///
    /// The `appname` shall be "imag-<command>".
    ///
    pub fn get_default_cli_builder(appname: &'a str,
                                   version: &'a str,
                                   about: &'a str)
        -> App<'a, 'a>
    {
        App::new(appname)
            .version(version)
            .author("Matthias Beyer <mail@beyermatthias.de>")
            .about(about)
            .arg(Arg::with_name(Runtime::arg_verbosity_name())
                .short("v")
                .long("verbose")
                .help("Enables verbosity")
                .required(false)
                .takes_value(false))

            .arg(Arg::with_name(Runtime::arg_debugging_name())
                .long("debug")
                .help("Enables debugging output")
                .required(false)
                .takes_value(false))

            .arg(Arg::with_name(Runtime::arg_no_color_output_name())
                .long("no-color")
                .help("Disable color output")
                .required(false)
                .takes_value(false))

            .arg(Arg::with_name(Runtime::arg_config_name())
                .long("config")
                .help("Path to alternative config file")
                .required(false)
                .takes_value(true))

            .arg(Arg::with_name(Runtime::arg_config_override_name())
                 .long("override-config")
                 .help("Override a configuration settings. Use 'key=value' pairs, where the key is a path in the TOML configuration. The value must be present in the configuration and be convertible to the type of the configuration setting. If the argument does not contain a '=', it gets ignored. Setting Arrays and Tables is not yet supported.")
                 .required(false)
                 .takes_value(true))

            .arg(Arg::with_name(Runtime::arg_runtimepath_name())
                .long("rtp")
                .help("Alternative runtimepath")
                .required(false)
                .takes_value(true))

            .arg(Arg::with_name(Runtime::arg_storepath_name())
                .long("store")
                .help("Alternative storepath. Must be specified as full path, can be outside of the RTP")
                .required(false)
                .takes_value(true))

            .arg(Arg::with_name(Runtime::arg_editor_name())
                .long("editor")
                .help("Set editor")
                .required(false)
                .takes_value(true))

            .arg(Arg::with_name(Runtime::arg_generate_compl())
                .long("generate-commandline-completion")
                .help("Generate the commandline completion for bash or zsh or fish")
                .required(false)
                .takes_value(true)
                .value_name("SHELL")
                .possible_values(&["bash", "fish", "zsh"]))

    }

    /// Get the argument names of the Runtime which are available
    pub fn arg_names() -> Vec<&'static str> {
        vec![
            Runtime::arg_verbosity_name(),
            Runtime::arg_debugging_name(),
            Runtime::arg_no_color_output_name(),
            Runtime::arg_config_name(),
            Runtime::arg_config_override_name(),
            Runtime::arg_runtimepath_name(),
            Runtime::arg_storepath_name(),
            Runtime::arg_editor_name(),
        ]
    }

    /// Get the verbosity argument name for the Runtime
    pub fn arg_verbosity_name() -> &'static str {
        "verbosity"
    }

    /// Get the debugging argument name for the Runtime
    pub fn arg_debugging_name() -> &'static str {
        "debugging"
    }

    /// Get the argument name for no color output of the Runtime
    pub fn arg_no_color_output_name() -> &'static str {
        "no-color-output"
    }

    /// Get the config argument name for the Runtime
    pub fn arg_config_name() -> &'static str {
        "config"
    }

    /// Get the config-override argument name for the Runtime
    pub fn arg_config_override_name() -> &'static str {
        "config-override"
    }

    /// Get the runtime argument name for the Runtime
    pub fn arg_runtimepath_name() -> &'static str {
        "runtimepath"
    }

    /// Get the storepath argument name for the Runtime
    pub fn arg_storepath_name() -> &'static str {
        "storepath"
    }

    /// Get the editor argument name for the Runtime
    pub fn arg_editor_name() -> &'static str {
        "editor"
    }

    /// Get the argument name for generating the completion
    pub fn arg_generate_compl() -> &'static str {
        "generate-completion"
    }

    /// Initialize the internal logger
    fn init_logger(is_debugging: bool, is_verbose: bool, colored: bool) {
        use std::env::var as env_var;
        use env_logger;

        if env_var("IMAG_LOG_ENV").is_ok() {
            env_logger::init().unwrap();
        } else {
            let lvl = if is_debugging {
                LogLevelFilter::Debug
            } else if is_verbose {
                LogLevelFilter::Info
            } else {
                LogLevelFilter::Warn
            };

            log::set_logger(|max_log_lvl| {
                max_log_lvl.set(lvl);
                debug!("Init logger with {}", lvl);
                Box::new(ImagLogger::new(lvl.to_log_level().unwrap()).with_color(colored))
            })
            .map_err(|e| panic!("Could not setup logger: {:?}", e))
            .ok();
        }
    }

    /// Get the verbosity flag value
    pub fn is_verbose(&self) -> bool {
        self.cli_matches.is_present("verbosity")
    }

    /// Get the debugging flag value
    pub fn is_debugging(&self) -> bool {
        self.cli_matches.is_present("debugging")
    }

    /// Get the runtimepath
    pub fn rtp(&self) -> &PathBuf {
        &self.rtp
    }

    /// Get the commandline interface matches
    pub fn cli(&self) -> &ArgMatches {
        &self.cli_matches
    }

    /// Get the configuration object
    pub fn config(&self) -> Option<&Configuration> {
        self.configuration.as_ref()
    }

    /// Get the store object
    pub fn store(&self) -> &Store {
        &self.store
    }

    /// Change the store backend to stdout
    ///
    /// For the documentation on purpose and cavecats, have a look at the documentation of the
    /// `Store::reset_backend()` function.
    ///
    pub fn store_backend_to_stdio(&mut self) -> Result<(), RuntimeError> {
        use libimagstore::file_abstraction::stdio::*;
        use libimagstore::file_abstraction::stdio::mapper::json::JsonMapper;
        use std::rc::Rc;
        use std::cell::RefCell;

        let mut input = ::std::io::stdin();
        let output    = ::std::io::stdout();
        let output    = Rc::new(RefCell::new(output));
        let mapper    = JsonMapper::new();

        StdIoFileAbstraction::new(&mut input, output, mapper)
            .map_err_into(RuntimeErrorKind::Instantiate)
            .and_then(|backend| {
                self.store
                    .reset_backend(Box::new(backend))
                    .map_err_into(RuntimeErrorKind::Instantiate)
            })
    }

    pub fn store_backend_to_stdout(&mut self) -> Result<(), RuntimeError> {
        use libimagstore::file_abstraction::stdio::mapper::json::JsonMapper;
        use libimagstore::file_abstraction::stdio::out::StdoutFileAbstraction;
        use std::rc::Rc;
        use std::cell::RefCell;

        let output    = ::std::io::stdout();
        let output    = Rc::new(RefCell::new(output));
        let mapper    = JsonMapper::new();

        StdoutFileAbstraction::new(output, mapper)
            .map_err_into(RuntimeErrorKind::Instantiate)
            .and_then(|backend| {
                self.store
                    .reset_backend(Box::new(backend))
                    .map_err_into(RuntimeErrorKind::Instantiate)
            })
    }

    /// Get a editor command object which can be called to open the $EDITOR
    pub fn editor(&self) -> Option<Command> {
        self.cli()
            .value_of("editor")
            .map(String::from)
            .or(match self.configuration {
                Some(ref c) => c.editor().cloned(),
                _ => None,
            })
            .or(env::var("EDITOR").ok())
            .map(Command::new)
    }
}

fn get_override_specs(matches: &ArgMatches) -> Vec<String> {
    matches
        .values_of("config-override")
        .map(|values| {
             values
             .filter(|s| {
                 let b = s.contains("=");
                 if !b { warn!("override '{}' does not contain '=' - will be ignored!", s); }
                 b
             })
             .map(String::from)
             .collect()
        })
        .unwrap_or(vec![])
}

<|endoftext|>


<commit_before><commit_msg>Remove alias for Boxed FnOnce<commit_after><|endoftext|>


<commit_before><commit_msg>added inline<commit_after><|endoftext|>


<commit_before><commit_msg>Add helper function http::client() with NativeTlsClient<commit_after>use hyper;
use hyper_native_tls;

pub fn client() -> hyper::Client {
    let tls        = hyper_native_tls::NativeTlsClient::new().unwrap();
    let connector  = hyper::net::HttpsConnector::new(tls);
    hyper::Client::with_connector(connector)
}
<|endoftext|>


<commit_before><commit_msg>Split logging middleware into separate chain link calls.<commit_after><|endoftext|>


<commit_before><commit_msg>working feedforward<commit_after><|endoftext|>


<commit_before><commit_msg> #18 Fixed cursor visibility issues on OS X<commit_after><|endoftext|>


<commit_before>extern crate hyper;
extern crate time;

use hyper::Client;
use hyper::header::Connection;
use time::*;
use std::thread;
use std::sync::{Arc, Mutex};

struct Request {
    elapsed_time: f64
}

impl Request{
    fn new(elapsed_time: f64) -> Request{
        Request {
            elapsed_time: elapsed_time,
        }
    }
}

fn main() {
    let requests = Arc::new(Mutex::new(Vec::new()));
    let mut threads = Vec::new();

    for _x in 0..100 {
        println!("Spawning thread: {}", _x);

        let mut client = Client::new();
        let thread_items = requests.clone();

        let handle = thread::spawn(move || {
            for _y in 0..100 {
                println!("Firing requests: {}", _y);

                let start = time::precise_time_s();

                let _res = client.get("http://jacob.uk.com")
                    .header(Connection::close())
                    .send().unwrap();

                let end = time::precise_time_s();

                thread_items.lock().unwrap().push((Request::new(end-start)));
            }
        });

        threads.push(handle);
    }

    for t in threads.into_iter() {
        t.join();
    }
}
<commit_msg>Deps alphabetical<commit_after>extern crate hyper;
extern crate time;

use hyper::Client;
use hyper::header::Connection;
use std::sync::{Arc, Mutex};
use std::thread;
use time::*;

struct Request {
    elapsed_time: f64
}

impl Request{
    fn new(elapsed_time: f64) -> Request{
        Request {
            elapsed_time: elapsed_time,
        }
    }
}

fn main() {
    let requests = Arc::new(Mutex::new(Vec::new()));
    let mut threads = Vec::new();

    for _x in 0..100 {
        println!("Spawning thread: {}", _x);

        let mut client = Client::new();
        let thread_items = requests.clone();

        let handle = thread::spawn(move || {
            for _y in 0..100 {
                println!("Firing requests: {}", _y);

                let start = time::precise_time_s();

                let _res = client.get("http://jacob.uk.com")
                    .header(Connection::close())
                    .send().unwrap();

                let end = time::precise_time_s();

                thread_items.lock().unwrap().push((Request::new(end-start)));
            }
        });

        threads.push(handle);
    }

    for t in threads.into_iter() {
        t.join();
    }
}
<|endoftext|>


<commit_before><commit_msg>Add basic label support<commit_after><|endoftext|>


<commit_before><commit_msg>Create file when appending<commit_after><|endoftext|>


<commit_before><commit_msg>add new run-pass test weird_field_pos<commit_after>// Copyright (c) 2022 Yureka <yuka@yuka.dev>
//
// 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 pnet_macros;
extern crate pnet_macros_support;
use pnet_macros::packet;
use pnet_macros_support::types::*;

#[packet]
pub struct Test {
    banana: u2,
    apple: u4,
    potato: u6,
    the_rest: u20be,
    #[payload]
    payload: Vec<u8>,
}

fn main() {
    let test = Test {
        banana: 0b10,
        apple: 0b1010,
        potato: 0b101010,
        the_rest: 0b10101010101010101010,
        payload: vec![],
    };

    let mut buf = vec![0; TestPacket::packet_size(&test)];
    let mut packet = MutableTestPacket::new(&mut buf).unwrap();
    packet.populate(&test);
    assert_eq!(packet.get_banana(), test.banana);
    assert_eq!(packet.get_apple(), test.apple);
    assert_eq!(packet.get_potato(), test.potato);
    assert_eq!(packet.get_the_rest(), test.the_rest);
}
<|endoftext|>


<commit_before><commit_msg>Added from_fn constructor function for Matrix. (#43)<commit_after><|endoftext|>


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

// Crate use statements

#[cfg(bogus)]
use flippity;

#[cfg(bogus)]
static b: bool = false;

static b: bool = true;

mod rustrt {
    #[cfg(bogus)]
    extern {
        // This symbol doesn't exist and would be a link error if this
        // module was translated
        pub fn bogus();
    }

    extern {}
}

#[cfg(bogus)]
type t = isize;

type t = bool;

#[cfg(bogus)]
enum tg { foo, }

enum tg { bar, }

#[cfg(bogus)]
struct r {
  i: isize,
}

#[cfg(bogus)]
fn r(i:isize) -> r {
    r {
        i: i
    }
}

struct r {
  i: isize,
}

fn r(i:isize) -> r {
    r {
        i: i
    }
}

#[cfg(bogus)]
mod m {
    // This needs to parse but would fail in typeck. Since it's not in
    // the current config it should not be typechecked.
    pub fn bogus() { return 0; }
}

mod m {
    // Submodules have slightly different code paths than the top-level
    // module, so let's make sure this jazz works here as well
    #[cfg(bogus)]
    pub fn f() { }

    pub fn f() { }
}

// Since the bogus configuration isn't defined main will just be
// parsed, but nothing further will be done with it
#[cfg(bogus)]
pub fn main() { panic!() }

pub fn main() {
    // Exercise some of the configured items in ways that wouldn't be possible
    // if they had the bogus definition
    assert!((b));
    let _x: t = true;
    let _y: tg = tg::bar;

    test_in_fn_ctxt();
}

fn test_in_fn_ctxt() {
    #[cfg(bogus)]
    fn f() { panic!() }
    fn f() { }
    f();

    #[cfg(bogus)]
    static i: isize = 0;
    static i: isize = 1;
    assert_eq!(i, 1);
}

mod test_foreign_items {
    pub mod rustrt {
        extern {
            #[cfg(bogus)]
            pub fn write() -> String;
            pub fn write() -> String;
        }
    }
}

mod test_use_statements {
    #[cfg(bogus)]
    use flippity_foo;
}

mod test_methods {
    struct Foo {
        bar: usize
    }

    impl Fooable for Foo {
        #[cfg(bogus)]
        fn what(&self) { }

        fn what(&self) { }

        #[cfg(bogus)]
        fn the(&self) { }

        fn the(&self) { }
    }

    trait Fooable {
        #[cfg(bogus)]
        fn what(&self);

        fn what(&self);

        #[cfg(bogus)]
        fn the(&self);

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

// Crate use statements

#[cfg(bogus)]
use flippity;

#[cfg(bogus)]
static b: bool = false;

static b: bool = true;

mod rustrt {
    #[cfg(bogus)]
    extern {
        // This symbol doesn't exist and would be a link error if this
        // module was translated
        pub fn bogus();
    }

    extern {}
}

#[cfg(bogus)]
type t = isize;

type t = bool;

#[cfg(bogus)]
enum tg { foo, }

enum tg { bar, }

#[cfg(bogus)]
struct r {
  i: isize,
}

#[cfg(bogus)]
fn r(i:isize) -> r {
    r {
        i: i
    }
}

struct r {
  i: isize,
}

fn r(i:isize) -> r {
    r {
        i: i
    }
}

#[cfg(bogus)]
mod m {
    // This needs to parse but would fail in typeck. Since it's not in
    // the current config it should not be typechecked.
    pub fn bogus() { return 0; }
}

mod m {
    // Submodules have slightly different code paths than the top-level
    // module, so let's make sure this jazz works here as well
    #[cfg(bogus)]
    pub fn f() { }

    pub fn f() { }
}

// Since the bogus configuration isn't defined main will just be
// parsed, but nothing further will be done with it
#[cfg(bogus)]
pub fn main() { panic!() }

pub fn main() {
    // Exercise some of the configured items in ways that wouldn't be possible
    // if they had the bogus definition
    assert!((b));
    let _x: t = true;
    let _y: tg = tg::bar;

    test_in_fn_ctxt();
}

fn test_in_fn_ctxt() {
    #[cfg(bogus)]
    fn f() { panic!() }
    fn f() { }
    f();

    #[cfg(bogus)]
    static i: isize = 0;
    static i: isize = 1;
    assert_eq!(i, 1);
}

mod test_foreign_items {
    pub mod rustrt {
        extern {
            #[cfg(bogus)]
            pub fn write() -> String;
            pub fn write() -> String;
        }
    }
}

mod test_use_statements {
    #[cfg(bogus)]
    use flippity_foo;
}

mod test_methods {
    struct Foo {
        bar: usize
    }

    impl Fooable for Foo {
        #[cfg(bogus)]
        fn what(&self) { }

        fn what(&self) { }

        #[cfg(bogus)]
        fn the(&self) { }

        fn the(&self) { }
    }

    trait Fooable {
        #[cfg(bogus)]
        fn what(&self);

        fn what(&self);

        #[cfg(bogus)]
        fn the(&self);

        fn the(&self);
    }
}

#[cfg(any())]
mod nonexistent_file; // Check that unconfigured non-inline modules are not loaded or parsed.
<|endoftext|>


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

use core::pipes::*;

// tests that ctrl's type gets inferred properly
type command<K, V> = {key: K, val: V};

fn cache_server<K: Owned, V: Owned>(c: Chan<Chan<command<K, V>>>) {
    let (ctrl_port, ctrl_chan) = core::pipes::stream();
    c.send(ctrl_chan);
}
fn main() { }
<commit_msg>test: Attempt to fix Windows check-fast resolve bustage. rs=bustage<commit_after>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use core::pipes::*;

// tests that ctrl's type gets inferred properly
type command<K, V> = {key: K, val: V};

fn cache_server<K: Owned, V: Owned>(c: Chan<Chan<command<K, V>>>) {
    let (ctrl_port, ctrl_chan) = stream();
    c.send(ctrl_chan);
}
fn main() { }
<|endoftext|>


<commit_before><commit_msg>Add code for health-statistics<commit_after>pub struct User {
    name: String,
    age: u32,
    weight: f32,
}

impl User {
    pub fn new(name: String, age: u32, weight: f32) -> Self {
        User { name, age, weight }
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn age(&self) -> u32 {
        self.age
    }

    pub fn weight(&self) -> f32 {
        self.weight
    }

    pub fn set_age(&mut self, new_age: u32) {
        self.age = new_age
    }

    pub fn set_weight(&mut self, new_weight: f32) {
        self.weight = new_weight
    }
}
<|endoftext|>


<commit_before><commit_msg>Add french example<commit_after>extern crate crowbook_text_processing;
use crowbook_text_processing::french::FrenchFormatter;
use std::borrow::Cow;

// Code to end shell colouring
pub const SHELL_COLOUR_OFF: &'static str = "\x1B[0m";
pub const SHELL_COLOUR_RED: &'static str = "\x1B[1m\x1B[31m";
pub const SHELL_COLOUR_BLUE: &'static str = "\x1B[1m\x1B[36m";
pub const SHELL_COLOUR_ORANGE: &'static str = "\x1B[1m\x1B[33m";
pub const SHELL_COLOUR_GREEN: &'static str = "\x1B[1m\x1B[32m";

fn display_spaces(s: &str) {
    let mut res = String::with_capacity(s.len());
    let nb_char = ' ';
    let nb_char_narrow = '\u{202F}'; // narrow non breaking space
    let nb_char_em = '\u{2002}'; // demi em space

    for c in s.chars() {
        if c == nb_char {
            res.push_str(&format!("{}{}{}",
                                  SHELL_COLOUR_ORANGE,
                                  '_',
                                  SHELL_COLOUR_OFF));
        } else if c == nb_char_narrow {
            res.push_str(&format!("{}{}{}",
                                  SHELL_COLOUR_BLUE,
                                  '_',
                                  SHELL_COLOUR_OFF));
        } else if c == nb_char_em {
            res.push_str(&format!("{}{}{}",
                                  SHELL_COLOUR_RED,
                                  '_',
                                  SHELL_COLOUR_OFF));
        } else {
            res.push(c);
        }
    }
    println!("{}\n\n", res);
}

fn main() {
    let french = FrenchFormatter::new();
    let s = Cow::Borrowed("10 000 €");
    display_spaces(french.format(s).as_ref());

    let s = Cow::Borrowed("10 000 EUR");
    display_spaces(french.format(s).as_ref());

    let s = Cow::Borrowed("10 000 EUROS");
    display_spaces(french.format(s).as_ref());

    let s = Cow::Borrowed("10 000 fr");
    display_spaces(french.format(s).as_ref());

    let s = Cow::Borrowed("tiret cadratin en début : espace insécable non justifiante, pour que les dialogues restent alignés");
    display_spaces(french.format(s).as_ref());

    let s = Cow::Borrowed(r#"– tiret non cadratin en début : question délicate, est-ce l'ouverture
d'un dialogue ? une liste ? cela dit ce n'est pas a priori l'usage
normal d'un tiret non cadratin suivi d'espace, qui est..."#);
    display_spaces(french.format(s).as_ref());

    let s = Cow::Borrowed(r#"l'angoisse : l'incise. J'ai bien aimé ce film — pas vous ? Là, il semblerait logique de mettre une espace insécable après le tiret. Mais il faut en mettre une avant lorsque ça se referme — comme ça —, sauf
qu'on ne peut pas juste compter les tirets parce que des fois une
incise n'est pas refermée par un tiret — comme en fin de phrase. Le
problème c'est qu'il est dur de trouver des règles simples — repérer
un point n'est pas suffisant, M. le petit malin ! — et qu'au final
avoir une règle qui marche à cent pour cent nécessiterait de l'analyse
syntaxique assez poussée – ce qui va au-delà des prétentions de mon logiciel.."#);
    display_spaces(french.format(s).as_ref());

    let s = Cow::Borrowed(r#"« en début : on pourrait aussi avoir une espace insécable non justifiante, mais de fait l'alignement sera de toute façon rompu car
suivi en général par tiret cadratin. Il faut juste éviter l'espace
fine, qui colle un peu trop le guillemet au dialogue..."#);
    display_spaces(french.format(s).as_ref());

    let s = Cow::Borrowed(r#"— par contre », objecta-t-elle, « il serait bien que si le premier guillemet fermant apparaît sans ouvrant, on en conclut qu'il s'agissait d'un dialogue »"#);
    display_spaces(french.format(s).as_ref());

    let s = Cow::Borrowed(r#"Un « guillemet » pas en début : là, par contre, l'espace insécable fine est bien,
parce que c'est pas terrible d'avoir de grand espaces quand « on » met
un mot entre guillemets"#);
    display_spaces(french.format(s).as_ref());
}
<|endoftext|>


<commit_before><commit_msg>examples: add little cmdline lipsum generator<commit_after>extern crate lipsum;

use std::env;

fn main() {
    // First command line argument or "" if not supplied.
    let arg = env::args().skip(1).next().unwrap_or_default();
    // Number of words to generate.
    let n = arg.parse().unwrap_or(25);
    // Print n words of lorem ipsum text.
    println!("{}", lipsum::lipsum(n));
}
<|endoftext|>


<commit_before>use std::net::{ToSocketAddrs, TcpListener, TcpStream};
use std::io::{Read, Write};
use std::thread;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{Sender, channel};

use super::command::command;
use super::database::Database;
use super::parser::parse;
use super::parser::ParseError;

pub struct Client {
    pub stream: TcpStream,
    pub db: Arc<Mutex<Database>>
}

pub struct Server<A: ToSocketAddrs + Clone> {
    pub addr: A,
    pub db: Arc<Mutex<Database>>,
    pub listener_channel: Option<Sender<u8>>,
    pub listener_thread: Option<thread::JoinHandle>,
}

impl Client {
    pub fn new(stream: TcpStream, db: Arc<Mutex<Database>>) -> Client {
        return Client {
            stream: stream,
            db: db,
        }
    }

    pub fn run(&mut self) {
        let mut buffer = [0u8; 512];
        loop {
            let result = self.stream.read(&mut buffer);
            if result.is_err() {
                break;
            }
            let len = result.unwrap();
            if len == 0 {
                break;
            }
            let try_parser = parse(&buffer, len);
            if try_parser.is_err() {
                let err = try_parser.unwrap_err();
                match err {
                    ParseError::BadProtocol => { break; }
                    ParseError::Incomplete => { continue; }
                };
            }
            let parser = try_parser.unwrap();
            let mut db = self.db.lock().unwrap();
            let response = command(&parser, &mut *db);
            let writeres = self.stream.write(&*response.as_bytes());
            if writeres.is_err() {
                break;
            }
        };
    }
}

impl<A: ToSocketAddrs + Clone> Server<A> {
    pub fn new(addr: A) -> Server<A> {
        return Server {
            addr: addr,
            db: Arc::new(Mutex::new(Database::new())),
            listener_channel: None,
            listener_thread: None,
        }
    }

    fn get_listener(&self) -> TcpListener {
        return TcpListener::bind(self.addr.clone()).unwrap();
    }

    pub fn run(&mut self) {
        self.start();
        self.join();
    }

    pub fn join(&mut self) {
        #![allow(unused_must_use)]
        match self.listener_thread.take() {
            Some(th) => { th.join(); },
            _ => {},
        }
    }

    pub fn start(&mut self) {
        let listener = self.get_listener();
        let db = self.db.clone();
        let (tx, rx) = channel();
        self.listener_channel = Some(tx);
        let th =  thread::spawn(move || {
            for stream in listener.incoming() {
                if rx.try_recv().is_ok() {
                    // any new message should break
                    break;
                }
                match stream {
                    Ok(stream) => {
                        let db1 = db.clone();
                        thread::spawn(move || {
                            let mut client = Client::new(stream, db1);
                            client.run();
                        });
                    }
                    Err(e) => { println!("error {}", e); }
                }
            }
        });
        self.listener_thread = Some(th);
    }

    pub fn stop(&mut self) {
        #![allow(unused_must_use)]
        match self.listener_channel {
            Some(ref sender) => {
                sender.send(0);
                for addrs in self.addr.to_socket_addrs().unwrap() {
                    TcpStream::connect(addrs);
                }
            },
            _ => {},
        }
        self.join();
    }
}
<commit_msg>Move socket write into a separate thread<commit_after>use std::net::{ToSocketAddrs, TcpListener, TcpStream};
use std::io::{Read, Write};
use std::thread;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{Sender, channel};

use super::command::command;
use super::command::Response;
use super::database::Database;
use super::parser::parse;
use super::parser::ParseError;

pub struct Client {
    pub stream: TcpStream,
    pub db: Arc<Mutex<Database>>
}

pub struct Server<A: ToSocketAddrs + Clone> {
    pub addr: A,
    pub db: Arc<Mutex<Database>>,
    pub listener_channel: Option<Sender<u8>>,
    pub listener_thread: Option<thread::JoinHandle>,
}

impl Client {
    pub fn new(stream: TcpStream, db: Arc<Mutex<Database>>) -> Client {
        return Client {
            stream: stream,
            db: db,
        }
    }

    pub fn run(&mut self) {
        #![allow(unused_must_use)]
        let (tx, rx) = channel();
        {
            let mut stream = self.stream.try_clone().unwrap();
            thread::spawn(move || {
                loop {
                    let try_recv = rx.recv();
                    if try_recv.is_err() {
                        break;
                    }
                    let msg:Response = try_recv.unwrap();
                    let resp = msg.as_bytes();
                    stream.write(&*resp);
                }
            });
        }
        let mut buffer = [0u8; 512];
        loop {
            let result = self.stream.read(&mut buffer);
            if result.is_err() {
                break;
            }
            let len = result.unwrap();
            if len == 0 {
                break;
            }
            let try_parser = parse(&buffer, len);
            if try_parser.is_err() {
                let err = try_parser.unwrap_err();
                match err {
                    ParseError::BadProtocol => { break; }
                    ParseError::Incomplete => { continue; }
                };
            }
            let parser = try_parser.unwrap();
            let mut db = self.db.lock().unwrap();
            let response = command(&parser, &mut *db);
            if tx.send(response).is_err() {
                // TODO: send a kill signal to the writer thread?
                break;
            }
        };
    }
}

impl<A: ToSocketAddrs + Clone> Server<A> {
    pub fn new(addr: A) -> Server<A> {
        return Server {
            addr: addr,
            db: Arc::new(Mutex::new(Database::new())),
            listener_channel: None,
            listener_thread: None,
        }
    }

    fn get_listener(&self) -> TcpListener {
        return TcpListener::bind(self.addr.clone()).unwrap();
    }

    pub fn run(&mut self) {
        self.start();
        self.join();
    }

    pub fn join(&mut self) {
        #![allow(unused_must_use)]
        match self.listener_thread.take() {
            Some(th) => { th.join(); },
            _ => {},
        }
    }

    pub fn start(&mut self) {
        let listener = self.get_listener();
        let db = self.db.clone();
        let (tx, rx) = channel();
        self.listener_channel = Some(tx);
        let th =  thread::spawn(move || {
            for stream in listener.incoming() {
                if rx.try_recv().is_ok() {
                    // any new message should break
                    break;
                }
                match stream {
                    Ok(stream) => {
                        let db1 = db.clone();
                        thread::spawn(move || {
                            let mut client = Client::new(stream, db1);
                            client.run();
                        });
                    }
                    Err(e) => { println!("error {}", e); }
                }
            }
        });
        self.listener_thread = Some(th);
    }

    pub fn stop(&mut self) {
        #![allow(unused_must_use)]
        match self.listener_channel {
            Some(ref sender) => {
                sender.send(0);
                for addrs in self.addr.to_socket_addrs().unwrap() {
                    TcpStream::connect(addrs);
                }
            },
            _ => {},
        }
        self.join();
    }
}
<|endoftext|>


<commit_before><commit_msg>small test for extern_type<commit_after>#![feature(extern_types)]

extern {
    type Foo;
}

fn main() {
    let x: &Foo = unsafe { &*(16 as *const Foo) };
    let _y: &Foo = &*x;
}
<|endoftext|>


<commit_before><commit_msg>added morton.rs<commit_after>
// 21.21.21-bit morton codes: 63 bits total, largest that can fit in uint64_t
// 10.10.10-bit morton codes: 30 bits total, largest that can fit in uint32_t
// 7.7.7-bit morton codes: 21 bits total, components can be computed simultaneously in uint64_t
// 5.5.5-bit morton codes: 15 bits total, largest that can fit in uint16_t

#![feature(zero_one)]
extern crate num;

use std::ops::{Add, Sub, BitAnd, BitOr, Not};
use std::cmp::PartialOrd;

pub const MORTON3_21_X: u64 = 0x1249249249249249;
pub const MORTON3_21_Y: u64 = MORTON3_21_X << 1;
pub const MORTON3_21_Z: u64 = MORTON3_21_X << 2;
pub const MORTON3_21_MASK: u64 = MORTON3_21_X | MORTON3_21_Y | MORTON3_21_Z;

pub const MORTON3_7_X: u32 = 0x00049249;
pub const MORTON3_7_Y: u32 = MORTON3_7_X << 1;
pub const MORTON3_7_Z: u32 = MORTON3_7_X << 2;
pub const MORTON3_7_MASK: u32 = MORTON3_7_X | MORTON3_7_Y | MORTON3_7_Z;

pub const MORTON3_5_X: u16 = 0x1249;
pub const MORTON3_5_Y: u16 = MORTON3_5_X << 1;
pub const MORTON3_5_Z: u16 = MORTON3_5_X << 2;
pub const MORTON3_5_MASK: u16 = MORTON3_5_X | MORTON3_5_Y | MORTON3_5_Z;

pub fn spread2_16(x0: u32) -> u32 {
    //              0b00000000_00000000_11111111_11111111
    let x1 = ((x0 & 0b00000000_00000000_11111111_00000000) << 8) | (x0 & 0b00000000_00000000_00000000_11111111);
    //              0b00000000_11111111_00000000_11111111
    let x2 = ((x1 & 0b00000000_11110000_00000000_11110000) << 4) | (x1 & 0b00000000_00001111_00000000_00001111);
    //              0b00001111_00001111_00001111_00001111
    let x3 = ((x2 & 0b00001100_00001100_00001100_00001100) << 2) | (x2 & 0b00000011_00000011_00000011_00000011);
    //              0b00110011_00110011_00110011_00110011
             ((x3 & 0b00100010_00100010_00100010_00100010) << 1) | (x3 & 0b00010001_00010001_00010001_00010001)
    //              0b01010101_01010101_01010101_01010101
}

pub fn unspread2_16(x0: u32) -> u32 {
    //              0b01010101_01010101_01010101_01010101
    let x1 = ((x0 & 0b01000100_01000100_01000100_01000100) >> 1) | (x0 & 0b00010001_00010001_00010001_00010001);
    //              0b00110011_00110011_00110011_00110011
    let x2 = ((x1 & 0b00110000_00110000_00110000_00110000) >> 2) | (x1 & 0b00000011_00000011_00000011_00000011);
    //              0b00001111_00001111_00001111_00001111
    let x3 = ((x2 & 0b00001111_00000000_00001111_00000000) >> 4) | (x2 & 0b00000000_00001111_00000000_00001111);
    //              0b00000000_11111111_00000000_11111111
             ((x3 & 0b00000000_11111111_00000000_00000000) >> 8) | (x3 & 0b00000000_00000000_00000000_11111111)
    //              0b00000000_00000000_11111111_11111111
}

pub fn spread3_21(x: u32) -> u64 {
    // 0b0000000000000000000000000000000000000000000111111111111111111111
    // 0b0000000000000000000000011111111111000000000000000000001111111111
    // 0b0000000000000111111000000000011111000000000011111000000000011111
    // 0b0000000111000000111000011000000111000011000000111000011000000111
    // 0b0001000011001000011000011001000011000011001000011000011001000011
    // 0b0001001001001001001001001001001001001001001001001001001001001001
    let x0 = x as u64;
    let x1 = ((x0 & 0x00000000001FFC00) << 20) | (x0 & 0x00000000000003FF);
    let x2 = ((x1 & 0x000001F8000003E0) << 10) | (x1 & 0x00000007C000001F);
    let x3 = ((x2 & 0x00070006000C0018) << 6)  | (x2 & 0x0000E001C0038007);
    let x4 = ((x3 & 0x0100800100020004) << 4)  | (x3 & 0x00C06180C3018603);
             ((x4 & 0x0080410082010402) << 2)  | (x4 & 0x1048209041208241)
}

pub fn unspread3_21(x0: u64) -> u32 {
    // 0b0001001001001001001001001001001001001001001001001001001001001001
    // 0b0001000011001000011000011001000011000011001000011000011001000011
    // 0b0000000111000000111000011000000111000011000000111000011000000111
    // 0b0000000000000111111000000000011111000000000011111000000000011111
    // 0b0000000000000000000000011111111111000000000000000000001111111111
    // 0b0000000000000000000000000000000000000000000111111111111111111111
    let x1 = ((x0 & 0x0201040208041008) >> 2)  | (x0 & 0x1048209041208241);
    let x2 = ((x1 & 0x1008001000200040) >> 4)  | (x1 & 0x00C06180C3018603);
    let x3 = ((x2 & 0x01C0018003000600) >> 6)  | (x2 & 0x0000E001C0038007);
    let x4 = ((x3 & 0x0007E000000F8000) >> 10) | (x3 & 0x00000007C000001F);
             (((x4 & 0x000001FFC0000000) >> 20) | (x4 & 0x00000000000003FF)) as u32
}

// Spread each bit of input out to every third bit of the output. This spreads the 5
// least-significant bits of the input into a 15-bit result.
pub fn spread3_5(x0: u16) -> u16 {
    // 0b0000000000011111
    let x1 = ((x0 & 0x0018) << 6) | (x0 & 0x0007);
    // 0b0000011000000111
    let x2 = ((x1 & 0x0004) << 4) | (x1 & 0x8603);
    // 0b0000011001000011
             ((x2 & 0x0402) << 2) | (x2 & 0x8241)
    // 0b0001001001001001
}

// A wide version of SpreadBits3_15(), operating on 4 input values at once.
// Intended for byte-packed coordinates.
pub fn spread3_5x4(x0: u64) -> u64 {
    // 0b0000000000011111 0000000000011111 0000000000011111 0000000000011111
    let x1 = ((x0 & 0x0018001800180018) << 6) | (x0 & 0x0007000700070007);
    // 0b0000011000000111 0000011000000111 0000011000000111 0000011000000111
    let x2 = ((x1 & 0x0004000400040004) << 4) | (x1 & 0x8603860386038603);
    // 0b0000011001000011 0000011001000011 0000011001000011 0000011001000011
             ((x2 & 0x0402040204020402) << 2) | (x2 & 0x8241824182418241)
    // 0b0001001001001001 0001001001001001 0001001001001001 0001001001001001
}

// Convert to and from Morton numbers.
// Naming convention is (morton|unmorton)(DIM)d(SIZE), where DIM is the number of dimensions and
// SIZE is the total number of bits for all components.

// Generate 16.16-bit Morton code
pub fn morton2d32(x: u32, y: u32) -> u32 {
    spread2_16(x) | (spread2_16(y) << 1)
}

pub fn unmorton2d32(x: u32) -> (u32, u32) {
    (unspread2_16(x & 0b01010101_01010101_01010101_01010101),
     unspread2_16((x & 0b10101010_10101010_10101010_10101010) >> 1))
}

// Generate 21.21.21-bit Morton code
pub fn morton3d63(x: u32, y: u32, z: u32) -> u64 {
    spread3_21(x) | (spread3_21(y) << 1) | (spread3_21(z) << 2)
}

pub fn unmorton3d63(m: u64) -> (u32, u32, u32) {
    (unspread3_21(m & MORTON3_21_X),
     unspread3_21((m & MORTON3_21_Y) >> 1),
     unspread3_21((m & MORTON3_21_Z) >> 2))
}

// Generate 7.7.7-bit Morton code
pub fn morton3d21(x: u32, y: u32, z: u32) -> u32 {
    let tmp = spread3_21((z << 14) | (y << 7) | x);
    (((tmp >> 42) | (tmp >> 21) | tmp) & 0x1FFFFF) as u32
}

pub fn unmorton3d21(m: u32) -> (u32, u32, u32) {
    let m64 = m as u64;
    let tmp = unspread3_21(((m64 & MORTON3_21_X) << 42) | ((m64 & MORTON3_21_Y) << 21) | (m64 & MORTON3_21_X));
    (tmp & 0x7F, (tmp >> 7) & 0x7F, (tmp >> 14) & 0x7F)
}

// Mathematical operations on Morton numbers.
fn morton_inc<T>(m: T, dim: T) -> T
    where T: Add<Output = T> + BitAnd<Output = T> + BitOr<Output = T> + Not<Output = T> +
        num::traits::Num + Copy
{
    (((m | !dim) + T::one() & dim) | (m & !dim))
}

fn morton_dec<T>(m: T, dim: T) -> T
    where T: Add<Output = T> + BitAnd<Output = T> + BitOr<Output = T> + Not<Output = T> +
        num::traits::Num + Copy
{
    (((m & dim) - T::one()) & dim) | (m & !dim)
}

fn morton_neq<T>(l: T, r: T, dim: T) -> bool
    where T: BitAnd<Output = T> + num::traits::Num + Copy + PartialOrd
{
    (l & dim) != (r & dim)
}

fn morton_eq<T> (l: T, r: T, dim: T) -> bool
    where T: BitAnd<Output = T> + num::traits::Num + Copy + PartialOrd
{
    (l & dim) == (r & dim)
}

fn morton_lt<T> (l: T, r: T, dim: T) -> bool
    where T: BitAnd<Output = T> + num::traits::Num + Copy + PartialOrd
{
    (l & dim) < (r & dim)
}

fn morton_gt<T> (l: T, r: T, dim: T) -> bool
    where T: BitAnd<Output = T> + num::traits::Num + Copy + PartialOrd
{
    (l & dim) > (r & dim)
}

<|endoftext|>


<commit_before><commit_msg>Buffer output of env for speed<commit_after><|endoftext|>


<commit_before><commit_msg>Fix small typo<commit_after><|endoftext|>


<commit_before><commit_msg>redoc BTree::find<commit_after><|endoftext|>


<commit_before>use std::process::{Command,Output};

pub struct InstructionOut {
    pub stdout: String,
    pub stderr: String,
}

pub fn run(input_command: Vec<&str>) -> Option<InstructionOut> {
    let args = input_command.as_slice();
    let length = args.len();
    let output: Option<Output>;
    if length ==0 {
        output = Command::new("").output().ok();
    } else if length ==  1 {
        output = Command::new(&args[0]).output().ok();
    } else {
        output = Command::new(&args[0]).args(&args[1..]).output().ok();
    };
    if output.is_some() {
        let output = output.unwrap();
        Some(InstructionOut {
            stdout: String::from_utf8(output.stdout).ok().expect("No stdout"),
            stderr: String::from_utf8(output.stderr).ok().expect("No stderr"),
        })
    } else {
        None
    }
}
<commit_msg>Changed if else in run function<commit_after>use std::process::{Command,Output};

pub struct InstructionOut {
    pub stdout: String,
    pub stderr: String,
}

pub fn run(input_command: Vec<&str>) -> Option<InstructionOut> {
    let args = input_command.as_slice();
    let output: Option<Output>;
    match args.len() {
        0 => output = Command::new("").output().ok(),
        1 => output = Command::new(&args[0]).output().ok(),
        _ => output = Command::new(&args[0]).args(&args[1..]).output().ok(),
    }
    if output.is_some() {
        let output = output.unwrap();
        Some(InstructionOut {
            stdout: String::from_utf8(output.stdout).ok().expect("No stdout"),
            stderr: String::from_utf8(output.stderr).ok().expect("No stderr"),
        })
    } else {
        None
    }
}
<|endoftext|>


<commit_before><commit_msg>Add enum specifying commands<commit_after>pub enum Command {
    Output,
    Input,
    Increment,
    Decrement,
    RightShift,
    LeftShift
}
<|endoftext|>


<commit_before><commit_msg>Block ids are unsigned.<commit_after><|endoftext|>


<commit_before>// run-pass
// ignore-wasm
// ignore-wasm32
// ignore-cloudabi no processes
// ignore-emscripten no processes

// Tests ensuring that `dbg!(expr)` has the expected run-time behavior.
// as well as some compile time properties we expect.

#![feature(dbg_macro)]

#[derive(Copy, Clone, Debug)]
struct Unit;

#[derive(Copy, Clone, Debug, PartialEq)]
struct Point<T> {
    x: T,
    y: T,
}

#[derive(Debug, PartialEq)]
struct NoCopy(usize);

fn test() {
    let a: Unit = dbg!(Unit);
    let _: Unit = dbg!(a);
    // We can move `a` because it's Copy.
    drop(a);

    // `Point<T>` will be faithfully formatted according to `{:#?}`.
    let a = Point { x: 42, y: 24 };
    let b: Point<u8> = dbg!(Point { x: 42, y: 24 }); // test stringify!(..)
    let c: Point<u8> = dbg!(b);
    // Identity conversion:
    assert_eq!(a, b);
    assert_eq!(a, c);
    // We can move `b` because it's Copy.
    drop(b);

    // Test that we can borrow and that successive applications is still identity.
    let a = NoCopy(1337);
    let b: &NoCopy = dbg!(dbg!(&a));
    assert_eq!(&a, b);

    // Test involving lifetimes of temporaries:
    fn f<'a>(x: &'a u8) -> &'a u8 { x }
    let a: &u8 = dbg!(f(&42));
    assert_eq!(a, &42);

    // Test side effects:
    let mut foo = 41;
    assert_eq!(7331, dbg!({
        foo += 1;
        eprintln!("before");
        7331
    }));
    assert_eq!(foo, 42);
}

fn validate_stderr(stderr: Vec<String>) {
    assert_eq!(stderr, &[
        ":22] Unit = Unit",

        ":23] a = Unit",

        ":29] Point{x: 42, y: 24,} = Point {",
        "    x: 42,",
        "    y: 24",
        "}",

        ":30] b = Point {",
        "    x: 42,",
        "    y: 24",
        "}",

        ":39] &a = NoCopy(",
        "    1337",
        ")",

        ":39] dbg!(& a) = NoCopy(",
        "    1337",
        ")",
        ":44] f(&42) = 42",

        "before",
        ":49] { foo += 1; eprintln!(\"before\"); 7331 } = 7331",
    ]);
}

fn main() {
    // The following is a hack to deal with compiletest's inability
    // to check the output (to stdout) of run-pass tests.
    use std::env;
    use std::process::Command;

    let mut args = env::args();
    let prog = args.next().unwrap();
    let child = args.next();
    if let Some("child") = child.as_ref().map(|s| &**s) {
        // Only run the test if we've been spawned as 'child'
        test()
    } else {
        // This essentially spawns as 'child' to run the tests
        // and then it collects output of stderr and checks the output
        // against what we expect.
        let out = Command::new(&prog).arg("child").output().unwrap();
        assert!(out.status.success());
        assert!(out.stdout.is_empty());

        let stderr = String::from_utf8(out.stderr).unwrap();
        let stderr = stderr.lines().map(|mut s| {
            if s.starts_with("[") {
                // Strip `[` and file path:
                s = s.trim_start_matches("[");
                assert!(s.starts_with(file!()));
                s = s.trim_start_matches(file!());
            }
            s.to_owned()
        }).collect();

        validate_stderr(stderr);
    }
}
<commit_msg>dbg_macro: only ignore cloudabi and emscripten<commit_after>// run-pass
// ignore-cloudabi no processes
// ignore-emscripten no processes

// Tests ensuring that `dbg!(expr)` has the expected run-time behavior.
// as well as some compile time properties we expect.

#![feature(dbg_macro)]

#[derive(Copy, Clone, Debug)]
struct Unit;

#[derive(Copy, Clone, Debug, PartialEq)]
struct Point<T> {
    x: T,
    y: T,
}

#[derive(Debug, PartialEq)]
struct NoCopy(usize);

fn test() {
    let a: Unit = dbg!(Unit);
    let _: Unit = dbg!(a);
    // We can move `a` because it's Copy.
    drop(a);

    // `Point<T>` will be faithfully formatted according to `{:#?}`.
    let a = Point { x: 42, y: 24 };
    let b: Point<u8> = dbg!(Point { x: 42, y: 24 }); // test stringify!(..)
    let c: Point<u8> = dbg!(b);
    // Identity conversion:
    assert_eq!(a, b);
    assert_eq!(a, c);
    // We can move `b` because it's Copy.
    drop(b);

    // Test that we can borrow and that successive applications is still identity.
    let a = NoCopy(1337);
    let b: &NoCopy = dbg!(dbg!(&a));
    assert_eq!(&a, b);

    // Test involving lifetimes of temporaries:
    fn f<'a>(x: &'a u8) -> &'a u8 { x }
    let a: &u8 = dbg!(f(&42));
    assert_eq!(a, &42);

    // Test side effects:
    let mut foo = 41;
    assert_eq!(7331, dbg!({
        foo += 1;
        eprintln!("before");
        7331
    }));
    assert_eq!(foo, 42);
}

fn validate_stderr(stderr: Vec<String>) {
    assert_eq!(stderr, &[
        ":22] Unit = Unit",

        ":23] a = Unit",

        ":29] Point{x: 42, y: 24,} = Point {",
        "    x: 42,",
        "    y: 24",
        "}",

        ":30] b = Point {",
        "    x: 42,",
        "    y: 24",
        "}",

        ":39] &a = NoCopy(",
        "    1337",
        ")",

        ":39] dbg!(& a) = NoCopy(",
        "    1337",
        ")",
        ":44] f(&42) = 42",

        "before",
        ":49] { foo += 1; eprintln!(\"before\"); 7331 } = 7331",
    ]);
}

fn main() {
    // The following is a hack to deal with compiletest's inability
    // to check the output (to stdout) of run-pass tests.
    use std::env;
    use std::process::Command;

    let mut args = env::args();
    let prog = args.next().unwrap();
    let child = args.next();
    if let Some("child") = child.as_ref().map(|s| &**s) {
        // Only run the test if we've been spawned as 'child'
        test()
    } else {
        // This essentially spawns as 'child' to run the tests
        // and then it collects output of stderr and checks the output
        // against what we expect.
        let out = Command::new(&prog).arg("child").output().unwrap();
        assert!(out.status.success());
        assert!(out.stdout.is_empty());

        let stderr = String::from_utf8(out.stderr).unwrap();
        let stderr = stderr.lines().map(|mut s| {
            if s.starts_with("[") {
                // Strip `[` and file path:
                s = s.trim_start_matches("[");
                assert!(s.starts_with(file!()));
                s = s.trim_start_matches(file!());
            }
            s.to_owned()
        }).collect();

        validate_stderr(stderr);
    }
}
<|endoftext|>