<commit_before>#![crate_id = "piston"]
#![deny(missing_doc)]
#![warn(dead_code)]

//! A user friendly graphics engine.

extern crate time;
extern crate sync;

pub use ConcurrentGame = concurrent_game::ConcurrentGame;
pub use Game = game::Game;

pub use GameWindow = game_window::GameWindow;
pub use RenderWindow = game_window::RenderWindow;
pub use GameWindowSettings = game_window_settings::GameWindowSettings;
pub use AssetStore = asset_store::AssetStore;

pub use game_iterator::Render;
pub use game_iterator::Update;
pub use game_iterator::KeyPress;
pub use game_iterator::KeyRelease;
pub use game_iterator::MousePress;
pub use game_iterator::MouseRelease;
pub use game_iterator::MouseMove;
pub use game_iterator::MouseRelativeMove;
pub use game_iterator::MouseScroll;

pub use game_iterator::GameEvent;
pub use game_iterator::GameIterator;
pub use game_iterator::GameIteratorSettings;
pub use game_iterator::RenderArgs;
pub use game_iterator::UpdateArgs;
pub use game_iterator::KeyPressArgs;
pub use game_iterator::KeyReleaseArgs;
pub use game_iterator::MousePressArgs;
pub use game_iterator::MouseReleaseArgs;
pub use game_iterator::MouseMoveArgs;
pub use game_iterator::MouseRelativeMoveArgs;
pub use game_iterator::MouseScrollArgs;

pub mod game_window;
pub mod keyboard;
pub mod event;
pub mod mouse;

mod concurrent_game;
mod game;
mod game_iterator;
mod game_window_settings;
mod asset_store;
<commit_msg>Update crate_id to crate_name in lib.rs<commit_after>#![crate_name = "piston"]
#![deny(missing_doc)]
#![warn(dead_code)]

//! A user friendly graphics engine.

extern crate time;
extern crate sync;

pub use ConcurrentGame = concurrent_game::ConcurrentGame;
pub use Game = game::Game;

pub use GameWindow = game_window::GameWindow;
pub use RenderWindow = game_window::RenderWindow;
pub use GameWindowSettings = game_window_settings::GameWindowSettings;
pub use AssetStore = asset_store::AssetStore;

pub use game_iterator::Render;
pub use game_iterator::Update;
pub use game_iterator::KeyPress;
pub use game_iterator::KeyRelease;
pub use game_iterator::MousePress;
pub use game_iterator::MouseRelease;
pub use game_iterator::MouseMove;
pub use game_iterator::MouseRelativeMove;
pub use game_iterator::MouseScroll;

pub use game_iterator::GameEvent;
pub use game_iterator::GameIterator;
pub use game_iterator::GameIteratorSettings;
pub use game_iterator::RenderArgs;
pub use game_iterator::UpdateArgs;
pub use game_iterator::KeyPressArgs;
pub use game_iterator::KeyReleaseArgs;
pub use game_iterator::MousePressArgs;
pub use game_iterator::MouseReleaseArgs;
pub use game_iterator::MouseMoveArgs;
pub use game_iterator::MouseRelativeMoveArgs;
pub use game_iterator::MouseScrollArgs;

pub mod game_window;
pub mod keyboard;
pub mod event;
pub mod mouse;

mod concurrent_game;
mod game;
mod game_iterator;
mod game_window_settings;
mod asset_store;
<|endoftext|>


<commit_before><commit_msg>Implemented simple combinators following what exists in parsec<commit_after>#![allow(unstable)]

#[derive(Show, PartialEq)]
pub struct Error;

pub type ParseResult<O, I> = Result<(O, I), Error>;
pub type StrResult<'a, O> = ParseResult<O, &'a str>;

pub trait Parser {
    type Input: Clone;
    type Output;
    fn parse(&mut self, input: <Self as Parser>::Input) ->
        Result<(<Self as Parser>::Output, <Self as Parser>::Input), Error>;
}
impl <'a, I, O, P> Parser for &'a mut P
    where I: Clone, P: Parser<Input=I, Output=O> {
    type Input = I;
    type Output = O;
    fn parse(&mut self, input: I) -> Result<(O, I), Error> {
        (*self).parse(input)
    }
}

pub fn char<'a>(input: &'a str) -> ParseResult<char, &'a str> {
    match input.slice_shift_char() {
        Some(x) => Ok(x),
        None => Err(Error)
    }
}

pub struct Many<P> {
    parser: P
}
impl <P: Parser> Parser for Many<P> {
    type Input = <P as Parser>::Input;
    type Output = Vec<<P as Parser>::Output>;
    fn parse(&mut self, mut input: <P as Parser>::Input) -> Result<(Vec<<P as Parser>::Output>, <P as Parser>::Input), Error> {
        let mut result = Vec::new();
        loop {
            match self.parser.parse(input.clone()) {
                Ok((x, rest)) => {
                    result.push(x);
                    input = rest;
                }
                Err(_) => break
            }
        }
        Ok((result, input))
    }
}
pub fn many<P: Parser>(p: P) -> Many<P> {
    Many { parser: p }
}

pub fn many1<'a, P: Clone + 'a>(mut p: P) -> FnParser<'a, <P as Parser>::Input, Vec<<P as Parser>::Output>>
    where P: Parser {
    Box::new(move |&mut:input| {
        let (first, input) = try!(p.parse(input));
        let (mut rest, input) = try!(many(&mut p).parse(input));
        rest.insert(0, first);
        Ok((rest, input))
    })
}

pub struct SepBy<P, S> {
    parser: P,
    separator: S
}
impl <P, S> Parser for SepBy<P, S>
    where P: Parser, S: Parser<Input=<P as Parser>::Input> {

    type Input = <P as Parser>::Input;
    type Output = Vec<<P as Parser>::Output>;
    fn parse(&mut self, mut input: <P as Parser>::Input) -> Result<(Vec<<P as Parser>::Output>, <P as Parser>::Input), Error> {
        let mut result = Vec::new();
        match self.parser.parse(input.clone()) {
            Ok((x, rest)) => {
                result.push(x);
                input = rest;
            }
            Err(_) => return Ok((result, input))
        }
        loop {
            match self.separator.parse(input.clone()) {
                Ok((_, rest)) => input = rest,
                Err(e) => break
            }
            match self.parser.parse(input.clone()) {
                Ok((x, rest)) => {
                    result.push(x);
                    input = rest;
                }
                Err(e) => return Err(e)
            }
        }
        Ok((result, input))
    }
}
pub fn sep_by<P: Parser, S: Parser>(parser: P, separator: S) -> SepBy<P, S> {
    SepBy { parser: parser, separator: separator }
}

pub type FnParser<'a, I, O> = Box<FnMut(I) -> Result<(O, I), Error> + 'a>;

impl <'a, I: Clone, O> Parser for FnParser<'a, I, O> {
    type Input = I;
    type Output = O;
    fn parse(&mut self, input: I) -> Result<(O, I), Error> {
        self(input)
    }
}

impl <'a, I: Clone, O> Parser for fn (I) -> ParseResult<O, I> {
    type Input = I;
    type Output = O;
    fn parse(&mut self, input: I) -> ParseResult<O, I> {
        self(input)
    }
}

pub struct Satisfy<Pred> { pred: Pred }

impl <'a, Pred> Parser for Satisfy<Pred>
    where Pred: FnMut(char) -> bool {

    type Input = &'a str;
    type Output = char;
    fn parse(&mut self, input: &'a str) -> Result<(char, &'a str), Error> {
        match input.slice_shift_char() {
            Some((c, s)) => {
                if (self.pred)(c) { Ok((c, s)) }
                else { Err(Error) }
            }
            None => Err(Error)
        }
    }
}

pub fn satisfy<Pred>(pred: Pred) -> Satisfy<Pred>
    where Pred: FnMut(char) -> bool {
    Satisfy { pred: pred }
}

pub fn space() -> Satisfy<fn (char) -> bool> {
    satisfy(CharExt::is_whitespace as fn (char) -> bool)
}

pub struct StringP<'a> { s: &'a str }
impl <'a, 'b> Parser for StringP<'b> {
    type Input = &'a str;
    type Output = &'a str;
    fn parse(&mut self, input: &'a str) -> Result<(&'a str, &'a str), Error> {
        if input.starts_with(self.s) {
            let l = self.s.len();
            Ok((&input[..l], &input[l..]))
        }
        else {
            Err(Error)
        }
    }
}

pub fn string(s: &str) -> StringP {
    StringP { s: s }
}

pub struct AndThen<P1, P2>(P1, P2);
impl <I: Clone, A, B, P1, P2> Parser for AndThen<P1, P2>
    where P1: Parser<Input=I, Output=A>, P2: Parser<Input=I, Output=B> {

    type Input = I;
    type Output = (A, B);
    fn parse(&mut self, input: I) -> Result<((A, B), I), Error> {
        let (a, rest) = try!(self.0.parse(input));
        let (b, rest) = try!(self.1.parse(rest));
        Ok(((a, b), rest))
    }
}
pub fn and_then<P1, P2>(p1: P1, p2: P2) -> AndThen<P1, P2>
    where P1: Parser, P2: Parser {
    AndThen(p1, p2)
}

pub struct Optional<P>(P);
impl <P> Parser for Optional<P>
    where P: Parser {
    type Input = <P as Parser>::Input;
    type Output = Option<<P as Parser>::Output>;
    fn parse(&mut self, input: <P as Parser>::Input) -> Result<(Option<<P as Parser>::Output>, <P as Parser>::Input), Error> {
        match self.0.parse(input.clone()) {
            Ok((x, rest)) => Ok((Some(x), rest)),
            Err(_) => Ok((None, input))
        }
    }
}
pub fn optional<P>(parser: P) -> Optional<P> {
    Optional(parser)
}

pub struct Env<I> {
    input: I
}

impl <I: Clone> Env<I> {
    pub fn new(input: I) -> Env<I> {
        Env { input: input }
    }

    pub fn with<P, O>(&mut self, mut parser: P) -> Result<O, Error>
        where P: Parser<Input=I, Output=O> {
        let (o, rest) = try!(parser.parse(self.input.clone()));
        self.input = rest;
        Ok(o)
    }

    pub fn result<O>(self, output: O) -> Result<(O, I), Error> {
        Ok((output, self.input))
    }
}

pub fn digit<'a>(input: &'a str) -> ParseResult<char, &'a str> {
    match input.slice_shift_char() {
        Some(x) if x.0.is_digit(10) => Ok(x),
        Some((c, _)) => Err(Error),
        None => Err(Error)
    }
}

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

    fn integer<'a>(input: &'a str) -> Result<(i64, &'a str), Error> {
        let mut env = Env::new(input);
        let chars = try!(env.with(many(digit as fn(_) -> _)));
        let mut n = 0;
        for &c in chars.iter() {
            n = n * 10 + (c as i64 - '0' as i64);
        }
        env.result(n)
    }

    #[test]
    fn test_integer() {
        assert_eq!((integer as fn(_) -> _).parse("123"), Ok((123i64, "")));
    }
    #[test]
    fn list() {
        let mut p = sep_by(integer as fn(_) -> _, satisfy(|c| c == ','));
        assert_eq!(p.parse("123,4,56"), Ok((vec![123, 4, 56], "")));
    }
}

/*

impl Parser for  {
    type Input = ;
    type Output = ;
    fn parse(&mut self, input: ) -> Result<(, ), Error>;
}
 */
<|endoftext|>


<commit_before><commit_msg>`IXAudio2Voice::SetVolume()`<commit_after><|endoftext|>


<commit_before><commit_msg>Update doc examples for new APIs.<commit_after><|endoftext|>


<commit_before><commit_msg>Add docs for if_mut, if_const, ptr and raw_ptr macros<commit_after><|endoftext|>


<commit_before><commit_msg>Be less forgiving for contract violations.<commit_after><|endoftext|>


<commit_before><commit_msg>Added group tests<commit_after><|endoftext|>


<commit_before><commit_msg>Enable unboxed closures<commit_after><|endoftext|>


<commit_before><commit_msg>fix(lib): actually add #![feature(slicing_syntax)] this time<commit_after><|endoftext|>


<commit_before><commit_msg>this is done<commit_after><|endoftext|>


<commit_before><commit_msg>set npc sprite to default after player interaction<commit_after><|endoftext|>


<commit_before><commit_msg>delete unused import<commit_after><|endoftext|>


<commit_before><commit_msg>Start new buffer data structure<commit_after>use std::mem::swap;

/// The buffer data structure, that Sodium is using.
///
/// This structure consists of two "subbuffers", which are just vectors over lines (defined by
/// Strings). The split is where the cursor currently is.
///
/// The second buffer is in reverse order to get the particular efficiency we want.
pub struct SplitBuffer {
    before: Vec<String>,
    after: Vec<String>,
}

impl SplitBuffer {
    /// Create a new empty buffer
    pub fn new() -> Self {
        SplitBuffer {
            before: vec![String::new()],
            after: Vec::new(),
        }
    }

    pub fn get_line(&self) -> &String {
        self.before.last().expect("Unexpected condition (the first part of the split buffer is empty)")
    }

    pub fn get_line_mut(&mut self) -> &mut String {
        self.before.last_mut().expect("Unexpected condition (the first part of the split buffer is empty)")
    }

    pub fn up(&mut self) -> bool {
        if self.before.len() == 1 {
            false
        } else {
            self.after.push(self.before.pop());
            true
        }
    }

    pub fn down(&mut self) -> bool {
        if self.after.len() == 1 {
            false
        } else {
            self.before.push(self.after.pop());
            true
        }
    }

    pub fn line(&self) -> usize {
        self.before.len()
    }

    pub fn get_nth_line(&self, n: usize) -> Option<&String> {
        if n < self.before.len() {
            Some(&self.before[n])
        } else if n < self.before.len() + self.after.len() {
            Some(&self.after[n - self.before.len()])
        } else {
            None
        }
    }

    pub fn get_nth_line_mut(&mut self, n: usize) -> Option<&mut String> {
        if n < self.before.len() {
            Some(&mut self.before[n])
        } else if n < self.before.len() + self.after.len() {
            Some(&mut self.after[n - self.before.len()])
        } else {
            None
        }
    }

    pub fn remove_line(&mut self, n: usize) {
        if n < self.before.len() {
            self.before.remove(n);
            Some(&mut self.before[n])
        } else if n < self.before.len() + self.after.len() {
            self.after.remove(n - self.before.len());
        }
    }

    pub fn from_lines(vec: Vec<String>) -> SplitBuffer {
        SplitBuffer {
            before: vec,
            after: Vec::new(),
        }
    }

    pub fn goto(&mut self, y: usize) {
        if y < self.line() {
            for _ in 1..self.line() - y {
                if !self.up() {
                    break;
                }
            }
        } else if y > self.line() {
            for _ in 1..y - self.line() {
                if !self.down() {
                    break;
                }
            }
        }
    }

    pub fn pop_line(&mut self) -> String {
        self.before.expect("Unexpected condition (Popped the last line)")
    }

    pub fn len(&self) -> usize {
        self.before.len() + self.after.len()
    }

    pub fn iter(&self) -> ::std::iter::Once<Vec<char>> {
        self.after.iter().chain(self.before.iter().reverse())
    }
}
<|endoftext|>


<commit_before>// Copyright 2017 The Gfx-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 env_logger;
extern crate gfx_corell;
#[cfg(all(target_os = "windows", not(feature = "vulkan")))]
extern crate gfx_device_dx12ll as back;
#[cfg(feature = "vulkan")]
extern crate gfx_device_vulkanll as back;

extern crate winit;

use gfx_corell::{Instance, Adapter, Surface, SwapChain, QueueFamily};

pub type ColorFormat = gfx_corell::format::Rgba8;

fn main() {
    env_logger::init().unwrap();
    let window = winit::WindowBuilder::new()
        .with_dimensions(1024, 768)
        .with_title("triangle (Low Level)".to_string())
        .build()
        .unwrap();

    // instantiate backend
    let instance = back::Instance::create();
    let physical_devices = instance.enumerate_adapters();
    let surface = instance.create_surface(&window);

    let queue_descs = physical_devices[0].get_queue_families().map(|family| { (family, family.num_queues()) });

    for device in &physical_devices {
        println!("{:?}", device.get_info());
    }

    // build a new device and associated command queues
    let (device, queues) = physical_devices[0].open(queue_descs);

    let mut swap_chain = surface.build_swapchain::<ColorFormat>(&queues[0]);

    'main: loop {
        for event in window.poll_events() {
            match event {
                winit::Event::KeyboardInput(_, _, Some(winit::VirtualKeyCode::Escape)) |
                winit::Event::Closed => break 'main,
                _ => {},
            }
        }

        let frame = swap_chain.acquire_frame();

        // rendering

        // present frame
        swap_chain.present();
    }
}<commit_msg>Auto merge of #1174 - msiglreith:trianglell_osx, r=kvark<commit_after>// Copyright 2017 The Gfx-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 env_logger;
extern crate gfx_corell;
#[cfg(all(target_os = "windows", not(feature = "vulkan")))]
extern crate gfx_device_dx12ll as back;
#[cfg(feature = "vulkan")]
extern crate gfx_device_vulkanll as back;

extern crate winit;

use gfx_corell::{Instance, Adapter, Surface, SwapChain, QueueFamily};

pub type ColorFormat = gfx_corell::format::Rgba8;

#[cfg(any(feature = "vulkan", target_os = "windows"))]
fn main() {
    env_logger::init().unwrap();
    let window = winit::WindowBuilder::new()
        .with_dimensions(1024, 768)
        .with_title("triangle (Low Level)".to_string())
        .build()
        .unwrap();

    // instantiate backend
    let instance = back::Instance::create();
    let physical_devices = instance.enumerate_adapters();
    let surface = instance.create_surface(&window);

    let queue_descs = physical_devices[0].get_queue_families().map(|family| { (family, family.num_queues()) });

    for device in &physical_devices {
        println!("{:?}", device.get_info());
    }

    // build a new device and associated command queues
    let (device, queues) = physical_devices[0].open(queue_descs);

    let mut swap_chain = surface.build_swapchain::<ColorFormat>(&queues[0]);

    'main: loop {
        for event in window.poll_events() {
            match event {
                winit::Event::KeyboardInput(_, _, Some(winit::VirtualKeyCode::Escape)) |
                winit::Event::Closed => break 'main,
                _ => {},
            }
        }

        let frame = swap_chain.acquire_frame();

        // rendering

        // present frame
        swap_chain.present();
    }
}

#[cfg(not(any(feature = "vulkan", target_os = "windows")))]
fn main() {}
<|endoftext|>


<commit_before><commit_msg>Add a regression test for issue-70292<commit_after>// check-pass

#![feature(associated_type_bounds)]

fn foo<F>(_: F)
where
    F: for<'a> Trait<Output: 'a>,
{
}

trait Trait {
    type Output;
}

impl<T> Trait for T {
    type Output = ();
}

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


<commit_before>use super::package::*;
use super::executor::*;

use alloc::boxed::Box;

use core::{cmp, ptr, mem};

use common::event::{self, Event, EventOption, KeyEvent, MouseEvent};
use common::resource::{NoneResource, Resource, ResourceType, URL, VecResource};
use common::scheduler::*;
use common::string::{String, ToString};
use common::vec::Vec;

use graphics::bmp::*;
use graphics::color::Color;
use graphics::display::Display;
use graphics::point::Point;
use graphics::size::Size;
use graphics::window::Window;

use programs::common::SessionItem;

pub struct Session {
    pub display: Display,
    pub background: BMPFile,
    pub cursor: BMPFile,
    pub mouse_point: Point,
    last_mouse_event: MouseEvent,
    pub items: Vec<Box<SessionItem>>,
    pub packages: Vec<Box<Package>>,
    pub windows: Vec<*mut Window>,
    pub windows_ordered: Vec<*mut Window>,
    pub redraw: usize,
}

impl Session {
    pub fn new() -> Self {
        unsafe {
            Session {
                display: Display::root(),
                background: BMPFile::new(),
                cursor: BMPFile::new(),
                mouse_point: Point::new(0, 0),
                last_mouse_event: MouseEvent {
                    x: 0,
                    y: 0,
                    left_button: false,
                    middle_button: false,
                    right_button: false,
                },
                items: Vec::new(),
                packages: Vec::new(),
                windows: Vec::new(),
                windows_ordered: Vec::new(),
                redraw: event::REDRAW_ALL,
            }
        }
    }

    pub unsafe fn add_window(&mut self, add_window_ptr: *mut Window) {
        self.windows.push(add_window_ptr);
        self.windows_ordered.push(add_window_ptr);
        self.redraw = cmp::max(self.redraw, event::REDRAW_ALL);
    }

    pub unsafe fn remove_window(&mut self, remove_window_ptr: *mut Window) {
        let mut i = 0;
        while i < self.windows.len() {
            let mut remove = false;

            match self.windows.get(i) {
                Option::Some(window_ptr) => if *window_ptr == remove_window_ptr {
                    remove = true;
                } else {
                    i += 1;
                },
                Option::None => break,
            }

            if remove {
                self.windows.remove(i);
            }
        }

        i = 0;
        while i < self.windows_ordered.len() {
            let mut remove = false;

            match self.windows_ordered.get(i) {
                Option::Some(window_ptr) => if *window_ptr == remove_window_ptr {
                    remove = true;
                } else {
                    i += 1;
                },
                Option::None => break,
            }

            if remove {
                self.windows_ordered.remove(i);
            }
        }

        self.redraw = cmp::max(self.redraw, event::REDRAW_ALL);
    }

    pub unsafe fn on_irq(&mut self, irq: u8) {
        for item in self.items.iter() {
            let reenable = start_no_ints();
            item.on_irq(irq);
            end_no_ints(reenable);
        }
    }

    pub unsafe fn on_poll(&mut self) {
        for item in self.items.iter() {
            let reenable = start_no_ints();
            item.on_poll();
            end_no_ints(reenable);
        }
    }

    pub fn open(&self, url: &URL) -> Box<Resource> {
        if url.scheme().len() == 0 {
            let mut list = String::new();

            for item in self.items.iter() {
                let scheme = item.scheme();
                if scheme.len() > 0 {
                    if list.len() > 0 {
                        list = list + "\n" + scheme;
                    } else {
                        list = scheme;
                    }
                }
            }

            box VecResource::new(URL::new(), ResourceType::Dir, list.to_utf8())
        } else {
            for item in self.items.iter() {
                if item.scheme() == url.scheme() {
                    return item.open(url);
                }
            }
            box NoneResource
        }
    }

    fn on_key(&mut self, key_event: KeyEvent) {
        if self.windows.len() > 0 {
            match self.windows.get(self.windows.len() - 1) {
                Option::Some(window_ptr) => {
                    unsafe {
                        (**window_ptr).on_key(key_event);
                        self.redraw = cmp::max(self.redraw, event::REDRAW_ALL);
                    }
                }
                Option::None => (),
            }
        }
    }

    fn on_mouse(&mut self, mouse_event: MouseEvent) {
        let mut catcher = -1;

        if mouse_event.y >= self.display.height as isize - 32 {
            if mouse_event.left_button && !self.last_mouse_event.left_button {
                let mut x = 0;
                for package in self.packages.iter() {
                    if package.icon.data.len() > 0 {
                        if mouse_event.x >= x &&
                           mouse_event.x < x + package.icon.size.width as isize {
                            execute(&package.binary, &package.url, &Vec::new());
                        }
                        x += package.icon.size.width as isize;
                    }
                }

                let mut chars = 32;
                while chars > 4 &&
                      (x as usize + (chars * 8 + 3 * 4) * self.windows.len()) >
                      self.display.width + 32 {
                    chars -= 1;
                }

                x += 4;
                for window_ptr in self.windows_ordered.iter() {
                    let w = (chars*8 + 2*4) as usize;
                    if mouse_event.x >= x && mouse_event.x < x + w as isize {
                        for j in 0..self.windows.len() {
                            match self.windows.get(j) {
                                Option::Some(catcher_window_ptr) =>
                                    if catcher_window_ptr == window_ptr {
                                    unsafe {
                                        if j == self.windows.len() - 1 {
                                            (**window_ptr).minimized = !(**window_ptr).minimized;
                                        } else {
                                            catcher = j as isize;
                                            (**window_ptr).minimized = false;
                                        }
                                    }
                                    break;
                                },
                                Option::None => break,
                            }
                        }
                        self.redraw = cmp::max(self.redraw, event::REDRAW_ALL);
                        break;
                    }
                    x += w as isize;
                }
            }
        } else {
            for reverse_i in 0..self.windows.len() {
                let i = self.windows.len() - 1 - reverse_i;
                match self.windows.get(i) {
                    Option::Some(window_ptr) => unsafe {
                        if reverse_i == 0 ||
                           (mouse_event.left_button && !self.last_mouse_event.left_button) {
                            if (**window_ptr).on_mouse(mouse_event, catcher < 0) {
                                catcher = i as isize;

                                self.redraw = cmp::max(self.redraw, event::REDRAW_ALL);
                            }
                        }
                    },
                    Option::None => (),
                }
            }
        }

        if catcher >= 0 && catcher < self.windows.len() as isize - 1 {
            match self.windows.remove(catcher as usize) {
                Option::Some(window_ptr) => self.windows.push(window_ptr),
                Option::None => (),
            }
        }

        self.last_mouse_event = mouse_event;
    }

    pub unsafe fn redraw(&mut self) {
        if self.redraw > event::REDRAW_NONE {
            //if self.redraw >= REDRAW_ALL {
            self.display.set(Color::new(64, 64, 64));
            if self.background.data.len() > 0 {
                self.background.draw(&self.display,
                                     Point::new((self.display.width as isize -
                                                 self.background.size.width as isize) /
                                                2,
                                                (self.display.height as isize -
                                                 self.background.size.height as isize) /
                                                2));
            }

            for i in 0..self.windows.len() {
                match self.windows.get(i) {
                    Option::Some(window_ptr) => {
                        (**window_ptr).focused = i == self.windows.len() - 1;
                        (**window_ptr).draw(&self.display);
                    }
                    Option::None => (),
                }
            }

            self.display.rect(Point::new(0, self.display.height as isize - 32),
                              Size::new(self.display.width, 32),
                              Color::alpha(0, 0, 0, 128));

            let mut x = 0;
            for package in self.packages.iter() {
                if package.icon.data.len() > 0 {
                    let y = self.display.height as isize - package.icon.size.height as isize;
                    if self.mouse_point.y >= y && self.mouse_point.x >= x &&
                       self.mouse_point.x < x + package.icon.size.width as isize {
                        self.display.rect(Point::new(x, y),
                                          package.icon.size,
                                          Color::alpha(128, 128, 128, 128));

                        let mut c_x = x;
                        for c in package.name.chars() {
                            self.display
                                .char(Point::new(c_x, y - 16), c, Color::new(255, 255, 255));
                            c_x += 8;
                        }
                    }
                    package.icon.draw(&self.display, Point::new(x, y));
                    x += package.icon.size.width as isize;
                }
            }

            let mut chars = 32;
            while chars > 4 &&
                  (x as usize + (chars * 8 + 3 * 4) * self.windows.len()) >
                  self.display.width + 32 {
                chars -= 1;
            }

            x += 4;
            for window_ptr in self.windows_ordered.iter() {
                let w = (chars*8 + 2*4) as usize;
                self.display.rect(Point::new(x, self.display.height as isize - 32),
                                  Size::new(w, 32),
                                  (**window_ptr).border_color);
                x += 4;

                for i in 0..chars {
                    let c = (**window_ptr).title[i];
                    if c != '\0' {
                        self.display.char(Point::new(x, self.display.height as isize - 24),
                                          c,
                                          (**window_ptr).title_color);
                    }
                    x += 8;
                }
                x += 8;
            }

            if self.cursor.data.len() > 0 {
                self.display.image_alpha(self.mouse_point,
                                         self.cursor.data.as_ptr(),
                                         self.cursor.size);
            } else {
                self.display.char(Point::new(self.mouse_point.x - 3, self.mouse_point.y - 9),
                                  'X',
                                  Color::new(255, 255, 255));
            }
            //}

            let reenable = start_no_ints();

            self.display.flip();

            /*
            if self.cursor.data.len() > 0 {
                self.display.image_alpha_onscreen(self.mouse_point, self.cursor.data.as_ptr(), self.cursor.size);
            } else {
                self.display.char_onscreen(Point::new(self.mouse_point.x - 3, self.mouse_point.y - 9), 'X', Color::new(255, 255, 255));
            }
            */

            self.redraw = event::REDRAW_NONE;

            end_no_ints(reenable);
        }
    }

    pub fn event(&mut self, event: Event) {
        match event.to_option() {
            EventOption::Mouse(mouse_event) => self.on_mouse(mouse_event),
            EventOption::Key(key_event) => self.on_key(key_event),
            EventOption::Redraw(redraw_event) =>
                self.redraw = cmp::max(self.redraw, redraw_event.redraw),
            EventOption::Open(open_event) => {
                let url_string = open_event.url_string;

                if url_string.ends_with(".bin".to_string()) {
                    execute(&URL::from_string(&url_string),
                            &URL::new(),
                            &Vec::new());
                } else {
                    for package in self.packages.iter() {
                        let mut accepted = false;
                        for accept in package.accepts.iter() {
                            if url_string.ends_with(accept.substr(1, accept.len() - 1)) {
                                accepted = true;
                                break;
                            }
                        }
                        if accepted {
                            let mut args: Vec<String> = Vec::new();
                            args.push(url_string.clone());
                            execute(&package.binary, &package.url, &args);
                            break;
                        }
                    }
                }
            }
            _ => (),
        }
    }
}
<commit_msg>Fix issue with windows not focused being dragged at an offset<commit_after>use super::package::*;
use super::executor::*;

use alloc::boxed::Box;

use core::{cmp, ptr, mem};

use common::event::{self, Event, EventOption, KeyEvent, MouseEvent};
use common::resource::{NoneResource, Resource, ResourceType, URL, VecResource};
use common::scheduler::*;
use common::string::{String, ToString};
use common::vec::Vec;

use graphics::bmp::*;
use graphics::color::Color;
use graphics::display::Display;
use graphics::point::Point;
use graphics::size::Size;
use graphics::window::Window;

use programs::common::SessionItem;

pub struct Session {
    pub display: Display,
    pub background: BMPFile,
    pub cursor: BMPFile,
    pub mouse_point: Point,
    last_mouse_event: MouseEvent,
    pub items: Vec<Box<SessionItem>>,
    pub packages: Vec<Box<Package>>,
    pub windows: Vec<*mut Window>,
    pub windows_ordered: Vec<*mut Window>,
    pub redraw: usize,
}

impl Session {
    pub fn new() -> Self {
        unsafe {
            Session {
                display: Display::root(),
                background: BMPFile::new(),
                cursor: BMPFile::new(),
                mouse_point: Point::new(0, 0),
                last_mouse_event: MouseEvent {
                    x: 0,
                    y: 0,
                    left_button: false,
                    middle_button: false,
                    right_button: false,
                },
                items: Vec::new(),
                packages: Vec::new(),
                windows: Vec::new(),
                windows_ordered: Vec::new(),
                redraw: event::REDRAW_ALL,
            }
        }
    }

    pub unsafe fn add_window(&mut self, add_window_ptr: *mut Window) {
        self.windows.push(add_window_ptr);
        self.windows_ordered.push(add_window_ptr);
        self.redraw = cmp::max(self.redraw, event::REDRAW_ALL);
    }

    pub unsafe fn remove_window(&mut self, remove_window_ptr: *mut Window) {
        let mut i = 0;
        while i < self.windows.len() {
            let mut remove = false;

            match self.windows.get(i) {
                Option::Some(window_ptr) => if *window_ptr == remove_window_ptr {
                    remove = true;
                } else {
                    i += 1;
                },
                Option::None => break,
            }

            if remove {
                self.windows.remove(i);
            }
        }

        i = 0;
        while i < self.windows_ordered.len() {
            let mut remove = false;

            match self.windows_ordered.get(i) {
                Option::Some(window_ptr) => if *window_ptr == remove_window_ptr {
                    remove = true;
                } else {
                    i += 1;
                },
                Option::None => break,
            }

            if remove {
                self.windows_ordered.remove(i);
            }
        }

        self.redraw = cmp::max(self.redraw, event::REDRAW_ALL);
    }

    pub unsafe fn on_irq(&mut self, irq: u8) {
        for item in self.items.iter() {
            let reenable = start_no_ints();
            item.on_irq(irq);
            end_no_ints(reenable);
        }
    }

    pub unsafe fn on_poll(&mut self) {
        for item in self.items.iter() {
            let reenable = start_no_ints();
            item.on_poll();
            end_no_ints(reenable);
        }
    }

    pub fn open(&self, url: &URL) -> Box<Resource> {
        if url.scheme().len() == 0 {
            let mut list = String::new();

            for item in self.items.iter() {
                let scheme = item.scheme();
                if scheme.len() > 0 {
                    if list.len() > 0 {
                        list = list + "\n" + scheme;
                    } else {
                        list = scheme;
                    }
                }
            }

            box VecResource::new(URL::new(), ResourceType::Dir, list.to_utf8())
        } else {
            for item in self.items.iter() {
                if item.scheme() == url.scheme() {
                    return item.open(url);
                }
            }
            box NoneResource
        }
    }

    fn on_key(&mut self, key_event: KeyEvent) {
        if self.windows.len() > 0 {
            match self.windows.get(self.windows.len() - 1) {
                Option::Some(window_ptr) => {
                    unsafe {
                        (**window_ptr).on_key(key_event);
                        self.redraw = cmp::max(self.redraw, event::REDRAW_ALL);
                    }
                }
                Option::None => (),
            }
        }
    }

    fn on_mouse(&mut self, mouse_event: MouseEvent) {
        let mut catcher = -1;

        if mouse_event.y >= self.display.height as isize - 32 {
            if mouse_event.left_button && !self.last_mouse_event.left_button {
                let mut x = 0;
                for package in self.packages.iter() {
                    if package.icon.data.len() > 0 {
                        if mouse_event.x >= x &&
                           mouse_event.x < x + package.icon.size.width as isize {
                            execute(&package.binary, &package.url, &Vec::new());
                        }
                        x += package.icon.size.width as isize;
                    }
                }

                let mut chars = 32;
                while chars > 4 &&
                      (x as usize + (chars * 8 + 3 * 4) * self.windows.len()) >
                      self.display.width + 32 {
                    chars -= 1;
                }

                x += 4;
                for window_ptr in self.windows_ordered.iter() {
                    let w = (chars*8 + 2*4) as usize;
                    if mouse_event.x >= x && mouse_event.x < x + w as isize {
                        for j in 0..self.windows.len() {
                            match self.windows.get(j) {
                                Option::Some(catcher_window_ptr) =>
                                    if catcher_window_ptr == window_ptr {
                                    unsafe {
                                        if j == self.windows.len() - 1 {
                                            (**window_ptr).minimized = !(**window_ptr).minimized;
                                        } else {
                                            catcher = j as isize;
                                            (**window_ptr).minimized = false;
                                        }
                                    }
                                    break;
                                },
                                Option::None => break,
                            }
                        }
                        self.redraw = cmp::max(self.redraw, event::REDRAW_ALL);
                        break;
                    }
                    x += w as isize;
                }
            }
        } else {
            for reverse_i in 0..self.windows.len() {
                let i = self.windows.len() - 1 - reverse_i;
                match self.windows.get(i) {
                    Option::Some(window_ptr) => unsafe {
                        if (**window_ptr).on_mouse(mouse_event, catcher < 0) {
                            catcher = i as isize;

                            self.redraw = cmp::max(self.redraw, event::REDRAW_ALL);
                        }
                    },
                    Option::None => (),
                }
            }
        }

        if catcher >= 0 && catcher < self.windows.len() as isize - 1 {
            match self.windows.remove(catcher as usize) {
                Option::Some(window_ptr) => self.windows.push(window_ptr),
                Option::None => (),
            }
        }

        self.last_mouse_event = mouse_event;
    }

    pub unsafe fn redraw(&mut self) {
        if self.redraw > event::REDRAW_NONE {
            //if self.redraw >= REDRAW_ALL {
            self.display.set(Color::new(64, 64, 64));
            if self.background.data.len() > 0 {
                self.background.draw(&self.display,
                                     Point::new((self.display.width as isize -
                                                 self.background.size.width as isize) /
                                                2,
                                                (self.display.height as isize -
                                                 self.background.size.height as isize) /
                                                2));
            }

            for i in 0..self.windows.len() {
                match self.windows.get(i) {
                    Option::Some(window_ptr) => {
                        (**window_ptr).focused = i == self.windows.len() - 1;
                        (**window_ptr).draw(&self.display);
                    }
                    Option::None => (),
                }
            }

            self.display.rect(Point::new(0, self.display.height as isize - 32),
                              Size::new(self.display.width, 32),
                              Color::alpha(0, 0, 0, 128));

            let mut x = 0;
            for package in self.packages.iter() {
                if package.icon.data.len() > 0 {
                    let y = self.display.height as isize - package.icon.size.height as isize;
                    if self.mouse_point.y >= y && self.mouse_point.x >= x &&
                       self.mouse_point.x < x + package.icon.size.width as isize {
                        self.display.rect(Point::new(x, y),
                                          package.icon.size,
                                          Color::alpha(128, 128, 128, 128));

                        let mut c_x = x;
                        for c in package.name.chars() {
                            self.display
                                .char(Point::new(c_x, y - 16), c, Color::new(255, 255, 255));
                            c_x += 8;
                        }
                    }
                    package.icon.draw(&self.display, Point::new(x, y));
                    x += package.icon.size.width as isize;
                }
            }

            let mut chars = 32;
            while chars > 4 &&
                  (x as usize + (chars * 8 + 3 * 4) * self.windows.len()) >
                  self.display.width + 32 {
                chars -= 1;
            }

            x += 4;
            for window_ptr in self.windows_ordered.iter() {
                let w = (chars*8 + 2*4) as usize;
                self.display.rect(Point::new(x, self.display.height as isize - 32),
                                  Size::new(w, 32),
                                  (**window_ptr).border_color);
                x += 4;

                for i in 0..chars {
                    let c = (**window_ptr).title[i];
                    if c != '\0' {
                        self.display.char(Point::new(x, self.display.height as isize - 24),
                                          c,
                                          (**window_ptr).title_color);
                    }
                    x += 8;
                }
                x += 8;
            }

            if self.cursor.data.len() > 0 {
                self.display.image_alpha(self.mouse_point,
                                         self.cursor.data.as_ptr(),
                                         self.cursor.size);
            } else {
                self.display.char(Point::new(self.mouse_point.x - 3, self.mouse_point.y - 9),
                                  'X',
                                  Color::new(255, 255, 255));
            }
            //}

            let reenable = start_no_ints();

            self.display.flip();

            /*
            if self.cursor.data.len() > 0 {
                self.display.image_alpha_onscreen(self.mouse_point, self.cursor.data.as_ptr(), self.cursor.size);
            } else {
                self.display.char_onscreen(Point::new(self.mouse_point.x - 3, self.mouse_point.y - 9), 'X', Color::new(255, 255, 255));
            }
            */

            self.redraw = event::REDRAW_NONE;

            end_no_ints(reenable);
        }
    }

    pub fn event(&mut self, event: Event) {
        match event.to_option() {
            EventOption::Mouse(mouse_event) => self.on_mouse(mouse_event),
            EventOption::Key(key_event) => self.on_key(key_event),
            EventOption::Redraw(redraw_event) =>
                self.redraw = cmp::max(self.redraw, redraw_event.redraw),
            EventOption::Open(open_event) => {
                let url_string = open_event.url_string;

                if url_string.ends_with(".bin".to_string()) {
                    execute(&URL::from_string(&url_string),
                            &URL::new(),
                            &Vec::new());
                } else {
                    for package in self.packages.iter() {
                        let mut accepted = false;
                        for accept in package.accepts.iter() {
                            if url_string.ends_with(accept.substr(1, accept.len() - 1)) {
                                accepted = true;
                                break;
                            }
                        }
                        if accepted {
                            let mut args: Vec<String> = Vec::new();
                            args.push(url_string.clone());
                            execute(&package.binary, &package.url, &args);
                            break;
                        }
                    }
                }
            }
            _ => (),
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>#1 Added 5_shadowing.rs<commit_after>fn main() {
    let my_var = 7;
    println!("my_var = {:?}", my_var);
    {
        let my_var = 8; // shadow
        println!("inner scope my_var = {:?}", my_var);
    }
    let my_var = "foo"; // another shadow
    println!("shadowed my_var = {:?}", my_var);
}<|endoftext|>


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

use fmt;
use marker;
use usize;

use super::{FusedIterator, TrustedLen};

/// An iterator that repeats an element endlessly.
///
/// This `struct` is created by the [`repeat`] function. See its documentation for more.
///
/// [`repeat`]: fn.repeat.html
#[derive(Clone, Debug)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Repeat<A> {
    element: A
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<A: Clone> Iterator for Repeat<A> {
    type Item = A;

    #[inline]
    fn next(&mut self) -> Option<A> { Some(self.element.clone()) }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) { (usize::MAX, None) }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<A: Clone> DoubleEndedIterator for Repeat<A> {
    #[inline]
    fn next_back(&mut self) -> Option<A> { Some(self.element.clone()) }
}

#[unstable(feature = "fused", issue = "35602")]
impl<A: Clone> FusedIterator for Repeat<A> {}

#[unstable(feature = "trusted_len", issue = "37572")]
unsafe impl<A: Clone> TrustedLen for Repeat<A> {}

/// Creates a new iterator that endlessly repeats a single element.
///
/// The `repeat()` function repeats a single value over and over and over and
/// over and over and 🔁.
///
/// Infinite iterators like `repeat()` are often used with adapters like
/// [`take`], in order to make them finite.
///
/// [`take`]: trait.Iterator.html#method.take
///
/// If the element type of the iterator you need does not implement `Clone`,
/// or if you do not want to keep the repeated element in memory, you can
/// instead use the [`repeat_with`] function.
///
/// [`repeat_with`]: fn.repeat_with.html
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::iter;
///
/// // the number four 4ever:
/// let mut fours = iter::repeat(4);
///
/// assert_eq!(Some(4), fours.next());
/// assert_eq!(Some(4), fours.next());
/// assert_eq!(Some(4), fours.next());
/// assert_eq!(Some(4), fours.next());
/// assert_eq!(Some(4), fours.next());
///
/// // yup, still four
/// assert_eq!(Some(4), fours.next());
/// ```
///
/// Going finite with [`take`]:
///
/// ```
/// use std::iter;
///
/// // that last example was too many fours. Let's only have four fours.
/// let mut four_fours = iter::repeat(4).take(4);
///
/// assert_eq!(Some(4), four_fours.next());
/// assert_eq!(Some(4), four_fours.next());
/// assert_eq!(Some(4), four_fours.next());
/// assert_eq!(Some(4), four_fours.next());
///
/// // ... and now we're done
/// assert_eq!(None, four_fours.next());
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn repeat<T: Clone>(elt: T) -> Repeat<T> {
    Repeat{element: elt}
}

/// An iterator that repeats elements of type `A` endlessly by
/// applying the provided closure `F: FnMut() -> A`.
///
/// This `struct` is created by the [`repeat_with`] function.
/// See its documentation for more.
///
/// [`repeat_with`]: fn.repeat_with.html
#[derive(Copy, Clone, Debug)]
#[unstable(feature = "iterator_repeat_with", issue = "0")]
pub struct RepeatWith<F> {
    repeater: F
}

#[unstable(feature = "iterator_repeat_with", issue = "0")]
impl<A, F: FnMut() -> A> Iterator for RepeatWith<F> {
    type Item = A;

    #[inline]
    fn next(&mut self) -> Option<A> { Some((self.repeater)()) }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) { (usize::MAX, None) }
}

#[unstable(feature = "iterator_repeat_with", issue = "0")]
impl<A, F: FnMut() -> A> DoubleEndedIterator for RepeatWith<F> {
    #[inline]
    fn next_back(&mut self) -> Option<A> { self.next() }
}

#[unstable(feature = "fused", issue = "35602")]
impl<A, F: FnMut() -> A> FusedIterator for RepeatWith<F> {}

#[unstable(feature = "trusted_len", issue = "37572")]
unsafe impl<A, F: FnMut() -> A> TrustedLen for RepeatWith<F> {}

/// Creates a new that repeats elements of type `A` endlessly by
/// applying the provided closure, the repeater, `F: FnMut() -> A`.
///
/// The `repeat_with()` function calls the repeater over and over and over and
/// over and over and 🔁.
///
/// Infinite iterators like `repeat_with()` are often used with adapters like
/// [`take`], in order to make them finite.
///
/// [`take`]: trait.Iterator.html#method.take
///
/// If the element type of the iterator you need implements `Clone`, and
/// it is OK to keep the source element in memory, you should instead use
/// the [`repeat`] function.
///
/// [`repeat`]: fn.repeat.html
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature("iterator_repeat_with")]
///
/// use std::iter;
///
/// // let's assume we have some value of a type that is not `Clone`
/// // or which don't want to have in memory just yet because it is expensive:
/// #[derive(PartialEq, Debug)]
/// struct Expensive;
///
/// // a particular value forever:
/// let mut things = iter::repeat_with(|| Expensive);
///
/// assert_eq!(Some(Expensive), things.next());
/// assert_eq!(Some(Expensive), things.next());
/// assert_eq!(Some(Expensive), things.next());
/// assert_eq!(Some(Expensive), things.next());
/// assert_eq!(Some(Expensive), things.next());
/// ```
///
/// Using mutation and going finite:
///
/// ```rust
/// #![feature("iterator_repeat_with")]
///
/// use std::iter;
///
/// // From the zeroth to the third power of two:
/// let mut curr = 1;
/// let mut pow2 = iter::repeat_with(|| { let tmp = curr; curr *= 2; tmp })
///                     .take(4);
///
/// assert_eq!(Some(1), pow2.next());
/// assert_eq!(Some(2), pow2.next());
/// assert_eq!(Some(4), pow2.next());
/// assert_eq!(Some(8), pow2.next());
///
/// // ... and now we're done
/// assert_eq!(None, pow2.next());
/// ```
#[inline]
#[unstable(feature = "iterator_repeat_with", issue = "0")]
pub fn repeat_with<A, F: FnMut() -> A>(repeater: F) -> RepeatWith<F> {
    RepeatWith { repeater }
}

/// An iterator that yields nothing.
///
/// This `struct` is created by the [`empty`] function. See its documentation for more.
///
/// [`empty`]: fn.empty.html
#[stable(feature = "iter_empty", since = "1.2.0")]
pub struct Empty<T>(marker::PhantomData<T>);

#[stable(feature = "core_impl_debug", since = "1.9.0")]
impl<T> fmt::Debug for Empty<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.pad("Empty")
    }
}

#[stable(feature = "iter_empty", since = "1.2.0")]
impl<T> Iterator for Empty<T> {
    type Item = T;

    fn next(&mut self) -> Option<T> {
        None
    }

    fn size_hint(&self) -> (usize, Option<usize>){
        (0, Some(0))
    }
}

#[stable(feature = "iter_empty", since = "1.2.0")]
impl<T> DoubleEndedIterator for Empty<T> {
    fn next_back(&mut self) -> Option<T> {
        None
    }
}

#[stable(feature = "iter_empty", since = "1.2.0")]
impl<T> ExactSizeIterator for Empty<T> {
    fn len(&self) -> usize {
        0
    }
}

#[unstable(feature = "trusted_len", issue = "37572")]
unsafe impl<T> TrustedLen for Empty<T> {}

#[unstable(feature = "fused", issue = "35602")]
impl<T> FusedIterator for Empty<T> {}

// not #[derive] because that adds a Clone bound on T,
// which isn't necessary.
#[stable(feature = "iter_empty", since = "1.2.0")]
impl<T> Clone for Empty<T> {
    fn clone(&self) -> Empty<T> {
        Empty(marker::PhantomData)
    }
}

// not #[derive] because that adds a Default bound on T,
// which isn't necessary.
#[stable(feature = "iter_empty", since = "1.2.0")]
impl<T> Default for Empty<T> {
    fn default() -> Empty<T> {
        Empty(marker::PhantomData)
    }
}

/// Creates an iterator that yields nothing.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::iter;
///
/// // this could have been an iterator over i32, but alas, it's just not.
/// let mut nope = iter::empty::<i32>();
///
/// assert_eq!(None, nope.next());
/// ```
#[stable(feature = "iter_empty", since = "1.2.0")]
pub fn empty<T>() -> Empty<T> {
    Empty(marker::PhantomData)
}

/// An iterator that yields an element exactly once.
///
/// This `struct` is created by the [`once`] function. See its documentation for more.
///
/// [`once`]: fn.once.html
#[derive(Clone, Debug)]
#[stable(feature = "iter_once", since = "1.2.0")]
pub struct Once<T> {
    inner: ::option::IntoIter<T>
}

#[stable(feature = "iter_once", since = "1.2.0")]
impl<T> Iterator for Once<T> {
    type Item = T;

    fn next(&mut self) -> Option<T> {
        self.inner.next()
    }

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

#[stable(feature = "iter_once", since = "1.2.0")]
impl<T> DoubleEndedIterator for Once<T> {
    fn next_back(&mut self) -> Option<T> {
        self.inner.next_back()
    }
}

#[stable(feature = "iter_once", since = "1.2.0")]
impl<T> ExactSizeIterator for Once<T> {
    fn len(&self) -> usize {
        self.inner.len()
    }
}

#[unstable(feature = "trusted_len", issue = "37572")]
unsafe impl<T> TrustedLen for Once<T> {}

#[unstable(feature = "fused", issue = "35602")]
impl<T> FusedIterator for Once<T> {}

/// Creates an iterator that yields an element exactly once.
///
/// This is commonly used to adapt a single value into a [`chain`] of other
/// kinds of iteration. Maybe you have an iterator that covers almost
/// everything, but you need an extra special case. Maybe you have a function
/// which works on iterators, but you only need to process one value.
///
/// [`chain`]: trait.Iterator.html#method.chain
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::iter;
///
/// // one is the loneliest number
/// let mut one = iter::once(1);
///
/// assert_eq!(Some(1), one.next());
///
/// // just one, that's all we get
/// assert_eq!(None, one.next());
/// ```
///
/// Chaining together with another iterator. Let's say that we want to iterate
/// over each file of the `.foo` directory, but also a configuration file,
/// `.foorc`:
///
/// ```no_run
/// use std::iter;
/// use std::fs;
/// use std::path::PathBuf;
///
/// let dirs = fs::read_dir(".foo").unwrap();
///
/// // we need to convert from an iterator of DirEntry-s to an iterator of
/// // PathBufs, so we use map
/// let dirs = dirs.map(|file| file.unwrap().path());
///
/// // now, our iterator just for our config file
/// let config = iter::once(PathBuf::from(".foorc"));
///
/// // chain the two iterators together into one big iterator
/// let files = dirs.chain(config);
///
/// // this will give us all of the files in .foo as well as .foorc
/// for f in files {
///     println!("{:?}", f);
/// }
/// ```
#[stable(feature = "iter_once", since = "1.2.0")]
pub fn once<T>(value: T) -> Once<T> {
    Once { inner: Some(value).into_iter() }
}
<commit_msg>core::iter::repeat_with: fix doc tests<commit_after>// Copyright 2013-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.

use fmt;
use marker;
use usize;

use super::{FusedIterator, TrustedLen};

/// An iterator that repeats an element endlessly.
///
/// This `struct` is created by the [`repeat`] function. See its documentation for more.
///
/// [`repeat`]: fn.repeat.html
#[derive(Clone, Debug)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Repeat<A> {
    element: A
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<A: Clone> Iterator for Repeat<A> {
    type Item = A;

    #[inline]
    fn next(&mut self) -> Option<A> { Some(self.element.clone()) }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) { (usize::MAX, None) }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<A: Clone> DoubleEndedIterator for Repeat<A> {
    #[inline]
    fn next_back(&mut self) -> Option<A> { Some(self.element.clone()) }
}

#[unstable(feature = "fused", issue = "35602")]
impl<A: Clone> FusedIterator for Repeat<A> {}

#[unstable(feature = "trusted_len", issue = "37572")]
unsafe impl<A: Clone> TrustedLen for Repeat<A> {}

/// Creates a new iterator that endlessly repeats a single element.
///
/// The `repeat()` function repeats a single value over and over and over and
/// over and over and 🔁.
///
/// Infinite iterators like `repeat()` are often used with adapters like
/// [`take`], in order to make them finite.
///
/// [`take`]: trait.Iterator.html#method.take
///
/// If the element type of the iterator you need does not implement `Clone`,
/// or if you do not want to keep the repeated element in memory, you can
/// instead use the [`repeat_with`] function.
///
/// [`repeat_with`]: fn.repeat_with.html
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::iter;
///
/// // the number four 4ever:
/// let mut fours = iter::repeat(4);
///
/// assert_eq!(Some(4), fours.next());
/// assert_eq!(Some(4), fours.next());
/// assert_eq!(Some(4), fours.next());
/// assert_eq!(Some(4), fours.next());
/// assert_eq!(Some(4), fours.next());
///
/// // yup, still four
/// assert_eq!(Some(4), fours.next());
/// ```
///
/// Going finite with [`take`]:
///
/// ```
/// use std::iter;
///
/// // that last example was too many fours. Let's only have four fours.
/// let mut four_fours = iter::repeat(4).take(4);
///
/// assert_eq!(Some(4), four_fours.next());
/// assert_eq!(Some(4), four_fours.next());
/// assert_eq!(Some(4), four_fours.next());
/// assert_eq!(Some(4), four_fours.next());
///
/// // ... and now we're done
/// assert_eq!(None, four_fours.next());
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn repeat<T: Clone>(elt: T) -> Repeat<T> {
    Repeat{element: elt}
}

/// An iterator that repeats elements of type `A` endlessly by
/// applying the provided closure `F: FnMut() -> A`.
///
/// This `struct` is created by the [`repeat_with`] function.
/// See its documentation for more.
///
/// [`repeat_with`]: fn.repeat_with.html
#[derive(Copy, Clone, Debug)]
#[unstable(feature = "iterator_repeat_with", issue = "0")]
pub struct RepeatWith<F> {
    repeater: F
}

#[unstable(feature = "iterator_repeat_with", issue = "0")]
impl<A, F: FnMut() -> A> Iterator for RepeatWith<F> {
    type Item = A;

    #[inline]
    fn next(&mut self) -> Option<A> { Some((self.repeater)()) }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) { (usize::MAX, None) }
}

#[unstable(feature = "iterator_repeat_with", issue = "0")]
impl<A, F: FnMut() -> A> DoubleEndedIterator for RepeatWith<F> {
    #[inline]
    fn next_back(&mut self) -> Option<A> { self.next() }
}

#[unstable(feature = "fused", issue = "35602")]
impl<A, F: FnMut() -> A> FusedIterator for RepeatWith<F> {}

#[unstable(feature = "trusted_len", issue = "37572")]
unsafe impl<A, F: FnMut() -> A> TrustedLen for RepeatWith<F> {}

/// Creates a new that repeats elements of type `A` endlessly by
/// applying the provided closure, the repeater, `F: FnMut() -> A`.
///
/// The `repeat_with()` function calls the repeater over and over and over and
/// over and over and 🔁.
///
/// Infinite iterators like `repeat_with()` are often used with adapters like
/// [`take`], in order to make them finite.
///
/// [`take`]: trait.Iterator.html#method.take
///
/// If the element type of the iterator you need implements `Clone`, and
/// it is OK to keep the source element in memory, you should instead use
/// the [`repeat`] function.
///
/// [`repeat`]: fn.repeat.html
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(iterator_repeat_with)]
///
/// use std::iter;
///
/// // let's assume we have some value of a type that is not `Clone`
/// // or which don't want to have in memory just yet because it is expensive:
/// #[derive(PartialEq, Debug)]
/// struct Expensive;
///
/// // a particular value forever:
/// let mut things = iter::repeat_with(|| Expensive);
///
/// assert_eq!(Some(Expensive), things.next());
/// assert_eq!(Some(Expensive), things.next());
/// assert_eq!(Some(Expensive), things.next());
/// assert_eq!(Some(Expensive), things.next());
/// assert_eq!(Some(Expensive), things.next());
/// ```
///
/// Using mutation and going finite:
///
/// ```rust
/// #![feature(iterator_repeat_with)]
///
/// use std::iter;
///
/// // From the zeroth to the third power of two:
/// let mut curr = 1;
/// let mut pow2 = iter::repeat_with(|| { let tmp = curr; curr *= 2; tmp })
///                     .take(4);
///
/// assert_eq!(Some(1), pow2.next());
/// assert_eq!(Some(2), pow2.next());
/// assert_eq!(Some(4), pow2.next());
/// assert_eq!(Some(8), pow2.next());
///
/// // ... and now we're done
/// assert_eq!(None, pow2.next());
/// ```
#[inline]
#[unstable(feature = "iterator_repeat_with", issue = "0")]
pub fn repeat_with<A, F: FnMut() -> A>(repeater: F) -> RepeatWith<F> {
    RepeatWith { repeater }
}

/// An iterator that yields nothing.
///
/// This `struct` is created by the [`empty`] function. See its documentation for more.
///
/// [`empty`]: fn.empty.html
#[stable(feature = "iter_empty", since = "1.2.0")]
pub struct Empty<T>(marker::PhantomData<T>);

#[stable(feature = "core_impl_debug", since = "1.9.0")]
impl<T> fmt::Debug for Empty<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.pad("Empty")
    }
}

#[stable(feature = "iter_empty", since = "1.2.0")]
impl<T> Iterator for Empty<T> {
    type Item = T;

    fn next(&mut self) -> Option<T> {
        None
    }

    fn size_hint(&self) -> (usize, Option<usize>){
        (0, Some(0))
    }
}

#[stable(feature = "iter_empty", since = "1.2.0")]
impl<T> DoubleEndedIterator for Empty<T> {
    fn next_back(&mut self) -> Option<T> {
        None
    }
}

#[stable(feature = "iter_empty", since = "1.2.0")]
impl<T> ExactSizeIterator for Empty<T> {
    fn len(&self) -> usize {
        0
    }
}

#[unstable(feature = "trusted_len", issue = "37572")]
unsafe impl<T> TrustedLen for Empty<T> {}

#[unstable(feature = "fused", issue = "35602")]
impl<T> FusedIterator for Empty<T> {}

// not #[derive] because that adds a Clone bound on T,
// which isn't necessary.
#[stable(feature = "iter_empty", since = "1.2.0")]
impl<T> Clone for Empty<T> {
    fn clone(&self) -> Empty<T> {
        Empty(marker::PhantomData)
    }
}

// not #[derive] because that adds a Default bound on T,
// which isn't necessary.
#[stable(feature = "iter_empty", since = "1.2.0")]
impl<T> Default for Empty<T> {
    fn default() -> Empty<T> {
        Empty(marker::PhantomData)
    }
}

/// Creates an iterator that yields nothing.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::iter;
///
/// // this could have been an iterator over i32, but alas, it's just not.
/// let mut nope = iter::empty::<i32>();
///
/// assert_eq!(None, nope.next());
/// ```
#[stable(feature = "iter_empty", since = "1.2.0")]
pub fn empty<T>() -> Empty<T> {
    Empty(marker::PhantomData)
}

/// An iterator that yields an element exactly once.
///
/// This `struct` is created by the [`once`] function. See its documentation for more.
///
/// [`once`]: fn.once.html
#[derive(Clone, Debug)]
#[stable(feature = "iter_once", since = "1.2.0")]
pub struct Once<T> {
    inner: ::option::IntoIter<T>
}

#[stable(feature = "iter_once", since = "1.2.0")]
impl<T> Iterator for Once<T> {
    type Item = T;

    fn next(&mut self) -> Option<T> {
        self.inner.next()
    }

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

#[stable(feature = "iter_once", since = "1.2.0")]
impl<T> DoubleEndedIterator for Once<T> {
    fn next_back(&mut self) -> Option<T> {
        self.inner.next_back()
    }
}

#[stable(feature = "iter_once", since = "1.2.0")]
impl<T> ExactSizeIterator for Once<T> {
    fn len(&self) -> usize {
        self.inner.len()
    }
}

#[unstable(feature = "trusted_len", issue = "37572")]
unsafe impl<T> TrustedLen for Once<T> {}

#[unstable(feature = "fused", issue = "35602")]
impl<T> FusedIterator for Once<T> {}

/// Creates an iterator that yields an element exactly once.
///
/// This is commonly used to adapt a single value into a [`chain`] of other
/// kinds of iteration. Maybe you have an iterator that covers almost
/// everything, but you need an extra special case. Maybe you have a function
/// which works on iterators, but you only need to process one value.
///
/// [`chain`]: trait.Iterator.html#method.chain
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::iter;
///
/// // one is the loneliest number
/// let mut one = iter::once(1);
///
/// assert_eq!(Some(1), one.next());
///
/// // just one, that's all we get
/// assert_eq!(None, one.next());
/// ```
///
/// Chaining together with another iterator. Let's say that we want to iterate
/// over each file of the `.foo` directory, but also a configuration file,
/// `.foorc`:
///
/// ```no_run
/// use std::iter;
/// use std::fs;
/// use std::path::PathBuf;
///
/// let dirs = fs::read_dir(".foo").unwrap();
///
/// // we need to convert from an iterator of DirEntry-s to an iterator of
/// // PathBufs, so we use map
/// let dirs = dirs.map(|file| file.unwrap().path());
///
/// // now, our iterator just for our config file
/// let config = iter::once(PathBuf::from(".foorc"));
///
/// // chain the two iterators together into one big iterator
/// let files = dirs.chain(config);
///
/// // this will give us all of the files in .foo as well as .foorc
/// for f in files {
///     println!("{:?}", f);
/// }
/// ```
#[stable(feature = "iter_once", since = "1.2.0")]
pub fn once<T>(value: T) -> Once<T> {
    Once { inner: Some(value).into_iter() }
}
<|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.
//! Set and unset common attributes on LLVM values.

use libc::{c_uint, c_ulonglong};
use llvm::{self, ValueRef, AttrHelper};
use middle::ty::{self, ClosureTyper};
use syntax::abi;
use syntax::ast;
pub use syntax::attr::InlineAttr;
use trans::base;
use trans::common;
use trans::context::CrateContext;
use trans::machine;
use trans::type_of;

/// Mark LLVM function to use split stack.
#[inline]
pub fn split_stack(val: ValueRef, set: bool) {
    unsafe {
        let attr = "split-stack\0".as_ptr() as *const _;
        if set {
            llvm::LLVMAddFunctionAttrString(val, llvm::FunctionIndex as c_uint, attr);
        } else {
            llvm::LLVMRemoveFunctionAttrString(val, llvm::FunctionIndex as c_uint, attr);
        }
    }
}

/// Mark LLVM function to use provided inline heuristic.
#[inline]
pub fn inline(val: ValueRef, inline: InlineAttr) {
    use self::InlineAttr::*;
    match inline {
        Hint   => llvm::SetFunctionAttribute(val, llvm::InlineHintAttribute),
        Always => llvm::SetFunctionAttribute(val, llvm::AlwaysInlineAttribute),
        Never  => llvm::SetFunctionAttribute(val, llvm::NoInlineAttribute),
        None   => {
            let attr = llvm::InlineHintAttribute |
                       llvm::AlwaysInlineAttribute |
                       llvm::NoInlineAttribute;
            unsafe {
                llvm::LLVMRemoveFunctionAttr(val, attr.bits() as c_ulonglong)
            }
        },
    };
}

/// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
#[inline]
pub fn emit_uwtable(val: ValueRef, emit: bool) {
    if emit {
        llvm::SetFunctionAttribute(val, llvm::UWTableAttribute);
    } else {
        unsafe {
            llvm::LLVMRemoveFunctionAttr(val, llvm::UWTableAttribute.bits() as c_ulonglong);
        }
    }
}

/// Tell LLVM whether the function can or cannot unwind.
#[inline]
#[allow(dead_code)] // possibly useful function
pub fn unwind(val: ValueRef, can_unwind: bool) {
    if can_unwind {
        unsafe {
            llvm::LLVMRemoveFunctionAttr(val, llvm::NoUnwindAttribute.bits() as c_ulonglong);
        }
    } else {
        llvm::SetFunctionAttribute(val, llvm::NoUnwindAttribute);
    }
}

/// Tell LLVM whether it should optimise function for size.
#[inline]
#[allow(dead_code)] // possibly useful function
pub fn set_optimize_for_size(val: ValueRef, optimize: bool) {
    if optimize {
        llvm::SetFunctionAttribute(val, llvm::OptimizeForSizeAttribute);
    } else {
        unsafe {
            llvm::LLVMRemoveFunctionAttr(val, llvm::OptimizeForSizeAttribute.bits() as c_ulonglong);
        }
    }
}

/// Composite function which sets LLVM attributes for function depending on its AST (#[attribute])
/// attributes.
pub fn from_fn_attrs(ccx: &CrateContext, attrs: &[ast::Attribute], llfn: ValueRef) {
    use syntax::attr::*;
    inline(llfn, find_inline_attr(Some(ccx.sess().diagnostic()), attrs));

    for attr in attrs {
        if attr.check_name("no_stack_check") {
            split_stack(llfn, false);
        } else if attr.check_name("cold") {
            unsafe {
                llvm::LLVMAddFunctionAttribute(llfn,
                                               llvm::FunctionIndex as c_uint,
                                               llvm::ColdAttribute as u64)
            }
        } else if attr.check_name("allocator") {
            llvm::NoAliasAttribute.apply_llfn(llvm::ReturnIndex as c_uint, llfn);
        }
    }
}

/// Composite function which converts function type into LLVM attributes for the function.
pub fn from_fn_type<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fn_type: ty::Ty<'tcx>)
                              -> llvm::AttrBuilder {
    use middle::ty::{BrAnon, ReLateBound};

    let function_type;
    let (fn_sig, abi, env_ty) = match fn_type.sty {
        ty::ty_bare_fn(_, ref f) => (&f.sig, f.abi, None),
        ty::ty_closure(closure_did, substs) => {
            let typer = common::NormalizingClosureTyper::new(ccx.tcx());
            function_type = typer.closure_type(closure_did, substs);
            let self_type = base::self_type_for_closure(ccx, closure_did, fn_type);
            (&function_type.sig, abi::RustCall, Some(self_type))
        }
        _ => ccx.sess().bug("expected closure or function.")
    };

    let fn_sig = ty::erase_late_bound_regions(ccx.tcx(), fn_sig);

    let mut attrs = llvm::AttrBuilder::new();
    let ret_ty = fn_sig.output;

    // These have an odd calling convention, so we need to manually
    // unpack the input ty's
    let input_tys = match fn_type.sty {
        ty::ty_closure(..) => {
            assert!(abi == abi::RustCall);

            match fn_sig.inputs[0].sty {
                ty::ty_tup(ref inputs) => {
                    let mut full_inputs = vec![env_ty.expect("Missing closure environment")];
                    full_inputs.push_all(inputs);
                    full_inputs
                }
                _ => ccx.sess().bug("expected tuple'd inputs")
            }
        },
        ty::ty_bare_fn(..) if abi == abi::RustCall => {
            let mut inputs = vec![fn_sig.inputs[0]];

            match fn_sig.inputs[1].sty {
                ty::ty_tup(ref t_in) => {
                    inputs.push_all(&t_in[..]);
                    inputs
                }
                _ => ccx.sess().bug("expected tuple'd inputs")
            }
        }
        _ => fn_sig.inputs.clone()
    };

    // Index 0 is the return value of the llvm func, so we start at 1
    let mut first_arg_offset = 1;
    if let ty::FnConverging(ret_ty) = ret_ty {
        // A function pointer is called without the declaration
        // available, so we have to apply any attributes with ABI
        // implications directly to the call instruction. Right now,
        // the only attribute we need to worry about is `sret`.
        if type_of::return_uses_outptr(ccx, ret_ty) {
            let llret_sz = machine::llsize_of_real(ccx, type_of::type_of(ccx, ret_ty));

            // The outptr can be noalias and nocapture because it's entirely
            // invisible to the program. We also know it's nonnull as well
            // as how many bytes we can dereference
            attrs.arg(1, llvm::StructRetAttribute)
                 .arg(1, llvm::NoAliasAttribute)
                 .arg(1, llvm::NoCaptureAttribute)
                 .arg(1, llvm::DereferenceableAttribute(llret_sz));

            // Add one more since there's an outptr
            first_arg_offset += 1;
        } else {
            // The `noalias` attribute on the return value is useful to a
            // function ptr caller.
            match ret_ty.sty {
                // `~` pointer return values never alias because ownership
                // is transferred
                ty::ty_uniq(it) if !common::type_is_sized(ccx.tcx(), it) => {}
                ty::ty_uniq(_) => {
                    attrs.ret(llvm::NoAliasAttribute);
                }
                _ => {}
            }

            // We can also mark the return value as `dereferenceable` in certain cases
            match ret_ty.sty {
                // These are not really pointers but pairs, (pointer, len)
                ty::ty_uniq(it) |
                ty::ty_rptr(_, ty::mt { ty: it, .. }) if !common::type_is_sized(ccx.tcx(), it) => {}
                ty::ty_uniq(inner) | ty::ty_rptr(_, ty::mt { ty: inner, .. }) => {
                    let llret_sz = machine::llsize_of_real(ccx, type_of::type_of(ccx, inner));
                    attrs.ret(llvm::DereferenceableAttribute(llret_sz));
                }
                _ => {}
            }

            if let ty::ty_bool = ret_ty.sty {
                attrs.ret(llvm::ZExtAttribute);
            }
        }
    }

    for (idx, &t) in input_tys.iter().enumerate().map(|(i, v)| (i + first_arg_offset, v)) {
        match t.sty {
            // this needs to be first to prevent fat pointers from falling through
            _ if !common::type_is_immediate(ccx, t) => {
                let llarg_sz = machine::llsize_of_real(ccx, type_of::type_of(ccx, t));

                // For non-immediate arguments the callee gets its own copy of
                // the value on the stack, so there are no aliases. It's also
                // program-invisible so can't possibly capture
                attrs.arg(idx, llvm::NoAliasAttribute)
                     .arg(idx, llvm::NoCaptureAttribute)
                     .arg(idx, llvm::DereferenceableAttribute(llarg_sz));
            }

            ty::ty_bool => {
                attrs.arg(idx, llvm::ZExtAttribute);
            }

            // `~` pointer parameters never alias because ownership is transferred
            ty::ty_uniq(inner) => {
                let llsz = machine::llsize_of_real(ccx, type_of::type_of(ccx, inner));

                attrs.arg(idx, llvm::NoAliasAttribute)
                     .arg(idx, llvm::DereferenceableAttribute(llsz));
            }

            // `&mut` pointer parameters never alias other parameters, or mutable global data
            //
            // `&T` where `T` contains no `UnsafeCell<U>` is immutable, and can be marked as both
            // `readonly` and `noalias`, as LLVM's definition of `noalias` is based solely on
            // memory dependencies rather than pointer equality
            ty::ty_rptr(b, mt) if mt.mutbl == ast::MutMutable ||
                                  !ty::type_contents(ccx.tcx(), mt.ty).interior_unsafe() => {

                let llsz = machine::llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
                attrs.arg(idx, llvm::NoAliasAttribute)
                     .arg(idx, llvm::DereferenceableAttribute(llsz));

                if mt.mutbl == ast::MutImmutable {
                    attrs.arg(idx, llvm::ReadOnlyAttribute);
                }

                if let ReLateBound(_, BrAnon(_)) = *b {
                    attrs.arg(idx, llvm::NoCaptureAttribute);
                }
            }

            // When a reference in an argument has no named lifetime, it's impossible for that
            // reference to escape this function (returned or stored beyond the call by a closure).
            ty::ty_rptr(&ReLateBound(_, BrAnon(_)), mt) => {
                let llsz = machine::llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
                attrs.arg(idx, llvm::NoCaptureAttribute)
                     .arg(idx, llvm::DereferenceableAttribute(llsz));
            }

            // & pointer parameters are also never null and we know exactly how
            // many bytes we can dereference
            ty::ty_rptr(_, mt) => {
                let llsz = machine::llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
                attrs.arg(idx, llvm::DereferenceableAttribute(llsz));
            }
            _ => ()
        }
    }

    attrs
}
<commit_msg>Remove two cases of unecesary match branches<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.
//! Set and unset common attributes on LLVM values.

use libc::{c_uint, c_ulonglong};
use llvm::{self, ValueRef, AttrHelper};
use middle::ty::{self, ClosureTyper};
use syntax::abi;
use syntax::ast;
pub use syntax::attr::InlineAttr;
use trans::base;
use trans::common;
use trans::context::CrateContext;
use trans::machine;
use trans::type_of;

/// Mark LLVM function to use split stack.
#[inline]
pub fn split_stack(val: ValueRef, set: bool) {
    unsafe {
        let attr = "split-stack\0".as_ptr() as *const _;
        if set {
            llvm::LLVMAddFunctionAttrString(val, llvm::FunctionIndex as c_uint, attr);
        } else {
            llvm::LLVMRemoveFunctionAttrString(val, llvm::FunctionIndex as c_uint, attr);
        }
    }
}

/// Mark LLVM function to use provided inline heuristic.
#[inline]
pub fn inline(val: ValueRef, inline: InlineAttr) {
    use self::InlineAttr::*;
    match inline {
        Hint   => llvm::SetFunctionAttribute(val, llvm::InlineHintAttribute),
        Always => llvm::SetFunctionAttribute(val, llvm::AlwaysInlineAttribute),
        Never  => llvm::SetFunctionAttribute(val, llvm::NoInlineAttribute),
        None   => {
            let attr = llvm::InlineHintAttribute |
                       llvm::AlwaysInlineAttribute |
                       llvm::NoInlineAttribute;
            unsafe {
                llvm::LLVMRemoveFunctionAttr(val, attr.bits() as c_ulonglong)
            }
        },
    };
}

/// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
#[inline]
pub fn emit_uwtable(val: ValueRef, emit: bool) {
    if emit {
        llvm::SetFunctionAttribute(val, llvm::UWTableAttribute);
    } else {
        unsafe {
            llvm::LLVMRemoveFunctionAttr(val, llvm::UWTableAttribute.bits() as c_ulonglong);
        }
    }
}

/// Tell LLVM whether the function can or cannot unwind.
#[inline]
#[allow(dead_code)] // possibly useful function
pub fn unwind(val: ValueRef, can_unwind: bool) {
    if can_unwind {
        unsafe {
            llvm::LLVMRemoveFunctionAttr(val, llvm::NoUnwindAttribute.bits() as c_ulonglong);
        }
    } else {
        llvm::SetFunctionAttribute(val, llvm::NoUnwindAttribute);
    }
}

/// Tell LLVM whether it should optimise function for size.
#[inline]
#[allow(dead_code)] // possibly useful function
pub fn set_optimize_for_size(val: ValueRef, optimize: bool) {
    if optimize {
        llvm::SetFunctionAttribute(val, llvm::OptimizeForSizeAttribute);
    } else {
        unsafe {
            llvm::LLVMRemoveFunctionAttr(val, llvm::OptimizeForSizeAttribute.bits() as c_ulonglong);
        }
    }
}

/// Composite function which sets LLVM attributes for function depending on its AST (#[attribute])
/// attributes.
pub fn from_fn_attrs(ccx: &CrateContext, attrs: &[ast::Attribute], llfn: ValueRef) {
    use syntax::attr::*;
    inline(llfn, find_inline_attr(Some(ccx.sess().diagnostic()), attrs));

    for attr in attrs {
        if attr.check_name("no_stack_check") {
            split_stack(llfn, false);
        } else if attr.check_name("cold") {
            unsafe {
                llvm::LLVMAddFunctionAttribute(llfn,
                                               llvm::FunctionIndex as c_uint,
                                               llvm::ColdAttribute as u64)
            }
        } else if attr.check_name("allocator") {
            llvm::NoAliasAttribute.apply_llfn(llvm::ReturnIndex as c_uint, llfn);
        }
    }
}

/// Composite function which converts function type into LLVM attributes for the function.
pub fn from_fn_type<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fn_type: ty::Ty<'tcx>)
                              -> llvm::AttrBuilder {
    use middle::ty::{BrAnon, ReLateBound};

    let function_type;
    let (fn_sig, abi, env_ty) = match fn_type.sty {
        ty::ty_bare_fn(_, ref f) => (&f.sig, f.abi, None),
        ty::ty_closure(closure_did, substs) => {
            let typer = common::NormalizingClosureTyper::new(ccx.tcx());
            function_type = typer.closure_type(closure_did, substs);
            let self_type = base::self_type_for_closure(ccx, closure_did, fn_type);
            (&function_type.sig, abi::RustCall, Some(self_type))
        }
        _ => ccx.sess().bug("expected closure or function.")
    };

    let fn_sig = ty::erase_late_bound_regions(ccx.tcx(), fn_sig);

    let mut attrs = llvm::AttrBuilder::new();
    let ret_ty = fn_sig.output;

    // These have an odd calling convention, so we need to manually
    // unpack the input ty's
    let input_tys = match fn_type.sty {
        ty::ty_closure(..) => {
            assert!(abi == abi::RustCall);

            match fn_sig.inputs[0].sty {
                ty::ty_tup(ref inputs) => {
                    let mut full_inputs = vec![env_ty.expect("Missing closure environment")];
                    full_inputs.push_all(inputs);
                    full_inputs
                }
                _ => ccx.sess().bug("expected tuple'd inputs")
            }
        },
        ty::ty_bare_fn(..) if abi == abi::RustCall => {
            let mut inputs = vec![fn_sig.inputs[0]];

            match fn_sig.inputs[1].sty {
                ty::ty_tup(ref t_in) => {
                    inputs.push_all(&t_in[..]);
                    inputs
                }
                _ => ccx.sess().bug("expected tuple'd inputs")
            }
        }
        _ => fn_sig.inputs.clone()
    };

    // Index 0 is the return value of the llvm func, so we start at 1
    let mut first_arg_offset = 1;
    if let ty::FnConverging(ret_ty) = ret_ty {
        // A function pointer is called without the declaration
        // available, so we have to apply any attributes with ABI
        // implications directly to the call instruction. Right now,
        // the only attribute we need to worry about is `sret`.
        if type_of::return_uses_outptr(ccx, ret_ty) {
            let llret_sz = machine::llsize_of_real(ccx, type_of::type_of(ccx, ret_ty));

            // The outptr can be noalias and nocapture because it's entirely
            // invisible to the program. We also know it's nonnull as well
            // as how many bytes we can dereference
            attrs.arg(1, llvm::StructRetAttribute)
                 .arg(1, llvm::NoAliasAttribute)
                 .arg(1, llvm::NoCaptureAttribute)
                 .arg(1, llvm::DereferenceableAttribute(llret_sz));

            // Add one more since there's an outptr
            first_arg_offset += 1;
        } else {
            // The `noalias` attribute on the return value is useful to a
            // function ptr caller.
            match ret_ty.sty {
                // `~` pointer return values never alias because ownership
                // is transferred
                ty::ty_uniq(it) if common::type_is_sized(ccx.tcx(), it) => {
                    attrs.ret(llvm::NoAliasAttribute);
                }
                _ => {}
            }

            // We can also mark the return value as `dereferenceable` in certain cases
            match ret_ty.sty {
                // These are not really pointers but pairs, (pointer, len)
                ty::ty_rptr(_, ty::mt { ty: inner, .. })
                | ty::ty_uniq(inner) if common::type_is_sized(ccx.tcx(), inner) => {
                    let llret_sz = machine::llsize_of_real(ccx, type_of::type_of(ccx, inner));
                    attrs.ret(llvm::DereferenceableAttribute(llret_sz));
                }
                _ => {}
            }

            if let ty::ty_bool = ret_ty.sty {
                attrs.ret(llvm::ZExtAttribute);
            }
        }
    }

    for (idx, &t) in input_tys.iter().enumerate().map(|(i, v)| (i + first_arg_offset, v)) {
        match t.sty {
            // this needs to be first to prevent fat pointers from falling through
            _ if !common::type_is_immediate(ccx, t) => {
                let llarg_sz = machine::llsize_of_real(ccx, type_of::type_of(ccx, t));

                // For non-immediate arguments the callee gets its own copy of
                // the value on the stack, so there are no aliases. It's also
                // program-invisible so can't possibly capture
                attrs.arg(idx, llvm::NoAliasAttribute)
                     .arg(idx, llvm::NoCaptureAttribute)
                     .arg(idx, llvm::DereferenceableAttribute(llarg_sz));
            }

            ty::ty_bool => {
                attrs.arg(idx, llvm::ZExtAttribute);
            }

            // `~` pointer parameters never alias because ownership is transferred
            ty::ty_uniq(inner) => {
                let llsz = machine::llsize_of_real(ccx, type_of::type_of(ccx, inner));

                attrs.arg(idx, llvm::NoAliasAttribute)
                     .arg(idx, llvm::DereferenceableAttribute(llsz));
            }

            // `&mut` pointer parameters never alias other parameters, or mutable global data
            //
            // `&T` where `T` contains no `UnsafeCell<U>` is immutable, and can be marked as both
            // `readonly` and `noalias`, as LLVM's definition of `noalias` is based solely on
            // memory dependencies rather than pointer equality
            ty::ty_rptr(b, mt) if mt.mutbl == ast::MutMutable ||
                                  !ty::type_contents(ccx.tcx(), mt.ty).interior_unsafe() => {

                let llsz = machine::llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
                attrs.arg(idx, llvm::NoAliasAttribute)
                     .arg(idx, llvm::DereferenceableAttribute(llsz));

                if mt.mutbl == ast::MutImmutable {
                    attrs.arg(idx, llvm::ReadOnlyAttribute);
                }

                if let ReLateBound(_, BrAnon(_)) = *b {
                    attrs.arg(idx, llvm::NoCaptureAttribute);
                }
            }

            // When a reference in an argument has no named lifetime, it's impossible for that
            // reference to escape this function (returned or stored beyond the call by a closure).
            ty::ty_rptr(&ReLateBound(_, BrAnon(_)), mt) => {
                let llsz = machine::llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
                attrs.arg(idx, llvm::NoCaptureAttribute)
                     .arg(idx, llvm::DereferenceableAttribute(llsz));
            }

            // & pointer parameters are also never null and we know exactly how
            // many bytes we can dereference
            ty::ty_rptr(_, mt) => {
                let llsz = machine::llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
                attrs.arg(idx, llvm::DereferenceableAttribute(llsz));
            }
            _ => ()
        }
    }

    attrs
}
<|endoftext|>


<commit_before><commit_msg>Add clear example.<commit_after>use std::cell::Cell;

use orbtk::prelude::*;

#[derive(Default)]
pub struct MainViewState {
    clear: Cell<bool>,
}

impl MainViewState {
    // Sets an action the state
    fn clear(&self) {
        self.clear.set(true);
    }
}

impl State for MainViewState {
    fn update(&self, ctx: &mut Context<'_>) {
        if self.clear.get() {
            // Clears the text property of MainView and because
            // of the sharing also the text of the TextBox.
            ctx.widget().set("text", String16::from(""));
            self.clear.set(false);
        }
    }
}

widget!(MainView<MainViewState> {
    text: String16
});

impl Template for MainView {
    fn template(self, id: Entity, ctx: &mut BuildContext) -> Self {
        let state = self.clone_state();
        self.name("MainView").child(
            Stack::create()
                .orientation("horizontal")
                // By injecting the id of the parent the text property
                // is shared between the MainView and the TextBox. This
                // means both references the same String16 object.
                .child(TextBox::create().text(id).build(ctx))
                .child(
                    Button::create()
                        .margin((8.0, 0.0, 0.0, 0.0))
                        // mouse click event handler
                        .on_click(move |_| {
                            // Calls clear of the state of MainView
                            state.clear();
                            true
                        })
                        .text("Clear")
                        .build(ctx),
                )
                .build(ctx),
        )
    }
}

fn main() {
    Application::new()
        .window(|ctx| {
            Window::create()
                .title("OrbTk - minimal example")
                .position((100.0, 100.0))
                .size(420.0, 730.0)
                .child(MainView::create().margin(4.0).build(ctx))
                .build(ctx)
        })
        .run();
}
<|endoftext|>


<commit_before><commit_msg>audio.delete method<commit_after><|endoftext|>


<commit_before><commit_msg>Figure out how to split routes into segments.<commit_after><|endoftext|>


<commit_before><commit_msg>Avoid more than one thing being a by-position command line argument.<commit_after><|endoftext|>


<commit_before><commit_msg>Add serve subcommand.<commit_after><|endoftext|>


<commit_before><commit_msg>Add example that utilizes terminal default colors<commit_after>extern crate cursive;

use cursive::Cursive;
use cursive::theme::{Color, Theme};
use cursive::views::TextView;

fn custom_theme_from_cursive(siv: &Cursive) -> Theme {
    let mut theme = siv.current_theme().clone();
    theme.colors.background = Color::Default;
    theme
}

fn main() {
    let mut siv = Cursive::new();
    let theme = custom_theme_from_cursive(&siv);

    // We can quit by pressing `q`
    siv.add_global_callback('q', Cursive::quit);
    siv.set_theme(theme);

    siv.add_layer(TextView::new("Hello World with default terminal background color!\n\
                                Press q to quit the application."));

    siv.run();
}
<|endoftext|>


<commit_before><commit_msg>Added anagrams<commit_after>extern crate collections;

use std::str;
use collections::HashMap;
use std::io::File;
use std::io::BufferedReader;

fn sort_string(string: ~str) -> ~str {
	let mut chars = string.to_utf16();
	chars.sort();
	str::from_utf16(chars).unwrap()
}

fn main () {
	let path = Path::new("unixdict.txt");
	let mut file = BufferedReader::new(File::open(&path));

	let mut map: HashMap<~str, ~[~str]> = HashMap::new();

	for line in file.lines() {
		let s = line.trim().to_owned();
		map.mangle(sort_string(s.clone()), s,
				   |_k, v| ~[v],
				   |_k, v, string| v.push(string)
				);//, sort_string(line))
	}

	let mut max_length = 0;
	for (_k, v) in map.iter() {
		if v.len() > max_length {
			max_length = v.len()
		}
	}

	for (_k, v) in map.iter() {
		if v.len() == max_length {
			for s in v.iter() {
				print!("{} ", *s)
			}
			println!("")
		}
	}
}<|endoftext|>


<commit_before><commit_msg>Use std .is_digit()<commit_after><|endoftext|>


<commit_before><commit_msg>Initial import of KMP implementation.<commit_after>
use std::iter::{repeat, Enumerate};
use std::slice;
use std::collections::VecMap;

use alphabets::Alphabet;

type LPS = Vec<usize>;

#[derive(Copy)]
pub struct KMP {
    m: usize
}

fn get_lps(pattern: &[u8]) -> LPS {
    let (m, mut q) = (pattern.len(), 0us);
    let mut lps: LPS = repeat(0).take(m).collect();
    for i in 1..m {
        while q > 0 && pattern[q] != pattern[i] {
            q = lps[q];
        }
        if pattern[q] == pattern[i] {
            q += 1;
        }
        lps[i] = q;
    }

    lps
}

struct Delta {
    table: Vec<VecMap<usize>>
}

impl Delta {
    fn new(pattern: &[u8], alphabet: Alphabet) -> Self {
        //assert!(alphabet.is_word(pattern));
        let k = alphabet.max_symbol()
            .expect("Expecting non-empty alphabet.") as usize + 1;
        let m = pattern.len();

        let mut init = VecMap::with_capacity(k);
        for c in alphabet.symbols.iter() {
            init.insert(c, 0);
        }
        *init.get_mut(&(pattern[0] as usize)).unwrap() = 1;

        let lps = get_lps(pattern);

        let mut table = Vec::with_capacity(m + 1);
        table.push(init);
        for q in 1..m+1 {
            let mut dq = VecMap::with_capacity(k);
            for c in alphabet.symbols.iter() {
                dq.insert(c, *table[lps[q - 1]].get(&c).unwrap());
            }
            if q < m {
                *dq.get_mut(&(pattern[q] as usize)).unwrap() = q;
            }
            table.push(dq);
        }

        Delta { table: table }
    }
}

pub struct FindAll<'a> {
    kmp: KMP,
    q: usize,
    text: Enumerate<slice::Iter<'a, u8>>
}

impl<'a> Iterator for FindAll<'a> {
    type Item = usize;

    fn next(&mut self) -> Option<usize> {
        for (i, &c) in self.text {
            // TODO self.q = self.kmp.delta(self.q, c);
            if self.q == self.kmp.m {
                return Some(i - self.kmp.m + 1);
            }
        }

        None
    }
}

#[cfg(test)]
mod tests {
    use super::{get_lps, Delta};
    use alphabets::Alphabet;

    #[test]
    fn test_get_lps() {
        let pattern = b"ababaca";
        let lps = get_lps(pattern);
        assert_eq!(lps, [0, 0, 1, 2, 3, 0, 1]);
    }

    #[test]
    fn test_delta() {
        let pattern = b"ababaca";
        let alphabet = Alphabet::new(pattern);
        let delta = Delta::new(pattern, alphabet);

    }
}
<|endoftext|>


<commit_before><commit_msg>probably need to rework scalings some time<commit_after><|endoftext|>


<commit_before><commit_msg>Keep track of servers, channels; handle messages<commit_after><|endoftext|>


<commit_before><commit_msg>Refactored channel ID lookup into method<commit_after><|endoftext|>


<commit_before><commit_msg>implement caesar_cipher in rust<commit_after>use std::char;

fn caesar(text: &str, shift: u32) -> String {
    text.to_lowercase()
        .chars()
        .map(|c| char::from_u32(((c as u32) + shift - 97) % 26 + 97).unwrap())
        .collect()
}

fn main() {
    assert_eq!("khoor", caesar(&String::from("hello"), 3));
}
<|endoftext|>


<commit_before><commit_msg>Fix sizing next generation Field in tick()<commit_after><|endoftext|>


<commit_before><commit_msg>Fix formatting to comply rustfmt 0.8.6<commit_after><|endoftext|>