<commit_before><commit_msg>[katas] update<commit_after>impl Solution {
    pub fn reverse(x: i32) -> i32 {
        match x {
            -9..=9 => x,
            _ => {
                let mut divider = 10;
                let mut number = x;
                let mut reversed_number = 0;
                let mut numbers = Vec::with_capacity(10); // for i32

                while number != 0 {
                    numbers.push(number % 10);
                    number = number / 10;
                }

                if numbers.len() == 10 {
                    if (x < 0) {
                        if (!Self::no_negative_overflow_check(&numbers)) {
                            return 0;
                        }
                    } else {
                        if (!Self::no_positive_overflow_check(&numbers)) {
                            return 0;
                        }
                    }
                }

                reversed_number = *numbers.first().expect("should have at least one number");
                numbers.into_iter().skip(1).for_each(|number| {
                   reversed_number = reversed_number * 10 + number;
                });

                reversed_number
            }
        }
    }

    fn no_positive_overflow_check(numbers: &[i32]) -> bool {
        let max_int32 = [2,1,4,7,4,8,3,6,4,7];
        for i in 0..10 {
            let local_max = max_int32[i];
            let current_val = numbers[i];

            if current_val < local_max {
                return true
            }

            if current_val > local_max {
                return false
            }
        }

        true
    }

    fn no_negative_overflow_check(numbers: &[i32]) -> bool {
        let min_int32 = [-2,-1,-4,-7,-4,-8,-3,-6,-4,-8];
        for i in 0..10 {
            let local_min = min_int32[i];
            let current_val = numbers[i];

            if current_val > local_min {
                return true
            }

            if current_val < local_min {
                return false
            }
        }

        true
    }
}
<|endoftext|>


<commit_before><commit_msg>Update format.<commit_after><|endoftext|>


<commit_before><commit_msg>tuples added to data types<commit_after><|endoftext|>


<commit_before>use {Future, Poll, Async};
use std::marker::PhantomData;
/// Future for the `from_err` combinator, changing the error type of a future.
///
/// This is created by this `Future::from_err` method.
#[must_use = "futures do nothing unless polled"]
pub struct FromErr<A, E> where A: Future {
    future: A,
    f: PhantomData<E>
}

pub fn new<A, E>(future: A) -> FromErr<A, E>
    where A: Future
{
    FromErr {
        future: future,
        f: PhantomData
    }
}

impl<A:Future, E:From<A::Error>> Future for FromErr<A, E> {
    type Item = A::Item;
    type Error = E;

    fn poll(&mut self) -> Poll<A::Item, E> {
        let e = match self.future.poll() {
            Ok(Async::NotReady) => return Ok(Async::NotReady),
            other => other,
        };
        e.map_err(From::from)
    }
}
<commit_msg>Import from core, not std<commit_after>use core::marker::PhantomData;

use {Future, Poll, Async};

/// Future for the `from_err` combinator, changing the error type of a future.
///
/// This is created by this `Future::from_err` method.
#[must_use = "futures do nothing unless polled"]
pub struct FromErr<A, E> where A: Future {
    future: A,
    f: PhantomData<E>
}

pub fn new<A, E>(future: A) -> FromErr<A, E>
    where A: Future
{
    FromErr {
        future: future,
        f: PhantomData
    }
}

impl<A:Future, E:From<A::Error>> Future for FromErr<A, E> {
    type Item = A::Item;
    type Error = E;

    fn poll(&mut self) -> Poll<A::Item, E> {
        let e = match self.future.poll() {
            Ok(Async::NotReady) => return Ok(Async::NotReady),
            other => other,
        };
        e.map_err(From::from)
    }
}
<|endoftext|>


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

//! An interface for numeric types

pub trait Num {
    // FIXME: Trait composition. (#2616)
    pure fn add(&self, other: &Self) -> Self;
    pure fn sub(&self, other: &Self) -> Self;
    pure fn mul(&self, other: &Self) -> Self;
    pure fn div(&self, other: &Self) -> Self;
    pure fn modulo(&self, other: &Self) -> Self;
    pure fn neg(&self) -> Self;

    pure fn to_int(&self) -> int;
    static pure fn from_int(n: int) -> Self;
}

pub trait IntConvertible {
    pure fn to_int(&self) -> int;
    static pure fn from_int(n: int) -> Self;
}

pub trait Zero {
    static pure fn zero() -> Self;
}

pub trait One {
    static pure fn one() -> Self;
}

pub trait Round {
    pure fn round(&self, mode: RoundMode) -> self;

    pure fn floor(&self) -> self;
    pure fn ceil(&self)  -> self;
    pure fn fract(&self) -> self;
}

pub enum RoundMode {
    RoundDown,
    RoundUp,
    RoundToZero,
    RoundFromZero
}
<commit_msg>Added ToStrRadix and FromStrRadix traits<commit_after>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! An interface for numeric types
use cmp::Eq;
use option::{None, Option, Some};

pub trait Num {
    // FIXME: Trait composition. (#2616)
    pure fn add(&self, other: &Self) -> Self;
    pure fn sub(&self, other: &Self) -> Self;
    pure fn mul(&self, other: &Self) -> Self;
    pure fn div(&self, other: &Self) -> Self;
    pure fn modulo(&self, other: &Self) -> Self;
    pure fn neg(&self) -> Self;

    pure fn to_int(&self) -> int;
    static pure fn from_int(n: int) -> Self;
}

pub trait IntConvertible {
    pure fn to_int(&self) -> int;
    static pure fn from_int(n: int) -> Self;
}

pub trait Zero {
    static pure fn zero() -> Self;
}

pub trait One {
    static pure fn one() -> Self;
}

pub trait Round {
    pure fn round(&self, mode: RoundMode) -> self;

    pure fn floor(&self) -> self;
    pure fn ceil(&self)  -> self;
    pure fn fract(&self) -> self;
}

pub enum RoundMode {
    RoundDown,
    RoundUp,
    RoundToZero,
    RoundFromZero
}

pub trait ToStrRadix {
    pub pure fn to_str_radix(&self, radix: uint) -> ~str;
}

pub trait FromStrRadix {
    static pub pure fn from_str_radix(str: &str, radix: uint) -> Option<self>;
}<|endoftext|>


<commit_before><commit_msg>Add benchmark tests for ECS executions.<commit_after>#![feature(test)]
extern crate test;
extern crate crayon;
extern crate rayon;

use test::Bencher;
use crayon::prelude::*;

use std::thread;
use std::time;

#[derive(Debug, Copy, Clone, Default)]
struct PlaceHolderCMP {}

impl Component for PlaceHolderCMP {
    type Arena = ecs::VecArena<PlaceHolderCMP>;
}

fn execute() {
    thread::sleep(time::Duration::from_millis(1));
}

#[derive(Copy, Clone)]
struct HeavyCPU {}

impl<'a> System<'a> for HeavyCPU {
    type ViewWith = Fetch<'a, PlaceHolderCMP>;

    fn run(&mut self, view: View, _: Self::ViewWith) {
        for _ in view {
            execute();
        }
    }
}

fn setup() -> World {
    let mut world = World::new();
    world.register::<PlaceHolderCMP>();

    for _ in 1..3 {
        world.build().with_default::<PlaceHolderCMP>();
    }

    world
}

#[bench]
fn bench_sequence_execution(b: &mut Bencher) {
    b.iter(|| {
        let world = setup();
        let mut s1 = HeavyCPU {};
        let mut s2 = HeavyCPU {};
        let mut s3 = HeavyCPU {};
        s1.run_at(&world);
        s2.run_at(&world);
        s3.run_at(&world);
    });
}

#[bench]
fn bench_parralle_execution(b: &mut Bencher) {
    b.iter(|| {
        let world = setup();
        let mut s1 = HeavyCPU {};
        let mut s2 = HeavyCPU {};
        let mut s3 = HeavyCPU {};

        rayon::scope(|s| {
                         //
                         s.spawn(|_| s1.run_at(&world));
                         s.spawn(|_| s2.run_at(&world));
                         s.spawn(|_| s3.run_at(&world));
                     });
    });
}

#[derive(Copy, Clone)]
struct HeavyCPUWithRayon {}

impl<'a> System<'a> for HeavyCPUWithRayon {
    type ViewWith = Fetch<'a, PlaceHolderCMP>;

    fn run(&mut self, view: View, _: Self::ViewWith) {
        rayon::scope(|s| {
                         //
                         for _ in view {
                             s.spawn(|_| execute());
                         }
                     })
    }
}

#[bench]
fn bench_parralle_execution_2(b: &mut Bencher) {
    b.iter(|| {
        let world = setup();
        let mut s1 = HeavyCPUWithRayon {};
        let mut s2 = HeavyCPUWithRayon {};
        let mut s3 = HeavyCPUWithRayon {};

        rayon::scope(|s| {
                         //
                         s.spawn(|_| s1.run_at(&world));
                         s.spawn(|_| s2.run_at(&world));
                         s.spawn(|_| s3.run_at(&world));
                     });
    });
}
<|endoftext|>


<commit_before><commit_msg>disconnects on read line error<commit_after><|endoftext|>


<commit_before><commit_msg>test: panic at map_unit_fn.rs:202 for map() without args<commit_after>// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![allow(unused)]
struct Mappable {}

impl Mappable {
    pub fn map(&self) {}
}

fn main() {
    let m = Mappable {};
    m.map();
}
<|endoftext|>


<commit_before><commit_msg>Added mod example<commit_after>fn function() {
    println!("called `function()`");
}

// A module named `my`
mod my {
    // A module can contain items like functions
    #[allow(dead_code)]
    fn function() {
        println!("called `my::function()`");
    }

    // Modules can be nested
    mod nested {
        #[allow(dead_code)]
        fn function() {
            println!("called `my::nested::function()`");
        }
    }
}

fn main() {
    function();

    // Error! `my::function` is private
    // my::function();
    // TODO ^ Comment out this line
}
<|endoftext|>


<commit_before><commit_msg>Adjust the scrolling when PPUADDR is written to.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix the OpenGL renderer after the last commit<commit_after><|endoftext|>


<commit_before><commit_msg>Show the driver information in the OSD<commit_after><|endoftext|>


<commit_before><commit_msg>Add 6510 CPU based on the 6502 CPU<commit_after>use mem::Addressable;
use super::cpu::CPU;
use super::mos6502::Mos6502;

/// The MOS65010 processor
pub struct Mos6510 {
	priv cpu: Mos6502,						// Core CPU is a MOS6502
	priv port_ddr: u8,						// CPU port data direction register
	priv port_dat: u8,						// CPU port data register
}

impl Mos6510 {
	/// Create a new MOS6510 processor
	pub fn new () -> Mos6510 {
		// TODO: addresses $0000 (data direction) and $0001 (data) are hardwired for the processor I/O port
		Mos6510 { cpu: Mos6502::new(), port_ddr: 0, port_dat: 0 }
	}
}

impl CPU<u16> for Mos6510 {
	/// Reset the CPU
	fn reset<M: Addressable<u16>> (&mut self, mem: &M) {
		self.cpu.reset(mem);
	}

	/// Do one step (execute the next instruction). Returns the number of
	/// cycles the instruction needed
	fn step<M: Addressable<u16>> (&mut self, mem: &mut M) -> uint {
		self.cpu.step(mem)
	}
}
<|endoftext|>


<commit_before><commit_msg>First draw of a dumb raytracer<commit_after>extern mod png;

use std::num::{sqrt, min, max, cos, sin};

static WIDTH: f64 = 800.;
static HEIGHT: f64 = 800.;

struct Color {
  r: u8,
  g: u8,
  b: u8
}

static Red: Color = Color { r: 255, g: 0, b: 0 };
static Green: Color = Color { r: 0, g: 255, b: 0 };
static Blue: Color = Color { r: 0, g: 0, b: 255 };
static White: Color = Color { r: 255, g: 255, b: 255 };
static Black: Color = Color { r: 0, g: 0, b: 0 };

struct Point {
  x: f64,
  y: f64,
  z: f64
}

struct Spot {
  pos: Point,
  color: Color,
}

struct Sphere {
  pos: Point,
  radius: f64,
  shininess: f64,
  color: Color
}

struct Scene {
  eye: Point,
  spot: Spot,
  sphere: Sphere
}

fn solve_poly(a: f64, b: f64, c: f64) -> f64 {
  let delta = b.pow(&2.0) - 4. * a * c;

  if delta < 0. {
    return 0.;
  }

  let k1 = (-b - sqrt(delta)) / (2. * a);
  let k2 = (-b + sqrt(delta)) / (2. * a);

  return match (k1, k2) {
    (k1, k2) if k1 < 0. && k2 < 0. => 0.,
    (k1, k2) if k2 <= 0. => k1,
    (k1, k2) if k1 <= 0. => k2,
    _ => min(k1, k2)
  }
}

fn hit_sphere(sphere: &Sphere, eye: &Point, vector: &Point) -> f64 {
  let a = vector.x.pow(&2.) + vector.y.pow(&2.) + vector.z.pow(&2.);
  let b = 2. * (eye.x * vector.x + eye.y * vector.y + eye.z * vector.z);
  let c = eye.x.pow(&2.) + eye.y.pow(&2.) + eye.z.pow(&2.) - sphere.radius.pow(&2.);
  return solve_poly(a, b, c);
}

fn get_closest(obj: &Sphere, eye: &Point, vector: &Point) -> f64 {
  let e = ~Point { x: eye.x - obj.pos.x, y: eye.y - obj.pos.y, z: eye.z - obj.pos.z };
  let v = ~Point { x: vector.x, y: vector.y, z: vector.z };
  return hit_sphere(obj, e, v);
}

fn get_light(obj: &Sphere, spot: &Spot, inter: &Point, light: &Point) -> Color {
  let perp = Point { x: inter.x, y: inter.y, z: inter.z };
  let norme_l = sqrt(light.x.pow(&2.) + light.y.pow(&2.) + light.z.pow(&2.));
  let norme_n = sqrt(perp.x.pow(&2.) + perp.y.pow(&2.) + perp.z.pow(&2.));
  let cos_a = (light.x * perp.x + light.y * perp.y + light.z * perp.z) / (norme_l * norme_n);

  if cos_a <= 0. {
    return Black;
  }

  Color {
    r: ((obj.color.r as f64) * cos_a * (1. - obj.shininess) + (spot.color.r as f64) * cos_a * obj.shininess) as u8,
    g: ((obj.color.g as f64) * cos_a * (1. - obj.shininess) + (spot.color.g as f64) * cos_a * obj.shininess) as u8,
    b: ((obj.color.b as f64) * cos_a * (1. - obj.shininess) + (spot.color.b as f64) * cos_a * obj.shininess) as u8
  }
}

fn main() {
  let mut pixels = ~[Black, ..((WIDTH * HEIGHT) as uint)];

  let eye = ~Point { x: -300., y: 0., z: 200. };
  let spot = ~Spot {
    pos: Point { x: -300., y: 100., z: 200. },
    color: White
  };
  let sphere = ~Sphere {
    pos: Point { x: 0., y: 0., z: 0. },
    radius: 160.,
    shininess: 0.2,
    color: Red
  };

  for x in range(0., WIDTH) {
    for y in range(0., HEIGHT) {
      let vector = ~Point {
        x: 100.,
        y: (WIDTH / 2. - x),
        z: (HEIGHT / 2. - y)
      };

      // Always 0 :'(
      let closest = get_closest(sphere, eye, vector);

      // // Shadow
      // let inter = Point {
      //   x: eye.x + closest * vector.x,
      //   y: eye.y + closest * vector.y,
      //   z: eye.z + closest * vector.z
      // };
      // let light = Point {
      //   x: spot.pos.x - inter.x,
      //   y: spot.pos.y - inter.y,
      //   z: spot.pos.z - inter.z
      // };

      let inter = ~Point {
        x: (eye.x - sphere.pos.x) + closest * vector.x,
        y: (eye.y - sphere.pos.y) + closest * vector.y,
        z: (eye.z - sphere.pos.z) + closest * vector.z
      };
      let light = ~Point {
        x: spot.pos.x - inter.x,
        y: spot.pos.y - inter.y,
        z: spot.pos.z - inter.z
      };

      pixels[(x * WIDTH + y) as u32] = get_light(sphere, spot, inter, light);
    }
  }

  let img = png::Image {
    width: WIDTH as u32,
    height: HEIGHT as u32,
    color_type: png::RGB8,
    pixels: pixels.flat_map(|&Color { r: r, g: g, b: b }| { ~[r, g, b] })
  };

  png::store_png(&img, &Path::new("out.png"));
}
<|endoftext|>


<commit_before><commit_msg>Minimal DenseMatrix API refactoring<commit_after><|endoftext|>


<commit_before>import rustc::syntax::ast;

export extract;

#[doc = "Converts the Rust AST to the rustdoc document model"]
fn extract(
    crate: @ast::crate,
    default_name: str
) -> doc::cratedoc {
    ~{
        topmod: top_moddoc_from_crate(crate, default_name),
    }
}

fn top_moddoc_from_crate(
    crate: @ast::crate,
    default_name: str
) -> doc::moddoc {
    moddoc_from_mod(crate.node.module, default_name)
}

fn moddoc_from_mod(
    module: ast::_mod,
    name: ast::ident
) -> doc::moddoc {
    ~{
        name: name,
        mods: doc::modlist(
            vec::filter_map(module.items) {|item|
                alt item.node {
                  ast::item_mod(m) {
                    some(moddoc_from_mod(m, item.ident))
                  }
                  _ {
                    none
                  }
                }
            }),
        fns: doc::fnlist(
            vec::filter_map(module.items) {|item|
                alt item.node {
                  ast::item_fn(decl, _, _) {
                    some(fndoc_from_fn(
                        decl, item.ident, item.id))
                  }
                  _ {
                    none
                  }
                }
            })
    }
}

fn fndoc_from_fn(
    _decl: ast::fn_decl,
    name: ast::ident,
    id: ast::node_id
) -> doc::fndoc {
    ~{
        id: id,
        name: name,
        brief: none,
        desc: none,
        return: none,
        args: []
    }
}

#[cfg(test)]
mod tests {

    #[test]
    fn extract_empty_crate() {
        let source = ""; // empty crate
        let ast = parse::from_str(source);
        let doc = extract(ast, "");
        // FIXME #1535: These are boxed to prevent a crash
        assert ~doc.topmod.mods == ~doc::modlist([]);
        assert ~doc.topmod.fns == ~doc::fnlist([]);
    }

    #[test]
    fn extract_mods() {
        let source = "mod a { mod b { } mod c { } }";
        let ast = parse::from_str(source);
        let doc = extract(ast, "");
        assert doc.topmod.mods[0].name == "a";
        assert doc.topmod.mods[0].mods[0].name == "b";
        assert doc.topmod.mods[0].mods[1].name == "c";
    }

    #[test]
    fn extract_mods_deep() {
        let source = "mod a { mod b { mod c { } } }";
        let ast = parse::from_str(source);
        let doc = extract(ast, "");
        assert doc.topmod.mods[0].mods[0].mods[0].name == "c";
    }

    #[test]
    fn extract_fns() {
        let source =
            "fn a() { } \
             mod b { fn c() { } }";
        let ast = parse::from_str(source);
        let doc = extract(ast, "");
        assert doc.topmod.fns[0].name == "a";
        assert doc.topmod.mods[0].fns[0].name == "c";
    }

    #[test]
    fn extract_should_set_fn_ast_id() {
        let source = "fn a() { }";
        let ast = parse::from_str(source);
        let doc = extract(ast, "");
        assert doc.topmod.fns[0].id != 0;
    }

    #[test]
    fn extract_should_use_default_crate_name() {
        let source = "";
        let ast = parse::from_str(source);
        let doc = extract(ast, "burp");
        assert doc.topmod.name == "burp";
    }
}<commit_msg>rustdoc: Add extract::from_srv to extract a doc from an astsrv<commit_after>import rustc::syntax::ast;

export from_srv, extract;

// FIXME: Want this to be from_srv<T:ast::srv> but it crashes
fn from_srv(
    srv: astsrv::seq_srv,
    default_name: str
) -> doc::cratedoc {
    import astsrv::seq_srv;
    srv.exec {|ctxt|
        extract(ctxt.ast, default_name)
    }
}

#[doc = "Converts the Rust AST to the rustdoc document model"]
fn extract(
    crate: @ast::crate,
    default_name: str
) -> doc::cratedoc {
    ~{
        topmod: top_moddoc_from_crate(crate, default_name),
    }
}

fn top_moddoc_from_crate(
    crate: @ast::crate,
    default_name: str
) -> doc::moddoc {
    moddoc_from_mod(crate.node.module, default_name)
}

fn moddoc_from_mod(
    module: ast::_mod,
    name: ast::ident
) -> doc::moddoc {
    ~{
        name: name,
        mods: doc::modlist(
            vec::filter_map(module.items) {|item|
                alt item.node {
                  ast::item_mod(m) {
                    some(moddoc_from_mod(m, item.ident))
                  }
                  _ {
                    none
                  }
                }
            }),
        fns: doc::fnlist(
            vec::filter_map(module.items) {|item|
                alt item.node {
                  ast::item_fn(decl, _, _) {
                    some(fndoc_from_fn(
                        decl, item.ident, item.id))
                  }
                  _ {
                    none
                  }
                }
            })
    }
}

fn fndoc_from_fn(
    _decl: ast::fn_decl,
    name: ast::ident,
    id: ast::node_id
) -> doc::fndoc {
    ~{
        id: id,
        name: name,
        brief: none,
        desc: none,
        return: none,
        args: []
    }
}

#[cfg(test)]
mod tests {

    #[test]
    fn extract_empty_crate() {
        let source = ""; // empty crate
        let ast = parse::from_str(source);
        let doc = extract(ast, "");
        // FIXME #1535: These are boxed to prevent a crash
        assert ~doc.topmod.mods == ~doc::modlist([]);
        assert ~doc.topmod.fns == ~doc::fnlist([]);
    }

    #[test]
    fn extract_mods() {
        let source = "mod a { mod b { } mod c { } }";
        let ast = parse::from_str(source);
        let doc = extract(ast, "");
        assert doc.topmod.mods[0].name == "a";
        assert doc.topmod.mods[0].mods[0].name == "b";
        assert doc.topmod.mods[0].mods[1].name == "c";
    }

    #[test]
    fn extract_mods_deep() {
        let source = "mod a { mod b { mod c { } } }";
        let ast = parse::from_str(source);
        let doc = extract(ast, "");
        assert doc.topmod.mods[0].mods[0].mods[0].name == "c";
    }

    #[test]
    fn extract_fns() {
        let source =
            "fn a() { } \
             mod b { fn c() { } }";
        let ast = parse::from_str(source);
        let doc = extract(ast, "");
        assert doc.topmod.fns[0].name == "a";
        assert doc.topmod.mods[0].fns[0].name == "c";
    }

    #[test]
    fn extract_should_set_fn_ast_id() {
        let source = "fn a() { }";
        let ast = parse::from_str(source);
        let doc = extract(ast, "");
        assert doc.topmod.fns[0].id != 0;
    }

    #[test]
    fn extract_should_use_default_crate_name() {
        let source = "";
        let ast = parse::from_str(source);
        let doc = extract(ast, "burp");
        assert doc.topmod.name == "burp";
    }

    #[test]
    fn extract_from_seq_srv() {
        import astsrv::seq_srv;
        let source = "";
        let srv = astsrv::mk_seq_srv_from_str(source);
        let doc = from_srv(srv, "name");
        assert doc.topmod.name == "name";
    }
}<|endoftext|>


<commit_before><commit_msg>languages/rust/learn-rust/3-chapter/15-code.rs<commit_after><|endoftext|>


<commit_before><commit_msg>an empy message<commit_after><|endoftext|>


<commit_before><commit_msg> removed filter for testing<commit_after><|endoftext|>


<commit_before><commit_msg>rs: Square(n) Sum<commit_after><|endoftext|>


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

use std::c_str::ToCStr;
use std::libc::{c_char, c_int};
use std::{local_data, str, rt};
use std::unstable::finally::Finally;

#[cfg(stage0)]
pub mod rustrt {
    use std::libc::{c_char, c_int};

    extern {
        fn linenoise(prompt: *c_char) -> *c_char;
        fn linenoiseHistoryAdd(line: *c_char) -> c_int;
        fn linenoiseHistorySetMaxLen(len: c_int) -> c_int;
        fn linenoiseHistorySave(file: *c_char) -> c_int;
        fn linenoiseHistoryLoad(file: *c_char) -> c_int;
        fn linenoiseSetCompletionCallback(callback: *u8);
        fn linenoiseAddCompletion(completions: *(), line: *c_char);

        fn rust_take_linenoise_lock();
        fn rust_drop_linenoise_lock();
    }
}

#[cfg(not(stage0))]
pub mod rustrt {
    use std::libc::{c_char, c_int};

    externfn!(fn linenoise(prompt: *c_char) -> *c_char)
    externfn!(fn linenoiseHistoryAdd(line: *c_char) -> c_int)
    externfn!(fn linenoiseHistorySetMaxLen(len: c_int) -> c_int)
    externfn!(fn linenoiseHistorySave(file: *c_char) -> c_int)
    externfn!(fn linenoiseHistoryLoad(file: *c_char) -> c_int)
    externfn!(fn linenoiseSetCompletionCallback(callback: extern "C" fn(*i8, *())))
    externfn!(fn linenoiseAddCompletion(completions: *(), line: *c_char))

    externfn!(fn rust_take_linenoise_lock())
    externfn!(fn rust_drop_linenoise_lock())
}

macro_rules! locked {
    ($expr:expr) => {
        unsafe {
            // FIXME #9105: can't use a static mutex in pure Rust yet.
            rustrt::rust_take_linenoise_lock();
            let x = $expr;
            rustrt::rust_drop_linenoise_lock();
            x
        }
    }
}

/// Add a line to history
pub fn add_history(line: &str) -> bool {
    do line.with_c_str |buf| {
        (locked!(rustrt::linenoiseHistoryAdd(buf))) == 1 as c_int
    }
}

/// Set the maximum amount of lines stored
pub fn set_history_max_len(len: int) -> bool {
    (locked!(rustrt::linenoiseHistorySetMaxLen(len as c_int))) == 1 as c_int
}

/// Save line history to a file
pub fn save_history(file: &str) -> bool {
    do file.with_c_str |buf| {
        (locked!(rustrt::linenoiseHistorySave(buf))) == 1 as c_int
    }
}

/// Load line history from a file
pub fn load_history(file: &str) -> bool {
    do file.with_c_str |buf| {
        (locked!(rustrt::linenoiseHistoryLoad(buf))) == 1 as c_int
    }
}

/// Print out a prompt and then wait for input and return it
pub fn read(prompt: &str) -> Option<~str> {
    do prompt.with_c_str |buf| {
        let line = locked!(rustrt::linenoise(buf));

        if line.is_null() { None }
        else {
            unsafe {
                do (|| {
                    Some(str::raw::from_c_str(line))
                }).finally {
                    // linenoise's return value is from strdup, so we
                    // better not leak it.
                    rt::global_heap::exchange_free(line);
                }
            }
        }
    }
}

pub type CompletionCb = @fn(~str, @fn(~str));

static complete_key: local_data::Key<@CompletionCb> = &local_data::Key;

/// Bind to the main completion callback.
///
/// The completion callback should not call any `extra::rl` functions
/// other than the closure that it receives as its second
/// argument. Calling such a function will deadlock on the mutex used
/// to ensure that the calls are thread-safe.
pub fn complete(cb: CompletionCb) {
    local_data::set(complete_key, @cb);

    extern fn callback(line: *c_char, completions: *()) {
        do local_data::get(complete_key) |cb| {
            let cb = **cb.unwrap();

            unsafe {
                do cb(str::raw::from_c_str(line)) |suggestion| {
                    do suggestion.with_c_str |buf| {
                        // This isn't locked, because `callback` gets
                        // called inside `rustrt::linenoise`, which
                        // *is* already inside the mutex, so
                        // re-locking would be a deadlock.
                        rustrt::linenoiseAddCompletion(completions, buf);
                    }
                }
            }
        }
    }

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

use std::c_str::ToCStr;
use std::libc::{c_char, c_int};
use std::{local_data, str, rt};
use std::unstable::finally::Finally;

#[cfg(stage0)]
pub mod rustrt {
    use std::libc::{c_char, c_int};

    extern {
        fn linenoise(prompt: *c_char) -> *c_char;
        fn linenoiseHistoryAdd(line: *c_char) -> c_int;
        fn linenoiseHistorySetMaxLen(len: c_int) -> c_int;
        fn linenoiseHistorySave(file: *c_char) -> c_int;
        fn linenoiseHistoryLoad(file: *c_char) -> c_int;
        fn linenoiseSetCompletionCallback(callback: *u8);
        fn linenoiseAddCompletion(completions: *(), line: *c_char);

        fn rust_take_linenoise_lock();
        fn rust_drop_linenoise_lock();
    }
}

#[cfg(not(stage0))]
pub mod rustrt {
    use std::libc::{c_char, c_int};

    externfn!(fn linenoise(prompt: *c_char) -> *c_char)
    externfn!(fn linenoiseHistoryAdd(line: *c_char) -> c_int)
    externfn!(fn linenoiseHistorySetMaxLen(len: c_int) -> c_int)
    externfn!(fn linenoiseHistorySave(file: *c_char) -> c_int)
    externfn!(fn linenoiseHistoryLoad(file: *c_char) -> c_int)
    externfn!(fn linenoiseSetCompletionCallback(callback: extern "C" fn(*i8, *())))
    externfn!(fn linenoiseAddCompletion(completions: *(), line: *c_char))

    externfn!(fn rust_take_linenoise_lock())
    externfn!(fn rust_drop_linenoise_lock())
}

macro_rules! locked {
    ($expr:expr) => {
        unsafe {
            // FIXME #9105: can't use a static mutex in pure Rust yet.
            rustrt::rust_take_linenoise_lock();
            let x = $expr;
            rustrt::rust_drop_linenoise_lock();
            x
        }
    }
}

/// Add a line to history
pub fn add_history(line: &str) -> bool {
    do line.with_c_str |buf| {
        (locked!(rustrt::linenoiseHistoryAdd(buf))) == 1 as c_int
    }
}

/// Set the maximum amount of lines stored
pub fn set_history_max_len(len: int) -> bool {
    (locked!(rustrt::linenoiseHistorySetMaxLen(len as c_int))) == 1 as c_int
}

/// Save line history to a file
pub fn save_history(file: &str) -> bool {
    do file.with_c_str |buf| {
        // 0 on success, -1 on failure
        (locked!(rustrt::linenoiseHistorySave(buf))) == 0 as c_int
    }
}

/// Load line history from a file
pub fn load_history(file: &str) -> bool {
    do file.with_c_str |buf| {
        // 0 on success, -1 on failure
        (locked!(rustrt::linenoiseHistoryLoad(buf))) == 0 as c_int
    }
}

/// Print out a prompt and then wait for input and return it
pub fn read(prompt: &str) -> Option<~str> {
    do prompt.with_c_str |buf| {
        let line = locked!(rustrt::linenoise(buf));

        if line.is_null() { None }
        else {
            unsafe {
                do (|| {
                    Some(str::raw::from_c_str(line))
                }).finally {
                    // linenoise's return value is from strdup, so we
                    // better not leak it.
                    rt::global_heap::exchange_free(line);
                }
            }
        }
    }
}

pub type CompletionCb = @fn(~str, @fn(~str));

static complete_key: local_data::Key<CompletionCb> = &local_data::Key;

/// Bind to the main completion callback in the current task.
///
/// The completion callback should not call any `extra::rl` functions
/// other than the closure that it receives as its second
/// argument. Calling such a function will deadlock on the mutex used
/// to ensure that the calls are thread-safe.
pub fn complete(cb: CompletionCb) {
    local_data::set(complete_key, cb);

    extern fn callback(c_line: *c_char, completions: *()) {
        do local_data::get(complete_key) |opt_cb| {
            // only fetch completions if a completion handler has been
            // registered in the current task.
            match opt_cb {
                None => {},
                Some(cb) => {
                    let line = unsafe { str::raw::from_c_str(c_line) };
                    do (*cb)(line) |suggestion| {
                        do suggestion.with_c_str |buf| {
                            // This isn't locked, because `callback` gets
                            // called inside `rustrt::linenoise`, which
                            // *is* already inside the mutex, so
                            // re-locking would be a deadlock.
                            unsafe {
                                rustrt::linenoiseAddCompletion(completions, buf);
                            }
                        }
                    }
                }
            }
        }
    }

    locked!(rustrt::linenoiseSetCompletionCallback(callback));
}
<|endoftext|>


<commit_before><commit_msg>Increase Left Panel Spacing Fixes an issue of the Scrollbar consuming the status icons with some themes.<commit_after><|endoftext|>


<commit_before><commit_msg>:sparkles: Add the feature of fetch all completed tasks<commit_after><|endoftext|>


<commit_before><commit_msg>add deref trait to Time<commit_after><|endoftext|>


<commit_before><commit_msg>Initial 8 opcode support<commit_after><|endoftext|>


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

use log;
use rustc::hir::def_id::DefId;
use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
use rustc::hir::{self, Body, Pat, PatKind, Expr};
use rustc::middle::region::{RegionMaps, CodeExtent};
use rustc::ty::Ty;
use syntax::ast::NodeId;
use syntax::codemap::Span;
use std::rc::Rc;
use super::FnCtxt;
use util::nodemap::FxHashMap;

struct InteriorVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
    fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
    cache: FxHashMap<NodeId, Option<Span>>,

    // FIXME: Use an ordered hash map here
    types: Vec<Ty<'tcx>>,
    region_maps: Rc<RegionMaps>,
}

impl<'a, 'gcx, 'tcx> InteriorVisitor<'a, 'gcx, 'tcx> {
    fn record(&mut self, ty: Ty<'tcx>, scope: Option<CodeExtent>, expr: Option<&'tcx Expr>) {
        use syntax_pos::DUMMY_SP;

        let live_across_yield = scope.map(|s| {
            self.fcx.tcx.yield_in_extent(s, &mut self.cache).is_some()
        }).unwrap_or(true);

        if live_across_yield {
            let ty = self.fcx.resolve_type_vars_if_possible(&ty);

            if log_enabled!(log::LogLevel::Debug) {
                let span = scope.map(|s| s.span(&self.fcx.tcx.hir).unwrap_or(DUMMY_SP));
                debug!("type in expr = {:?}, scope = {:?}, type = {:?}, span = {:?}",
                       expr, scope, ty, span);
            }

            if !self.types.contains(&ty) {
                self.types.push(ty);
            }
        } else {
            debug!("no type in expr = {:?}, span = {:?}", expr, expr.map(|e| e.span));
        }
    }
}

pub fn resolve_interior<'a, 'gcx, 'tcx>(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
                                        def_id: DefId,
                                        body_id: hir::BodyId,
                                        witness: Ty<'tcx>) {
    let body = fcx.tcx.hir.body(body_id);
    let mut visitor = InteriorVisitor {
        fcx,
        types: Vec::new(),
        cache: FxHashMap(),
        region_maps: fcx.tcx.region_maps(def_id),
    };
    intravisit::walk_body(&mut visitor, body);

    let tuple = fcx.tcx.intern_tup(&visitor.types, false);

    debug!("Types in generator {:?}, span = {:?}", tuple, body.value.span);

    // Unify the tuple with the witness
    match fcx.at(&fcx.misc(body.value.span), fcx.param_env).eq(witness, tuple) {
        Ok(ok) => fcx.register_infer_ok_obligations(ok),
        _ => bug!(),
   }
}

impl<'a, 'gcx, 'tcx> Visitor<'tcx> for InteriorVisitor<'a, 'gcx, 'tcx> {
    fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
        NestedVisitorMap::None
    }

    fn visit_body(&mut self, _body: &'tcx Body) {
        // Closures inside are not considered part of the generator interior
    }

    fn visit_pat(&mut self, pat: &'tcx Pat) {
        if let PatKind::Binding(..) = pat.node {
            let scope = self.region_maps.var_scope(pat.id);
            let ty = self.fcx.tables.borrow().pat_ty(pat);
            self.record(ty, Some(scope), None);
        }

        intravisit::walk_pat(self, pat);
    }

    fn visit_expr(&mut self, expr: &'tcx Expr) {
        let scope = self.region_maps.temporary_scope(expr.id);
        let ty = self.fcx.tables.borrow().expr_ty_adjusted(expr);
        self.record(ty, scope, Some(expr));

        intravisit::walk_expr(self, expr);
    }
}
<commit_msg>Make gathering generator interior types O(n log n)<commit_after>// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use log;
use rustc::hir::def_id::DefId;
use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
use rustc::hir::{self, Body, Pat, PatKind, Expr};
use rustc::middle::region::{RegionMaps, CodeExtent};
use rustc::ty::Ty;
use syntax::ast::NodeId;
use syntax::codemap::Span;
use std::rc::Rc;
use super::FnCtxt;
use util::nodemap::FxHashMap;

struct InteriorVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
    fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
    cache: FxHashMap<NodeId, Option<Span>>,
    types: FxHashMap<Ty<'tcx>, usize>,
    region_maps: Rc<RegionMaps>,
}

impl<'a, 'gcx, 'tcx> InteriorVisitor<'a, 'gcx, 'tcx> {
    fn record(&mut self, ty: Ty<'tcx>, scope: Option<CodeExtent>, expr: Option<&'tcx Expr>) {
        use syntax_pos::DUMMY_SP;

        let live_across_yield = scope.map(|s| {
            self.fcx.tcx.yield_in_extent(s, &mut self.cache).is_some()
        }).unwrap_or(true);

        if live_across_yield {
            let ty = self.fcx.resolve_type_vars_if_possible(&ty);

            if log_enabled!(log::LogLevel::Debug) {
                let span = scope.map(|s| s.span(&self.fcx.tcx.hir).unwrap_or(DUMMY_SP));
                debug!("type in expr = {:?}, scope = {:?}, type = {:?}, span = {:?}",
                       expr, scope, ty, span);
            }

            // Map the type to the number of types added before it
            let entries = self.types.len();
            self.types.entry(&ty).or_insert(entries);
        } else {
            debug!("no type in expr = {:?}, span = {:?}", expr, expr.map(|e| e.span));
        }
    }
}

pub fn resolve_interior<'a, 'gcx, 'tcx>(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
                                        def_id: DefId,
                                        body_id: hir::BodyId,
                                        witness: Ty<'tcx>) {
    let body = fcx.tcx.hir.body(body_id);
    let mut visitor = InteriorVisitor {
        fcx,
        types: FxHashMap(),
        cache: FxHashMap(),
        region_maps: fcx.tcx.region_maps(def_id),
    };
    intravisit::walk_body(&mut visitor, body);

    let mut types: Vec<_> = visitor.types.drain().collect();

    // Sort types by insertion order
    types.sort_by_key(|t| t.1);

    // Extract type components
    let types: Vec<_> = types.into_iter().map(|t| t.0).collect();

    let tuple = fcx.tcx.intern_tup(&types, false);

    debug!("Types in generator {:?}, span = {:?}", tuple, body.value.span);

    // Unify the tuple with the witness
    match fcx.at(&fcx.misc(body.value.span), fcx.param_env).eq(witness, tuple) {
        Ok(ok) => fcx.register_infer_ok_obligations(ok),
        _ => bug!(),
   }
}

impl<'a, 'gcx, 'tcx> Visitor<'tcx> for InteriorVisitor<'a, 'gcx, 'tcx> {
    fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
        NestedVisitorMap::None
    }

    fn visit_body(&mut self, _body: &'tcx Body) {
        // Closures inside are not considered part of the generator interior
    }

    fn visit_pat(&mut self, pat: &'tcx Pat) {
        if let PatKind::Binding(..) = pat.node {
            let scope = self.region_maps.var_scope(pat.id);
            let ty = self.fcx.tables.borrow().pat_ty(pat);
            self.record(ty, Some(scope), None);
        }

        intravisit::walk_pat(self, pat);
    }

    fn visit_expr(&mut self, expr: &'tcx Expr) {
        let scope = self.region_maps.temporary_scope(expr.id);
        let ty = self.fcx.tables.borrow().expr_ty_adjusted(expr);
        self.record(ty, scope, Some(expr));

        intravisit::walk_expr(self, expr);
    }
}
<|endoftext|>


<commit_before><commit_msg>day 22 solved.<commit_after>use std::io::prelude::*;
use std::fs::File;
use std::path::Path;
use std::collections::HashMap;

const INFTY: i32 = 1 << 30;

#[derive(Clone, Hash, PartialEq, Eq)]
struct Wizard {
    hp  : i32,
    arm : i32,
    mana: i32
}

#[derive(Clone, Hash, PartialEq, Eq)]
struct Warrior {
    hp : i32,
    dmg: i32
}

#[derive(Clone, Hash, PartialEq, Eq)]
struct State {
    shield  : u8,
    poison  : u8,
    recharge: u8
}

impl Wizard {
    fn new(hp: i32, arm: i32, mana: i32) -> Wizard {
        Wizard {
            hp  : hp,
            arm : arm,
            mana: mana
        }
    }

    fn can_cast_spell(&self, st: State, name: &str, cost: i32) -> bool {
        self.mana >= cost
        && (name != "shld"  || st.shield   == 0)
        && (name != "psn"   || st.poison   == 0)
        && (name != "rchrg" || st.recharge == 0)
    }
}

impl Warrior {
    fn new(hp: i32, dmg: i32) -> Warrior {
        Warrior {
            hp : hp,
            dmg: dmg
        }
    }
}

impl State {
    fn new(shield: u8, poison: u8, recharge: u8) -> State {
        State {
            shield  : shield,
            poison  : poison,
            recharge: recharge
        }
    }
}

fn cripple(wiz: Wizard, turn: bool, hard: bool) -> (Wizard, bool) {
    if !hard || !turn {
        (wiz, false)
    } else {
        let next_hp = wiz.hp - 1;
        (Wizard::new(next_hp, wiz.arm, wiz.mana),
         next_hp <= 0)
    }
}

fn apply_effects(wiz: Wizard, war: Warrior, st: State) -> (Wizard, Warrior, State, bool) {
    let next_shield;
    let next_arm;
    if st.shield > 0 {
        next_arm = 7;
        next_shield = st.shield - 1;
    } else {
        next_arm = 0;
        next_shield = 0;
    }
    let next_poison;
    let next_war_hp;
    if st.poison > 0 {
        next_war_hp = war.hp - 3;
        next_poison = st.poison - 1;
    } else {
        next_war_hp = war.hp;
        next_poison = 0;
    }
    let next_recharge;
    let next_mana;
    if st.recharge > 0 {
        next_mana = wiz.mana + 101;
        next_recharge = st.recharge - 1;
    } else {
        next_mana = wiz.mana;
        next_recharge = 0;
    }
    (Wizard::new(wiz.hp, next_arm, next_mana),
     Warrior::new(next_war_hp, war.dmg),
     State::new(next_shield, next_poison, next_recharge),
     next_war_hp <= 0)
}

fn cast_spell(wiz: Wizard, war: Warrior, st: State, name: &str, cost: i32) -> (Wizard, Warrior, State, bool) {
    let next_mana = wiz.mana - cost;
    if name == "mssl" {
        let next_war_hp = war.hp - 4;
        (Wizard::new(wiz.hp, wiz.arm, next_mana),
         Warrior::new(next_war_hp, war.dmg),
         st,
         next_war_hp <= 0)
    } else if name == "drn" {
        let next_war_hp = war.hp - 2;
        let next_wiz_hp = wiz.hp + 2;
        (Wizard::new(next_wiz_hp, wiz.arm, next_mana),
         Warrior::new(next_war_hp, war.dmg),
         st,
         next_war_hp <= 0)
    } else if name == "shld" {
        (Wizard::new(wiz.hp, wiz.arm, next_mana),
         war,
         State::new(6, st.poison, st.recharge),
         false)
    } else if name == "psn" {
        (Wizard::new(wiz.hp, wiz.arm, next_mana),
         war,
         State::new(st.shield, 6, st.recharge),
         false)
    } else if name == "rchrg" {
        (Wizard::new(wiz.hp, wiz.arm, next_mana),
         war,
         State::new(st.shield, st.poison, 5),
         false)
    } else {
        panic!("Tried to cast a non-existent spell!");
    }
}

fn battle(wiz: Wizard, war: Warrior, st: State, wizard_turn: bool, hard: bool, mana_spent: i32, spells: Vec<(i32, &str)>, memo: &mut HashMap<(Wizard, Warrior, State, bool), i32>, ret: &mut i32) {
    if mana_spent >= *ret {
        return;
    }
    let key = (wiz.clone(), war.clone(), st.clone(), wizard_turn);
    if memo.contains_key(&key) && memo[&key] <= mana_spent {
        return;
    } else {
        memo.insert(key, mana_spent);
    }

    let (next_wiz, done) = cripple(wiz, wizard_turn, hard);
    if done {
        return;
    }
    else {
        let (next_wiz, next_war, next_st, done) = apply_effects(next_wiz, war, st);
        if done {
            *ret = mana_spent;
        } else if wizard_turn {
            for spell in spells.iter() {
                let (cost, name) = *spell;
                if mana_spent + cost >= *ret {
                    continue;
                }
                if next_wiz.can_cast_spell(next_st.clone(), name, cost) {
                    let (nexter_wiz, nexter_war, nexter_st, done) = cast_spell(next_wiz.clone(), next_war.clone(), next_st.clone(), name, cost);
                    if done {
                        *ret = mana_spent + cost;
                    } else {
                        battle(nexter_wiz,
                               nexter_war,
                               nexter_st,
                               false,
                               hard,
                               mana_spent + cost,
                               spells.clone(),
                               memo,
                               ret);
                    }
                }
            }
        } else {
            let dmg_done = if next_war.dmg > next_wiz.arm {
                next_war.dmg - next_wiz.arm
            } else {
                1
            };
            if next_wiz.hp <= dmg_done {
                return;
            } else {
                let next_wiz_hp = next_wiz.hp - dmg_done;
                battle(Wizard::new(next_wiz_hp, next_wiz.arm, next_wiz.mana),
                       next_war.clone(),
                       next_st,
                       true,
                       hard,
                       mana_spent,
                       spells,
                       memo,
                       ret);
            }
        }
    }
}

fn main() {
    let mut f = File::open(Path::new("/Users/PetarV/rust-proj/advent-of-rust/target/input.txt"))
    	.ok()
    	.expect("Failed to open the input file!");

	let mut input = String::new();
	f.read_to_string(&mut input)
		.ok()
		.expect("Failed to read from the input file!");

    let spells = vec![(53, "mssl"), (73, "drn"), (113, "shld"), (173, "psn"), (229, "rchrg")];

    let mut hp = 0;
    let mut dmg = 0;
    let mut ret = INFTY;

    for line in input.lines() {
        let parts: Vec<_> = line.split_whitespace().collect();
        if parts[0] == "Hit" {
            hp = parts[2].parse().ok().expect("Could not parse into an integer!");
        } else if parts[0] == "Damage:" {
            dmg = parts[1].parse().ok().expect("Could not parse into an integer!");
        }
    }

    let player = Wizard::new(50, 0, 500);
    let opponent = Warrior::new(hp, dmg);
    let state = State::new(0, 0, 0);
    let mut memo: HashMap<(Wizard, Warrior, State, bool), i32> = HashMap::new();

    battle(player.clone(), opponent.clone(), state.clone(), true, false, 0, spells.clone(), &mut memo, &mut ret);

    println!("The optimal amount of mana spent is {}.", ret);

    ret = INFTY;
    memo.clear();

    battle(player, opponent, state, true, true, 0, spells, &mut memo, &mut ret);

    println!("The optimal amount of mana spent on hard mode is {}.", ret);
}<|endoftext|>


<commit_before><commit_msg>Improve default values for tags<commit_after><|endoftext|>


<commit_before><commit_msg>Fix: Retry on interrupt in `utils::read_full`<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed bug where a quadtree could cause an object to collide with itself<commit_after><|endoftext|>


<commit_before><commit_msg>Translated a few entries of the parsing table<commit_after>use frontend::scanner::{scan_into_iterator, ScannerError, Token, TokenWithContext};
use std::iter::Peekable;
use vm::bytecode::Chunk;

enum CompilationError {
    ScannerError(ScannerError),
}

#[derive(PartialEq, PartialOrd)]
enum Precedence {
    None,
    Assignment,
    Or,
    And,
    Equality,
    Comparison,
    Term,
    Factor,
    Unary,
    Call,
    Primary,
}

enum RuleFunction {
    Grouping,
    Unary,
    Binary
}

struct Rule {
    precedence: Precedence,
    prefix: Option<RuleFunction>,
    infix: Option<RuleFunction>,
}

struct Parser<'a, I>
where
    I: Iterator<Item = Result<TokenWithContext, ScannerError>>,
{
    chunk: &'a mut Chunk,
    tokens: Peekable<I>,
    errors: Vec<CompilationError>,
}

impl<'a, I> Parser<'a, I>
where
    I: Iterator<Item = Result<TokenWithContext, ScannerError>>,
{
    fn new(chunk: &'a mut Chunk, tokens: I) -> Parser<I> {
        Parser {
            chunk: chunk,
            tokens: tokens.peekable(),
            errors: vec![],
        }
    }

    fn peek(&mut self) -> Option<&TokenWithContext> {
        match self.tokens.peek() {
            None => None,
            Some(Ok(t)) => Some(t),
            Some(Err(e)) => panic!("This should have been skipped while advancing"),
        }
    }

    fn advance(&mut self) -> Option<TokenWithContext> {
        loop {
            match self.tokens.next() {
                None => return None,
                Some(Ok(t)) => return Some(t),
                Some(Err(e)) => self.errors.push(CompilationError::ScannerError(e)),
            }
        }
    }

    fn find_rule(&mut self) -> Rule {
        match self.peek() {
            Some(t) => match t.token {
                Token::LeftParen => Rule {
                    precedence: Precedence::Call,
                    prefix: Some(RuleFunction::Grouping),
                    infix: None,
                },
                Token::LeftParen => Rule {
                    precedence: Precedence::None,
                    prefix: None,
                    infix: None,
                },
                Token::LeftBrace => Rule {
                    precedence: Precedence::None,
                    prefix: Some(RuleFunction::Grouping),
                    infix: None,
                },
                Token::RightBrace => Rule {
                    precedence: Precedence::None,
                    prefix: None,
                    infix: None,
                },
                Token::Comma => Rule {
                    precedence: Precedence::None,
                    prefix: None,
                    infix: None,
                },
                Token::Dot => Rule {
                    precedence: Precedence::Call,
                    prefix: None,
                    infix: None,
                },
                Token::Minus => Rule {
                    precedence: Precedence::Call,
                    prefix: Some(RuleFunction::Unary),
                    infix: Some(RuleFunction::Binary),
                },
                _ => unimplemented!(),
                /*
  { NULL,     binary,  PREC_TERM },       // TOKEN_PLUS
  { NULL,     NULL,    PREC_NONE },       // TOKEN_SEMICOLON
  { NULL,     binary,  PREC_FACTOR },     // TOKEN_SLASH
  { NULL,     binary,  PREC_FACTOR },     // TOKEN_STAR
  { NULL,     NULL,    PREC_NONE },       // TOKEN_BANG
  { NULL,     NULL,    PREC_EQUALITY },   // TOKEN_BANG_EQUAL
  { NULL,     NULL,    PREC_NONE },       // TOKEN_EQUAL
  { NULL,     NULL,    PREC_EQUALITY },   // TOKEN_EQUAL_EQUAL
  { NULL,     NULL,    PREC_COMPARISON }, // TOKEN_GREATER
  { NULL,     NULL,    PREC_COMPARISON }, // TOKEN_GREATER_EQUAL
  { NULL,     NULL,    PREC_COMPARISON }, // TOKEN_LESS
  { NULL,     NULL,    PREC_COMPARISON }, // TOKEN_LESS_EQUAL
  { NULL,     NULL,    PREC_NONE },       // TOKEN_IDENTIFIER
  { NULL,     NULL,    PREC_NONE },       // TOKEN_STRING
  { number,   NULL,    PREC_NONE },       // TOKEN_NUMBER
  { NULL,     NULL,    PREC_AND },        // TOKEN_AND
  { NULL,     NULL,    PREC_NONE },       // TOKEN_CLASS
  { NULL,     NULL,    PREC_NONE },       // TOKEN_ELSE
  { NULL,     NULL,    PREC_NONE },       // TOKEN_FALSE
  { NULL,     NULL,    PREC_NONE },       // TOKEN_FUN
  { NULL,     NULL,    PREC_NONE },       // TOKEN_FOR
  { NULL,     NULL,    PREC_NONE },       // TOKEN_IF
  { NULL,     NULL,    PREC_NONE },       // TOKEN_NIL
  { NULL,     NULL,    PREC_OR },         // TOKEN_OR
  { NULL,     NULL,    PREC_NONE },       // TOKEN_PRINT
  { NULL,     NULL,    PREC_NONE },       // TOKEN_RETURN
  { NULL,     NULL,    PREC_NONE },       // TOKEN_SUPER
  { NULL,     NULL,    PREC_NONE },       // TOKEN_THIS
  { NULL,     NULL,    PREC_NONE },       // TOKEN_TRUE
  { NULL,     NULL,    PREC_NONE },       // TOKEN_VAR
  { NULL,     NULL,    PREC_NONE },       // TOKEN_WHILE
  { NULL,     NULL,    PREC_NONE },       // TOKEN_ERROR
  { NULL,     NULL,    PREC_NONE },       // TOKEN_EOF
*/
            },
            None => unimplemented!(),
        }
    }

    fn dispatch(&mut self, rule_function: RuleFunction) -> Result<(), ()> {
      match rule_function{
        RuleFunction::Grouping => self.grouping(),
        RuleFunction::Unary => self.unary(),
        RuleFunction::Binary => self.binary(),
      }
    }

    fn parse_precedence(&mut self, precedence: Precedence) -> Result<(), ()> {
        let prefix_rule = self.find_rule();
        match prefix_rule.prefix {
            None => return Err(()), // TODO: make it meaningful. Was: error("Expect expression.");
            Some(prefix_function) => {
                try!{self.dispatch(prefix_function)}
            }
        };
        loop {
            let infix_rule = self.find_rule();
            if precedence <= infix_rule.precedence {
                match infix_rule.infix {
                    None => return Err(()), // TODO: make it meaningful. Was: error("Expect expression.");
                    Some(prefix_function) => {
                        try!{self.dispatch(prefix_function)}
                    }
                }
            } else {
                return Ok(());
            }
        }
    }

    fn expression(&mut self) -> Result<(), ()> {
        self.parse_precedence(Precedence::Assignment)
    }

    fn grouping(&mut self) -> Result<(), ()> {
      unimplemented!()
    }

    fn unary(&mut self) -> Result<(), ()> {
      unimplemented!()
    }

    fn binary(&mut self) -> Result<(), ()> {
      unimplemented!()
    }
}

pub fn compile(text: &str) -> Chunk {
    let mut chunk = Chunk::new();
    let tokens = scan_into_iterator(text);
    {
        let mut parser = Parser::new(&mut chunk, tokens);
        parser.expression();
    }
    chunk
}
<|endoftext|>


<commit_before><commit_msg>Add tests for m.room.create.<commit_after><|endoftext|>


<commit_before><commit_msg>Simplified parsing<commit_after><|endoftext|>


<commit_before><commit_msg>Add example for evaluating string frequency and using children iterator<commit_after>extern crate radix_trie;

use radix_trie::{Trie, TrieCommon};

fn main() {
    let example = "bananaphone".to_string();
    // Our frequency trie will store various strings with the frequency that they are used
    let mut trie: Trie<String, u32> = Trie::new();
    let v: Vec<char> = example.chars().collect();

    // We want the frequencies of all strings from 1 to 3 characters long
    for window_length in 1..4 {
        for a in v.windows(window_length) {
            // Create a new String to hold our key
            let mut s = String::new();
            // Append all chars in a to the String
            s.extend(a);
            // If the value at s exists, add 1. Otherwise, assign 1 as the key's value.
            trie.map_with_default(s, |v| { *v += 1; }, 1);
        }
    }

    // Iterate through all the values in the trie and print them with their frequencies.
    // Iterates and prints in lexicographic order.
    println!("All trie nodes");
    for (k, v) in trie.iter() {
        println!("{}: {}", k, v);
    }

    println!("All children of 'a'");
    for n in trie.subtrie(&"a".to_string()).unwrap().children() {
        println!("{}: {}", n.key().unwrap(), n.value().unwrap());
    }
}
<|endoftext|>


<commit_before>#![feature(custom_attribute)]
#![allow(dead_code, unused_attributes)]

#[derive(Debug, PartialEq)]
enum Unit { Unit(()) } // Force non-C-enum representation.

#[miri_run]
fn return_unit() -> Unit {
    Unit::Unit(())
}

#[derive(Debug, PartialEq)]
enum MyBool { False(()), True(()) } // Force non-C-enum representation.

#[miri_run]
fn return_true() -> MyBool {
    MyBool::True(())
}

#[miri_run]
fn return_false() -> MyBool {
    MyBool::False(())
}

#[miri_run]
fn return_none() -> Option<i64> {
    None
}

#[miri_run]
fn return_some() -> Option<i64> {
    Some(42)
}

#[miri_run]
fn match_opt_none() -> i8 {
    let x = None;
    match x {
        Some(data) => data,
        None => 42,
    }
}

#[miri_run]
fn match_opt_some() -> i8 {
    let x = Some(13);
    match x {
        Some(data) => data,
        None => 20,
    }
}

#[miri_run]
fn two_nones() -> (Option<i16>, Option<i16>) {
    (None, None)
}

#[miri_run]
fn main() {
    assert_eq!(two_nones(), (None, None));
    assert_eq!(match_opt_some(), 13);
    assert_eq!(match_opt_none(), 42);
    assert_eq!(return_some(), Some(42));
    assert_eq!(return_none(), None);
    assert_eq!(return_false(), MyBool::False(()));
    assert_eq!(return_true(), MyBool::True(()));
    assert_eq!(return_unit(), Unit::Unit(()));
}
<commit_msg>Disable a test that breaks on 32-bit.<commit_after>#![feature(custom_attribute)]
#![allow(dead_code, unused_attributes)]

#[derive(Debug, PartialEq)]
enum Unit { Unit(()) } // Force non-C-enum representation.

#[miri_run]
fn return_unit() -> Unit {
    Unit::Unit(())
}

#[derive(Debug, PartialEq)]
enum MyBool { False(()), True(()) } // Force non-C-enum representation.

#[miri_run]
fn return_true() -> MyBool {
    MyBool::True(())
}

#[miri_run]
fn return_false() -> MyBool {
    MyBool::False(())
}

#[miri_run]
fn return_none() -> Option<i64> {
    None
}

#[miri_run]
fn return_some() -> Option<i64> {
    Some(42)
}

#[miri_run]
fn match_opt_none() -> i8 {
    let x = None;
    match x {
        Some(data) => data,
        None => 42,
    }
}

#[miri_run]
fn match_opt_some() -> i8 {
    let x = Some(13);
    match x {
        Some(data) => data,
        None => 20,
    }
}

#[miri_run]
fn two_nones() -> (Option<i16>, Option<i16>) {
    (None, None)
}

// FIXME(solson): Casts inside PartialEq fails on 32-bit.
#[cfg_attr(target_pointer_width = "64", miri_run)]
fn main() {
    assert_eq!(two_nones(), (None, None));
    assert_eq!(match_opt_some(), 13);
    assert_eq!(match_opt_none(), 42);
    assert_eq!(return_some(), Some(42));
    assert_eq!(return_none(), None);
    assert_eq!(return_false(), MyBool::False(()));
    assert_eq!(return_true(), MyBool::True(()));
    assert_eq!(return_unit(), Unit::Unit(()));
}
<|endoftext|>


<commit_before><commit_msg>Refactor `print_count()` to accept padding as `Counter`<commit_after><|endoftext|>


<commit_before><commit_msg>Fix for merging emerald-rs/master<commit_after><|endoftext|>


<commit_before><commit_msg>Initial commit of plugin systme<commit_after>use std::os;
use std::str;
use std::collections::TreeMap;
use std::dynamic_lib::DynamicLibrary;

pub struct PluginLoader {
    plugins: TreeMap<String, Box<DynamicLibrary>>
}

impl PluginLoader {
    pub fn new() -> PluginLoader {
        PluginLoader { plugins: TreeMap::new() }
    }

    pub fn load(mut self, path: String) {
        let path = Path::new(path);
        let path = os::make_absolute(&path);
        let filename: String = path.filestem_str().expect("Couldn't get filename").to_string();

        match DynamicLibrary::open(Some(&path)) {
            Ok(lib) => self.plugins.insert(filename, box lib),
            Err(error) => panic!("Couldnt load library: {}", error)
        };
    }
}
<|endoftext|>


<commit_before><commit_msg>Fix tests for config load_config<commit_after><|endoftext|>


<commit_before><commit_msg>tests are good, mkay<commit_after>extern crate test;
extern crate uuid;
extern crate entity_system;

use std::default::Default;
use uuid::Uuid;

#[deriving(Default,Clone)]
struct TestComponent {
    id: Uuid,
    pub name: &'static str,
}

impl TestComponent {
    pub fn new() -> TestComponent {
        TestComponent {
            id: Uuid::new_v4(),
            ..Default::default()
        }
    }
}

impl entity_system::Component for TestComponent {
    fn get_id(&self) -> Uuid {
        self.id
    }
}

#[deriving(Default,Clone)]
struct OtherComponent {
    id: Uuid,
    pub name: &'static str,
}

impl OtherComponent {
    pub fn new() -> OtherComponent {
        OtherComponent {
            id: Uuid::new_v4(),
            ..Default::default()
        }
    }
}

impl entity_system::Component for OtherComponent {
    fn get_id(&self) -> Uuid {
        self.id
    }
}

mod entity_manager {
    extern crate entity_system;
    use entity_system::{Component};

    #[test]
    fn new_entities_are_unique() {
        let em = entity_system::EntityManager::new();
        let entity = em.create_entity();
        let entity2 = em.create_entity();

        assert!(entity != entity2);
    }

    #[test]
    fn named_entities() {
        let mut em = entity_system::EntityManager::new();
        let entity = em.create_named_entity("One");
        let entity2 = em.create_named_entity("Two");

        let result = em.get_named_entity("One").unwrap();
        let result2 = em.get_named_entity("Two").unwrap();

        assert!(result != result2);
        assert_eq!(entity, result);
        assert_eq!(entity2, result2)
    }

    #[test]
    fn finds_components_for_entity() {
        let mut em = entity_system::EntityManager::new();
        let entity = em.create_entity();
        let entity_other = em.create_entity();
        let component = super::TestComponent::new();
        let component2 = super::OtherComponent::new();
        let component_other = super::TestComponent::new();

        em.insert(entity, component);
        em.insert(entity, component);
        em.insert(entity, component2);
        em.insert(entity_other, component_other);

        {
            let result = em.find_for::<super::TestComponent>(entity);
            assert_eq!(result.len(), 2);
            assert_eq!(component.get_id(), result[0].get_id());
            assert_eq!(component.get_id(), result[1].get_id());
        }
        {
            let result = em.find_for_mut::<super::TestComponent>(entity);
            assert_eq!(result.len(), 2);
            assert_eq!(component.get_id(), result[0].get_id());
            assert_eq!(component.get_id(), result[1].get_id());
        }
    }

    #[test]
    fn finds_components_for_type() {
        let mut em = entity_system::EntityManager::new();
        let entity = em.create_entity();
        let entity2 = em.create_entity();
        let component = super::TestComponent::new();
        let component_other = super::OtherComponent::new();

        em.insert(entity, component);
        em.insert(entity, component_other);
        em.insert(entity2, component);

        {
            let result = em.find::<super::TestComponent>();
            assert_eq!(result.len(), 2);
            assert_eq!(component.get_id(), result[0].get_id());
            assert_eq!(component.get_id(), result[1].get_id());
        }
        {
            let result = em.find_mut::<super::TestComponent>();
            assert_eq!(result.len(), 2);
            assert_eq!(component.get_id(), result[0].get_id());
            assert_eq!(component.get_id(), result[1].get_id());
        }
    }

    #[test]
    fn find_immutable_before_find_mut() {
        let mut em = entity_system::EntityManager::new();
        let entity = em.create_entity();
        let component = super::TestComponent::new();
        em.insert(entity, component);
        {
            let immutable = em.find_for::<super::TestComponent>(entity);
            assert_eq!(immutable[0].get_id(), component.get_id());

            let mutable = em.find_for_mut::<super::TestComponent>(entity);
            assert_eq!(mutable[0].get_id(), component.get_id())
        }
        {
            let immutable = em.find::<super::TestComponent>();
            assert_eq!(immutable[0].get_id(), component.get_id());

            let mutable = em.find_mut::<super::TestComponent>();
            assert_eq!(mutable[0].get_id(), component.get_id())
        }
    }

    #[test]
    fn find_entities_for_type() {
        let mut em = entity_system::EntityManager::new();
        let entity = em.create_entity();
        let entity2 = em.create_entity();

        em.insert(entity, super::TestComponent::new());
        em.insert(entity, super::TestComponent::new());
        em.insert(entity2, super::TestComponent::new());
        em.insert(entity2, super::OtherComponent::new());

        let result = em.find_entities::<super::TestComponent>();
        assert_eq!(result.len(), 2);
        assert!(result[0] != result[1]);
        for result_entity in result.iter() {
            assert!(result_entity == &entity || result_entity == &entity2);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>brb trying to satisfy the borrow checker<commit_after><|endoftext|>


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

//! macros for use across the coreos-metadata project

#[macro_export]
macro_rules! log_and_die {
    () => {
        |err| {
            error!("error"; "error" => err);
            panic!()
        }
    };
    ($fmt:expr) => {
        |err| {
            error!($fmt; "error" => err);
            panic!()
        }
    };
    ($fmt:expr, $($arg:tt)*) => {
        |err| {
            error!($fmt, $($arg)*; "error" => err);
            panic!()
        }
    };
}

#[macro_export]
macro_rules! wrap_error {
    () => {
        |err| {
            format!("error: {}", err)
        }
    };
    ($fmt:expr) => {
        |err| {
            format!(concat!($fmt, ": {}"), err)
        }
    };
    ($fmt:expr, $($arg:tt)*) => {
        |err| {
            format!(concat!($fmt, ": {}"), $($arg)*, err)
        }
    };
}
<|endoftext|>


<commit_before><commit_msg>initial implementation of the memory data structure<commit_after>extern crate byteorder;
use std::io::Cursor;
use std::io::Write;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};

#[derive(Debug)]
pub enum MemoryError {
  PPUAccessViolation(String),
  APUAccessViolation(String),
}

pub struct Memory {
    mem: Vec<u8>,
}

impl Memory {
    fn read8(self:&Memory,addr: u16) -> Result<u8,MemoryError> {
        match self.resolve_address(addr) {
            Ok(raddr) => Ok(self.mem[raddr]),
            Err(err) => Err(err)
        }
    }
    fn read16(self:&Memory,addr: u16)  -> Result<u16,MemoryError> {
        match self.resolve_address(addr) {
            Ok(raddr) =>{
                let mut rdr = Cursor::new(&self.mem[raddr..raddr+1]);
                Ok(rdr.read_u16::<LittleEndian>().unwrap())
            },
            Err(err) => Err(err)
        }
    }
    fn write8(self:&mut Memory,addr: u16, val:u8) -> Option<MemoryError> {
        match self.resolve_address(addr) {
            Ok(raddr) => {
                self.mem[raddr] = val;
                Option::None
            },
            Err(err) => Option::Some(err)
        }
    }
    fn write16(self:&mut Memory,addr: u16, val:u16) -> Option<MemoryError> {
        match self.resolve_address(addr) {
            Ok(raddr) => {
                (&mut self.mem[raddr..(raddr+1)]).write_u16::<LittleEndian>(val).unwrap();
                Option::None
            },
            Err(err) => Option::Some(err)
        }
    }

    // https://en.wikibooks.org/wiki/NES_Programming/Memory_Map
    //
    fn resolve_address(self:&Memory,addr: u16) -> Result<usize,MemoryError> {
        if addr <= 0x1FFF { return Ok( (addr & 0x7FF) as usize); }
        if addr <= 0x2007 { return Err(MemoryError::PPUAccessViolation("PPU Memory access is currently not implemented".to_string())); }
        if addr <= 0x3FFF { return Ok( (addr & 0x7FF & 0x08) as usize); }
        if addr <= 0x401F { return Err(MemoryError::APUAccessViolation("Memory access is currently not implemented".to_string())); }
        Ok(addr as usize)
    }
}
<|endoftext|>


<commit_before><commit_msg>Add missing Datapoint fields<commit_after><|endoftext|>