<commit_before>#![cfg(unix)]

extern crate rexpect;

use std::process::Command;

use rexpect::errors::*;
use rexpect::session::{spawn_command, PtySession};

struct REPL {
    session: PtySession,
    prompt: &'static str,
}

impl REPL {
    fn new() -> REPL {
        let repl = REPL::new_().unwrap_or_else(|err| panic!("{}", err));
        repl
    }

    /// Defines the command, timeout, and prompt settings.
    /// Wraps a rexpect::session::PtySession. expecting the prompt after launch.
    fn new_() -> Result<REPL> {
        let timeout: u64 = 30_000;
        let prompt: &'static str = "REXPECT> ";

        let mut command = Command::new("../target/debug/gluon");
        command
            .args(&["-i", "--color", "never", "--prompt", prompt])
            .env("GLUON_PATH", "..");
        let mut session = spawn_command(command, Some(timeout))?;

        session.exp_string(prompt)?;

        Ok(REPL { session, prompt })
    }

    fn test(&mut self, send: &str, expect: Option<&str>) {
        self.test_(send, expect)
            .unwrap_or_else(|err| panic!("{}", err));
    }

    /// Ensures certain lines are expected to reduce race conditions.
    /// If no ouput is expected or desired to be tested, pass it an Option::None,
    /// causing rexpect to wait for the next prompt.
    fn test_(&mut self, send: &str, expect: Option<&str>) -> Result<()> {
        self.session.send_line(send)?;
        self.session.exp_string(send)?;

        if let Some(string) = expect {
            self.session.exp_string(string)?;
        }

        self.session.exp_string(self.prompt)?;
        Ok(())
    }

    fn quit(&mut self) {
        self.quit_().unwrap_or_else(|err| panic!("{}", err));
    }

    fn quit_(&mut self) -> Result<()> {
        let line: &'static str = ":q";
        self.session.send_line(line)?;
        self.session.exp_string(line)?;
        self.session.exp_eof()?;
        Ok(())
    }
}

#[test]
fn prompt() {
    let _repl = REPL::new();
}

#[test]
fn quit() {
    let mut repl = REPL::new();
    repl.quit();
}

#[test]
fn hello_world() {
    let mut repl = REPL::new();

    repl.test("let io = import! std.io", None);
    repl.test("io.println \"Hello world\"", Some("Hello world"));
}

#[test]
fn expression_types() {
    let mut repl = REPL::new();

    repl.test(":t 5", Some("Int"));
    repl.test(":t 5 + 5", Some("Int"));
    repl.test(":t \"gluon\"", Some("String"));
}

#[test]
fn names() {
    let mut repl = REPL::new();

    repl.test(
        ":i std.prelude.show",
        Some("std.prelude.show: forall a . [std.show.Show a] -> a -> String"),
    );
}

#[test]
fn comments() {
    let mut repl = REPL::new();

    repl.test("1 + 2 // Calls the + function on 1 and 2", Some("3"));
    repl.test("1 + 2 /* Calls the + function on 1 and 2 */", Some("3"));
}

#[test]
fn if_expressions() {
    let mut repl = REPL::new();

    repl.test("if True then 1 else 0", Some("1"));
    repl.test("if False then 1 else 0", Some("0"));
}

#[test]
fn records() {
    let mut repl = REPL::new();

    repl.test("let record = { pi = 3.14, add1 = (+) 1.0 }", None);
    repl.test("record.pi", Some("3.14"));

    repl.test("let record_2 = {x = 1 .. record }", None);
    repl.test("record_2.x", Some("1"));
    repl.test("record_2.pi", Some("3.14"));
}

#[test]
fn arrays() {
    let mut repl = REPL::new();

    repl.test("let array = import! std.array", None);
    repl.test("array.len [1, 2, 3]", Some("3"));
}

#[test]
fn comment() {
    let mut repl = REPL::new();

    repl.test("// test", None);
}

#[test]
fn error_reports_correct_line() {
    let mut repl = REPL::new();

    repl.test("let { x } = {}", Some("let { x } = {}"));
}

#[test]
fn import() {
    let mut repl = REPL::new();

    repl.test("let { assert } = import! std.test", None);
}

#[test]
fn assert() {
    let mut repl = REPL::new();

    repl.test("let { assert } = import! std.test", None);
    repl.test("assert False", None);
}
<commit_msg>test: Ignore the repl quit test which stopped working<commit_after>#![cfg(unix)]

extern crate rexpect;

use std::process::Command;

use rexpect::errors::*;
use rexpect::session::{spawn_command, PtySession};

struct REPL {
    session: PtySession,
    prompt: &'static str,
}

impl REPL {
    fn new() -> REPL {
        let repl = REPL::new_().unwrap_or_else(|err| panic!("{}", err));
        repl
    }

    /// Defines the command, timeout, and prompt settings.
    /// Wraps a rexpect::session::PtySession. expecting the prompt after launch.
    fn new_() -> Result<REPL> {
        let timeout: u64 = 30_000;
        let prompt: &'static str = "REXPECT> ";

        let mut command = Command::new("../target/debug/gluon");
        command
            .args(&["-i", "--color", "never", "--prompt", prompt])
            .env("GLUON_PATH", "..");
        let mut session = spawn_command(command, Some(timeout))?;

        session.exp_string(prompt)?;

        Ok(REPL { session, prompt })
    }

    fn test(&mut self, send: &str, expect: Option<&str>) {
        self.test_(send, expect)
            .unwrap_or_else(|err| panic!("{}", err));
    }

    /// Ensures certain lines are expected to reduce race conditions.
    /// If no ouput is expected or desired to be tested, pass it an Option::None,
    /// causing rexpect to wait for the next prompt.
    fn test_(&mut self, send: &str, expect: Option<&str>) -> Result<()> {
        self.session.send_line(send)?;
        self.session.exp_string(send)?;

        if let Some(string) = expect {
            self.session.exp_string(string)?;
        }

        self.session.exp_string(self.prompt)?;
        Ok(())
    }

    fn quit(&mut self) {
        self.quit_().unwrap_or_else(|err| panic!("{}", err));
    }

    fn quit_(&mut self) -> Result<()> {
        let line: &'static str = ":q";
        self.session.send_line(line)?;
        self.session.exp_string(line)?;
        self.session.exp_eof()?;
        Ok(())
    }
}

#[test]
fn prompt() {
    let _repl = REPL::new();
}

#[test]
#[ignore]
fn quit() {
    let mut repl = REPL::new();
    repl.quit();
}

#[test]
fn hello_world() {
    let mut repl = REPL::new();

    repl.test("let io = import! std.io", None);
    repl.test("io.println \"Hello world\"", Some("Hello world"));
}

#[test]
fn expression_types() {
    let mut repl = REPL::new();

    repl.test(":t 5", Some("Int"));
    repl.test(":t 5 + 5", Some("Int"));
    repl.test(":t \"gluon\"", Some("String"));
}

#[test]
fn names() {
    let mut repl = REPL::new();

    repl.test(
        ":i std.prelude.show",
        Some("std.prelude.show: forall a . [std.show.Show a] -> a -> String"),
    );
}

#[test]
fn comments() {
    let mut repl = REPL::new();

    repl.test("1 + 2 // Calls the + function on 1 and 2", Some("3"));
    repl.test("1 + 2 /* Calls the + function on 1 and 2 */", Some("3"));
}

#[test]
fn if_expressions() {
    let mut repl = REPL::new();

    repl.test("if True then 1 else 0", Some("1"));
    repl.test("if False then 1 else 0", Some("0"));
}

#[test]
fn records() {
    let mut repl = REPL::new();

    repl.test("let record = { pi = 3.14, add1 = (+) 1.0 }", None);
    repl.test("record.pi", Some("3.14"));

    repl.test("let record_2 = {x = 1 .. record }", None);
    repl.test("record_2.x", Some("1"));
    repl.test("record_2.pi", Some("3.14"));
}

#[test]
fn arrays() {
    let mut repl = REPL::new();

    repl.test("let array = import! std.array", None);
    repl.test("array.len [1, 2, 3]", Some("3"));
}

#[test]
fn comment() {
    let mut repl = REPL::new();

    repl.test("// test", None);
}

#[test]
fn error_reports_correct_line() {
    let mut repl = REPL::new();

    repl.test("let { x } = {}", Some("let { x } = {}"));
}

#[test]
fn import() {
    let mut repl = REPL::new();

    repl.test("let { assert } = import! std.test", None);
}

#[test]
fn assert() {
    let mut repl = REPL::new();

    repl.test("let { assert } = import! std.test", None);
    repl.test("assert False", None);
}
<|endoftext|>


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

use crate::dom::bindings::codegen::Bindings::HTMLTableElementBinding::HTMLTableElementMethods;
use crate::dom::bindings::codegen::Bindings::HTMLTableRowElementBinding::HTMLTableRowElementMethods;
use crate::dom::bindings::codegen::Bindings::HTMLTableSectionElementBinding::HTMLTableSectionElementMethods;
use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use crate::dom::bindings::error::{ErrorResult, Fallible};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::root::{DomRoot, LayoutDom, MutNullableDom};
use crate::dom::bindings::str::DOMString;
use crate::dom::document::Document;
use crate::dom::element::{Element, RawLayoutElementHelpers};
use crate::dom::htmlcollection::{CollectionFilter, HTMLCollection};
use crate::dom::htmlelement::HTMLElement;
use crate::dom::htmltablecellelement::HTMLTableCellElement;
use crate::dom::htmltableelement::HTMLTableElement;
use crate::dom::htmltablesectionelement::HTMLTableSectionElement;
use crate::dom::node::{window_from_node, Node};
use crate::dom::virtualmethods::VirtualMethods;
use cssparser::RGBA;
use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};
use style::attr::AttrValue;

#[derive(JSTraceable)]
struct CellsFilter;
impl CollectionFilter for CellsFilter {
    fn filter(&self, elem: &Element, root: &Node) -> bool {
        (elem.is::<HTMLTableCellElement>()) &&
            elem.upcast::<Node>().GetParentNode().as_deref() == Some(root)
    }
}

#[dom_struct]
pub struct HTMLTableRowElement {
    htmlelement: HTMLElement,
    cells: MutNullableDom<HTMLCollection>,
}

impl HTMLTableRowElement {
    fn new_inherited(
        local_name: LocalName,
        prefix: Option<Prefix>,
        document: &Document,
    ) -> HTMLTableRowElement {
        HTMLTableRowElement {
            htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
            cells: Default::default(),
        }
    }

    #[allow(unrooted_must_root)]
    pub fn new(
        local_name: LocalName,
        prefix: Option<Prefix>,
        document: &Document,
    ) -> DomRoot<HTMLTableRowElement> {
        Node::reflect_node(
            Box::new(HTMLTableRowElement::new_inherited(
                local_name, prefix, document,
            )),
            document,
        )
    }

    /// Determine the index for this `HTMLTableRowElement` within the given
    /// `HTMLCollection`. Returns `-1` if not found within collection.
    fn row_index(&self, collection: DomRoot<HTMLCollection>) -> i32 {
        collection
            .elements_iter()
            .position(|elem| (&elem as &Element) == self.upcast())
            .map_or(-1, |i| i as i32)
    }
}

impl HTMLTableRowElementMethods for HTMLTableRowElement {
    // https://html.spec.whatwg.org/multipage/#dom-tr-bgcolor
    make_getter!(BgColor, "bgcolor");

    // https://html.spec.whatwg.org/multipage/#dom-tr-bgcolor
    make_legacy_color_setter!(SetBgColor, "bgcolor");

    // https://html.spec.whatwg.org/multipage/#dom-tr-cells
    fn Cells(&self) -> DomRoot<HTMLCollection> {
        self.cells.or_init(|| {
            let window = window_from_node(self);
            let filter = Box::new(CellsFilter);
            HTMLCollection::create(&window, self.upcast(), filter)
        })
    }

    // https://html.spec.whatwg.org/multipage/#dom-tr-insertcell
    fn InsertCell(&self, index: i32) -> Fallible<DomRoot<HTMLElement>> {
        let node = self.upcast::<Node>();
        node.insert_cell_or_row(
            index,
            || self.Cells(),
            || HTMLTableCellElement::new(local_name!("td"), None, &node.owner_doc()),
        )
    }

    // https://html.spec.whatwg.org/multipage/#dom-tr-deletecell
    fn DeleteCell(&self, index: i32) -> ErrorResult {
        let node = self.upcast::<Node>();
        node.delete_cell_or_row(index, || self.Cells(), |n| n.is::<HTMLTableCellElement>())
    }

    // https://html.spec.whatwg.org/multipage/#dom-tr-rowindex
    fn RowIndex(&self) -> i32 {
        let parent = match self.upcast::<Node>().GetParentNode() {
            Some(parent) => parent,
            None => return -1,
        };
        if let Some(table) = parent.downcast::<HTMLTableElement>() {
            return self.row_index(table.Rows());
        }
        if !parent.is::<HTMLTableSectionElement>() {
            return -1;
        }
        let grandparent = match parent.upcast::<Node>().GetParentNode() {
            Some(parent) => parent,
            None => return -1,
        };
        grandparent
            .downcast::<HTMLTableElement>()
            .map_or(-1, |table| self.row_index(table.Rows()))
    }

    // https://html.spec.whatwg.org/multipage/#dom-tr-sectionrowindex
    fn SectionRowIndex(&self) -> i32 {
        let parent = match self.upcast::<Node>().GetParentNode() {
            Some(parent) => parent,
            None => return -1,
        };
        let collection = if let Some(table) = parent.downcast::<HTMLTableElement>() {
            table.Rows()
        } else if let Some(table_section) = parent.downcast::<HTMLTableSectionElement>() {
            table_section.Rows()
        } else {
            return -1;
        };
        self.row_index(collection)
    }
}

pub trait HTMLTableRowElementLayoutHelpers {
    fn get_background_color(&self) -> Option<RGBA>;
}

#[allow(unsafe_code)]
impl HTMLTableRowElementLayoutHelpers for LayoutDom<'_, HTMLTableRowElement> {
    fn get_background_color(&self) -> Option<RGBA> {
        unsafe {
            (&*self.upcast::<Element>().unsafe_get())
                .get_attr_for_layout(&ns!(), &local_name!("bgcolor"))
                .and_then(AttrValue::as_color)
                .cloned()
        }
    }
}

impl VirtualMethods for HTMLTableRowElement {
    fn super_type(&self) -> Option<&dyn VirtualMethods> {
        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
    }

    fn parse_plain_attribute(&self, local_name: &LocalName, value: DOMString) -> AttrValue {
        match *local_name {
            local_name!("bgcolor") => AttrValue::from_legacy_color(value.into()),
            _ => self
                .super_type()
                .unwrap()
                .parse_plain_attribute(local_name, value),
        }
    }
}
<commit_msg>Make HTMLTableRowElementLayoutHelpers methods take self<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use crate::dom::bindings::codegen::Bindings::HTMLTableElementBinding::HTMLTableElementMethods;
use crate::dom::bindings::codegen::Bindings::HTMLTableRowElementBinding::HTMLTableRowElementMethods;
use crate::dom::bindings::codegen::Bindings::HTMLTableSectionElementBinding::HTMLTableSectionElementMethods;
use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use crate::dom::bindings::error::{ErrorResult, Fallible};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::root::{DomRoot, LayoutDom, MutNullableDom};
use crate::dom::bindings::str::DOMString;
use crate::dom::document::Document;
use crate::dom::element::{Element, RawLayoutElementHelpers};
use crate::dom::htmlcollection::{CollectionFilter, HTMLCollection};
use crate::dom::htmlelement::HTMLElement;
use crate::dom::htmltablecellelement::HTMLTableCellElement;
use crate::dom::htmltableelement::HTMLTableElement;
use crate::dom::htmltablesectionelement::HTMLTableSectionElement;
use crate::dom::node::{window_from_node, Node};
use crate::dom::virtualmethods::VirtualMethods;
use cssparser::RGBA;
use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};
use style::attr::AttrValue;

#[derive(JSTraceable)]
struct CellsFilter;
impl CollectionFilter for CellsFilter {
    fn filter(&self, elem: &Element, root: &Node) -> bool {
        (elem.is::<HTMLTableCellElement>()) &&
            elem.upcast::<Node>().GetParentNode().as_deref() == Some(root)
    }
}

#[dom_struct]
pub struct HTMLTableRowElement {
    htmlelement: HTMLElement,
    cells: MutNullableDom<HTMLCollection>,
}

impl HTMLTableRowElement {
    fn new_inherited(
        local_name: LocalName,
        prefix: Option<Prefix>,
        document: &Document,
    ) -> HTMLTableRowElement {
        HTMLTableRowElement {
            htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
            cells: Default::default(),
        }
    }

    #[allow(unrooted_must_root)]
    pub fn new(
        local_name: LocalName,
        prefix: Option<Prefix>,
        document: &Document,
    ) -> DomRoot<HTMLTableRowElement> {
        Node::reflect_node(
            Box::new(HTMLTableRowElement::new_inherited(
                local_name, prefix, document,
            )),
            document,
        )
    }

    /// Determine the index for this `HTMLTableRowElement` within the given
    /// `HTMLCollection`. Returns `-1` if not found within collection.
    fn row_index(&self, collection: DomRoot<HTMLCollection>) -> i32 {
        collection
            .elements_iter()
            .position(|elem| (&elem as &Element) == self.upcast())
            .map_or(-1, |i| i as i32)
    }
}

impl HTMLTableRowElementMethods for HTMLTableRowElement {
    // https://html.spec.whatwg.org/multipage/#dom-tr-bgcolor
    make_getter!(BgColor, "bgcolor");

    // https://html.spec.whatwg.org/multipage/#dom-tr-bgcolor
    make_legacy_color_setter!(SetBgColor, "bgcolor");

    // https://html.spec.whatwg.org/multipage/#dom-tr-cells
    fn Cells(&self) -> DomRoot<HTMLCollection> {
        self.cells.or_init(|| {
            let window = window_from_node(self);
            let filter = Box::new(CellsFilter);
            HTMLCollection::create(&window, self.upcast(), filter)
        })
    }

    // https://html.spec.whatwg.org/multipage/#dom-tr-insertcell
    fn InsertCell(&self, index: i32) -> Fallible<DomRoot<HTMLElement>> {
        let node = self.upcast::<Node>();
        node.insert_cell_or_row(
            index,
            || self.Cells(),
            || HTMLTableCellElement::new(local_name!("td"), None, &node.owner_doc()),
        )
    }

    // https://html.spec.whatwg.org/multipage/#dom-tr-deletecell
    fn DeleteCell(&self, index: i32) -> ErrorResult {
        let node = self.upcast::<Node>();
        node.delete_cell_or_row(index, || self.Cells(), |n| n.is::<HTMLTableCellElement>())
    }

    // https://html.spec.whatwg.org/multipage/#dom-tr-rowindex
    fn RowIndex(&self) -> i32 {
        let parent = match self.upcast::<Node>().GetParentNode() {
            Some(parent) => parent,
            None => return -1,
        };
        if let Some(table) = parent.downcast::<HTMLTableElement>() {
            return self.row_index(table.Rows());
        }
        if !parent.is::<HTMLTableSectionElement>() {
            return -1;
        }
        let grandparent = match parent.upcast::<Node>().GetParentNode() {
            Some(parent) => parent,
            None => return -1,
        };
        grandparent
            .downcast::<HTMLTableElement>()
            .map_or(-1, |table| self.row_index(table.Rows()))
    }

    // https://html.spec.whatwg.org/multipage/#dom-tr-sectionrowindex
    fn SectionRowIndex(&self) -> i32 {
        let parent = match self.upcast::<Node>().GetParentNode() {
            Some(parent) => parent,
            None => return -1,
        };
        let collection = if let Some(table) = parent.downcast::<HTMLTableElement>() {
            table.Rows()
        } else if let Some(table_section) = parent.downcast::<HTMLTableSectionElement>() {
            table_section.Rows()
        } else {
            return -1;
        };
        self.row_index(collection)
    }
}

pub trait HTMLTableRowElementLayoutHelpers {
    fn get_background_color(self) -> Option<RGBA>;
}

#[allow(unsafe_code)]
impl HTMLTableRowElementLayoutHelpers for LayoutDom<'_, HTMLTableRowElement> {
    fn get_background_color(self) -> Option<RGBA> {
        unsafe {
            (&*self.upcast::<Element>().unsafe_get())
                .get_attr_for_layout(&ns!(), &local_name!("bgcolor"))
                .and_then(AttrValue::as_color)
                .cloned()
        }
    }
}

impl VirtualMethods for HTMLTableRowElement {
    fn super_type(&self) -> Option<&dyn VirtualMethods> {
        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
    }

    fn parse_plain_attribute(&self, local_name: &LocalName, value: DOMString) -> AttrValue {
        match *local_name {
            local_name!("bgcolor") => AttrValue::from_legacy_color(value.into()),
            _ => self
                .super_type()
                .unwrap()
                .parse_plain_attribute(local_name, value),
        }
    }
}
<|endoftext|>


<commit_before>extern crate find_folder;
extern crate conrod;

use conrod::backend::piston::{self, Window, WindowEvents, OpenGL};
use conrod::backend::piston::event::UpdateEvent;

const WIDTH: u32 = 800;
const HEIGHT: u32 = 600;
const BUTTON_W: f64 = 150.0;
const BUTTON_H: f64 = 30.0;

enum Screen {
    Title,
    Play,
    Options,
}

struct App {
    screen: Screen,
    label_color: conrod::Color,
}

impl App {
    fn new() -> Self {
        App {
            screen: Screen::Title,
            label_color: conrod::color::BLACK,
        }
    }
}

pub fn draw_window() {
    // Construct the window.
    let mut window: Window =
        piston::window::WindowSettings::new("PokemonBattleArena", [WIDTH, HEIGHT])
            .opengl(OpenGL::V3_2)
            .vsync(true)
            .samples(4)
            .exit_on_esc(true)
            .build()
            .unwrap_or_else(|e| { panic!("Failed to build window: {}", e) });

    // Create the event loop.
    let mut events = WindowEvents::new();

    // Construct the `Ui`.
    let mut ui = conrod::UiBuilder::new([WIDTH as f64, HEIGHT as f64]).build();

    // Create Ids for every used widget
    let mut ids = Ids::new(ui.widget_id_generator());

    // Add a font from file
    let assets = find_folder::Search::KidsThenParents(3, 5).for_folder("assets").unwrap_or_else(
        |e| { panic!("Failed to find folder: {}", e) }
    );
    let font_path = assets.join("fonts/arial/arial.ttf");
    ui.fonts.insert_from_file(font_path).unwrap_or_else(
        |e| { panic!("Failed to get font: {}", e) }
    );

    // No text to draw -> create an empty text texture cache.
    let mut text_texture_cache = piston::window::GlyphCache::new(&mut window, WIDTH, HEIGHT);

    // The image map describing each of our widget->image mappings (in this case none)
    let image_map = conrod::image::Map::new();

    let mut app = App::new();

    // Poll events from the window.
    while let Some(event) = window.next_event(&mut events) {
        // Convert the piston event to a conrod event.
        if let Some(e) = piston::window::convert_event(event.clone(), &window) {
            ui.handle_event(e);
        }

        event.update(|_| {
            let mut ui = ui.set_widgets();
            set_ui(&mut ui, &mut ids, &mut app)
        });

        window.draw_2d(&event, |c, g| {
            if let Some(primitives) = ui.draw_if_changed() {
                fn texture_from_image<T>(img: &T) -> &T { img };
                piston::window::draw(c, g, primitives,
                                     &mut text_texture_cache,
                                     &image_map,
                                     texture_from_image);
            }
        });
    }
}

widget_ids! {
    struct Ids {
        // *** canvas ***
        canvas,

        // *** buttons ***
        button_play,
        button_options,
        button_exit,
        button_sp,
        button_mp,
        button_play_back,
    }
}

fn set_ui(ui: &mut conrod::UiCell, ids: &mut Ids, app: &mut App) {
    use conrod::{widget, Borderable, Colorable, Labelable, Positionable, Sizeable, Widget};

    // Create new empty canvas
    widget::Canvas::new().color(conrod::color::WHITE).set(ids.canvas, ui);

    // draws Title-Screen
    if let Screen::Title = app.screen {
        // Play button
        // Shows Play-Screen when clicked
        if widget::Button::new()
            .border(1.0)
            .color(conrod::color::WHITE)
            .label("Play")
            .label_color(app.label_color)
            .middle_of(ids.canvas)
            .w_h(BUTTON_W, BUTTON_H)
            .set(ids.button_play, ui)
            .was_clicked()
        {
            println!("Play");
            app.screen = Screen::Play;
        }

        // Options button
        // TODO: draw new window with options menu
        if widget::Button::new()
            .border(1.0)
            .color(conrod::color::WHITE)
            .label("Options")
            .label_color(app.label_color)
            .down_from(ids.button_play, 0.0)
            .w_h(BUTTON_W, BUTTON_H)
            .set(ids.button_options, ui)
            .was_clicked()
        {
            println!("Options");
        }

        // Exit button
        // closes the window
        if widget::Button::new()
            .border(1.0)
            .color(conrod::color::WHITE)
            .label("Exit")
            .label_color(app.label_color)
            .down_from(ids.button_options, 0.0)
            .w_h(BUTTON_W, BUTTON_H)
            .set(ids.button_exit, ui)
            .was_clicked()
        {
            ::std::process::exit(0);
        }
    }

    // draws Play-Screen
    if let Screen::Play = app.screen {
        // Singleplayer button
        // not implemented yet
        if widget::Button::new()
            .border(1.0)
            .color(conrod::color::WHITE)
            .label("Singleplayer")
            .label_color(app.label_color)
            .middle_of(ids.canvas)
            .w_h(BUTTON_W, BUTTON_H)
            .set(ids.button_sp, ui)
            .was_clicked()
        {
            println!("Singleplayer");
        }

        // Multiplayer button
        // not implemented yet
        if widget::Button::new()
            .border(1.0)
            .color(conrod::color::WHITE)
            .label("Multiplayer")
            .label_color(app.label_color)
            .down_from(ids.button_sp, 0.0)
            .w_h(BUTTON_W, BUTTON_H)
            .set(ids.button_mp, ui)
            .was_clicked()
        {
            println!("Multiplayer");
        }

        // Back button
        // returns to previous screen
        if widget::Button::new()
            .border(1.0)
            .color(conrod::color::WHITE)
            .label("Back")
            .label_color(app.label_color)
            .down_from(ids.button_mp, 0.0)
            .w_h(BUTTON_W, BUTTON_H)
            .set(ids.button_play_back, ui)
            .was_clicked()
        {
            println!("Back");
            app.screen = Screen::Title;
        }
    }

    //draws Options-Screen
    if let Screen::Options = app.screen {}
}
<commit_msg>added a choose window for the pokemon. still WiP<commit_after>extern crate find_folder;
extern crate conrod;

use conrod::backend::piston::{self, Window, WindowEvents, OpenGL};
use conrod::backend::piston::event::UpdateEvent;
use db;

const WIDTH: u32 = 800;
const HEIGHT: u32 = 600;
const BUTTON_W: f64 = 150.0;
const BUTTON_H: f64 = 30.0;

enum Screen {
    Title,
    Play,
    Options,
    PokemonChoose,
}

struct App {
    screen: Screen,
    label_color: conrod::Color,
}

impl App {
    fn new() -> Self {
        App {
            screen: Screen::Title,
            label_color: conrod::color::BLACK,
        }
    }
}

pub fn draw_window() {
    // Construct the window.
    let mut window: Window =
        piston::window::WindowSettings::new("PokemonBattleArena", [WIDTH, HEIGHT])
            .opengl(OpenGL::V3_2)
            .vsync(true)
            .samples(4)
            .exit_on_esc(true)
            .build()
            .unwrap_or_else(|e| { panic!("Failed to build window: {}", e) });

    // Create the event loop.
    let mut events = WindowEvents::new();

    // Construct the `Ui`.
    let mut ui = conrod::UiBuilder::new([WIDTH as f64, HEIGHT as f64]).build();

    // Create Ids for every used widget
    let mut ids = Ids::new(ui.widget_id_generator());

    // Add a font from file
    let assets = find_folder::Search::KidsThenParents(3, 5).for_folder("assets").unwrap_or_else(
        |e| { panic!("Failed to find folder: {}", e) }
    );
    let font_path = assets.join("fonts/arial/arial.ttf");
    ui.fonts.insert_from_file(font_path).unwrap_or_else(
        |e| { panic!("Failed to get font: {}", e) }
    );

    // No text to draw -> create an empty text texture cache.
    let mut text_texture_cache = piston::window::GlyphCache::new(&mut window, WIDTH, HEIGHT);

    // The image map describing each of our widget->image mappings (in this case none)
    let image_map = conrod::image::Map::new();

    let mut app = App::new();

    // Poll events from the window.
    while let Some(event) = window.next_event(&mut events) {
        // Convert the piston event to a conrod event.
        if let Some(e) = piston::window::convert_event(event.clone(), &window) {
            ui.handle_event(e);
        }

        event.update(|_| {
            let mut ui = ui.set_widgets();
            set_ui(&mut ui, &mut ids, &mut app)
        });

        window.draw_2d(&event, |c, g| {
            if let Some(primitives) = ui.draw_if_changed() {
                fn texture_from_image<T>(img: &T) -> &T { img };
                piston::window::draw(c, g, primitives,
                                     &mut text_texture_cache,
                                     &image_map,
                                     texture_from_image);
            }
        });
    }
}

widget_ids! {
    struct Ids {
        // *** canvas ***
        canvas,

        // *** buttons ***
        button_play,
        button_options,
        button_exit,
        button_sp,
        button_mp,
        button_play_back,
        button_up,
        button_down,
        button_choose,
    }
}

fn set_ui(ui: &mut conrod::UiCell, ids: &mut Ids, app: &mut App) {
    use conrod::{widget, Borderable, Colorable, Labelable, Positionable, Sizeable, Widget};

    // Create new empty canvas
    widget::Canvas::new().color(conrod::color::WHITE).set(ids.canvas, ui);

    // draws Title-Screen
    if let Screen::Title = app.screen {
        // Play button
        // Shows Play-Screen when clicked
        if widget::Button::new()
            .border(1.0)
            .color(conrod::color::WHITE)
            .label("Play")
            .label_color(app.label_color)
            .middle_of(ids.canvas)
            .w_h(BUTTON_W, BUTTON_H)
            .set(ids.button_play, ui)
            .was_clicked()
        {
            println!("Play");
            app.screen = Screen::Play;
        }

        // Options button
        // TODO: draw new window with options menu
        if widget::Button::new()
            .border(1.0)
            .color(conrod::color::WHITE)
            .label("Options")
            .label_color(app.label_color)
            .down_from(ids.button_play, 0.0)
            .w_h(BUTTON_W, BUTTON_H)
            .set(ids.button_options, ui)
            .was_clicked()
        {
            app.screen = Screen::Options;
            println!("Options");
        }

        // Exit button
        // closes the window
        if widget::Button::new()
            .border(1.0)
            .color(conrod::color::WHITE)
            .label("Exit")
            .label_color(app.label_color)
            .down_from(ids.button_options, 0.0)
            .w_h(BUTTON_W, BUTTON_H)
            .set(ids.button_exit, ui)
            .was_clicked()
        {
            ::std::process::exit(0);
        }
    }

    // draws Play-Screen
    if let Screen::Play = app.screen {
        // Singleplayer button
        // not implemented yet
        if widget::Button::new()
            .border(1.0)
            .color(conrod::color::WHITE)
            .label("Singleplayer")
            .label_color(app.label_color)
            .middle_of(ids.canvas)
            .w_h(BUTTON_W, BUTTON_H)
            .set(ids.button_sp, ui)
            .was_clicked()
        {
            app.screen = Screen::PokemonChoose;
            println!("Singleplayer");
        }

        // Multiplayer button
        // not implemented yet
        if widget::Button::new()
            .border(1.0)
            .color(conrod::color::WHITE)
            .label("Multiplayer")
            .label_color(app.label_color)
            .down_from(ids.button_sp, 0.0)
            .w_h(BUTTON_W, BUTTON_H)
            .set(ids.button_mp, ui)
            .was_clicked()
        {
            println!("Multiplayer");
        }

        // Back button
        // returns to previous screen
        if widget::Button::new()
            .border(1.0)
            .color(conrod::color::WHITE)
            .label("Back")
            .label_color(app.label_color)
            .down_from(ids.button_mp, 0.0)
            .w_h(BUTTON_W, BUTTON_H)
            .set(ids.button_play_back, ui)
            .was_clicked()
        {
            println!("Back");
            app.screen = Screen::Title;
        }
    }

    //draws Options-Screen
    if let Screen::Options = app.screen {
        if widget::Button::new()
            .border(1.0)
            .color(conrod::color::WHITE)
            .label("Back")
            .label_color(app.label_color)
            .down_from(ids.button_mp, 0.0)
            .w_h(BUTTON_W, BUTTON_H)
            .set(ids.button_play_back, ui)
            .was_clicked()
        {
            println!("Back");
            app.screen = Screen::Title;
        }
    }

    // Pokemon choose Screen should be able to setup a vec with atleast one but a maximum of 6
    // pokemon for a player.
    let mut index = 0;
    if let Screen::PokemonChoose = app.screen {

        // let pokedex = db::pokedex::Pokedex::new();
        // let entries = pokedex.get_entries();
        let string1: String = index.to_string();
        let string: &str = &string1;

        if widget::Button::new()
            .border(1.0)
            .color(conrod::color::WHITE)
            .label("<-")
            .label_color(app.label_color)
            .middle_of(ids.canvas)
            .w_h(BUTTON_W, BUTTON_H)
            .set(ids.button_up, ui)
            .was_clicked()
        {
            println!("<-");
            index -= 1;
            app.screen = Screen::PokemonChoose;
        }

        if widget::Button::new()
            .border(1.0)
            .color(conrod::color::WHITE)
            .label(string)
            .label_color(app.label_color)
            .down_from(ids.button_up, 0.0)
            .w_h(BUTTON_W, BUTTON_H)
            .set(ids.button_choose, ui)
            .was_clicked()
        {
            println!("{}", index);
            app.screen = Screen::PokemonChoose;
        }

        if widget::Button::new()
            .border(1.0)
            .color(conrod::color::WHITE)
            .label("->")
            .label_color(app.label_color)
            .down_from(ids.button_choose, 0.0)
            .w_h(BUTTON_W, BUTTON_H)
            .set(ids.button_down, ui)
            .was_clicked()
        {
            println!("->");
            index += 1;
            app.screen = Screen::PokemonChoose;
        }

        if widget::Button::new()
            .border(1.0)
            .color(conrod::color::WHITE)
            .label("Back")
            .label_color(app.label_color)
            .down_from(ids.button_down, 0.0)
            .w_h(BUTTON_W, BUTTON_H)
            .set(ids.button_play_back, ui)
            .was_clicked()
        {
            println!("Back");
            app.screen = Screen::Title;
        }
    }
}
<|endoftext|>


<commit_before>#[repr(packed)]
struct ElfSectionTag {
    tag_type: u32,
    size: u32,
    num: u16,
    entsize: u16,
    shndx: u16,
    reserved: u16,
    first_section: ElfSectionHeader
}

impl ElfSectionTag {
    pub fn elf_sections(&'static self) -> ElfSectionIter {
        ElfSectionIter {
            current_section: &self.first_section,
            section_index: 0,
            total_sections: self.num as u32,
            entry_size: self.entsize as u64
        }
    }
}

#[repr(C)]
struct ElfSectionHeader {
    sh_name: u32,
    sh_type: u32,
    sh_flags: u64,
    sh_addr: u64,
    sh_offset: u64,
    sh_size: u64,
    sh_link: u32,
    sh_info: u32,
    sh_addralign: u64,
    sh_entsize: u64
}

impl ElfSectionHeader {
    pub fn name(&self) -> usize {
        self.sh_name as usize
    }

    pub fn section_type(&self) -> usize {
        self.sh_type as usize
    }

    pub fn start_address(&self) -> usize {
        self.sh_addr as usize
    }

    pub fn end_address(&self) -> usize {
        (self.sh_addr + self.sh_size) as usize
    }
}

struct ElfSectionIter {
    current_section: &'static ElfSectionHeader,
    section_index: u32,
    total_sections: u32,
    entry_size: u64
}

impl Iterator for ElfSectionIter {
    type Item = &'static ElfSectionHeader;

    fn next(&mut self) -> Option<Self::Item> {
        if self.section_index >= self.total_sections {
            return None;
        } else {
            let section = self.current_section;
            let next_section_addr =
                (self.current_section as *const ElfSectionHeader as u64) + self.entry_size;
            let next_section = unsafe {
                &*(next_section_addr as *const ElfSectionHeader)
            };

            self.current_section = next_section;
            self.section_index += 1;

            Some(section)
        }
    }
}
<commit_msg>elf_symbols -> self_sections.<commit_after><|endoftext|>


<commit_before>pub trait NumberOps : Sized {
   fn rounding_div(self, other: Self) -> Self;
}

impl NumberOps for i64 {
   #[inline]
   fn rounding_div(self, other: i64) -> i64 {
      if (self < 0) ^ (other < 0) {
         (self - (other / 2)) / other
      } else {
         (self + (other / 2)) / other
      }
   }
}

#[cfg(test)]
mod tests {
   use test::{Bencher, black_box};

   use super::*;

   #[bench]
   fn bench_rounding_div(b: &mut Bencher) {
      b.iter(|| {
         for _ in 0..1000 {
            black_box(15023081_i64.rounding_div(black_box(108877_i64)));
         }
      });
   }
}
<commit_msg>i64 sqrt function using the f64 implementation<commit_after>pub trait NumberOps : Sized {
   fn rounding_div(self, other: Self) -> Self;

   fn sqrt(self) -> Self;
}

impl NumberOps for i64 {
   #[inline]
   fn rounding_div(self, other: i64) -> i64 {
      if (self < 0) ^ (other < 0) {
         (self - (other / 2)) / other
      } else {
         (self + (other / 2)) / other
      }
   }

   #[inline]
   fn sqrt(self) -> i64 {
      (self as f64).sqrt() as i64
   }
}

#[cfg(test)]
mod tests {
   use test::{Bencher, black_box};

   use super::*;

   #[bench]
   fn bench_rounding_div(b: &mut Bencher) {
      b.iter(|| {
         for _ in 0..1000 {
            black_box(15023081_i64.rounding_div(black_box(108877_i64)));
         }
      });
   }
}
<|endoftext|>


<commit_before>
use buffer::{ImageBuffer, Pixel, ArrayLike};
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};

use std::old_io;
use std::old_io::IoResult;
use std::num::Int;

use color::{Rgb, Rgba};
use utils::lzw;
use utils::bitstream::LsbWriter;

use super::{Extension, Block, DisposalMethod};

#[derive(Debug, Copy)]
#[allow(unused_qualifications)]
/// The color mode the encoder will use to encode the image.
pub enum ColorMode {
    /// Image will be encoded in multiple frames if more than 256 colors are present
    TrueColor,
    /// Number of colors will be reduced
    Indexed(u8),
}
use self::ColorMode::{TrueColor, Indexed};

/// A GIF encoder.
///
/// Encodes the image either in true color using indexed colors.
/// If the mode is set to TrueColor the image is split into multiple frames
/// when the number of colors including transparent color exceeds 256.
/// Pixels with an alpha value != 1.0 will be set to alpha = 0.
pub struct Encoder<Image> {
    image: Image,
    bg_color: Option<Rgb<u8>>,
    color_mode: ColorMode
}

const TRANSPARENT: Rgba<u8> = Rgba([0, 0, 0, 0]);

impl<Container> Encoder<ImageBuffer<Rgba<u8>, Container>>
where Container: ArrayLike<u8> {
    /// Creates a new GIF encoder
    pub fn new(image: ImageBuffer<Rgba<u8>, Container>,
               bg_color: Option<Rgb<u8>>,
               color_mode: ColorMode,
              ) -> Encoder<ImageBuffer<Rgba<u8>, Container>> {
        Encoder {
            image: image,
            bg_color: bg_color,
            color_mode: color_mode
        }
    }

    /// Encodes the image
    pub fn encode<W: Writer>(&mut self, w: &mut W) -> IoResult<()> {
        // Header
        try!(w.write_all(b"GIF89a"));
        // Logical screen descriptor
        let height = self.image.height();
        let width = self.image.width();
        if width > <u16 as Int>::max_value() as u32 ||
           height > <u16 as Int>::max_value() as u32 {
            return Err(old_io::IoError{
                kind: old_io::InvalidInput,
                desc: "Image dimensions are to large for the gif format.",
                detail: None
            })
        }
        try!(w.write_le_u16(width as u16));
        try!(w.write_le_u16(height as u16));

        let (hist, transparent) = self.histogram();
        let num_colors = hist.len();

        try!(self.write_global_table(w, &hist[]));

        match self.color_mode {
            // Global color table has been written, just write the image data now
            TrueColor if num_colors <= 256 => {
                // NOTE: copy paste any changes to case: Indexed(n) if n as usize <= num_colors
                try!(self.write_control_ext(w, 0, transparent));
                try!(self.write_descriptor(w, None));
                try!(self.write_image_simple(w, &hist[], transparent));
            },
            TrueColor => {
                try!(self.write_true_color(w, hist, transparent));
            },
            Indexed(n) if n as usize <= num_colors => {
                // NOTE: copy paste from case: TrueColor if num_colors <= 256
                try!(self.write_control_ext(w, 0, transparent));
                try!(self.write_descriptor(w, None));
                try!(self.write_image_simple(w, &hist[], transparent));
            }
            Indexed(_) => {
                panic!("Indexed(n) unimplemented")
            }

        }
        w.write_u8(Block::Trailer as u8)
    }

    /// Returns a histogram of the colors in the image
    fn histogram(&self) -> (Vec<(Rgba<u8>, usize)>, Option<usize>){
        let mut hist: HashMap<_, usize> = HashMap::new();
        // Add bg_color to table
        if let Some(bg_color) = self.bg_color {
            let _ = hist.insert(bg_color.to_rgba(), 0);
        }
        for p in self.image.pixels() {
            let mut p = *p;
            // Replace transparent pixels with black, alpha = 0
            if let Some(bg_color) = self.bg_color {
                p.blend(&bg_color.to_rgba())
            // do not use 255 as a limit there could be rounding error etc.
            // thus take 250 to give it some security margin.
            } else if p[3] < 250 {
                p = TRANSPARENT;
            }
            match hist.entry(p) {
                Occupied(mut entry) => {
                    let val = entry.get_mut();
                    *val = *val + 1;
                },
                Vacant(entry) => {
                    entry.insert(1);
                }
            }
        }
        let mut colors: Vec<(Rgba<u8>, usize)> = hist.into_iter().collect();
        // Sort color map with decreasing color freqs
        colors.sort_by(|a, b| b.1.cmp(&a.1));
        // Add bg_color to table
        let transparent = colors.iter().position(|x| x.0 == TRANSPARENT);
        (colors, transparent)
    }

    /// Write the global color table and the corresponding flags
    fn write_global_table<W: Writer>(&mut self,
                                     w: &mut W,
                                     hist: &[(Rgba<u8>, usize)]
                                    ) -> IoResult<()>
    {
        let num_colors = hist.len();
        let mut flags = 0;
        flags |= 1 << 4; // sort flag
        let n = flag_n(num_colors);
        flags |= n << 4; // 2^(n+1) colors
        let (global_table, bg_index) = if num_colors <= 256 {
            flags |= 1 << 7; // glocal table flag
            flags |= n;
            let mut bg_index = 0;
            let mut table = Vec::with_capacity(3*(2 << n));
            for (i, &(color, _)) in hist.iter().enumerate() {
                let channels = &color.channels()[..3];
                if let Some(bg_color) = self.bg_color {
                    if channels == bg_color.channels() {
                        bg_index = i;
                    }
                }
                table.push_all(channels)
            }
            // Waste some space as of gif spec
            for _ in 0..((2 << n) - num_colors) {
                table.push_all(&[0, 0, 0]);
            }
            (Some(table), bg_index as u8)
        } else if let Some(bg_color) = self.bg_color {
            flags |= 1 << 7; // glocal table flag
            let mut table = Vec::with_capacity(6);
            table.push_all(&bg_color.channels()[..3]);
            table.push_all(&[0, 0, 0]);
            (Some(table), 0)
        } else {
            (None, 0)
        };
        try!(w.write_u8(flags));
        try!(w.write_u8(bg_index));
        try!(w.write_u8(0)); // aspect ration, disregard
        if let Some(global_table) = global_table {
            try!(w.write_all(&global_table[]));
        }
        Ok(())
    }

    /// Writes the graphics control extension
    fn write_control_ext<W: Writer>(&mut self,
                                    w: &mut W,
                                    delay: u16,
                                    transparent: Option<usize>
                                   ) -> IoResult<()>
    {
        try!(w.write_u8(Block::Extension as u8));
        try!(w.write_u8(Extension::Control as u8));
        try!(w.write_u8(4)); // size
        let mut field = 0;
        field |= (DisposalMethod::None as u8) << 2;
        let idx = if let Some(idx) = transparent {
            field |=  1;
            idx as u8
        } else {
            0
        };
        try!(w.write_u8(field));
        try!(w.write_le_u16(delay));
        try!(w.write_u8(idx));
        w.write_u8(0)
    }

    /// Writes the image descriptor
    fn write_descriptor<W: Writer>(&mut self,
                                   w: &mut W,
                                   table_len: Option<usize>
                                  ) -> IoResult<()>
    {
        try!(w.write_u8(Block::Image as u8));
        try!(w.write_le_u16(0)); // left
        try!(w.write_le_u16(0)); // top
        let height = self.image.height();
        let width = self.image.width();
        try!(w.write_le_u16(width as u16));
        try!(w.write_le_u16(height as u16));
        if let Some(len) = table_len {
            w.write_u8(flag_n(len) | 0x80)
        } else {
            w.write_u8(0)
        }
    }

    /// Writes and compresses the indexed data
    fn write_indices<W: Writer>(&mut self,
                                w: &mut W,
                                indices: &[u8],
                               ) -> IoResult<()>
    {
        let code_size = match flag_n(indices.len()) + 1 {
            1 => 2,
            n => n
        };
        let mut encoded_data = Vec::new();
        try!(lzw::encode(indices, LsbWriter::new(&mut encoded_data), code_size));
        try!(w.write_u8(code_size));
        for chunk in encoded_data.chunks(255) {
            try!(w.write_u8((chunk.len()) as u8));
            try!(w.write_all(chunk));
        }
        w.write_u8(0) // block terminator

    }

    /// Writes the image to the file assuming that every pixel is in the color table
    /// If not, the index of the transparent pixel is written
    fn write_image_simple<W: Writer>(&mut self,
                                     w: &mut W,
                                     hist: &[(Rgba<u8>, usize)],
                                     transparent: Option<usize>,
                                    ) -> IoResult<()>
    {
        let t_idx = match transparent { Some(i) => i as u8, None => 0 };
        let data: Vec<u8> = self.image.pixels().map(|p| {
            if let Some(idx) = hist.iter().position(|x| x.0 == *p) {
                idx as u8
            } else {
                t_idx
            }
        }).collect();
        self.write_indices(w, &data[])

    }

    /// Writes the image as a true color image by splitting the colors
    /// over several frames
    fn write_true_color<W: Writer>(&mut self,
                                   w: &mut W,
                                   hist: Vec<(Rgba<u8>, usize)>,
                                   transparent: Option<usize>
                                  ) -> IoResult<()>
    {
        let mut hist = hist;
        // Remove transparent idx
        if let Some(transparent) = transparent {
            let _ = hist.swap_remove(transparent);
        }
        let transparent = Some(0);
        // Calculating the indices is expensive so just do it once
        let indices: Vec<u32> = self.image.pixels().map(|p| {
            if let Some(idx) = hist.iter().position(|x| x.0 == *p) {
                idx as u32
            } else {
                0
            }
        }).collect();
        let mut chunk_indices = Vec::with_capacity(self.image.as_slice().len());
        // starting from 1 since we inject the transparent color in every frame
        for (j, chunk) in hist.chunks(255).enumerate() {
            // Now we can reuse the indices for every subimage
            // if the substract j*255 from each an replace it with 0 if it gets negative
            chunk_indices.clear();
            for &idx in indices.iter() {
                let i: i64 = idx as i64 - j as i64*255;
                chunk_indices.push(if i < 0 || i > 255 { 0 } else { i as u8 + 1 })
            }
            // Write local color table
            let num_local_colors = chunk.len() + 1;
            let n = flag_n(num_local_colors);
            try!(self.write_control_ext(w, 0, transparent));
            try!(self.write_descriptor(w, Some(num_local_colors)));
            // Inject transparent color
            try!(w.write_all(&TRANSPARENT.channels()[..3]));
            for &(color, _) in chunk.iter() {
                try!(w.write_all(&color.channels()[..3]));
            }
            // waste some space as of gif spec
            for _ in 0..((2 << n) - num_local_colors) {
                try!(w.write_all(&[0, 0, 0]));
            }
            // write indices
            try!(self.write_indices(w, &chunk_indices[]));
        }
        Ok(())
    }

    /// Writes the netscape application block to set the number `n` of repetitions
    #[allow(dead_code)]
    fn write_nab<W: Writer>(&mut self, w: &mut W, n: u16) -> IoResult<()> {
        try!(w.write_u8(Block::Extension as u8));
        try!(w.write_u8(Extension::Application as u8));
        try!(w.write_u8(0x0B)); // size
        try!(w.write_all(b"NETSCAPE2.0"));
        try!(w.write_u8(0x03)); // sub-block size
        try!(w.write_u8(0x01)); // sub-block id
        try!(w.write_le_u16(n));
        w.write_u8(0) // terminator
    }
}

// Color table len converted to flag bits
fn flag_n(size: usize) -> u8 {
    match size {
        0  ...2   => 0,
        3  ...4   => 1,
        5  ...8   => 2,
        7  ...16  => 3,
        17 ...32  => 4,
        33 ...64  => 5,
        65 ...128 => 6,
        129...256 => 7,
        _ => 7
    }
}<commit_msg>Do not allocare the array<commit_after>
use buffer::{ImageBuffer, Pixel, ArrayLike};
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};

use std::old_io;
use std::old_io::IoResult;
use std::num::Int;

use color::{Rgb, Rgba};
use utils::lzw;
use utils::bitstream::LsbWriter;

use super::{Extension, Block, DisposalMethod};

#[derive(Debug, Copy)]
#[allow(unused_qualifications)]
/// The color mode the encoder will use to encode the image.
pub enum ColorMode {
    /// Image will be encoded in multiple frames if more than 256 colors are present
    TrueColor,
    /// Number of colors will be reduced
    Indexed(u8),
}
use self::ColorMode::{TrueColor, Indexed};

/// A GIF encoder.
///
/// Encodes the image either in true color using indexed colors.
/// If the mode is set to TrueColor the image is split into multiple frames
/// when the number of colors including transparent color exceeds 256.
/// Pixels with an alpha value != 1.0 will be set to alpha = 0.
pub struct Encoder<Image> {
    image: Image,
    bg_color: Option<Rgb<u8>>,
    color_mode: ColorMode
}

const TRANSPARENT: Rgba<u8> = Rgba([0, 0, 0, 0]);

impl<Container> Encoder<ImageBuffer<Rgba<u8>, Container>>
where Container: ArrayLike<u8> {
    /// Creates a new GIF encoder
    pub fn new(image: ImageBuffer<Rgba<u8>, Container>,
               bg_color: Option<Rgb<u8>>,
               color_mode: ColorMode,
              ) -> Encoder<ImageBuffer<Rgba<u8>, Container>> {
        Encoder {
            image: image,
            bg_color: bg_color,
            color_mode: color_mode
        }
    }

    /// Encodes the image
    pub fn encode<W: Writer>(&mut self, w: &mut W) -> IoResult<()> {
        // Header
        try!(w.write_all(b"GIF89a"));
        // Logical screen descriptor
        let height = self.image.height();
        let width = self.image.width();
        if width > <u16 as Int>::max_value() as u32 ||
           height > <u16 as Int>::max_value() as u32 {
            return Err(old_io::IoError{
                kind: old_io::InvalidInput,
                desc: "Image dimensions are to large for the gif format.",
                detail: None
            })
        }
        try!(w.write_le_u16(width as u16));
        try!(w.write_le_u16(height as u16));

        let (hist, transparent) = self.histogram();
        let num_colors = hist.len();

        try!(self.write_global_table(w, &hist[]));

        match self.color_mode {
            // Global color table has been written, just write the image data now
            TrueColor if num_colors <= 256 => {
                // NOTE: copy paste any changes to case: Indexed(n) if n as usize <= num_colors
                try!(self.write_control_ext(w, 0, transparent));
                try!(self.write_descriptor(w, None));
                try!(self.write_image_simple(w, &hist[], transparent));
            },
            TrueColor => {
                try!(self.write_true_color(w, hist, transparent));
            },
            Indexed(n) if n as usize <= num_colors => {
                // NOTE: copy paste from case: TrueColor if num_colors <= 256
                try!(self.write_control_ext(w, 0, transparent));
                try!(self.write_descriptor(w, None));
                try!(self.write_image_simple(w, &hist[], transparent));
            }
            Indexed(_) => {
                panic!("Indexed(n) unimplemented")
            }

        }
        w.write_u8(Block::Trailer as u8)
    }

    /// Returns a histogram of the colors in the image
    fn histogram(&self) -> (Vec<(Rgba<u8>, usize)>, Option<usize>){
        let mut hist: HashMap<_, usize> = HashMap::new();
        // Add bg_color to table
        if let Some(bg_color) = self.bg_color {
            let _ = hist.insert(bg_color.to_rgba(), 0);
        }
        for p in self.image.pixels() {
            let mut p = *p;
            // Replace transparent pixels with black, alpha = 0
            if let Some(bg_color) = self.bg_color {
                p.blend(&bg_color.to_rgba())
            // do not use 255 as a limit there could be rounding error etc.
            // thus take 250 to give it some security margin.
            } else if p[3] < 250 {
                p = TRANSPARENT;
            }
            match hist.entry(p) {
                Occupied(mut entry) => {
                    let val = entry.get_mut();
                    *val = *val + 1;
                },
                Vacant(entry) => {
                    entry.insert(1);
                }
            }
        }
        let mut colors: Vec<(Rgba<u8>, usize)> = hist.into_iter().collect();
        // Sort color map with decreasing color freqs
        colors.sort_by(|a, b| b.1.cmp(&a.1));
        // Add bg_color to table
        let transparent = colors.iter().position(|x| x.0 == TRANSPARENT);
        (colors, transparent)
    }

    /// Write the global color table and the corresponding flags
    fn write_global_table<W: Writer>(&mut self,
                                     w: &mut W,
                                     hist: &[(Rgba<u8>, usize)]
                                    ) -> IoResult<()>
    {
        let num_colors = hist.len();
        let mut flags = 0;
        flags |= 1 << 4; // sort flag
        let n = flag_n(num_colors);
        flags |= n << 4; // 2^(n+1) colors
        let (global_table, bg_index) = if num_colors <= 256 {
            flags |= 1 << 7; // glocal table flag
            flags |= n;
            let mut bg_index = 0;
            let mut table = Vec::with_capacity(3*(2 << n));
            for (i, &(color, _)) in hist.iter().enumerate() {
                let channels = &color.channels()[..3];
                if let Some(bg_color) = self.bg_color {
                    if channels == bg_color.channels() {
                        bg_index = i;
                    }
                }
                table.push_all(channels)
            }
            // Waste some space as of gif spec
            for _ in 0..((2 << n) - num_colors) {
                table.push_all(&[0, 0, 0]);
            }
            (Some(table), bg_index as u8)
        } else if let Some(bg_color) = self.bg_color {
            flags |= 1 << 7; // glocal table flag
            let mut table = Vec::with_capacity(6);
            table.push_all(&bg_color.channels()[..3]);
            table.push_all(&[0, 0, 0]);
            (Some(table), 0)
        } else {
            (None, 0)
        };
        try!(w.write_u8(flags));
        try!(w.write_u8(bg_index));
        try!(w.write_u8(0)); // aspect ration, disregard
        if let Some(global_table) = global_table {
            try!(w.write_all(&global_table[]));
        }
        Ok(())
    }

    /// Writes the graphics control extension
    fn write_control_ext<W: Writer>(&mut self,
                                    w: &mut W,
                                    delay: u16,
                                    transparent: Option<usize>
                                   ) -> IoResult<()>
    {
        try!(w.write_u8(Block::Extension as u8));
        try!(w.write_u8(Extension::Control as u8));
        try!(w.write_u8(4)); // size
        let mut field = 0;
        field |= (DisposalMethod::None as u8) << 2;
        let idx = if let Some(idx) = transparent {
            field |=  1;
            idx as u8
        } else {
            0
        };
        try!(w.write_u8(field));
        try!(w.write_le_u16(delay));
        try!(w.write_u8(idx));
        w.write_u8(0)
    }

    /// Writes the image descriptor
    fn write_descriptor<W: Writer>(&mut self,
                                   w: &mut W,
                                   table_len: Option<usize>
                                  ) -> IoResult<()>
    {
        try!(w.write_u8(Block::Image as u8));
        try!(w.write_le_u16(0)); // left
        try!(w.write_le_u16(0)); // top
        let height = self.image.height();
        let width = self.image.width();
        try!(w.write_le_u16(width as u16));
        try!(w.write_le_u16(height as u16));
        if let Some(len) = table_len {
            w.write_u8(flag_n(len) | 0x80)
        } else {
            w.write_u8(0)
        }
    }

    /// Writes and compresses the indexed data
    fn write_indices<W: Writer>(&mut self,
                                w: &mut W,
                                indices: &[u8],
                               ) -> IoResult<()>
    {
        let code_size = match flag_n(indices.len()) + 1 {
            1 => 2,
            n => n
        };
        let mut encoded_data = Vec::new();
        try!(lzw::encode(indices, LsbWriter::new(&mut encoded_data), code_size));
        try!(w.write_u8(code_size));
        for chunk in encoded_data.chunks(255) {
            try!(w.write_u8((chunk.len()) as u8));
            try!(w.write_all(chunk));
        }
        w.write_u8(0) // block terminator

    }

    /// Writes the image to the file assuming that every pixel is in the color table
    /// If not, the index of the transparent pixel is written
    fn write_image_simple<W: Writer>(&mut self,
                                     w: &mut W,
                                     hist: &[(Rgba<u8>, usize)],
                                     transparent: Option<usize>,
                                    ) -> IoResult<()>
    {
        let t_idx = match transparent { Some(i) => i as u8, None => 0 };
        let data: Vec<u8> = self.image.pixels().map(|p| {
            if let Some(idx) = hist.iter().position(|x| x.0 == *p) {
                idx as u8
            } else {
                t_idx
            }
        }).collect();
        self.write_indices(w, &data[])

    }

    /// Writes the image as a true color image by splitting the colors
    /// over several frames
    fn write_true_color<W: Writer>(&mut self,
                                   w: &mut W,
                                   hist: Vec<(Rgba<u8>, usize)>,
                                   transparent: Option<usize>
                                  ) -> IoResult<()>
    {
        let mut hist = hist;
        // Remove transparent idx
        if let Some(transparent) = transparent {
            let _ = hist.swap_remove(transparent);
        }
        let transparent = Some(0);
        // Calculating the indices is expensive so just do it once
        let indices: Vec<u32> = self.image.pixels().map(|p| {
            if let Some(idx) = hist.iter().position(|x| x.0 == *p) {
                idx as u32
            } else {
                0
            }
        }).collect();
        let mut chunk_indices = Vec::with_capacity(
            self.image.width() as usize * self.image.height() as usize
        );
        // starting from 1 since we inject the transparent color in every frame
        for (j, chunk) in hist.chunks(255).enumerate() {
            // Now we can reuse the indices for every subimage
            // if the substract j*255 from each an replace it with 0 if it gets negative
            chunk_indices.clear();
            for &idx in indices.iter() {
                let i: i64 = idx as i64 - j as i64*255;
                chunk_indices.push(if i < 0 || i > 255 { 0 } else { i as u8 + 1 })
            }
            // Write local color table
            let num_local_colors = chunk.len() + 1;
            let n = flag_n(num_local_colors);
            try!(self.write_control_ext(w, 0, transparent));
            try!(self.write_descriptor(w, Some(num_local_colors)));
            // Inject transparent color
            try!(w.write_all(&TRANSPARENT.channels()[..3]));
            for &(color, _) in chunk.iter() {
                try!(w.write_all(&color.channels()[..3]));
            }
            // waste some space as of gif spec
            for _ in 0..((2 << n) - num_local_colors) {
                try!(w.write_all(&[0, 0, 0]));
            }
            // write indices
            try!(self.write_indices(w, &chunk_indices[]));
        }
        Ok(())
    }

    /// Writes the netscape application block to set the number `n` of repetitions
    #[allow(dead_code)]
    fn write_nab<W: Writer>(&mut self, w: &mut W, n: u16) -> IoResult<()> {
        try!(w.write_u8(Block::Extension as u8));
        try!(w.write_u8(Extension::Application as u8));
        try!(w.write_u8(0x0B)); // size
        try!(w.write_all(b"NETSCAPE2.0"));
        try!(w.write_u8(0x03)); // sub-block size
        try!(w.write_u8(0x01)); // sub-block id
        try!(w.write_le_u16(n));
        w.write_u8(0) // terminator
    }
}

// Color table len converted to flag bits
fn flag_n(size: usize) -> u8 {
    match size {
        0  ...2   => 0,
        3  ...4   => 1,
        5  ...8   => 2,
        7  ...16  => 3,
        17 ...32  => 4,
        33 ...64  => 5,
        65 ...128 => 6,
        129...256 => 7,
        _ => 7
    }
}<|endoftext|>


<commit_before>use parking_lot::Mutex;
use std::{fmt, ops::AddAssign, sync::Arc};

#[derive(Clone)]
pub(crate) struct IdSequence<T> {
    inner: Arc<Mutex<Inner<T>>>,
}

impl<T: Default + Copy + AddAssign<T> + PartialEq<T> + PartialOrd<T> + From<u8>> IdSequence<T> {
    pub(crate) fn new(allow_zero: bool) -> Self {
        Self {
            inner: Arc::new(Mutex::new(Inner::new(allow_zero))),
        }
    }

    pub(crate) fn next(&self) -> T {
        self.inner.lock().next()
    }

    pub(crate) fn set_max(&self, max: T) {
        self.inner.lock().set_max(max)
    }
}

impl<T: fmt::Debug> fmt::Debug for IdSequence<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut debug = f.debug_struct("IdSequence");
        if let Some(inner) = self.inner.try_lock() {
            debug
                .field("allow_zero", &inner.allow_zero)
                .field("max", &inner.max)
                .field("id", &inner.id);
        }
        debug.finish()
    }
}

#[derive(Debug)]
struct Inner<T> {
    allow_zero: bool,
    zero: T,
    one: T,
    max: Option<T>,
    id: T,
}

impl<T: Default + Copy + AddAssign<T> + PartialEq<T> + PartialOrd<T> + From<u8>> Inner<T> {
    fn new(allow_zero: bool) -> Self {
        Self {
            allow_zero,
            zero: 0.into(),
            one: 1.into(),
            max: None,
            id: T::default(),
        }
    }

    fn set_max(&mut self, max: T) {
        self.max = if max == self.zero { None } else { Some(max) };
    }

    fn next(&mut self) -> T {
        if !self.allow_zero && self.id == self.zero {
            self.id += self.one;
        }
        if self.check_max() {
            let id = self.id;
            self.id += self.one;
            id
        } else {
            self.id = self.zero;
            self.next()
        }
    }

    fn check_max(&self) -> bool {
        if let Some(max) = self.max {
            self.id < max
        } else {
            true
        }
    }
}
<commit_msg>IdSequence: make it a tuple<commit_after>use parking_lot::Mutex;
use std::{fmt, ops::AddAssign, sync::Arc};

#[derive(Clone)]
pub(crate) struct IdSequence<T>(Arc<Mutex<Inner<T>>>);

impl<T: Default + Copy + AddAssign<T> + PartialEq<T> + PartialOrd<T> + From<u8>> IdSequence<T> {
    pub(crate) fn new(allow_zero: bool) -> Self {
        Self(Arc::new(Mutex::new(Inner::new(allow_zero))))
    }

    pub(crate) fn next(&self) -> T {
        self.0.lock().next()
    }

    pub(crate) fn set_max(&self, max: T) {
        self.0.lock().set_max(max)
    }
}

impl<T: fmt::Debug> fmt::Debug for IdSequence<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut debug = f.debug_struct("IdSequence");
        if let Some(inner) = self.0.try_lock() {
            debug
                .field("allow_zero", &inner.allow_zero)
                .field("max", &inner.max)
                .field("id", &inner.id);
        }
        debug.finish()
    }
}

#[derive(Debug)]
struct Inner<T> {
    allow_zero: bool,
    zero: T,
    one: T,
    max: Option<T>,
    id: T,
}

impl<T: Default + Copy + AddAssign<T> + PartialEq<T> + PartialOrd<T> + From<u8>> Inner<T> {
    fn new(allow_zero: bool) -> Self {
        Self {
            allow_zero,
            zero: 0.into(),
            one: 1.into(),
            max: None,
            id: T::default(),
        }
    }

    fn set_max(&mut self, max: T) {
        self.max = if max == self.zero { None } else { Some(max) };
    }

    fn next(&mut self) -> T {
        if !self.allow_zero && self.id == self.zero {
            self.id += self.one;
        }
        if self.check_max() {
            let id = self.id;
            self.id += self.one;
            id
        } else {
            self.id = self.zero;
            self.next()
        }
    }

    fn check_max(&self) -> bool {
        if let Some(max) = self.max {
            self.id < max
        } else {
            true
        }
    }
}
<|endoftext|>


<commit_before>struct Droppable {
    name: &'static str,
}

// This `drop` implementation doesn't free resources; but instead reports its
// usage via a print to the console
impl Drop for Droppable {
    fn drop(&mut self) {
        println!("> Dropping {}", self.name);
    }
}

fn main() {
    let _a = Droppable { name: "a" };

    // block A
    {
        let _b = Droppable { name: "b" };

        // block B
        {
            let _c = Droppable { name: "c" };
            let _d = Droppable { name: "d" };

            println!("Exiting block B");
        }
        println!("Just exited block B");

        println!("Exiting block A");
    }
    println!("Just exited block A");

    // Variable can be manually dropped using the `drop` function
    drop(_a);
    // TODO ^ Try uncommenting this line

    println!("end of the main function");

    // `_a` *won't* be `drop`ed again here, because it already has been
    // (manually) `drop`ed
}
<commit_msg>Typo in drop example<commit_after>struct Droppable {
    name: &'static str,
}

// This `drop` implementation doesn't free resources; but instead reports its
// usage via a print to the console
impl Drop for Droppable {
    fn drop(&mut self) {
        println!("> Dropping {}", self.name);
    }
}

fn main() {
    let _a = Droppable { name: "a" };

    // block A
    {
        let _b = Droppable { name: "b" };

        // block B
        {
            let _c = Droppable { name: "c" };
            let _d = Droppable { name: "d" };

            println!("Exiting block B");
        }
        println!("Just exited block B");

        println!("Exiting block A");
    }
    println!("Just exited block A");

    // Variable can be manually dropped using the `drop` function
    drop(_a);
    // TODO ^ Try commenting this line

    println!("end of the main function");

    // `_a` *won't* be `drop`ed again here, because it already has been
    // (manually) `drop`ed
}
<|endoftext|>


<commit_before>enum_from_primitive!{
    /// Different addressing modes are denoted by the letters following the assembly instruction as follows:
    /// AAA_dx    - zero page indexed (x)
    /// AAA_dy    - zero page indexed (y)
    /// AAA_ax    - absolute indexed (x)
    /// AAA_ay    - absolute indexed (y)
    /// AAA_inx_x - indexed indirect
    /// AAA_ind_y - indirect indexed
    /// AAA_imm   - immediate
    /// AAA_z_pg  - zero page
    /// AAA_abs   - absolute
    /// AAA_rel   - relative
    /// AAA_ind   - indirect
    ///
    /// Otherwise, addressing is implied or obvious
    #[derive(Debug)]
    #[allow(non_camel_case_types)]
    pub enum Instruction {
        // BRK       = 0x00,

        // Stack
        // PHP       = 0x08,
        // PLP       = 0x28,
        // PHA       = 0x48,
        // PLA       = 0x68,
        // TXS       = 0x9a,
        // TSX       = 0xba,

        // Branch
        // BPL       = 0x10,
        // BMI       = 0x30,
        // BVC       = 0x50,
        // BVS       = 0x70,
        // BCC       = 0x90,
        // BCS       = 0xb0,
        // BNE       = 0xd0,
        // BEQ       = 0xf0,

        // Flag instructions
        // CLC       = 0x18,
        // SEC       = 0x38,
        // CLI       = 0x58,
        // SEI       = 0x78,
        // CLV       = 0xb8,
        // CLD       = 0xd8,
        // SED       = 0xf8,

        // Register instructions
        // DEY       = 0x88,
        // DEX       = 0xca,
        // INX       = 0xe8,
        // INY       = 0xc8,
        // TAX       = 0xaa,
        // TXA       = 0x8a,
        // TAY       = 0xa8,
        // TYA       = 0x98,

        // Compares
        // CPY_imm   = 0xc0,
        // CPY_z_pg  = 0xc4,
        // CPY_abs   = 0xcc,
        // CPX_imm   = 0xe0,
        // CPX_z_pg  = 0xe4,
        // CPX_abs   = 0xec,

        // Loads
        // LDA_inx_x = 0xa1,
        // LDA_z_pg  = 0xa5,
        // LDA_imm   = 0xa9,
        // LDA_abs   = 0xad,
        // LDA_ind_y = 0xb1,
        // LDA_dx    = 0xb5,
        // LDA_ax    = 0xbd,
        // LDA_ay    = 0xb9,

        // LDX_imm   = 0xa2,
        // LDX_z_pg  = 0xa6,
        // LDX_abs   = 0xae,
        // LDX_dy    = 0xb6,
        // LDX_ay    = 0xbe,

        // LDY_imm   = 0xa0,
        // LDY_z_pg  = 0xa4,
        // LDY_abs   = 0xac,
        // LDY_dx    = 0xb4,
        // LDY_ax    = 0xbc,

        // Stores
        // STA_inx_x = 0x81,
        // STA_z_pg  = 0x85,
        // STA_abs   = 0x8d,
        // STA_ind_y = 0x91,
        // STA_dx    = 0x95,
        // STA_ax    = 0x9d,
        // STA_ay    = 0x99,

        // STX_z_pg  = 0x86,
        // STX_abs   = 0x8e,
        // STX_dy    = 0x96,

        // STY_z_pg  = 0x84,
        // STY_abs   = 0x8c,
        // STY_dx    = 0x94,

        // Jumps
        // JSR_abs   = 0x20,
        // JMP_abs   = 0x4c,
        // JMP_ind   = 0x6c,

        // RTI       = 0x40,
        // RTS       = 0x60,

        // Bit tests
        // BIT_z_pg  = 0x24,
        // BIT_abs   = 0x2c,

        // ALU operations
        // ORA_inx_x = 0x01,
        // ORA_z_pg  = 0x05,
        // ORA_imm   = 0x09,
        // ORA_abs   = 0x0d,
        // ORA_ind_y = 0x11,
        // ORA_dx    = 0x15,
        // ORA_ax    = 0x19,
        // ORA_ay    = 0x1d,

        // AND_inx_x = 0x21,
        // AND_z_pg  = 0x25,
        // AND_imm   = 0x29,
        // AND_abs   = 0x2d,
        // AND_ind_y = 0x31,
        // AND_dx    = 0x35,
        // AND_ax    = 0x39,
        // AND_ay    = 0x3d,

        // EOR_inx_x = 0x41,
        // EOR_z_pg  = 0x45,
        // EOR_imm   = 0x49,
        // EOR_abs   = 0x4d,
        // EOR_ind_y = 0x51,
        // EOR_dx    = 0x55,
        // EOR_ax    = 0x59,
        // EOR_ay    = 0x5d,

        // ADC_inx_x = 0x61,
        // ADC_z_pg  = 0x65,
        // ADC_imm   = 0x69,
        // ADC_abs   = 0x6d,
        // ADC_ind_y = 0x71,
        // ADC_dx    = 0x75,
        // ADC_ax    = 0x79,
        // ADC_ay    = 0x7d,

        // CMP_inx_x = 0xc1,
        // CMP_z_pg  = 0xc5,
        // CMP_imm   = 0xc9,
        // CMP_abs   = 0xcd,
        // CMP_ind_y = 0xd1,
        // CMP_dx    = 0xd5,
        // CMP_ax    = 0xd9,
        // CMP_ay    = 0xdd,

        // SBC_inx_x = 0xe1,
        // SBC_z_pg  = 0xe5,
        // SBC_imm   = 0xe9,
        // SBC_abs   = 0xed,
        // SBC_ind_y = 0xf1,
        // SBC_dx    = 0xf5,
        // SBC_ax    = 0xf9,
        // SBC_ay    = 0xfd,

        // ASL_z_pg  = 0x06,
        // ASL       = 0x0a,
        // ASL_abs   = 0x0e,
        // ASL_dx    = 0x16,
        // ASL_ax    = 0x1e,

        // LSR_z_pg  = 0x46,
        // LSR       = 0x4a,
        // LSR_abs   = 0x4e,
        // LSR_dx    = 0x56,
        // LSR_ax    = 0x5e,

        // Rotates
        // ROL_z_pg  = 0x26,
        // ROL       = 0x2a,
        // ROL_abs   = 0x2e,
        // ROL_dx    = 0x36,
        // ROL_ax    = 0x3e,

        // ROR_z_pg  = 0x66,
        // ROR       = 0x6a,
        // ROR_abs   = 0x6e,
        // ROR_dx    = 0x76,
        // ROR_ax    = 0x7e,

        // Increment
        // DEC_z_pg  = 0xc6,
        // DEC_abs   = 0xce,
        // DEC_dx    = 0xd6,
        // DEC_ax    = 0xde,

        // INC_z_pg  = 0xe6,
        // INC_abs   = 0xee,
        // INC_dx    = 0xf6,
        // INC_ax    = 0xfe,

        // The ever important nop
        // Observe all its majesty
        // NOP       = 0xea,
    }
}
<commit_msg>Git pls<commit_after><|endoftext|>


<commit_before>extern mod extra;
extern mod frog;
use std::rand;
use std::vec;
use extra::time;
use frog::ga::GeneticAlgorithm;

fn bench(name: &str, thresh: f64, ga: &mut GeneticAlgorithm<f64>, fit_fn: &fn(code: &[f64]) -> f64)
{
    let old = time::precise_time_s();
    println("Testing " + name +" function\n");
    let mut count = 0u;
    while ga.best.score <= thresh {
      do ga.step |c| {
        fit_fn(c)
      }
      count = count + 1;
      println("Epoch : " + count.to_str() + " - best score: " + (ga.best.score).to_str());
    }

    let rand_code: ~[f64] = vec::from_fn(ga.best.code.len(), |_| rand::random());
    let time = time::precise_time_s() - old;

    println("\nElpased time: " + time.to_str() + " seconds\n");
    println("Best generation : " + ga.best.code.to_str());
    println("with performance : " + ga.best.score.to_str());
    println("\nRand generation : " + rand_code.to_str());
    println("with performance : " + fit_fn(rand_code).to_str());
}

#[main]
fn main() {
    let mut ga: GeneticAlgorithm<f64> = GeneticAlgorithm::new(3000, 2, 0.8, 60.0, 100);
    let bmax = 2.0 * 2.0;
    do bench("Goldstein", -3.0, &mut ga) |c| {
        // Restrict to hypercube -5.12 <= x <= 5.12
        let e1 = (c[0] - 0.5) * bmax;
        let e2 = (c[1] - 0.5) * bmax;

        let a = 1.0 + (e1 + e2 + 1.0).pow(~2.0) *
                 (19.0 - 14.0 * e1 + 13.0 * e1.pow(~2.0) - 14.0 * e2 +
                  6.0 * e1 * e2 + 3.0 * e2.pow(~2.0));
        let b =  30.0 + (2.0 * e1 - 3.0 * e2).pow(~2.0) *
                 (18.0 - 32.0 * e1 + 12.0 * e1.pow(~2.0) - 48.0 * e2 -
                  36.0 * e1 * e2 + 27.0 * e2 * e2);
        -a * b
    }
}
<commit_msg>Fix goldstein example<commit_after>extern mod extra;
extern mod frog;
use std::rand;
use std::vec;
use extra::time;
use frog::ga::GeneticAlgorithm;

fn bench(name: &str, thresh: f64, ga: &mut GeneticAlgorithm<f64>, fit_fn: &fn(code: &[f64]) -> f64)
{
    let old = time::precise_time_s();
    println("Testing " + name +" function\n");

    let mut test_arr: ~[f64] = ~[];
    test_arr.push(0.5);
    test_arr.push(0.25);
    println(fit_fn(test_arr).to_str());
    let mut count = 0u;
    while ga.best.score <= thresh {
      do ga.step |c| {
        fit_fn(c)
      }
      count = count + 1;
      println("Epoch : " + count.to_str() + " - best score: " + (ga.best.score).to_str());
    }

    let rand_code: ~[f64] = vec::from_fn(ga.best.code.len(), |_| rand::random());
    let time = time::precise_time_s() - old;

    println("\nElpased time: " + time.to_str() + " seconds\n");
    println("Best generation : " + ga.best.code.to_str());
    println("with performance : " + ga.best.score.to_str());
    println("\nRand generation : " + rand_code.to_str());
    println("with performance : " + fit_fn(rand_code).to_str());
}

#[main]
fn main() {
    let mut ga: GeneticAlgorithm<f64> = GeneticAlgorithm::new(3000, 2, 0.8, 60.0, 100);
    let bmax = 2.0 * 2.0;
    do bench("Goldstein", -3.0001, &mut ga) |c| {
        // Restrict to hypercube -5.12 <= x <= 5.12
        let e1 = (c[0] - 0.5) * bmax;
        let e2 = (c[1] - 0.5) * bmax;

        let a = 1.0 + (e1 + e2 + 1.0).pow(~2.0) *
                 (19.0 - 14.0 * e1 + 13.0 * e1.pow(~2.0) - 14.0 * e2 +
                  6.0 * e1 * e2 + 3.0 * e2.pow(~2.0));
        let b =  30.0 + (2.0 * e1 - 3.0 * e2).pow(~2.0) *
                 (18.0 - 32.0 * e1 + 12.0 * e1.pow(~2.0) + 48.0 * e2 -
                  36.0 * e1 * e2 + 27.0 * e2 * e2);
        -a * b
    }
}
<|endoftext|>


<commit_before>use log::*;
use simplelog::*;

mod a {
    use log::*;

    pub(crate) fn print(client_id: &str, connection_id: usize) {
        info!(
            "{:15.15}[I] {:20} id = {}",
            client_id, "connect", connection_id
        );
    }
}

mod aaaa {
    use log::*;

    pub fn print(client_id: &str, connection_id: usize) {
        info!(
            "{:15.15}[I] {:20} id = {}",
            client_id, "connect", connection_id
        );
    }
}

fn main() {
    let mut config = simplelog::ConfigBuilder::new();
    config
        .set_time_format("".to_owned())
        .set_location_level(LevelFilter::Off)
        .set_target_level(LevelFilter::Error)
        .set_target_padding(TargetPadding::Right(15))
        .set_thread_level(LevelFilter::Error)
        .set_thread_padding(ThreadPadding::Left(2))
        .set_level_color(Level::Trace, Some(Color::Cyan))
        .set_level_padding(LevelPadding::Right);

    let loggers = TermLogger::new(
        LevelFilter::Debug,
        config.build(),
        TerminalMode::Mixed,
        ColorChoice::Always,
    );
    CombinedLogger::init(vec![loggers]).unwrap();

    error!("Bright red error");
    info!("This only appears in the log file");
    debug!("This level is currently not enabled for any logger");

    a::print("hello", 1);
    aaaa::print("world", 10);
}
<commit_msg>Remove modulepad example<commit_after><|endoftext|>


<commit_before>//! This example shows how to wrap a data structure in a mutex to achieve safe mutability.
extern crate lazy_static;
use lazy_static::lazy_static;
use std::collections::HashMap;
use std::sync::Mutex;

lazy_static! {
    static ref MUTEX_MAP: Mutex<HashMap<u32, &'static str>> = {
        let mut m = HashMap::new();
        m.insert(0, "foo");
        m.insert(1, "bar");
        m.insert(2, "baz");
        Mutex::new(m)
    };
}

fn main() {
    MUTEX_MAP.lock().unwrap().insert(0, "boo");
    println!(
        "The entry for `0` is \"{}\".",
        MUTEX_MAP.lock().unwrap().get(&0).unwrap()
    );
}
<commit_msg>macro_use instead of use<commit_after>//! This example shows how to wrap a data structure in a mutex to achieve safe mutability.
#[macro_use(lazy_static)]
extern crate lazy_static;
use std::collections::HashMap;
use std::sync::Mutex;

lazy_static! {
    static ref MUTEX_MAP: Mutex<HashMap<u32, &'static str>> = {
        let mut m = HashMap::new();
        m.insert(0, "foo");
        m.insert(1, "bar");
        m.insert(2, "baz");
        Mutex::new(m)
    };
}

fn main() {
    MUTEX_MAP.lock().unwrap().insert(0, "boo");
    println!(
        "The entry for `0` is \"{}\".",
        MUTEX_MAP.lock().unwrap().get(&0).unwrap()
    );
}
<|endoftext|>


<commit_before>extern crate zip;
extern crate walkdir;

use std::io::prelude::*;
use std::io::{Write, Seek};
use std::iter::Iterator;
use zip::write::FileOptions;
use zip::result::ZipError;

use walkdir::{WalkDir, DirEntry};
use std::path::Path;
use std::fs::File;

fn main() {
    std::process::exit(real_main());
}

const METHOD_STORED : Option<zip::CompressionMethod> = Some(zip::CompressionMethod::Stored);

#[cfg(feature = "bzip2")]
const METHOD_BZIP2 : Option<zip::CompressionMethod> = Some(zip::CompressionMethod::Bzip2);
#[cfg(not(feature = "bzip2"))]
const METHOD_BZIP2 : Option<zip::CompressionMethod> = None;

#[cfg(feature = "deflate")]
const METHOD_DEFLATED : Option<zip::CompressionMethod> = Some(zip::CompressionMethod::Deflated);
#[cfg(not(feature = "deflate"))]
const METHOD_DEFLATED : Option<zip::CompressionMethod> = None;

fn real_main() -> i32 {
    let args: Vec<_> = std::env::args().collect();
    if args.len() < 3 {
        println!("Usage: {} <source_directory> <destination_zipfile>",
                 args[0]);
        return 1;
    }

    let src_dir = &*args[1];
    let dst_file = &*args[2];
    for &method in [METHOD_STORED, METHOD_BZIP2, METHOD_DEFLATED].iter() {
        if method.is_none() { continue }
        match doit(src_dir, dst_file, method.unwrap()) {
            Ok(_) => println!("done: {} written to {}", src_dir, dst_file),
            Err(e) => println!("Error: {:?}", e),
        }
    }

    return 0;
}

fn zip_dir<T>(it: &mut Iterator<Item=DirEntry>, prefix: &str, writer: T, method: zip::CompressionMethod)
              -> zip::result::ZipResult<()>
    where T: Write+Seek
{
    let mut zip = zip::ZipWriter::new(writer);
    let options = FileOptions::default()
        .compression_method(method)
        .unix_permissions(0o755);

    let mut buffer = Vec::new();
    for entry in it {
        let path = entry.path();
        let name = path.strip_prefix(Path::new(prefix))
            .unwrap()
            .to_str()
            .unwrap();

        if path.is_file() {
            println!("adding {:?} as {:?} ...", path, name);
            zip.start_file(name, options)?;
            let mut f = File::open(path)?;

            f.read_to_end(&mut buffer)?;
            zip.write_all(&*buffer)?;
            buffer.clear();
        }
    }
    zip.finish()?;
    Result::Ok(())
}

fn doit(src_dir: &str, dst_file: &str, method: zip::CompressionMethod) -> zip::result::ZipResult<()> {
    if !Path::new(src_dir).is_dir() {
        return Err(ZipError::FileNotFound);
    }

    let path = Path::new(dst_file);
    let file = File::create(&path).unwrap();

    let walkdir = WalkDir::new(src_dir.to_string());
    let it = walkdir.into_iter();

    zip_dir(&mut it.filter_map(|e| e.ok()), src_dir, file, method)?;

    Ok(())
}<commit_msg>revert the code order changes<commit_after>extern crate zip;
extern crate walkdir;

use std::io::prelude::*;
use std::io::{Write, Seek};
use std::iter::Iterator;
use zip::write::FileOptions;
use zip::result::ZipError;

use walkdir::{WalkDir, DirEntry};
use std::path::Path;
use std::fs::File;

fn main() {
    std::process::exit(real_main());
}

const METHOD_STORED : Option<zip::CompressionMethod> = Some(zip::CompressionMethod::Stored);

#[cfg(feature = "deflate")]
const METHOD_DEFLATED : Option<zip::CompressionMethod> = Some(zip::CompressionMethod::Deflated);
#[cfg(not(feature = "deflate"))]
const METHOD_DEFLATED : Option<zip::CompressionMethod> = None;

#[cfg(feature = "bzip2")]
const METHOD_BZIP2 : Option<zip::CompressionMethod> = Some(zip::CompressionMethod::Bzip2);
#[cfg(not(feature = "bzip2"))]
const METHOD_BZIP2 : Option<zip::CompressionMethod> = None;

fn real_main() -> i32 {
    let args: Vec<_> = std::env::args().collect();
    if args.len() < 3 {
        println!("Usage: {} <source_directory> <destination_zipfile>",
                 args[0]);
        return 1;
    }

    let src_dir = &*args[1];
    let dst_file = &*args[2];
    for &method in [METHOD_STORED, METHOD_DEFLATED, METHOD_BZIP2].iter() {
        if method.is_none() { continue }
        match doit(src_dir, dst_file, method.unwrap()) {
            Ok(_) => println!("done: {} written to {}", src_dir, dst_file),
            Err(e) => println!("Error: {:?}", e),
        }
    }

    return 0;
}

fn zip_dir<T>(it: &mut Iterator<Item=DirEntry>, prefix: &str, writer: T, method: zip::CompressionMethod)
              -> zip::result::ZipResult<()>
    where T: Write+Seek
{
    let mut zip = zip::ZipWriter::new(writer);
    let options = FileOptions::default()
        .compression_method(method)
        .unix_permissions(0o755);

    let mut buffer = Vec::new();
    for entry in it {
        let path = entry.path();
        let name = path.strip_prefix(Path::new(prefix))
            .unwrap()
            .to_str()
            .unwrap();

        if path.is_file() {
            println!("adding {:?} as {:?} ...", path, name);
            zip.start_file(name, options)?;
            let mut f = File::open(path)?;

            f.read_to_end(&mut buffer)?;
            zip.write_all(&*buffer)?;
            buffer.clear();
        }
    }
    zip.finish()?;
    Result::Ok(())
}

fn doit(src_dir: &str, dst_file: &str, method: zip::CompressionMethod) -> zip::result::ZipResult<()> {
    if !Path::new(src_dir).is_dir() {
        return Err(ZipError::FileNotFound);
    }

    let path = Path::new(dst_file);
    let file = File::create(&path).unwrap();

    let walkdir = WalkDir::new(src_dir.to_string());
    let it = walkdir.into_iter();

    zip_dir(&mut it.filter_map(|e| e.ok()), src_dir, file, method)?;

    Ok(())
}<|endoftext|>


<commit_before>use macos::window::Window;

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

pub fn init(window: &Window) {

}

pub fn create_context(window: &Window) -> GLContext {
    GLContext
}

pub fn swap_buffers() {

}

pub fn set_proc_loader() {

}
<commit_msg>Quick fixes after merge.<commit_after>use macos::window::Window;

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

pub fn init(window: &Window) {

}

pub fn create_context(window: &Window) -> GLContext {
    GLContext
}

pub fn swap_buffers(window: &Window) {

}

pub fn set_proc_loader() {

}
<|endoftext|>


<commit_before>use std::io;
use std::str;

use crate::wire_format::WireType;

/// `Result` alias for `ProtobufError`
pub type ProtobufResult<T> = Result<T, ProtobufError>;

/// Enum values added here for diagnostic purposes.
/// Users should not depend on specific values.
#[derive(Debug, thiserror::Error)]
pub enum WireError {
    #[error("Unexpected EOF")]
    UnexpectedEof,
    #[error("Unexpected wire type")]
    UnexpectedWireType(WireType),
    #[error("Incorrect tag")]
    IncorrectTag(u32),
    // unused since https://github.com/stepancheg/rust-protobuf/issues/318
    #[error("Incomplete map")]
    IncompleteMap,
    #[error("Incorrect varint")]
    IncorrectVarint,
    #[error("Invalid UTF-8 sequence")]
    Utf8Error,
    #[error("Invalid enum value: {}", .0)]
    InvalidEnumValue(i32),
    #[error("Over recursion limit")]
    OverRecursionLimit,
    #[error("Truncated message")]
    TruncatedMessage,
    // not really possible
    #[error("Limit overflow")]
    LimitOverflow,
    #[error("New limit must not be greater than current limit")]
    LimitIncrease,
}

/// Generic protobuf error
#[derive(Debug, thiserror::Error)]
pub enum ProtobufError {
    /// I/O error when reading or writing
    #[error(transparent)]
    IoError(#[from] io::Error),
    /// Malformed input
    #[error(transparent)]
    WireError(#[from] WireError),
    /// Protocol contains a string which is not valid UTF-8 string
    #[error("UTF-8 decode error")]
    Utf8(#[source] str::Utf8Error),
    /// Not all required fields of message set.
    #[error("Message `{}` is missing required fields", .0)]
    MessageNotInitialized(String),
    /// Protobuf type and runtime types mismatch.
    #[error("Protobuf type and runtime types are not compatible")]
    IncompatibleProtobufTypeAndRuntimeType,
    /// Group field type not implemented.
    #[error("Group field is not supported")]
    GroupIsNotImplemented,
}

impl From<ProtobufError> for io::Error {
    fn from(err: ProtobufError) -> Self {
        match err {
            ProtobufError::IoError(e) => e,
            ProtobufError::WireError(e) => {
                io::Error::new(io::ErrorKind::InvalidData, ProtobufError::WireError(e))
            }
            ProtobufError::MessageNotInitialized(message) => io::Error::new(
                io::ErrorKind::InvalidInput,
                ProtobufError::MessageNotInitialized(message),
            ),
            e => io::Error::new(io::ErrorKind::Other, Box::new(e)),
        }
    }
}
<commit_msg>Fix compilation when feature with-bytes<commit_after>use std::io;
use std::str;

use crate::wire_format::WireType;

/// `Result` alias for `ProtobufError`
pub type ProtobufResult<T> = Result<T, ProtobufError>;

/// Enum values added here for diagnostic purposes.
/// Users should not depend on specific values.
#[derive(Debug, thiserror::Error)]
pub enum WireError {
    #[error("Unexpected EOF")]
    UnexpectedEof,
    #[error("Unexpected wire type")]
    UnexpectedWireType(WireType),
    #[error("Incorrect tag")]
    IncorrectTag(u32),
    // unused since https://github.com/stepancheg/rust-protobuf/issues/318
    #[error("Incomplete map")]
    IncompleteMap,
    #[error("Incorrect varint")]
    IncorrectVarint,
    #[error("Invalid UTF-8 sequence")]
    Utf8Error,
    #[error("Invalid enum value: {}", .0)]
    InvalidEnumValue(i32),
    #[error("Over recursion limit")]
    OverRecursionLimit,
    #[error("Truncated message")]
    TruncatedMessage,
    // not really possible
    #[error("Limit overflow")]
    LimitOverflow,
    #[error("New limit must not be greater than current limit")]
    LimitIncrease,
}

/// Generic protobuf error
#[derive(Debug, thiserror::Error)]
pub enum ProtobufError {
    /// I/O error when reading or writing
    #[error(transparent)]
    IoError(#[from] io::Error),
    /// Malformed input
    #[error(transparent)]
    WireError(#[from] WireError),
    /// Protocol contains a string which is not valid UTF-8 string
    #[error("UTF-8 decode error")]
    Utf8(
        #[source]
        #[from]
        str::Utf8Error,
    ),
    /// Not all required fields of message set.
    #[error("Message `{}` is missing required fields", .0)]
    MessageNotInitialized(String),
    /// Protobuf type and runtime types mismatch.
    #[error("Protobuf type and runtime types are not compatible")]
    IncompatibleProtobufTypeAndRuntimeType,
    /// Group field type not implemented.
    #[error("Group field is not supported")]
    GroupIsNotImplemented,
}

impl From<ProtobufError> for io::Error {
    fn from(err: ProtobufError) -> Self {
        match err {
            ProtobufError::IoError(e) => e,
            ProtobufError::WireError(e) => {
                io::Error::new(io::ErrorKind::InvalidData, ProtobufError::WireError(e))
            }
            ProtobufError::MessageNotInitialized(message) => io::Error::new(
                io::ErrorKind::InvalidInput,
                ProtobufError::MessageNotInitialized(message),
            ),
            e => io::Error::new(io::ErrorKind::Other, Box::new(e)),
        }
    }
}
<|endoftext|>