<commit_before>use redox::{Box, String};
use redox::collections::VecDeque;
use redox::ops::DerefMut;

use orbital::{Color, Point, Size, Event, KeyEvent, MouseEvent, QuitEvent};

use super::display::Display;
use super::scheduler;

/// A window
pub struct Window {
    /// The position of the window
    pub point: Point,
    /// The size of the window
    pub size: Size,
    /// The title of the window
    pub title: String,
    /// The content of the window
    pub content: Box<Display>,
    /// The color of the window title
    pub title_color: Color,
    /// The color of the border
    pub border_color: Color,
    /// Is the window focused?
    pub focused: bool,
    /// Is the window minimized?
    pub minimized: bool,
    dragging: bool,
    last_mouse_event: MouseEvent,
    events: VecDeque<Event>,
    ptr: *mut Window,
}

impl Window {
    /// Create a new window
    pub fn new(point: Point, size: Size, title: String) -> Box<Self> {
        let mut ret = box Window {
            point: point,
            size: size,
            title: title,
            content: Display::new(size.width, size.height),
            title_color: Color::rgb(255, 255, 255),
            border_color: Color::rgba(64, 64, 64, 128),
            focused: false,
            minimized: false,
            dragging: false,
            last_mouse_event: MouseEvent {
                x: 0,
                y: 0,
                left_button: false,
                right_button: false,
                middle_button: false,
            },
            events: VecDeque::new(),
            ptr: 0 as *mut Window,
        };

        unsafe {
            ret.ptr = ret.deref_mut();

            if ret.ptr as usize > 0 {
                (*super::session_ptr).add_window(ret.ptr);
            }
        }

        ret
    }

    /// Poll the window (new)
    pub fn poll(&mut self) -> Option<Event> {
        let event_option;
        unsafe {
            let reenable = scheduler::start_no_ints();
            event_option = self.events.pop_front();
            scheduler::end_no_ints(reenable);
        }
        return event_option;
    }

    /// Redraw the window
    pub fn redraw(&mut self) {
        unsafe {
            let reenable = scheduler::start_no_ints();
            self.content.flip();
            (*super::session_ptr).redraw = true;
            scheduler::end_no_ints(reenable);
        }
    }

    /// Draw the window using a `Display`
    pub fn draw(&mut self, display: &Display, font: usize) {
        if self.focused {
            self.border_color = Color::rgba(128, 128, 128, 192);
        } else {
            self.border_color = Color::rgba(64, 64, 64, 128);
        }

        if self.minimized {
            self.title_color = Color::rgb(0, 0, 0);
        } else {
            self.title_color = Color::rgb(255, 255, 255);

            display.rect(Point::new(self.point.x - 2, self.point.y - 18),
                         Size::new(self.size.width + 4, 18),
                         self.border_color);

            let mut cursor = Point::new(self.point.x, self.point.y - 17);
            for c in self.title.chars() {
                if cursor.x + 8 <= self.point.x + self.size.width as isize {
                    display.char(cursor, c, self.title_color, font);
                }
                cursor.x += 8;
            }

            display.rect(Point::new(self.point.x - 2, self.point.y),
                         Size::new(2, self.size.height),
                         self.border_color);
            display.rect(Point::new(self.point.x - 2,
                                    self.point.y + self.size.height as isize),
                         Size::new(self.size.width + 4, 2),
                         self.border_color);
            display.rect(Point::new(self.point.x + self.size.width as isize,
                                    self.point.y),
                         Size::new(2, self.size.height),
                         self.border_color);

            unsafe {
                let reenable = scheduler::start_no_ints();
                display.image(self.point,
                              self.content.onscreen as *const Color,
                              Size::new(self.content.width, self.content.height));
                scheduler::end_no_ints(reenable);
            }
        }
    }

    /// Called on key press
    pub fn on_key(&mut self, key_event: KeyEvent) {
        unsafe {
            let reenable = scheduler::start_no_ints();
            self.events.push_back(key_event.to_event());
            scheduler::end_no_ints(reenable);
        }
    }

    fn on_window_decoration(&self, x: isize, y: isize) -> bool {
        !self.minimized && x >= -2 &&
            x < self.size.width as isize + 4 &&
            y >= -18 &&
            y < 0
    }

    fn on_window_body(&self, x: isize, y: isize) -> bool {
        !self.minimized && x >= 0 &&
            x < self.size.width as isize &&
            y >= 0 &&
            y < self.size.height as isize
    }

    /// Called on mouse movement
    pub fn on_mouse(&mut self, orig_mouse_event: MouseEvent, allow_catch: bool) -> bool {
        let mut mouse_event = orig_mouse_event;

        mouse_event.x -= self.point.x;
        mouse_event.y -= self.point.y;

        let mut caught = false;

        if allow_catch {
            if mouse_event.left_button {
                if self.on_window_body(mouse_event.x, mouse_event.y) {
                    caught = true;
                }else if self.on_window_decoration(mouse_event.x, mouse_event.y) {
                    caught = true;
                    if !self.last_mouse_event.left_button {
                        self.dragging = true;
                    }
                }
            } else {
                self.dragging = false;
            }

            if mouse_event.right_button {
                if self.on_window_body(mouse_event.x, mouse_event.y) {
                    caught = true;
                }else if self.on_window_decoration(mouse_event.x, mouse_event.y) {
                    caught = true;
                    if !self.last_mouse_event.right_button {
                        self.minimized = !self.minimized;
                    }
                }
            }

            if mouse_event.middle_button {
                if self.on_window_body(mouse_event.x, mouse_event.y) {
                    caught = true;
                }else if self.on_window_decoration(mouse_event.x, mouse_event.y) {
                    caught = true;
                    unsafe {
                        let reenable = scheduler::start_no_ints();
                        self.events.push_back(QuitEvent.to_event());
                        scheduler::end_no_ints(reenable);
                    }
                }
            }

            if self.dragging {
                self.point.x += orig_mouse_event.x - self.last_mouse_event.x;
                self.point.y += orig_mouse_event.y - self.last_mouse_event.y;
                caught = true;
            }
        } else {
            self.dragging = false;
        }

        self.last_mouse_event = orig_mouse_event;

        if (caught && !self.dragging) || self.on_window_body(mouse_event.x, mouse_event.y) {
            unsafe {
                let reenable = scheduler::start_no_ints();
                self.events.push_back(mouse_event.to_event());
                scheduler::end_no_ints(reenable);
            }
        }

        caught
    }
}

impl Drop for Window {
    fn drop(&mut self) {
        unsafe {
            if self.ptr as usize > 0 {
                (*super::session_ptr).remove_window(self.ptr);
            }
        }
    }
}
<commit_msg>Redraw on window flip<commit_after>use redox::{Box, String};
use redox::collections::VecDeque;
use redox::ops::DerefMut;

use orbital::{Color, Point, Size, Event, KeyEvent, MouseEvent, QuitEvent};

use super::display::Display;
use super::scheduler;

/// A window
pub struct Window {
    /// The position of the window
    pub point: Point,
    /// The size of the window
    pub size: Size,
    /// The title of the window
    pub title: String,
    /// The content of the window
    pub content: Box<Display>,
    /// The color of the window title
    pub title_color: Color,
    /// The color of the border
    pub border_color: Color,
    /// Is the window focused?
    pub focused: bool,
    /// Is the window minimized?
    pub minimized: bool,
    dragging: bool,
    last_mouse_event: MouseEvent,
    events: VecDeque<Event>,
    ptr: *mut Window,
}

impl Window {
    /// Create a new window
    pub fn new(point: Point, size: Size, title: String) -> Box<Self> {
        let mut ret = box Window {
            point: point,
            size: size,
            title: title,
            content: Display::new(size.width, size.height),
            title_color: Color::rgb(255, 255, 255),
            border_color: Color::rgba(64, 64, 64, 128),
            focused: false,
            minimized: false,
            dragging: false,
            last_mouse_event: MouseEvent {
                x: 0,
                y: 0,
                left_button: false,
                right_button: false,
                middle_button: false,
            },
            events: VecDeque::new(),
            ptr: 0 as *mut Window,
        };

        unsafe {
            ret.ptr = ret.deref_mut();

            if ret.ptr as usize > 0 {
                (*super::session_ptr).add_window(ret.ptr);
            }
        }

        ret
    }

    /// Poll the window (new)
    pub fn poll(&mut self) -> Option<Event> {
        let event_option;
        unsafe {
            let reenable = scheduler::start_no_ints();
            event_option = self.events.pop_front();
            scheduler::end_no_ints(reenable);
        }
        return event_option;
    }

    /// Redraw the window
    pub fn redraw(&mut self) {
        unsafe {
            let reenable = scheduler::start_no_ints();
            self.content.flip();
            (*super::session_ptr).redraw = true;
            (*super::session_ptr).redraw();
            scheduler::end_no_ints(reenable);
        }
    }

    /// Draw the window using a `Display`
    pub fn draw(&mut self, display: &Display, font: usize) {
        if self.focused {
            self.border_color = Color::rgba(128, 128, 128, 192);
        } else {
            self.border_color = Color::rgba(64, 64, 64, 128);
        }

        if self.minimized {
            self.title_color = Color::rgb(0, 0, 0);
        } else {
            self.title_color = Color::rgb(255, 255, 255);

            display.rect(Point::new(self.point.x - 2, self.point.y - 18),
                         Size::new(self.size.width + 4, 18),
                         self.border_color);

            let mut cursor = Point::new(self.point.x, self.point.y - 17);
            for c in self.title.chars() {
                if cursor.x + 8 <= self.point.x + self.size.width as isize {
                    display.char(cursor, c, self.title_color, font);
                }
                cursor.x += 8;
            }

            display.rect(Point::new(self.point.x - 2, self.point.y),
                         Size::new(2, self.size.height),
                         self.border_color);
            display.rect(Point::new(self.point.x - 2,
                                    self.point.y + self.size.height as isize),
                         Size::new(self.size.width + 4, 2),
                         self.border_color);
            display.rect(Point::new(self.point.x + self.size.width as isize,
                                    self.point.y),
                         Size::new(2, self.size.height),
                         self.border_color);

            unsafe {
                let reenable = scheduler::start_no_ints();
                display.image(self.point,
                              self.content.onscreen as *const Color,
                              Size::new(self.content.width, self.content.height));
                scheduler::end_no_ints(reenable);
            }
        }
    }

    /// Called on key press
    pub fn on_key(&mut self, key_event: KeyEvent) {
        unsafe {
            let reenable = scheduler::start_no_ints();
            self.events.push_back(key_event.to_event());
            scheduler::end_no_ints(reenable);
        }
    }

    fn on_window_decoration(&self, x: isize, y: isize) -> bool {
        !self.minimized && x >= -2 &&
            x < self.size.width as isize + 4 &&
            y >= -18 &&
            y < 0
    }

    fn on_window_body(&self, x: isize, y: isize) -> bool {
        !self.minimized && x >= 0 &&
            x < self.size.width as isize &&
            y >= 0 &&
            y < self.size.height as isize
    }

    /// Called on mouse movement
    pub fn on_mouse(&mut self, orig_mouse_event: MouseEvent, allow_catch: bool) -> bool {
        let mut mouse_event = orig_mouse_event;

        mouse_event.x -= self.point.x;
        mouse_event.y -= self.point.y;

        let mut caught = false;

        if allow_catch {
            if mouse_event.left_button {
                if self.on_window_body(mouse_event.x, mouse_event.y) {
                    caught = true;
                }else if self.on_window_decoration(mouse_event.x, mouse_event.y) {
                    caught = true;
                    if !self.last_mouse_event.left_button {
                        self.dragging = true;
                    }
                }
            } else {
                self.dragging = false;
            }

            if mouse_event.right_button {
                if self.on_window_body(mouse_event.x, mouse_event.y) {
                    caught = true;
                }else if self.on_window_decoration(mouse_event.x, mouse_event.y) {
                    caught = true;
                    if !self.last_mouse_event.right_button {
                        self.minimized = !self.minimized;
                    }
                }
            }

            if mouse_event.middle_button {
                if self.on_window_body(mouse_event.x, mouse_event.y) {
                    caught = true;
                }else if self.on_window_decoration(mouse_event.x, mouse_event.y) {
                    caught = true;
                    unsafe {
                        let reenable = scheduler::start_no_ints();
                        self.events.push_back(QuitEvent.to_event());
                        scheduler::end_no_ints(reenable);
                    }
                }
            }

            if self.dragging {
                self.point.x += orig_mouse_event.x - self.last_mouse_event.x;
                self.point.y += orig_mouse_event.y - self.last_mouse_event.y;
                caught = true;
            }
        } else {
            self.dragging = false;
        }

        self.last_mouse_event = orig_mouse_event;

        if (caught && !self.dragging) || self.on_window_body(mouse_event.x, mouse_event.y) {
            unsafe {
                let reenable = scheduler::start_no_ints();
                self.events.push_back(mouse_event.to_event());
                scheduler::end_no_ints(reenable);
            }
        }

        caught
    }
}

impl Drop for Window {
    fn drop(&mut self) {
        unsafe {
            if self.ptr as usize > 0 {
                (*super::session_ptr).remove_window(self.ptr);
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>added Weilin's gash reference solution that works on Rust 0.8<commit_after>//
// gash.rs
//
// Reference solution for PS2
// Running on Rust 0.8
//
// Special thanks to Kiet Tran for porting code from Rust 0.7 to Rust 0.8.
//
// University of Virginia - cs4414 Fall 2013
// Weilin Xu, Purnam Jantrania, David Evans
// Version 0.2
//

use std::{io, run, os, path, libc};
use std::task;

fn get_fd(fpath: &str, mode: &str) -> libc::c_int {
    #[fixed_stack_segment]; #[inline(never)];

    unsafe {
        let fpathbuf = fpath.to_c_str().unwrap();
        let modebuf = mode.to_c_str().unwrap();
        return libc::fileno(libc::fopen(fpathbuf, modebuf));
    }
}

fn exit(status: libc::c_int) {
    #[fixed_stack_segment]; #[inline(never)];
    unsafe { libc::exit(status); }
}

fn handle_cmd(cmd_line: &str, pipe_in: libc::c_int, pipe_out: libc::c_int, pipe_err: libc::c_int) {
    let mut out_fd = pipe_out;
    let mut in_fd = pipe_in;
    let err_fd = pipe_err;

    let mut argv: ~[~str] =
        cmd_line.split_iter(' ').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec();
    let mut i = 0;
    // found problem on redirection
    // `ping google.com | grep 1 > ping.txt &` didn't work
    // because grep won't flush the buffer until terminated (only) by SIGINT.
    while (i < argv.len()) {
        if (argv[i] == ~">") {
            argv.remove(i);
            out_fd = get_fd(argv.remove(i), "w");
        } else if (argv[i] == ~"<") {
            argv.remove(i);
            in_fd = get_fd(argv.remove(i), "r");
        }
        i += 1;
    }

    if argv.len() > 0 {
        let program = argv.remove(0);
        match program {
            ~"help" => {println("This is a new shell implemented in Rust!")}
            ~"cd" => {if argv.len()>0 {os::change_dir(&path::PosixPath(argv[0]));}}
            //global variable?
            //~"history" => {for i in range(0, history.len()) {println(fmt!("%5u %s", i+1, history[i]));}}
            ~"exit" => {exit(0);}
            _ => {let mut prog = run::Process::new(program, argv, run::ProcessOptions {
                                                                                env: None,
                                                                                dir: None,
                                                                                in_fd: Some(in_fd),
                                                                                out_fd: Some(out_fd),
                                                                                err_fd: Some(err_fd)
                                                                                });
                             prog.finish();
                             // close the pipes after process terminates.
                             if in_fd != 0 {os::close(in_fd);}
                             if out_fd != 1 {os::close(out_fd);}
                             if err_fd != 2 {os::close(err_fd);}
                            }
        }//match
    }//if
}

fn handle_cmdline(cmd_line:&str, bg_flag:bool)
{
    // handle pipes
    let progs: ~[~str] =
        cmd_line.split_iter('|').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec();

    let mut pipes: ~[os::Pipe] = ~[];

    // create pipes
    if (progs.len() > 1) {
        for _ in range(0, progs.len()-1) {
            pipes.push(os::pipe());
        }
    }

    if progs.len() == 1 {
        if bg_flag == false { handle_cmd(progs[0], 0, 1, 2); }
        else {task::spawn_sched(task::SingleThreaded, ||{handle_cmd(progs[0], 0, 1, 2)});}
    } else {
        for i in range(0, progs.len()) {
            let prog = progs[i].to_owned();

            if i == 0 {
                let pipe_i = pipes[i];
                task::spawn_sched(task::SingleThreaded, ||{handle_cmd(prog, 0, pipe_i.out, 2)});
            } else if i == progs.len() - 1 {
                let pipe_i_1 = pipes[i-1];
                if bg_flag == true {
                    task::spawn_sched(task::SingleThreaded, ||{handle_cmd(prog, pipe_i_1.input, 1, 2)});
                } else {
                    handle_cmd(prog, pipe_i_1.input, 1, 2);
                }
            } else {
                let pipe_i = pipes[i];
                let pipe_i_1 = pipes[i-1];
                task::spawn_sched(task::SingleThreaded, ||{handle_cmd(prog, pipe_i_1.input, pipe_i.out, 2)});
            }
        }
    }
}

fn main() {
    static CMD_PROMPT: &'static str = "gash > ";
    let mut history: ~[~str] = ~[];

    loop {
        print(CMD_PROMPT);

        let mut cmd_line = io::stdin().read_line();
        cmd_line = cmd_line.trim().to_owned();
        if cmd_line.len() > 0 {
            history.push(cmd_line.to_owned());
        }
        let mut bg_flag = false;
        if cmd_line.ends_with("&") {
            cmd_line = cmd_line.trim_right_chars(&'&').to_owned();
            bg_flag = true;
        }

        if cmd_line == ~"exit" {
            break;
        } else if cmd_line == ~"history" {
            for i in range(0, history.len()) {
                println(fmt!("%5u %s", i+1, history[i]));
            }
        } else {
            handle_cmdline(cmd_line, bg_flag);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add integration test<commit_after>// Copyright 2014 the objc-rs developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

extern crate objc;
extern crate sync;

use objc::NSObject;

pub struct Thing;

#[inline]
pub unsafe fn Thing() -> objc::Class {
    use sync::one::{Once, ONCE_INIT};
    static START: Once = ONCE_INIT;

    START.doit(|| {
        extern fn doSomething(this: objc::Id, _: objc::Selector) -> objc::Id {
            println!("doSomething");
            this
        }

        extern fn doSomethingElse(this: objc::Id, _: objc::Selector) -> objc::Id {
            println!("doSomethingElse");
            this
        }

        let thing = NSObject().allocate_class_pair("Thing", 0);
        thing.add_method(objc::selector("doSomething"), std::mem::transmute(doSomething), "@@:");
        thing.add_method(objc::selector("doSomethingElse"), std::mem::transmute(doSomethingElse), "@@:");
        thing.register_class_pair();
    });

    objc::class("Thing")
}

impl Thing {
    pub unsafe fn doSomething(this: Id) {
        objc::msg_send()(this, objc::selector("doSomething"))
    }

    pub unsafe fn doSomethingElse(this: Id) {
        objc::msg_send()(this, objc::selector("doSomethingElse"))
    }
}

fn main() {
    unsafe {
        let obj = NSObject::new(Thing());
        Thing::doSomething(obj);
        Thing::doSomethingElse(obj);
        NSObject::dealloc(obj);
    }
}
<|endoftext|>


<commit_before><commit_msg>End of short_number_info<commit_after><|endoftext|>


<commit_before><commit_msg>Fix message test naming<commit_after><|endoftext|>


<commit_before><commit_msg>refactoring<commit_after><|endoftext|>


<commit_before><commit_msg>Added example of autoreconnection.<commit_after>#![feature(slicing_syntax)]
extern crate irc;

use std::default::Default;
use std::sync::Arc;
use irc::data::{Command, Config};
use irc::server::{IrcServer, Server};
use irc::server::utils::Wrapper;

fn main() {
    let config = Config {
        nickname: Some(format!("pickles")),
        server: Some(format!("irc.fyrechat.net")),
        channels: Some(vec![format!("#vana")]),
        .. Default::default()
    };
    let irc_server = Arc::new(IrcServer::from_config(config).unwrap());
    irc_server.conn().set_keepalive(Some(5)).unwrap();
    // The wrapper provides us with methods like send_privmsg(...) and identify(...)
    spawn(move || {
        let server = Wrapper::new(&*irc_server);
        server.identify().unwrap();
        loop {
            let mut quit = false;
            for msg in server.iter() {
                match msg {
                    Ok(msg) => {
                        print!("{}", msg.into_string());
                        match Command::from_message(&msg) {
                            Ok(Command::PRIVMSG(_, msg)) => if msg.contains("bye") {
                                server.send_quit("").unwrap()
                            },
                            Ok(Command::ERROR(msg)) if msg.contains("Quit") => quit = true,
                            _ => (),
                        }
                    },
                    Err(_)  => break,
                }
            }
            if quit { break }
            irc_server.reconnect().unwrap();
            server.identify().unwrap();
        }
    });
}
<|endoftext|>


<commit_before><commit_msg>Use FlashMessage in todo example.<commit_after><|endoftext|>


<commit_before><commit_msg>Add test case.<commit_after>extern crate nalgebra as na;
extern crate ncollide;
extern crate nphysics3d;

use ncollide::shape::{Ball};
use nphysics3d::world::World;
use nphysics3d::object::{RigidBody, Sensor};

#[test]
fn free_sensor_update() {
    let mut world = World::new();

    let mut ball = RigidBody::new_dynamic(Ball::new(0.5), 1.0, 0.3, 0.5);
    ball.set_transformation(na::Isometry3::from_parts(na::Translation3::new(1.0, 1.0, 1.0), na::one()));
    world.add_rigid_body(ball);

    let mut sensor = Sensor::new(Ball::new(0.1), None);
    sensor.enable_interfering_bodies_collection();
    sensor.set_relative_position(na::Isometry3::from_parts(na::Translation3::new(0.0, 0.0, 0.0), na::one()));

    let sensor = world.add_sensor(sensor);
    world.step(1.0);
    assert_eq!(sensor.borrow().interfering_bodies().unwrap().len(), 0);

    sensor.borrow_mut().set_relative_position(na::Isometry3::from_parts(na::Translation3::new(1.0, 1.0, 1.0), na::one()));
    world.step(1.0);
    assert_eq!(sensor.borrow().interfering_bodies().unwrap().len(), 1);
}
<|endoftext|>


<commit_before><commit_msg>Add temperature_calculator.rs<commit_after><|endoftext|>


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

#![feature(const_int_wrapping)]

const ADD_A: u32 = 200u32.wrapping_add(55);
const ADD_B: u32 = 200u32.wrapping_add(u32::max_value());

const SUB_A: u32 = 100u32.wrapping_sub(100);
const SUB_B: u32 = 100u32.wrapping_sub(u32::max_value());

const MUL_A: u8 = 10u8.wrapping_mul(12);
const MUL_B: u8 = 25u8.wrapping_mul(12);

const SHL_A: u32 = 1u32.wrapping_shl(7);
const SHL_B: u32 = 1u32.wrapping_shl(128);

const SHR_A: u32 = 128u32.wrapping_shr(7);
const SHR_B: u32 = 128u32.wrapping_shr(128);

fn ident<T>(ident: T) -> T {
    ident
}

fn main() {
    assert_eq!(ADD_A, ident(255));
    assert_eq!(ADD_B, ident(199));

    assert_eq!(SUB_A, ident(0));
    assert_eq!(SUB_B, ident(101));

    assert_eq!(MUL_A, ident(120));
    assert_eq!(MUL_B, ident(44));

    assert_eq!(SHL_A, ident(128));
    assert_eq!(SHL_B, ident(1));

    assert_eq!(SHR_A, ident(1);
    assert_eq!(SHR_B, ident(128));
}
<commit_msg>Add missing brace<commit_after>// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![feature(const_int_wrapping)]

const ADD_A: u32 = 200u32.wrapping_add(55);
const ADD_B: u32 = 200u32.wrapping_add(u32::max_value());

const SUB_A: u32 = 100u32.wrapping_sub(100);
const SUB_B: u32 = 100u32.wrapping_sub(u32::max_value());

const MUL_A: u8 = 10u8.wrapping_mul(12);
const MUL_B: u8 = 25u8.wrapping_mul(12);

const SHL_A: u32 = 1u32.wrapping_shl(7);
const SHL_B: u32 = 1u32.wrapping_shl(128);

const SHR_A: u32 = 128u32.wrapping_shr(7);
const SHR_B: u32 = 128u32.wrapping_shr(128);

fn ident<T>(ident: T) -> T {
    ident
}

fn main() {
    assert_eq!(ADD_A, ident(255));
    assert_eq!(ADD_B, ident(199));

    assert_eq!(SUB_A, ident(0));
    assert_eq!(SUB_B, ident(101));

    assert_eq!(MUL_A, ident(120));
    assert_eq!(MUL_B, ident(44));

    assert_eq!(SHL_A, ident(128));
    assert_eq!(SHL_B, ident(1));

    assert_eq!(SHR_A, ident(1));
    assert_eq!(SHR_B, ident(128));
}
<|endoftext|>


<commit_before><commit_msg>new test for loaning out an index<commit_after>// compile-flags:--borrowck=err

// Here we check that it is allowed to lend out an element of a
// (locally rooted) mutable, unique vector, and that we then prevent
// modifications to the contents.

fn takes_imm_elt(_v: &int, f: fn()) {
    f();
}

fn has_mut_vec_and_does_not_try_to_change_it() {
    let v = [mut 1, 2, 3];
    takes_imm_elt(&v[0]) {||
    }
}

fn has_mut_vec_but_tries_to_change_it() {
    let v = [mut 1, 2, 3];
    takes_imm_elt(&v[0]) {|| //! NOTE loan of mutable vec content granted here
        v[1] = 4; //! ERROR assigning to mutable vec content prohibited due to outstanding loan
    }
}

fn takes_const_elt(_v: &const int, f: fn()) {
    f();
}

fn has_mut_vec_and_tries_to_change_it() {
    let v = [mut 1, 2, 3];
    takes_const_elt(&const v[0]) {||
        v[1] = 4;
    }
}

fn main() {
}<|endoftext|>


<commit_before><commit_msg>Add regression test for issue 68477.<commit_after>// edition:2018
// revisions:rpass1
#![feature(const_generics)]

const FOO: usize = 1;

struct Container<T> {
    val: std::marker::PhantomData<T>,
    blah: [(); FOO]
}

async fn dummy() {}

async fn foo() {
    let a: Container<&'static ()>;
    dummy().await;
}

fn is_send<T: Send>(_: T) {}

fn main() {
    is_send(foo());
}
<|endoftext|>


<commit_before><commit_msg>Problem 63<commit_after>enum BinaryTree<T> {
    Node(T, ~BinaryTree<T>, ~BinaryTree<T>),
    Empty
}

impl<T: Eq> Eq for BinaryTree<T> {
    fn eq(&self, other: &BinaryTree<T>) -> bool {
        match (self, other) {
            (&Empty, &Empty) => true,
            (&Node(ref lv, ~ref ll, ~ref lr),
             &Node(ref rv, ~ref rl, ~ref rr)) => lv == rv &&
                                                 ll == rl &&
                                                 lr == rr,
            _ => false
        }
    }
}

fn complete_binary_tree(n: uint) -> BinaryTree<uint> {
    fn aux(start: uint, n: uint) -> BinaryTree<uint> {
        if start > n {
            Empty
        } else if 2*start + 1 > n {
            Node(start, ~aux(2*start, n),
                        ~Empty)
        } else {
            Node(start, ~aux(2*start, n),
                        ~aux(2*start+1, n))
        }
    }
    aux(1, n)
}

fn main() {
    assert!(complete_binary_tree(6) == Node(1, ~Node(2, ~Node(4, ~Empty, ~Empty),
                                                        ~Node(5, ~Empty, ~Empty)),
                                               ~Node(3, ~Node(6, ~Empty, ~Empty),
                                                        ~Empty)));
}

<|endoftext|>


<commit_before><commit_msg>start rust version and fighting with pointer<commit_after>#[derive(Debug)]
struct ListNode {
    Val: i32,
    Next: Option<Box<ListNode>>,
}

impl ListNode {
    fn new(i: i32) -> Self {
        ListNode { Val: i, Next: None }
    }

    fn addL(&mut self, l: &Vec<i32>) {
        let org: *mut ListNode = self as *mut ListNode;
        let mut p: *mut ListNode = org;
        for i in l {
            unsafe {
                println!("{:?}", *p);
                (*p).Next = Some(Box::new(ListNode::new(*i)));
                let temp_b = Box::from_raw(p);
                p = Box::into_raw(temp_b.Next.unwrap());
            };
        }
    }
    fn removeNthFromEnd(&self, n: i32) {}
}
fn main() {
    let mut a = ListNode::new(1);
    a.addL(&vec![2, 3, 4, 5]);
    println!("{:?}", a);
}
<|endoftext|>


<commit_before><commit_msg>Regression test for #58435.<commit_after>// The const-evaluator was at one point ICE'ing while trying to
// evaluate the body of `fn id` during the `s.id()` call in main.

struct S<T>(T);

impl<T> S<T> {
    const ID: fn(&S<T>) -> &S<T> = |s| s;
    pub fn id(&self) -> &Self {
        Self::ID(self) // This, plus call below ...
    }
}

fn main() {
    let s = S(10u32);
    assert!(S::<u32>::ID(&s).0 == 10); // Works fine
    assert!(s.id().0 == 10); // ... causes compiler to panic
}
<|endoftext|>


<commit_before><commit_msg>Change 1 -> GLX_VENDOR Replace 1 with GLX_VENDOR for glXGetClientString call.<commit_after><|endoftext|>


<commit_before><commit_msg>Feat(Sync): update native file from sync<commit_after><|endoftext|>


<commit_before><commit_msg>Chore(TODO): more todo slaughter<commit_after><|endoftext|>


<commit_before><commit_msg>Feat(sync): when unpacking a sync file, if local data matches the sync data, don't update local file<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed integer underflow in polygon collision functions<commit_after><|endoftext|>


<commit_before><commit_msg>Don't save duplicate job offers<commit_after><|endoftext|>


<commit_before><commit_msg>counter > value<commit_after><|endoftext|>


<commit_before><commit_msg>Fix build errors<commit_after><|endoftext|>


<commit_before><commit_msg>Add AND + basic priority (no parenthesis)<commit_after><|endoftext|>


<commit_before>#![feature(box_syntax)]
#![feature(plugin)]
#![plugin(peg_syntax_ext)]

use std::collections::{BTreeMap, HashMap};
use std::fs::File;
use std::io::{stdout, Read, Write};
use std::env;
use std::process;

use self::to_num::ToNum;
use self::directory_stack::DirectoryStack;
use self::input_editor::readln;
use self::peg::parse;
use self::expansion::expand_variables;

pub mod builtin;
pub mod directory_stack;
pub mod to_num;
pub mod input_editor;
pub mod peg;
pub mod expansion;

pub type Variables = BTreeMap<String, String>;

/// This struct will contain all of the data structures related to this
/// instance of the shell.
pub struct Shell {
    pub variables: Variables,
    pub modes: Vec<Mode>,
    pub directory_stack: DirectoryStack,
}

impl Shell {
    /// Panics if DirectoryStack construction fails
    pub fn new() -> Self {
        Shell {
            variables: BTreeMap::new(),
            modes: vec![],
            directory_stack: DirectoryStack::new().expect(""),
        }
    }
}

/// Structure which represents a Terminal's command.
/// This command structure contains a name, and the code which run the
/// functionnality associated to this one, with zero, one or several argument(s).
/// # Example
/// ```
/// let my_command = Command {
///     name: "my_command",
///     help: "Describe what my_command does followed by a newline showing usage",
///     main: box|args: &[String]| {
///         println!("Say 'hello' to my command! :-D");
///     }
/// }
/// ```
pub struct Command {
    pub name: &'static str,
    pub help: &'static str,
    pub main: Box<Fn(&[String], &mut Shell)>,
}

impl Command {
    /// Return the map from command names to commands
    pub fn map() -> HashMap<&'static str, Self> {
        let mut commands: HashMap<&str, Self> = HashMap::new();

        commands.insert("cd",
                        Command {
                            name: "cd",
                            help: "To change the current directory\n    cd <your_destination>",
                            main: box |args: &[String], _: &mut Shell| {
                                builtin::cd(args);
                            },
                        });

        commands.insert("exit",
                        Command {
                            name: "exit",
                            help: "To exit the curent session",
                            main: box |_: &[String], _: &mut Shell| {},
                        });

        commands.insert("read",
                        Command {
                            name: "read",
                            help: "To read some variables\n    read <my_variable>",
                            main: box |args: &[String], shell: &mut Shell| {
                                builtin::read(args, &mut shell.variables);
                            },
                        });

        commands.insert("run",
                        Command {
                            name: "run",
                            help: "Run a script\n    run <script>",
                            main: box |args: &[String], shell: &mut Shell| {
                                builtin::run(args, &mut shell.variables);
                            },
                        });

        commands.insert("pushd",
                        Command {
                            name: "pushd",
                            help: "Make a sleep in the current session\n    sleep \
                                   <number_of_seconds>",
                            main: box |args: &[String], shell: &mut Shell| {
                                shell.directory_stack.pushd(args);
                            },
                        });

        commands.insert("popd",
                        Command {
                            name: "popd",
                            help: "Make a sleep in the current session\n    sleep \
                                   <number_of_seconds>",
                            main: box |args: &[String], shell: &mut Shell| {
                                shell.directory_stack.popd(args);
                            },
                        });

        commands.insert("dirs",
                        Command {
                            name: "dirs",
                            help: "Make a sleep in the current session\n    sleep \
                                   <number_of_seconds>",
                            main: box |args: &[String], shell: &mut Shell| {
                                shell.directory_stack.dirs(args);
                            },
                        });

        // TODO: Someone should implement FromIterator for HashMap before
        //       changing the type back to HashMap
        let command_helper: HashMap<String, String> = commands.iter()
                                                              .map(|(k, v)| {
                                                                  (k.to_string(),
                                                                   v.help.to_string())
                                                              })
                                                              .collect();

        commands.insert("help",
                        Command {
                            name: "help",
                            help: "Display a little helper for a given command\n    help ls",
                            main: box move |args: &[String], _: &mut Shell| {
                                if let Some(command) = args.get(1) {
                                    if command_helper.contains_key(command) {
                                        match command_helper.get(command) {
                                            Some(help) => println!("{}", help),
                                            None => {
                                                println!("Command helper not found [run 'help']...")
                                            }
                                        }
                                    } else {
                                        println!("Command helper not found [run 'help']...");
                                    }
                                } else {
                                    for (command, _help) in command_helper.iter() {
                                        println!("{}", command);
                                    }
                                }
                            },
                        });

        commands
    }
}

pub struct Mode {
    value: bool,
}

fn on_command(command_string: &str, commands: &HashMap<&str, Command>, shell: &mut Shell) {
    // Show variables
    if command_string == "$" {
        for (key, value) in shell.variables.iter() {
            println!("{}={}", key, value);
        }
        return;
    }

    let mut jobs = parse(command_string);
    expand_variables(&mut jobs, &shell.variables);

    // Execute commands
    for job in jobs.iter() {
        if job.command == "if" {
            let mut value = false;

            if let Some(left) = job.args.get(0) {
                if let Some(cmp) = job.args.get(1) {
                    if let Some(right) = job.args.get(2) {
                        if cmp == "==" {
                            value = *left == *right;
                        } else if cmp == "!=" {
                            value = *left != *right;
                        } else if cmp == ">" {
                            value = left.to_num_signed() > right.to_num_signed();
                        } else if cmp == ">=" {
                            value = left.to_num_signed() >= right.to_num_signed();
                        } else if cmp == "<" {
                            value = left.to_num_signed() < right.to_num_signed();
                        } else if cmp == "<=" {
                            value = left.to_num_signed() <= right.to_num_signed();
                        } else {
                            println!("Unknown comparison: {}", cmp);
                        }
                    } else {
                        println!("No right hand side");
                    }
                } else {
                    println!("No comparison operator");
                }
            } else {
                println!("No left hand side");
            }

            shell.modes.insert(0, Mode { value: value });
            continue;
        }

        if job.command == "else" {
            if let Some(mode) = shell.modes.get_mut(0) {
                mode.value = !mode.value;
            } else {
                println!("Syntax error: else found with no previous if");
            }
            continue;
        }

        if job.command == "fi" {
            if !shell.modes.is_empty() {
                shell.modes.remove(0);
            } else {
                println!("Syntax error: fi found with no previous if");
            }
            continue;
        }

        let mut skipped: bool = false;
        for mode in shell.modes.iter() {
            if !mode.value {
                skipped = true;
                break;
            }
        }
        if skipped {
            continue;
        }

        // Set variables
        if let Some(i) = job.command.find('=') {
            let name = job.command[0..i].trim();
            let mut value = job.command[i + 1..job.command.len()].trim().to_string();

            for i in 0..job.args.len() {
                if let Some(arg) = job.args.get(i) {
                    value = value + " " + &arg;
                }
            }

            set_var(&mut shell.variables, name, &value);
            continue;
        }

        // Commands
        let mut args = job.args.clone();
        args.insert(0, job.command.clone());
        if let Some(command) = commands.get(&job.command.as_str()) {
            (*command.main)(&args, shell);
        } else {
            run_external_commmand(args, &mut shell.variables);
        }
    }
}

pub fn set_var(variables: &mut Variables, name: &str, value: &str) {
    if name.is_empty() {
        return;
    }

    if value.is_empty() {
        variables.remove(&name.to_string());
    } else {
        variables.insert(name.to_string(), value.to_string());
    }
}

fn print_prompt(modes: &Vec<Mode>) {
    for mode in modes.iter().rev() {
        if mode.value {
            print!("+ ");
        } else {
            print!("- ");
        }
    }

    let cwd = match env::current_dir() {
        Ok(path) => {
            match path.to_str() {
                Some(path_str) => path_str.to_string(),
                None => "?".to_string(),
            }
        }
        Err(_) => "?".to_string(),
    };

    print!("ion:{}# ", cwd);
    if let Err(message) = stdout().flush() {
        println!("{}: failed to flush prompt to stdout", message);
    }
}

fn run_external_commmand(args: Vec<String>, variables: &mut Variables) {
    if let Some(path) = args.get(0) {
        let mut command = process::Command::new(path);
        for i in 1..args.len() {
            if let Some(arg) = args.get(i) {
                command.arg(arg);
            }
        }
        match command.spawn() {
            Ok(mut child) => {
                match child.wait() {
                    Ok(status) => {
                        if let Some(code) = status.code() {
                            set_var(variables, "?", &code.to_string());
                        } else {
                            println!("{}: No child exit code", path);
                        }
                    }
                    Err(err) => println!("{}: Failed to wait: {}", path, err),
                }
            }
            Err(err) => println!("{}: Failed to execute: {}", path, err),
        }
    }
}

fn main() {
    let commands = Command::map();
    let mut shell = Shell::new();

    for arg in env::args().skip(1) {
        let mut command_list = String::new();
        if let Ok(mut file) = File::open(&arg) {
            if let Err(message) = file.read_to_string(&mut command_list) {
                println!("{}: Failed to read {}", message, arg);
            }
        }
        on_command(&command_list, &commands, &mut shell);

        return;
    }

    loop {

        print_prompt(&shell.modes);

        if let Some(command_original) = readln() {
            let command = command_original.trim();
            if command == "exit" {
                break;
            } else if !command.is_empty() {
                on_command(&command, &commands, &mut shell);
            }
        } else {
            break;
        }
    }
}
<commit_msg>Refactor `print_prompt()`<commit_after>#![feature(box_syntax)]
#![feature(plugin)]
#![plugin(peg_syntax_ext)]

use std::collections::{BTreeMap, HashMap};
use std::fs::File;
use std::io::{stdout, Read, Write};
use std::env;
use std::process;

use self::to_num::ToNum;
use self::directory_stack::DirectoryStack;
use self::input_editor::readln;
use self::peg::parse;
use self::expansion::expand_variables;

pub mod builtin;
pub mod directory_stack;
pub mod to_num;
pub mod input_editor;
pub mod peg;
pub mod expansion;

pub type Variables = BTreeMap<String, String>;

/// This struct will contain all of the data structures related to this
/// instance of the shell.
pub struct Shell {
    pub variables: Variables,
    pub modes: Vec<Mode>,
    pub directory_stack: DirectoryStack,
}

impl Shell {
    /// Panics if DirectoryStack construction fails
    pub fn new() -> Self {
        Shell {
            variables: BTreeMap::new(),
            modes: vec![],
            directory_stack: DirectoryStack::new().expect(""),
        }
    }
}

/// Structure which represents a Terminal's command.
/// This command structure contains a name, and the code which run the
/// functionnality associated to this one, with zero, one or several argument(s).
/// # Example
/// ```
/// let my_command = Command {
///     name: "my_command",
///     help: "Describe what my_command does followed by a newline showing usage",
///     main: box|args: &[String]| {
///         println!("Say 'hello' to my command! :-D");
///     }
/// }
/// ```
pub struct Command {
    pub name: &'static str,
    pub help: &'static str,
    pub main: Box<Fn(&[String], &mut Shell)>,
}

impl Command {
    /// Return the map from command names to commands
    pub fn map() -> HashMap<&'static str, Self> {
        let mut commands: HashMap<&str, Self> = HashMap::new();

        commands.insert("cd",
                        Command {
                            name: "cd",
                            help: "To change the current directory\n    cd <your_destination>",
                            main: box |args: &[String], _: &mut Shell| {
                                builtin::cd(args);
                            },
                        });

        commands.insert("exit",
                        Command {
                            name: "exit",
                            help: "To exit the curent session",
                            main: box |_: &[String], _: &mut Shell| {},
                        });

        commands.insert("read",
                        Command {
                            name: "read",
                            help: "To read some variables\n    read <my_variable>",
                            main: box |args: &[String], shell: &mut Shell| {
                                builtin::read(args, &mut shell.variables);
                            },
                        });

        commands.insert("run",
                        Command {
                            name: "run",
                            help: "Run a script\n    run <script>",
                            main: box |args: &[String], shell: &mut Shell| {
                                builtin::run(args, &mut shell.variables);
                            },
                        });

        commands.insert("pushd",
                        Command {
                            name: "pushd",
                            help: "Make a sleep in the current session\n    sleep \
                                   <number_of_seconds>",
                            main: box |args: &[String], shell: &mut Shell| {
                                shell.directory_stack.pushd(args);
                            },
                        });

        commands.insert("popd",
                        Command {
                            name: "popd",
                            help: "Make a sleep in the current session\n    sleep \
                                   <number_of_seconds>",
                            main: box |args: &[String], shell: &mut Shell| {
                                shell.directory_stack.popd(args);
                            },
                        });

        commands.insert("dirs",
                        Command {
                            name: "dirs",
                            help: "Make a sleep in the current session\n    sleep \
                                   <number_of_seconds>",
                            main: box |args: &[String], shell: &mut Shell| {
                                shell.directory_stack.dirs(args);
                            },
                        });

        // TODO: Someone should implement FromIterator for HashMap before
        //       changing the type back to HashMap
        let command_helper: HashMap<String, String> = commands.iter()
                                                              .map(|(k, v)| {
                                                                  (k.to_string(),
                                                                   v.help.to_string())
                                                              })
                                                              .collect();

        commands.insert("help",
                        Command {
                            name: "help",
                            help: "Display a little helper for a given command\n    help ls",
                            main: box move |args: &[String], _: &mut Shell| {
                                if let Some(command) = args.get(1) {
                                    if command_helper.contains_key(command) {
                                        match command_helper.get(command) {
                                            Some(help) => println!("{}", help),
                                            None => {
                                                println!("Command helper not found [run 'help']...")
                                            }
                                        }
                                    } else {
                                        println!("Command helper not found [run 'help']...");
                                    }
                                } else {
                                    for (command, _help) in command_helper.iter() {
                                        println!("{}", command);
                                    }
                                }
                            },
                        });

        commands
    }
}

pub struct Mode {
    value: bool,
}

fn on_command(command_string: &str, commands: &HashMap<&str, Command>, shell: &mut Shell) {
    // Show variables
    if command_string == "$" {
        for (key, value) in shell.variables.iter() {
            println!("{}={}", key, value);
        }
        return;
    }

    let mut jobs = parse(command_string);
    expand_variables(&mut jobs, &shell.variables);

    // Execute commands
    for job in jobs.iter() {
        if job.command == "if" {
            let mut value = false;

            if let Some(left) = job.args.get(0) {
                if let Some(cmp) = job.args.get(1) {
                    if let Some(right) = job.args.get(2) {
                        if cmp == "==" {
                            value = *left == *right;
                        } else if cmp == "!=" {
                            value = *left != *right;
                        } else if cmp == ">" {
                            value = left.to_num_signed() > right.to_num_signed();
                        } else if cmp == ">=" {
                            value = left.to_num_signed() >= right.to_num_signed();
                        } else if cmp == "<" {
                            value = left.to_num_signed() < right.to_num_signed();
                        } else if cmp == "<=" {
                            value = left.to_num_signed() <= right.to_num_signed();
                        } else {
                            println!("Unknown comparison: {}", cmp);
                        }
                    } else {
                        println!("No right hand side");
                    }
                } else {
                    println!("No comparison operator");
                }
            } else {
                println!("No left hand side");
            }

            shell.modes.insert(0, Mode { value: value });
            continue;
        }

        if job.command == "else" {
            if let Some(mode) = shell.modes.get_mut(0) {
                mode.value = !mode.value;
            } else {
                println!("Syntax error: else found with no previous if");
            }
            continue;
        }

        if job.command == "fi" {
            if !shell.modes.is_empty() {
                shell.modes.remove(0);
            } else {
                println!("Syntax error: fi found with no previous if");
            }
            continue;
        }

        let mut skipped: bool = false;
        for mode in shell.modes.iter() {
            if !mode.value {
                skipped = true;
                break;
            }
        }
        if skipped {
            continue;
        }

        // Set variables
        if let Some(i) = job.command.find('=') {
            let name = job.command[0..i].trim();
            let mut value = job.command[i + 1..job.command.len()].trim().to_string();

            for i in 0..job.args.len() {
                if let Some(arg) = job.args.get(i) {
                    value = value + " " + &arg;
                }
            }

            set_var(&mut shell.variables, name, &value);
            continue;
        }

        // Commands
        let mut args = job.args.clone();
        args.insert(0, job.command.clone());
        if let Some(command) = commands.get(&job.command.as_str()) {
            (*command.main)(&args, shell);
        } else {
            run_external_commmand(args, &mut shell.variables);
        }
    }
}

pub fn set_var(variables: &mut Variables, name: &str, value: &str) {
    if name.is_empty() {
        return;
    }

    if value.is_empty() {
        variables.remove(&name.to_string());
    } else {
        variables.insert(name.to_string(), value.to_string());
    }
}

fn print_prompt(modes: &[Mode]) {
    let mode = modes.iter().rev().fold(String::new(), |acc, mode| {
        acc + if mode.value { "+ " } else { "- " }
    });
    print!("{}", mode.trim_right());

    let cwd = env::current_dir().ok().map_or("?".to_string(), |ref p| p.to_str().unwrap_or("?").to_string());

    print!("ion:{}# ", cwd);
    if let Err(message) = stdout().flush() {
        println!("{}: failed to flush prompt to stdout", message);
    }
}

fn run_external_commmand(args: Vec<String>, variables: &mut Variables) {
    if let Some(path) = args.get(0) {
        let mut command = process::Command::new(path);
        for i in 1..args.len() {
            if let Some(arg) = args.get(i) {
                command.arg(arg);
            }
        }
        match command.spawn() {
            Ok(mut child) => {
                match child.wait() {
                    Ok(status) => {
                        if let Some(code) = status.code() {
                            set_var(variables, "?", &code.to_string());
                        } else {
                            println!("{}: No child exit code", path);
                        }
                    }
                    Err(err) => println!("{}: Failed to wait: {}", path, err),
                }
            }
            Err(err) => println!("{}: Failed to execute: {}", path, err),
        }
    }
}

fn main() {
    let commands = Command::map();
    let mut shell = Shell::new();

    for arg in env::args().skip(1) {
        let mut command_list = String::new();
        if let Ok(mut file) = File::open(&arg) {
            if let Err(message) = file.read_to_string(&mut command_list) {
                println!("{}: Failed to read {}", message, arg);
            }
        }
        on_command(&command_list, &commands, &mut shell);

        return;
    }

    loop {

        print_prompt(&shell.modes);

        if let Some(command_original) = readln() {
            let command = command_original.trim();
            if command == "exit" {
                break;
            } else if !command.is_empty() {
                on_command(&command, &commands, &mut shell);
            }
        } else {
            break;
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>dont generate numbers inside loops<commit_after><|endoftext|>


<commit_before><commit_msg>basic rand functions<commit_after>extern crate rand;

use rand::{task_rng,Rng};

fn main(){
    let mut rng = task_rng();
    println!("{:b}", rng.gen_weighted_bool(3));
    println!("{}", task_rng().gen_ascii_str(10));

    let n: uint = rng.gen_range(0u, 10);
    println!("{}", n);
    let m: f64 = rng.gen_range(-40.0, 1.3e5);
    println!("{}", m);
}
<|endoftext|>


<commit_before><commit_msg>Start sketching out server connection<commit_after>#![allow(dead_code, unused_variables)]

use std::collections::HashSet;

use crate::proto::{Capability, MessageKind, RawMessage};

/// Represents Birch <-> IRC network connection
// TODO: Rename NetworkConnection?
struct ServerConnection {
    nick: String,
    caps: HashSet<Capability>,
    // writer: dyn IRCWriter,
    // user_fanout: dyn IRCWriter,
}

impl ServerConnection {
    fn handle(&mut self, msg: &RawMessage) {
        let kind = MessageKind::from(msg);

        let should_forward = match kind {
            MessageKind::Ping => {
                // TODO: Respond to network PING
                false
            }

            _ => true,
        };

        if should_forward {
            // TODO: send message to user_fanout
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Re-group imports.<commit_after><|endoftext|>


<commit_before>fn main() {

    // The commented-out lines are ones that fail currently.  I'm
    // working on figuring out why (#1425). -- lkuper

    fn id_i8(n: i8) -> i8 { n }
    fn id_i16(n: i16) -> i16 { n }
    fn id_i32(n: i32) -> i32 { n }
    fn id_i64(n: i64) -> i64 { n }

    fn id_uint(n: uint) -> uint { n }
    fn id_u8(n: u8) -> u8 { n }
    fn id_u16(n: u16) -> u16 { n }
    fn id_u32(n: u32) -> u32 { n }
    fn id_u64(n: u64) -> u64 { n }

    let _i: i8 = -128;
    let j = -128;
    id_i8(j);
    id_i8(-128);

    let _i: i16 = -32_768;
    let j = -32_768;
    id_i16(j);
    id_i16(-32_768);

    let _i: i32 = -2_147_483_648;
    let j = -2_147_483_648;
    id_i32(j);
    id_i32(-2_147_483_648);

    let _i: i64 = -9_223_372_036_854_775_808;
    let j = -9_223_372_036_854_775_808;
    id_i64(j);
    id_i64(-9_223_372_036_854_775_808);

    let _i: uint = 1;
    let j = 1;
    id_uint(j);
    id_uint(1);

    let _i: u8 = 255;
    let j = 255;
    id_u8(j);
    id_u8(255);

    let _i: u16 = 65_535;
    let j = 65_535;
    id_u16(j);
    id_u16(65_535);

    let _i: u32 = 4_294_967_295;
    let j = 4_294_967_295;
    id_u32(j);
    id_u32(4_294_967_295);

    let _i: u64 = 18_446_744_073_709_551_615;
    let j = 18_446_744_073_709_551_615;
    id_u64(j);
    id_u64(18_446_744_073_709_551_615);
}
<commit_msg>Remove obsolete comment.<commit_after>fn main() {
    fn id_i8(n: i8) -> i8 { n }
    fn id_i16(n: i16) -> i16 { n }
    fn id_i32(n: i32) -> i32 { n }
    fn id_i64(n: i64) -> i64 { n }

    fn id_uint(n: uint) -> uint { n }
    fn id_u8(n: u8) -> u8 { n }
    fn id_u16(n: u16) -> u16 { n }
    fn id_u32(n: u32) -> u32 { n }
    fn id_u64(n: u64) -> u64 { n }

    let _i: i8 = -128;
    let j = -128;
    id_i8(j);
    id_i8(-128);

    let _i: i16 = -32_768;
    let j = -32_768;
    id_i16(j);
    id_i16(-32_768);

    let _i: i32 = -2_147_483_648;
    let j = -2_147_483_648;
    id_i32(j);
    id_i32(-2_147_483_648);

    let _i: i64 = -9_223_372_036_854_775_808;
    let j = -9_223_372_036_854_775_808;
    id_i64(j);
    id_i64(-9_223_372_036_854_775_808);

    let _i: uint = 1;
    let j = 1;
    id_uint(j);
    id_uint(1);

    let _i: u8 = 255;
    let j = 255;
    id_u8(j);
    id_u8(255);

    let _i: u16 = 65_535;
    let j = 65_535;
    id_u16(j);
    id_u16(65_535);

    let _i: u32 = 4_294_967_295;
    let j = 4_294_967_295;
    id_u32(j);
    id_u32(4_294_967_295);

    let _i: u64 = 18_446_744_073_709_551_615;
    let j = 18_446_744_073_709_551_615;
    id_u64(j);
    id_u64(18_446_744_073_709_551_615);
}
<|endoftext|>


<commit_before><commit_msg>Changed mutable reference in example/client.rs to immutable reference<commit_after><|endoftext|>


<commit_before><commit_msg>example use<commit_after>#[macro_use]
extern crate log;
extern crate env_logger;

extern crate commodore;
extern crate hyper;

use commodore::{Captures, Command, Mux, Response, Responder};
use hyper::Server;

pub fn main() {
    env_logger::init().unwrap();
    let addr = format!("0.0.0.0:{}", 4567);
    let mut mux = Mux::new();
    mux.command("/commadore", "secrettoken", |_: &Command, _: &Option<Captures>, _: Box<Responder>| -> Option<Response> {
        None
    });
    let srvc = Server::http(&addr[..]).unwrap()
        .handle(mux);
    println!("listening on {}", addr);
    srvc.unwrap();
}
<|endoftext|>


<commit_before><commit_msg>Skeleton for problem 2365<commit_after>// https://leetcode.com/problems/task-scheduler-ii/
pub fn task_scheduler_ii(tasks: Vec<i32>, space: i32) -> i64 {
    todo!()
}

fn main() {
    println!("{}", task_scheduler_ii(vec![1, 2, 1, 2, 3, 1], 3)); // 9
    println!("{}", task_scheduler_ii(vec![5, 8, 8, 5], 2)); // 6
}
<|endoftext|>


<commit_before><commit_msg>Cleaned up server setup<commit_after><|endoftext|>


<commit_before><commit_msg>popd now does not alter the stack, when changing to the new directory fails<commit_after><|endoftext|>


<commit_before><commit_msg>Add blur.rs external project<commit_after>#pragma version(1)
#pragma rs_fp_inprecise
#pragma rs java_package_name(com.enrique.stackblur)

static unsigned short const stackblur_mul[255] =
{
        512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,
        454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,
        482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,
        437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,
        497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,
        320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,
        446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,
        329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,
        505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,
        399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,
        324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,
        268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,
        451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,
        385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,
        332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,
        289,287,285,282,280,278,275,273,271,269,267,265,263,261,259
};

static unsigned char const stackblur_shr[255] =
{
        9, 11, 12, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 17,
        17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19,
        19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20,
        20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21,
        21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
        21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22,
        22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
        22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23,
        23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
        23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
        23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
        23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
        24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
        24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
        24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
        24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24
};

rs_allocation gIn;

uint32_t width;
uint32_t height;

uint32_t radius;

void __attribute__((kernel)) blur_v(uint32_t in) {
    uint x, y, xp, yp, i;
    uint sp;
    uint stack_start;
    uchar3* stack_ptr;

    uint32_t src_i;
    uint32_t dst_i;

    uint3 sum;
    uint3 sum_in;
    uint3 sum_out;
    uint3 sum_tmp;

    uchar3 inPixel;

    uint32_t wm = width - 1;
    uint32_t hm = height - 1;
    uint32_t div = (radius * 2) + 1;
    uint32_t mul_sum = stackblur_mul[radius];
    uchar shr_sum = stackblur_shr[radius];
    uchar3 stack[div];

    x = in;
    sum = sum_in = sum_out = 0;

    src_i = x; // x,0
    for(i = 0; i <= radius; i++)
    {
        stack_ptr    = &stack[i];

        inPixel = rsGetElementAt_uchar4(gIn, src_i).xyz;

        *stack_ptr = inPixel;

        sum_tmp = convert_uint3(inPixel);
        sum += sum_tmp * (i + 1);
        sum_out += sum_tmp;
    }
    for(i = 1; i <= radius; i++)
    {
        if(i <= hm) src_i += width; // +stride

        stack_ptr = &stack[i + radius];

        inPixel = rsGetElementAt_uchar4(gIn, src_i).xyz;

        *stack_ptr = inPixel;

        sum_tmp = convert_uint3(inPixel);
        sum += sum_tmp * (radius + 1 - i);
        sum_in += sum_tmp;
    }

    sp = radius;
    yp = radius;
    if (yp > hm) yp = hm;
    src_i = x + yp * width; // img.pix_ptr(x, yp);
    dst_i = x;               // img.pix_ptr(x, 0);
    for(y = 0; y < height; y++)
    {
        uchar4 outPixel;
        outPixel.xyz = convert_uchar3((sum * mul_sum) >> shr_sum);
        outPixel.w = rsGetElementAt_uchar4(gIn, dst_i).w;
        outPixel = min(max(outPixel, 0), outPixel.w);
        rsSetElementAt_uchar4(gIn, outPixel, dst_i);
        dst_i += width;

        sum -= sum_out;

        stack_start = sp + div - radius;
        if(stack_start >= div) stack_start -= div;
        stack_ptr = &stack[stack_start];

        sum_out -= convert_uint3(*stack_ptr);

        if(yp < hm)
        {
            src_i += width; // stride
            ++yp;
        }

        inPixel = rsGetElementAt_uchar4(gIn, src_i).xyz;

        *stack_ptr = inPixel;

        sum_in += convert_uint3(inPixel);

        sum += sum_in;

        ++sp;
        if (sp >= div) sp = 0;
        stack_ptr = &stack[sp];

        sum_tmp = convert_uint3(*stack_ptr);

        sum_out += sum_tmp;
        sum_in -= sum_tmp;
    }
}

void __attribute__((kernel)) blur_h(uint32_t in) {
    uint x, y, xp, yp, i;
    uint sp;
    uint stack_start;
    uchar3* stack_ptr;

    uint32_t src_i;
    uint32_t dst_i;

    uint3 sum;
    uint3 sum_in;
    uint3 sum_out;
    uint3 sum_tmp;

    uchar3 inPixel;

    uint32_t wm = width - 1;
    uint32_t hm = height - 1;
    uint32_t div = (radius * 2) + 1;
    uint32_t mul_sum = stackblur_mul[radius];
    uchar shr_sum = stackblur_shr[radius];
    uchar3 stack[div];

    y = in;
    sum = sum_in = sum_out = 0;

    src_i = width * y; // start of line (0,y)

    for(i = 0; i <= radius; i++)
    {
        stack_ptr    = &stack[ i ];
        inPixel = rsGetElementAt_uchar4(gIn, src_i).xyz;
        *stack_ptr = inPixel;
        sum_tmp = convert_uint3(inPixel);
        sum_out += sum_tmp;
        sum += sum_tmp * (i + 1);
    }

    for(i = 1; i <= radius; i++)
    {
        if (i <= wm) src_i += 1;
        stack_ptr = &stack[ (i + radius) ];
        inPixel = rsGetElementAt_uchar4(gIn, src_i).xyz;

        *stack_ptr = inPixel;
        sum_tmp = convert_uint3(inPixel);
        sum += sum_tmp * (radius + 1 - i);
        sum_in += sum_tmp;
    }

    sp = radius;
    xp = radius;
    if (xp > wm) xp = wm;
    src_i = xp + y * width; //   img.pix_ptr(xp, y);
    dst_i = y * width; // img.pix_ptr(0, y);
    for(x = 0; x < width; x++)
    {
        uchar4 outPixel;
        outPixel.xyz = convert_uchar3((sum * mul_sum) >> shr_sum);
        outPixel.w = rsGetElementAt_uchar4(gIn, dst_i).w;
        outPixel = min(max(outPixel, 0), outPixel.w);

        rsSetElementAt_uchar4(gIn, outPixel, dst_i);
        dst_i += 1;

        sum -= sum_out;

        stack_start = sp + div - radius;
        if (stack_start >= div) stack_start -= div;
        stack_ptr = &stack[stack_start];

        sum_out -= convert_uint3(*stack_ptr);

        if(xp < wm)
        {
            src_i += 1;
            ++xp;
        }

        inPixel = rsGetElementAt_uchar4(gIn, src_i).xyz;

        *stack_ptr = inPixel;
        sum_in += convert_uint3(inPixel);
        sum += sum_in;

        ++sp;
        if (sp >= div) sp = 0;
        stack_ptr = &stack[sp];

        sum_out += convert_uint3(*stack_ptr);
        sum_in -= convert_uint3(*stack_ptr);
    }

}
<|endoftext|>


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

use hir::def_id::DefId;
use traits::specialization_graph;
use ty::fast_reject;
use ty::fold::TypeFoldable;
use ty::{Ty, TyCtxt};
use std::rc::Rc;
use hir;

/// A trait's definition with type information.
pub struct TraitDef {
    pub def_id: DefId,

    pub unsafety: hir::Unsafety,

    /// If `true`, then this trait had the `#[rustc_paren_sugar]`
    /// attribute, indicating that it should be used with `Foo()`
    /// sugar. This is a temporary thing -- eventually any trait will
    /// be usable with the sugar (or without it).
    pub paren_sugar: bool,

    pub has_default_impl: bool,

    /// The ICH of this trait's DefPath, cached here so it doesn't have to be
    /// recomputed all the time.
    pub def_path_hash: u64,
}

// We don't store the list of impls in a flat list because each cached list of
// `relevant_impls_for` we would then duplicate all blanket impls. By keeping
// blanket and non-blanket impls separate, we can share the list of blanket
// impls.
#[derive(Clone)]
pub struct TraitImpls {
    blanket_impls: Rc<Vec<DefId>>,
    non_blanket_impls: Rc<Vec<DefId>>,
}

impl TraitImpls {
    pub fn iter(&self) -> TraitImplsIter {
        TraitImplsIter {
            blanket_impls: self.blanket_impls.clone(),
            non_blanket_impls: self.non_blanket_impls.clone(),
            index: 0
        }
    }
}

#[derive(Clone)]
pub struct TraitImplsIter {
    blanket_impls: Rc<Vec<DefId>>,
    non_blanket_impls: Rc<Vec<DefId>>,
    index: usize,
}

impl Iterator for TraitImplsIter {
    type Item = DefId;

    fn next(&mut self) -> Option<DefId> {
        if self.index < self.blanket_impls.len() {
            let bi_index = self.index;
            self.index += 1;
            Some(self.blanket_impls[bi_index])
        } else {
            let nbi_index = self.index - self.blanket_impls.len();
            if nbi_index < self.non_blanket_impls.len() {
                self.index += 1;
                Some(self.non_blanket_impls[nbi_index])
            } else {
                None
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let items_left = (self.blanket_impls.len() + self.non_blanket_impls.len()) - self.index;
        (items_left, Some(items_left))
    }
}

impl ExactSizeIterator for TraitImplsIter {}

impl<'a, 'gcx, 'tcx> TraitDef {
    pub fn new(def_id: DefId,
               unsafety: hir::Unsafety,
               paren_sugar: bool,
               has_default_impl: bool,
               def_path_hash: u64)
               -> TraitDef {
        TraitDef {
            def_id,
            paren_sugar,
            unsafety,
            has_default_impl,
            def_path_hash,
        }
    }

    pub fn ancestors(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
                     of_impl: DefId)
                     -> specialization_graph::Ancestors {
        specialization_graph::ancestors(tcx, self.def_id, of_impl)
    }

    pub fn for_each_impl<F: FnMut(DefId)>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, mut f: F) {
        for impl_def_id in tcx.trait_impls_of(self.def_id).iter() {
            f(impl_def_id);
        }
    }

    /// Iterate over every impl that could possibly match the
    /// self-type `self_ty`.
    pub fn for_each_relevant_impl<F: FnMut(DefId)>(&self,
                                                   tcx: TyCtxt<'a, 'gcx, 'tcx>,
                                                   self_ty: Ty<'tcx>,
                                                   mut f: F)
    {
        // simplify_type(.., false) basically replaces type parameters and
        // projections with infer-variables. This is, of course, done on
        // the impl trait-ref when it is instantiated, but not on the
        // predicate trait-ref which is passed here.
        //
        // for example, if we match `S: Copy` against an impl like
        // `impl<T:Copy> Copy for Option<T>`, we replace the type variable
        // in `Option<T>` with an infer variable, to `Option<_>` (this
        // doesn't actually change fast_reject output), but we don't
        // replace `S` with anything - this impl of course can't be
        // selected, and as there are hundreds of similar impls,
        // considering them would significantly harm performance.
        let relevant_impls = if let Some(simplified_self_ty) =
                fast_reject::simplify_type(tcx, self_ty, true) {
            tcx.relevant_trait_impls_for((self.def_id, simplified_self_ty))
        } else {
            tcx.trait_impls_of(self.def_id)
        };

        for impl_def_id in relevant_impls.iter() {
            f(impl_def_id);
        }
    }
}

// Query provider for `trait_impls_of`.
pub(super) fn trait_impls_of_provider<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                                trait_id: DefId)
                                                -> TraitImpls {
    let remote_impls = if trait_id.is_local() {
        // Traits defined in the current crate can't have impls in upstream
        // crates, so we don't bother querying the cstore.
        Vec::new()
    } else {
        tcx.sess.cstore.implementations_of_trait(Some(trait_id))
    };

    let mut blanket_impls = Vec::new();
    let mut non_blanket_impls = Vec::new();

    let local_impls = tcx.hir
                         .trait_impls(trait_id)
                         .into_iter()
                         .map(|&node_id| tcx.hir.local_def_id(node_id));

     for impl_def_id in local_impls.chain(remote_impls.into_iter()) {
        let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
        if impl_def_id.is_local() && impl_trait_ref.references_error() {
            continue
        }

        if fast_reject::simplify_type(tcx, impl_trait_ref.self_ty(), false).is_some() {
            non_blanket_impls.push(impl_def_id);
        } else {
            blanket_impls.push(impl_def_id);
        }
    }

    TraitImpls {
        blanket_impls: Rc::new(blanket_impls),
        non_blanket_impls: Rc::new(non_blanket_impls),
    }
}

// Query provider for `relevant_trait_impls_for`.
pub(super) fn relevant_trait_impls_provider<'a, 'tcx>(
    tcx: TyCtxt<'a, 'tcx, 'tcx>,
    (trait_id, self_ty): (DefId, fast_reject::SimplifiedType))
    -> TraitImpls
{
    let all_trait_impls = tcx.trait_impls_of(trait_id);

    let relevant: Vec<DefId> = all_trait_impls
        .non_blanket_impls
        .iter()
        .cloned()
        .filter(|&impl_def_id| {
            let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
            let impl_simple_self_ty = fast_reject::simplify_type(tcx,
                                                                 impl_trait_ref.self_ty(),
                                                                 false).unwrap();
            impl_simple_self_ty == self_ty
        })
        .collect();

    if all_trait_impls.non_blanket_impls.len() == relevant.len() {
        // If we didn't filter anything out, re-use the existing vec.
        all_trait_impls
    } else {
        TraitImpls {
            blanket_impls: all_trait_impls.blanket_impls.clone(),
            non_blanket_impls: Rc::new(relevant),
        }
    }
}
<commit_msg>Use tcx.type_of(impl) instead of TraitRef::self_ty() for getting Self in relevant_impls_for().<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.

use hir::def_id::DefId;
use traits::specialization_graph;
use ty::fast_reject;
use ty::fold::TypeFoldable;
use ty::{Ty, TyCtxt};
use std::rc::Rc;
use hir;

/// A trait's definition with type information.
pub struct TraitDef {
    pub def_id: DefId,

    pub unsafety: hir::Unsafety,

    /// If `true`, then this trait had the `#[rustc_paren_sugar]`
    /// attribute, indicating that it should be used with `Foo()`
    /// sugar. This is a temporary thing -- eventually any trait will
    /// be usable with the sugar (or without it).
    pub paren_sugar: bool,

    pub has_default_impl: bool,

    /// The ICH of this trait's DefPath, cached here so it doesn't have to be
    /// recomputed all the time.
    pub def_path_hash: u64,
}

// We don't store the list of impls in a flat list because each cached list of
// `relevant_impls_for` we would then duplicate all blanket impls. By keeping
// blanket and non-blanket impls separate, we can share the list of blanket
// impls.
#[derive(Clone)]
pub struct TraitImpls {
    blanket_impls: Rc<Vec<DefId>>,
    non_blanket_impls: Rc<Vec<DefId>>,
}

impl TraitImpls {
    pub fn iter(&self) -> TraitImplsIter {
        TraitImplsIter {
            blanket_impls: self.blanket_impls.clone(),
            non_blanket_impls: self.non_blanket_impls.clone(),
            index: 0
        }
    }
}

#[derive(Clone)]
pub struct TraitImplsIter {
    blanket_impls: Rc<Vec<DefId>>,
    non_blanket_impls: Rc<Vec<DefId>>,
    index: usize,
}

impl Iterator for TraitImplsIter {
    type Item = DefId;

    fn next(&mut self) -> Option<DefId> {
        if self.index < self.blanket_impls.len() {
            let bi_index = self.index;
            self.index += 1;
            Some(self.blanket_impls[bi_index])
        } else {
            let nbi_index = self.index - self.blanket_impls.len();
            if nbi_index < self.non_blanket_impls.len() {
                self.index += 1;
                Some(self.non_blanket_impls[nbi_index])
            } else {
                None
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let items_left = (self.blanket_impls.len() + self.non_blanket_impls.len()) - self.index;
        (items_left, Some(items_left))
    }
}

impl ExactSizeIterator for TraitImplsIter {}

impl<'a, 'gcx, 'tcx> TraitDef {
    pub fn new(def_id: DefId,
               unsafety: hir::Unsafety,
               paren_sugar: bool,
               has_default_impl: bool,
               def_path_hash: u64)
               -> TraitDef {
        TraitDef {
            def_id,
            paren_sugar,
            unsafety,
            has_default_impl,
            def_path_hash,
        }
    }

    pub fn ancestors(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
                     of_impl: DefId)
                     -> specialization_graph::Ancestors {
        specialization_graph::ancestors(tcx, self.def_id, of_impl)
    }

    pub fn for_each_impl<F: FnMut(DefId)>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, mut f: F) {
        for impl_def_id in tcx.trait_impls_of(self.def_id).iter() {
            f(impl_def_id);
        }
    }

    /// Iterate over every impl that could possibly match the
    /// self-type `self_ty`.
    pub fn for_each_relevant_impl<F: FnMut(DefId)>(&self,
                                                   tcx: TyCtxt<'a, 'gcx, 'tcx>,
                                                   self_ty: Ty<'tcx>,
                                                   mut f: F)
    {
        // simplify_type(.., false) basically replaces type parameters and
        // projections with infer-variables. This is, of course, done on
        // the impl trait-ref when it is instantiated, but not on the
        // predicate trait-ref which is passed here.
        //
        // for example, if we match `S: Copy` against an impl like
        // `impl<T:Copy> Copy for Option<T>`, we replace the type variable
        // in `Option<T>` with an infer variable, to `Option<_>` (this
        // doesn't actually change fast_reject output), but we don't
        // replace `S` with anything - this impl of course can't be
        // selected, and as there are hundreds of similar impls,
        // considering them would significantly harm performance.
        let relevant_impls = if let Some(simplified_self_ty) =
                fast_reject::simplify_type(tcx, self_ty, true) {
            tcx.relevant_trait_impls_for((self.def_id, simplified_self_ty))
        } else {
            tcx.trait_impls_of(self.def_id)
        };

        for impl_def_id in relevant_impls.iter() {
            f(impl_def_id);
        }
    }
}

// Query provider for `trait_impls_of`.
pub(super) fn trait_impls_of_provider<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                                trait_id: DefId)
                                                -> TraitImpls {
    let remote_impls = if trait_id.is_local() {
        // Traits defined in the current crate can't have impls in upstream
        // crates, so we don't bother querying the cstore.
        Vec::new()
    } else {
        tcx.sess.cstore.implementations_of_trait(Some(trait_id))
    };

    let mut blanket_impls = Vec::new();
    let mut non_blanket_impls = Vec::new();

    let local_impls = tcx.hir
                         .trait_impls(trait_id)
                         .into_iter()
                         .map(|&node_id| tcx.hir.local_def_id(node_id));

     for impl_def_id in local_impls.chain(remote_impls.into_iter()) {
        let impl_self_ty = tcx.type_of(impl_def_id);
        if impl_def_id.is_local() && impl_self_ty.references_error() {
            continue
        }

        if fast_reject::simplify_type(tcx, impl_self_ty, false).is_some() {
            non_blanket_impls.push(impl_def_id);
        } else {
            blanket_impls.push(impl_def_id);
        }
    }

    TraitImpls {
        blanket_impls: Rc::new(blanket_impls),
        non_blanket_impls: Rc::new(non_blanket_impls),
    }
}

// Query provider for `relevant_trait_impls_for`.
pub(super) fn relevant_trait_impls_provider<'a, 'tcx>(
    tcx: TyCtxt<'a, 'tcx, 'tcx>,
    (trait_id, self_ty): (DefId, fast_reject::SimplifiedType))
    -> TraitImpls
{
    let all_trait_impls = tcx.trait_impls_of(trait_id);

    let relevant: Vec<DefId> = all_trait_impls
        .non_blanket_impls
        .iter()
        .cloned()
        .filter(|&impl_def_id| {
            let impl_self_ty = tcx.type_of(impl_def_id);
            let impl_simple_self_ty = fast_reject::simplify_type(tcx,
                                                                 impl_self_ty,
                                                                 false).unwrap();
            impl_simple_self_ty == self_ty
        })
        .collect();

    if all_trait_impls.non_blanket_impls.len() == relevant.len() {
        // If we didn't filter anything out, re-use the existing vec.
        all_trait_impls
    } else {
        TraitImpls {
            blanket_impls: all_trait_impls.blanket_impls.clone(),
            non_blanket_impls: Rc::new(relevant),
        }
    }
}
<|endoftext|>