<commit_before><commit_msg>Add ZDT1 example from evo-rs<commit_after>/// Optimizes the zdt1 function using NSGA-II

extern crate rand;
extern crate nsga2;

use rand::{Rng, Closed01};
use nsga2::{Driver, DriverConfig};
use nsga2::mo::MultiObjective2;

/// optimal pareto front (f_1, 1 - sqrt(f_1))
/// 0 <= x[i] <= 1.0
fn zdt1(x: &[f32]) -> (f32, f32) {
    let n = x.len();
    assert!(n >= 2);

    let f1 = x[0];
    let g = 1.0 + (9.0 / (n - 1) as f32) * x[1..].iter().fold(0.0, |b, &i| b + i);
    let f2 = g * (1.0 - (f1 / g).sqrt());

    (f1, f2)
}

#[inline]
fn sbx_beta(u: f32, eta: f32) -> f32 {
    assert!(u >= 0.0 && u < 1.0);

    if u <= 0.5 {
        2.0 * u
    } else {
        1.0 / (2.0 * (1.0 - u))
    }
    .powf(1.0 / (eta + 1.0))
}

#[inline]
fn sbx_beta_bounded(u: f32, eta: f32, gamma: f32) -> f32 {
    assert!(u >= 0.0 && u < 1.0);

    let g = 1.0 - gamma;
    let ug = u * g;

    if u <= 0.5 / g {
        2.0 * ug
    } else {
        1.0 / (2.0 * (1.0 - ug))
    }
    .powf(1.0 / (eta + 1.0))
}

#[inline]
pub fn sbx_single_var<R: Rng>(rng: &mut R, p: (f32, f32), eta: f32) -> (f32, f32) {
    let u = rng.gen::<f32>();
    let beta = sbx_beta(u, eta);

    (0.5 * (((1.0 + beta) * p.0) + ((1.0 - beta) * p.1)),
     0.5 * (((1.0 - beta) * p.0) + ((1.0 + beta) * p.1)))
}

#[inline]
fn _sbx_single_var_bounded<R: Rng>(rng: &mut R,
                                   p: (f32, f32),
                                   bounds: (f32, f32),
                                   eta: f32)
                                   -> (f32, f32) {
    let (a, b) = bounds;
    let p_diff = p.1 - p.0;

    assert!(a <= b);
    assert!(p_diff > 0.0);
    assert!(p.0 >= a && p.0 <= b);
    assert!(p.1 >= a && p.1 <= b);

    let beta_a = 1.0 + (p.0 - a) / p_diff;
    let beta_b = 1.0 + (b - p.1) / p_diff;

    fn gamma(beta: f32, eta: f32) -> f32 {
        1.0 / (2.0 * beta.powf(eta + 1.0))
    }

    let gamma_a = gamma(beta_a, eta);
    let gamma_b = gamma(beta_b, eta);

    let u = rng.gen::<f32>();
    let beta_ua = sbx_beta_bounded(u, eta, gamma_a);
    let beta_ub = sbx_beta_bounded(u, eta, gamma_b);

    let c = (0.5 * (((1.0 + beta_ua) * p.0) + ((1.0 - beta_ua) * p.1)),
             0.5 * (((1.0 - beta_ub) * p.0) + ((1.0 + beta_ub) * p.1)));

    assert!(c.0 >= a && c.0 <= b);
    assert!(c.1 >= a && c.1 <= b);

    return c;
}

#[inline]
pub fn sbx_single_var_bounded<R: Rng>(rng: &mut R,
                                      p: (f32, f32),
                                      bounds: (f32, f32),
                                      eta: f32)
                                      -> (f32, f32) {
    if p.0 < p.1 {
        _sbx_single_var_bounded(rng, (p.0, p.1), bounds, eta)
    } else if p.0 > p.1 {
        let r = _sbx_single_var_bounded(rng, (p.1, p.0), bounds, eta);
        (r.1, r.0)
    } else {
        debug_assert!(p.0 == p.1);
        (p.0, p.1)
    }
}

#[derive(Clone, Debug)]
struct ZdtGenome {
    xs: Vec<f32>,
}

impl ZdtGenome {
    fn new(xs: Vec<f32>) -> Self {
        assert!(xs.len() >= 2);
        for &x in xs.iter() {
            assert!(x >= 0.0 && x <= 1.0);
        }
        ZdtGenome { xs: xs }
    }

    fn random<R: Rng>(rng: &mut R, n: usize) -> Self {
        ZdtGenome::new((0..n).map(|_| rng.gen::<Closed01<f32>>().0).collect())
    }

    fn fitness(&self) -> MultiObjective2<f32> {
        MultiObjective2::from(zdt1(&self.xs[..]))
    }

    fn len(&self) -> usize {
        self.xs.len()
    }

    fn crossover1<R: Rng>(rng: &mut R, parents: (&Self, &Self), eta: f32) -> Self {
        assert!(parents.0.len() == parents.1.len());
        let xs: Vec<_> = parents.0
                          .xs
                          .iter()
                          .zip(parents.1.xs.iter())
                          .map(|(&x1, &x2)| {
                              let (c1, _c2) = sbx_single_var_bounded(rng,
                                                                     (x1, x2),
                                                                     (0.0, 1.0),
                                                                     eta);
                              c1
                          })
                          .collect();
        ZdtGenome::new(xs)
    }
}

struct ZdtDriver {
    zdt_order: usize,
    mating_eta: f32,
}

impl Driver<ZdtGenome, MultiObjective2<f32>> for ZdtDriver {

    fn random_individual<R: Rng>(&self, rng: &mut R) -> ZdtGenome {
        ZdtGenome::random(rng, self.zdt_order)
    }

    fn fitness(&self, ind: &ZdtGenome) -> MultiObjective2<f32> {
        ind.fitness()
    }

    fn mate<R: Rng>(&self, rng: &mut R, parent1: &ZdtGenome, parent2: &ZdtGenome) -> ZdtGenome {
        ZdtGenome::crossover1(rng, (parent1, parent2), self.mating_eta)
    }
}

fn main() {
    let mut rng = rand::thread_rng();

    let driver = ZdtDriver {
        zdt_order: 2, // ZDT1 order
        mating_eta: 2.0,  // cross-over variance
    };

    let driver_config = DriverConfig {
        mu: 600, // size of population
        lambda: 300, // size of offspring population
        k: 2, // tournament
        ngen: 100, // max number of generations
        num_objectives: 2, // number of objectives
    };

    let final_population = driver.run(&mut rng, &driver_config, 1.0, &|_, _, _, _| {});

    final_population.all(&mut|ind, fitness| {
        println!("{:?}", ind);
        println!("{:?}", fitness);
    });
}
<|endoftext|>


<commit_before><commit_msg>Added new canvas example to investigate issue #304<commit_after>//! An example of how to use a `SpriteBatch`.
//!
//! You really want to run this one in release mode.

extern crate ggez;
extern crate rand;

use ggez::conf;
use ggez::event;
use ggez::{Context, GameResult};
use ggez::graphics;
use ggez::timer;
use ggez::nalgebra as na;
use std::env;
use std::path;

struct MainState {
    spritebatch: graphics::spritebatch::SpriteBatch,
    canvas: graphics::Canvas,
    draw_pt: graphics::Point2,
    draw_vec: na::Vector2<f32>,
}

impl MainState {
    fn new(ctx: &mut Context) -> GameResult<MainState> {
        let image = graphics::Image::new(ctx, "/tile.png").unwrap();
        let spritebatch = graphics::spritebatch::SpriteBatch::new(image);
        let canvas = graphics::Canvas::with_window_size(ctx)?;
        let draw_pt = na::origin();
        let draw_vec = na::Vector2::new(1.0, 1.0);
        let s = MainState {
            spritebatch,
            canvas ,
            draw_pt,
            draw_vec,
        };
        Ok(s)
    }
}

impl MainState {
    fn draw_spritebatch(&mut self, ctx: &mut Context) -> GameResult<()> {
        graphics::set_canvas(ctx, Some(&self.canvas));
        graphics::set_background_color(ctx, graphics::WHITE);
        graphics::clear(ctx);

        // Freeze the animation so things are easier to see.
        // let time = (timer::duration_to_f64(timer::get_time_since_start(ctx)) * 1000.0) as u32;
        let time = 2000;
        let cycle = 10_000;
        for x in 0..150 {
            for y in 0..150 {
                let x = x as f32;
                let y = y as f32;
                let p = graphics::DrawParam {
                    dest: graphics::Point2::new(x * 10.0, y * 10.0),
                    // scale: graphics::Point::new(0.0625, 0.0625),
                    scale: graphics::Point2::new(
                        ((time % cycle * 2) as f32 / cycle as f32 * 6.28)
                            .cos()
                            .abs() * 0.0625,
                        ((time % cycle * 2) as f32 / cycle as f32 * 6.28)
                            .cos()
                            .abs() * 0.0625,
                    ),
                    rotation: -2.0 * ((time % cycle) as f32 / cycle as f32 * 6.28),
                    ..Default::default()
                };
                self.spritebatch.add(p);
            }
        }
        let param = graphics::DrawParam {
            dest: graphics::Point2::new(
                ((time % cycle) as f32 / cycle as f32 * 6.28).cos() * 50.0 - 350.0,
                ((time % cycle) as f32 / cycle as f32 * 6.28).sin() * 50.0 - 450.0,
            ),
            scale: graphics::Point2::new(
                ((time % cycle) as f32 / cycle as f32 * 6.28).sin().abs() * 2.0 + 1.0,
                ((time % cycle) as f32 / cycle as f32 * 6.28).sin().abs() * 2.0 + 1.0,
            ),
            rotation: ((time % cycle) as f32 / cycle as f32 * 6.28),
            offset: graphics::Point2::new(750.0, 750.0),
            ..Default::default()
        };
        graphics::draw_ex(ctx, &self.spritebatch, param)?;
        self.spritebatch.clear();
        graphics::set_canvas(ctx, None);
        Ok(())
    }

}

impl event::EventHandler for MainState {
    fn update(&mut self, ctx: &mut Context) -> GameResult<()> {
        if timer::get_ticks(ctx) % 100 == 0 {
            println!("Delta frame time: {:?} ", timer::get_delta(ctx));
            println!("Average FPS: {}", timer::get_fps(ctx));
        }

        // Bounce the rect if necessary
        let (w, h) = graphics::get_size(ctx);
        if self.draw_pt.x + (w as f32 / 2.0) > (w as f32) || self.draw_pt.x < 0.0 {
            self.draw_vec.x *= -1.0;
        }
        // println!("{:?}", self.draw_pt);
        // BUGGO: The height bounds are hella wrong!
        if self.draw_pt.y + (h as f32 / 2.0) > (h as f32 / 2.0) || self.draw_pt.y < -(h as f32 / 2.0) {
            self.draw_vec.y *= -1.0;
        }
        self.draw_pt += self.draw_vec;
        Ok(())
    }

    fn draw(&mut self, ctx: &mut Context) -> GameResult<()> {
        graphics::set_background_color(ctx, [0.1, 0.2, 0.3, 1.0].into());
        graphics::clear(ctx);
        self.draw_spritebatch(ctx)?;
        let dims = self.canvas.get_image().get_dimensions();
        let src_x = self.draw_pt.x / dims.w;
        let src_y = self.draw_pt.y / dims.h;
        graphics::draw_ex(ctx, &self.canvas,
            graphics::DrawParam {
                dest: self.draw_pt,
                src: graphics::Rect::new(src_x, -src_y, 0.5, 0.5),
                .. Default::default()
                })?;
        graphics::present(ctx);
        Ok(())
    }
}

// Creating a gamestate depends on having an SDL context to load resources.
// Creating a context depends on loading a config file.
// Loading a config file depends on having FS (or we can just fake our way around it
// by creating an FS and then throwing it away; the costs are not huge.)
pub fn main() {
    let c = conf::Conf::new();
    println!("Starting with default config: {:#?}", c);
    let ctx = &mut Context::load_from_conf("spritebatch", "ggez", c).unwrap();

    // We add the CARGO_MANIFEST_DIR/resources do the filesystems paths so
    // we we look in the cargo project for files.
    if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
        let mut path = path::PathBuf::from(manifest_dir);
        path.push("resources");
        ctx.filesystem.mount(&path, true);
    }

    let state = &mut MainState::new(ctx).unwrap();
    if let Err(e) = event::run(ctx, state) {
        println!("Error encountered: {}", e);
    } else {
        println!("Game exited cleanly.");
    }
}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #9889 - ehuss:macos-strip, r=alexcrichton<commit_after><|endoftext|>


<commit_before>use redox::*;

use super::Mode;
use super::Mode::*;
use super::Editor;

pub fn exec(editor: &mut Editor, mode: &mut Mode, multiplier: &mut Option<u32>, last_change: &mut String, key_event: KeyEvent, window: &mut Window, swap: &mut usize, period: &mut String, is_recording: &mut bool) {
    match (*mode, key_event.scancode) {
        (Insert, K_ESC) => {
            *mode = Normal;
        },
        (Insert, K_BKSP) => editor.backspace(window),
        (Insert, K_DEL) => editor.delete(window),
        (_, K_F5) => editor.reload(window),
        (_, K_F6) => editor.save(window),
        (_, K_HOME) => editor.offset = 0,
        (_, K_UP) => editor.up(),
        (_, K_LEFT) => editor.left(),
        (_, K_RIGHT) => editor.right(),
        (_, K_END) => editor.offset = editor.string.len(),
        (_, K_DOWN) => editor.down(),
        (m, _) => {
            let (no_mult, mut times) = match *multiplier {
                Some(n) => (false, n),
                None => (true, 1),
            };
            let mut is_none = false;

            match (*mode, key_event.character) {
                (Normal, '0') if !no_mult => times *= 10,

                (Normal, '1') if no_mult => times = 1,
                (Normal, '1') => times = times * 10 + 1,

                (Normal, '2') if no_mult => times = 2,
                (Normal, '2') => times = times * 10 + 2,

                (Normal, '3') if no_mult => times = 3,
                (Normal, '3') => times = times * 10 + 3,

                (Normal, '4') if no_mult => times = 4,
                (Normal, '4') => times = times * 10 + 4,

                (Normal, '5') if no_mult => times = 5,
                (Normal, '5') => times = times * 10 + 5,

                (Normal, '6') if no_mult => times = 6,
                (Normal, '6') => times = times * 10 + 6,

                (Normal, '7') if no_mult => times = 7,
                (Normal, '7') => times = times * 10 + 7,

                (Normal, '8') if no_mult => times = 8,
                (Normal, '8') => times = times * 10 + 8,

                (Normal, '9') if no_mult => times = 9,
                (Normal, '9') => times = times * 10 + 9,
                (_, _) => {
                    if *is_recording {
                        if key_event.character == ',' {
                            *is_recording = false;
                        } else {
                            period.push(key_event.character);
                        }
                    } else {
                        for _ in 0 .. times {
                            match (m, key_event.character) {
                                (Normal, 'i') => {
                                    *mode = Insert;
                                    *last_change = editor.string.clone();
                                },
                                (Normal, 'h') => editor.left(),
                                (Normal, 'l') => editor.right(),
                                (Normal, 'k') => editor.up(),
                                (Normal, 'j') => editor.down(),
                                (Normal, 'g') => editor.offset = 0,
                                (Normal, 'G') => editor.offset = editor.string.len(),
                                (Normal, 'a') => {
                                    editor.right();
                                    *mode = Insert;
                                    *last_change = editor.string.clone();
                                },
                                (Normal, 'x') => editor.delete(window),
                                (Normal, 'X') => editor.backspace(window),
                                (Normal, 'u') => {
                                    editor.offset = 0;
                                    ::core::mem::swap(last_change, &mut editor.string);
                                },
                                (Normal, 's') => {
                                    ::core::mem::swap(&mut editor.offset, swap);
                                },
                                (Normal, 'o') => {
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: '$',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: 'i',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: '\n',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                },
                                (Normal, 'O') => {
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: 'k',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: '$',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: 'i',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: '\n',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                },
                                (Normal, '$') => {
                                    let mut new_offset = editor.string.len();
                                    for i in editor.offset..editor.string.len() {
                                        match editor.string.as_bytes()[i] {
                                            0 => break,
                                            10 => {
                                                new_offset = i;
                                                break;
                                            }
                                            _ => (),
                                        }
                                    }
                                    editor.offset = new_offset;
                                },
                                (Normal, '0') => {

                                    let mut new_offset = 0;
                                    for i in 2..editor.offset {
                                        match editor.string.as_bytes()[editor.offset - i] {
                                            0 => break,
                                            10 => {
                                                new_offset = editor.offset - i + 1;
                                                break;
                                            }
                                            _ => (),
                                        }
                                    }
                                    editor.offset = new_offset;
                                },
                                (Normal, 'd') => {
                                    let mut new_offset = editor.string.len();
                                    for i in editor.offset..editor.string.len() {
                                        match editor.string.as_bytes()[i] {
                                            0 => break,
                                            10 => {
                                                new_offset = i;
                                                break;
                                            }
                                            _ => {}
                                        }
                                    }
                                    for _ in 1..new_offset {
                                        editor.delete(window);
                                    }
                                    editor.offset = new_offset;
                                },
                                (Normal, ',') => {
                                    *is_recording = true;
                                    *period = String::new();
                                },
                                (Normal, '!') => {
                                    for c in period.clone().chars() {
                                        exec(editor, mode, multiplier, last_change, KeyEvent {
                                            character: c,
                                            scancode: 0,
                                            pressed: true,
                                        }, window, swap, period, is_recording);
                                    }
                                },
                                (Insert, '\0') => (),
                                (Insert, _) => {
                                    window.set_title(&format!("{}{}{}","Editor (", &editor.url, ") Changed"));
                                    editor.string = editor.string[0 .. editor.offset].to_string() +
                                        &key_event.character.to_string() +
                                        &editor.string[editor.offset .. editor.string.len()];
                                    editor.offset += 1;
                                },
                                _ => {},
                            }
                        }
                    }
                    is_none = true;
                }
            }

            if !is_none {
                *multiplier = Some(times);
            } else {
                *multiplier = None;
            }
        }
    }
}
<commit_msg>Add todo<commit_after>use redox::*;

use super::Mode;
use super::Mode::*;
use super::Editor;

pub fn exec(editor: &mut Editor, mode: &mut Mode, multiplier: &mut Option<u32>, last_change: &mut String, key_event: KeyEvent, window: &mut Window, swap: &mut usize, period: &mut String, is_recording: &mut bool) {
    match (*mode, key_event.scancode) {
        (Insert, K_ESC) => {
            *mode = Normal;
        },
        (Insert, K_BKSP) => editor.backspace(window),
        (Insert, K_DEL) => editor.delete(window),
        (_, K_F5) => editor.reload(window),
        (_, K_F6) => editor.save(window),
        (_, K_HOME) => editor.offset = 0,
        (_, K_UP) => editor.up(),
        (_, K_LEFT) => editor.left(),
        (_, K_RIGHT) => editor.right(),
        (_, K_END) => editor.offset = editor.string.len(),
        (_, K_DOWN) => editor.down(),
        (m, _) => {
            let (no_mult, mut times) = match *multiplier {
                Some(n) => (false, n),
                None => (true, 1),
            };
            let mut is_none = false;

            match (*mode, key_event.character) {
                (Normal, '0') if !no_mult => times *= 10,

                (Normal, '1') if no_mult => times = 1,
                (Normal, '1') => times = times * 10 + 1,

                (Normal, '2') if no_mult => times = 2,
                (Normal, '2') => times = times * 10 + 2,

                (Normal, '3') if no_mult => times = 3,
                (Normal, '3') => times = times * 10 + 3,

                (Normal, '4') if no_mult => times = 4,
                (Normal, '4') => times = times * 10 + 4,

                (Normal, '5') if no_mult => times = 5,
                (Normal, '5') => times = times * 10 + 5,

                (Normal, '6') if no_mult => times = 6,
                (Normal, '6') => times = times * 10 + 6,

                (Normal, '7') if no_mult => times = 7,
                (Normal, '7') => times = times * 10 + 7,

                (Normal, '8') if no_mult => times = 8,
                (Normal, '8') => times = times * 10 + 8,

                (Normal, '9') if no_mult => times = 9,
                (Normal, '9') => times = times * 10 + 9,
                (_, _) => {
                    if *is_recording {
                        if key_event.character == ',' {
                            *is_recording = false;
                        } else {
                            period.push(key_event.character);
                        }
                    } else {
                        for _ in 0 .. times {
                            match (m, key_event.character) {
                                (Normal, 'i') => {
                                    *mode = Insert;
                                    *last_change = editor.string.clone();
                                },
                                (Normal, 'h') => editor.left(),
                                (Normal, 'l') => editor.right(),
                                (Normal, 'k') => editor.up(),
                                (Normal, 'j') => editor.down(),
                                (Normal, 'g') => editor.offset = 0,
                                (Normal, 'G') => editor.offset = editor.string.len(),
                                (Normal, 'a') => {
                                    editor.right();
                                    *mode = Insert;
                                    *last_change = editor.string.clone();
                                },
                                (Normal, 'x') => editor.delete(window),
                                (Normal, 'X') => editor.backspace(window),
                                (Normal, 'u') => {
                                    editor.offset = 0;
                                    ::core::mem::swap(last_change, &mut editor.string);
                                },
                                (Normal, 's') => {
                                    ::core::mem::swap(&mut editor.offset, swap);
                                },
                                (Normal, 'o') => {
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: '$',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: 'i',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: '\n',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                },
                                (Normal, 'O') => {
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: 'k',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: '$',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: 'i',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                    exec(editor, mode, multiplier, last_change, KeyEvent {
                                        character: '\n',
                                        scancode: 0,
                                        pressed: true,
                                    }, window, swap, period, is_recording);
                                },
                                (Normal, '$') => {
                                    let mut new_offset = editor.string.len();
                                    for i in editor.offset..editor.string.len() {
                                        match editor.string.as_bytes()[i] {
                                            0 => break,
                                            10 => {
                                                new_offset = i;
                                                break;
                                            }
                                            _ => (),
                                        }
                                    }
                                    editor.offset = new_offset;
                                },
                                (Normal, '0') => {

                                    let mut new_offset = 0;
                                    for i in 2..editor.offset {
                                        match editor.string.as_bytes()[editor.offset - i] {
                                            0 => break,
                                            10 => {
                                                new_offset = editor.offset - i + 1;
                                                break;
                                            }
                                            _ => (),
                                        }
                                    }
                                    editor.offset = new_offset;
                                },
                                (Normal, 'd') => {
                                    // TODO: Is this crash proof?
                                    let mut new_offset = editor.string.len();
                                    for i in editor.offset..editor.string.len() {
                                        match editor.string.as_bytes()[i] {
                                            0 => break,
                                            10 => {
                                                new_offset = i;
                                                break;
                                            }
                                            _ => {}
                                        }
                                    }
                                    for _ in 1..new_offset {
                                        editor.delete(window);
                                    }
                                    editor.offset = new_offset;
                                },
                                (Normal, ',') => {
                                    *is_recording = true;
                                    *period = String::new();
                                },
                                (Normal, '!') => {
                                    for c in period.clone().chars() {
                                        exec(editor, mode, multiplier, last_change, KeyEvent {
                                            character: c,
                                            scancode: 0,
                                            pressed: true,
                                        }, window, swap, period, is_recording);
                                    }
                                },
                                (Insert, '\0') => (),
                                (Insert, _) => {
                                    window.set_title(&format!("{}{}{}","Editor (", &editor.url, ") Changed"));
                                    editor.string = editor.string[0 .. editor.offset].to_string() +
                                        &key_event.character.to_string() +
                                        &editor.string[editor.offset .. editor.string.len()];
                                    editor.offset += 1;
                                },
                                _ => {},
                            }
                        }
                    }
                    is_none = true;
                }
            }

            if !is_none {
                *multiplier = Some(times);
            } else {
                *multiplier = None;
            }
        }
    }
}
<|endoftext|>


<commit_before>use redox::Vec;

pub struct AvlNode<T> {
    value: T,
    left: Option<AvlNodeId>, // ID for left node
    right: Option<AvlNodeId>, // ID for right node
}

#[derive(Copy, Clone)]
pub struct AvlNodeId {
    index: usize,
    time_stamp: u64,
}

impl AvlNodeId {
    pub fn get<'a, T>(&self, avl: &'a Avl<T>) -> &'a AvlNode<T> {
        let ref slot = avl.nodes[self.index];
        if slot.time_stamp == self.time_stamp {
            slot.node.as_ref().unwrap()
        } else {
            panic!("AvlNodeId had invalid time_stamp");
        }
    }

    pub fn try_get<'a, T>(&self, avl: &'a Avl<T>) -> Option<&'a AvlNode<T>> {
        avl.nodes
           .get(self.index)
           .and_then(|slot| {
               if slot.time_stamp == self.time_stamp {
                   slot.node.as_ref()
               } else {
                   None
               }
           })
    }

    pub fn get_mut<'a, T>(&self, avl: &'a mut Avl<T>) -> &'a mut AvlNode<T> {
        let ref mut slot = avl.nodes[self.index];
        if slot.time_stamp == self.time_stamp {
            slot.node.as_mut().unwrap()
        } else {
            panic!("AvlNodeId had invalid time_stamp");
        }
    }

    pub fn try_get_mut<'a, T>(&self, avl: &'a mut Avl<T>) -> Option<&'a mut AvlNode<T>> {
        avl.nodes
           .get_mut(self.index)
           .and_then(|slot| {
               if slot.time_stamp == self.time_stamp {
                   slot.node.as_mut()
               } else {
                   None
               }
           })
    }
}

pub struct Avl<T> {
    root: usize, // Index of the root node
    nodes: Vec<AvlSlot<T>>,
    free_list: Vec<usize>,
}

impl<T> Avl<T> {
    pub fn new() -> Self {
        Avl {
            root: 0,
            nodes: Vec::new(),
            free_list: Vec::new(),
        }
    }

    pub fn insert(&mut self, value: T) -> AvlNodeId {
        // TODO this is just a placeholder, we need to deal with all the fancy rotation stuff that
        // AVL trees do
        self.allocate_node(value)
    }

    // Performs a left rotation on a tree/subtree.
    // Returns the replace the specified node with
    fn rotate_left(&mut self, node: AvlNodeId) -> AvlNodeId {
        // Keep track of the original node positions
        // For a rotate left, the right child node must exist
        let r = node.get(self).right.unwrap();
        let rl = r.get(self).left;

        let ret = r;
        node.get_mut(self).right = rl;
        ret.get_mut(self).left = Some(node);

        ret
    }

    // Performs a right rotation on a tree/subtree.
    // Returns the replace the specified node with
    fn rotate_right(&mut self, node: AvlNodeId) -> AvlNodeId {
        // Keep track of the original node positions
        // For a rotate right, the left child node must exist
        let l = node.get(self).left.unwrap();
        let lr = l.get(self).right;

        let ret = l;
        node.get_mut(self).left = lr;
        ret.get_mut(self).right = Some(node);

        ret
    }

    // performs a left-right double rotation on a tree/subtree.
    fn rotate_leftright(&mut self, node: AvlNodeId) -> AvlNodeId {
        let l = node.get(self).left.unwrap();
        let new_l = self.rotate_left(l); // Left node needs to exist
        node.get_mut(self).left = Some(new_l);
        self.rotate_right(node)
    }

    // performs a right-left double rotation on a tree/subtree.
    fn rotate_rightleft(&mut self, node: AvlNodeId) -> AvlNodeId {
        let r = node.get(self).right.unwrap();
        let new_r = self.rotate_right(r); // Right node needs to exist
        node.get_mut(self).right = Some(new_r);
        self.rotate_left(node)
    }

    // _ins is the implementation of the binary tree insert function. Lesser values will be stored on
    // the left, while greater values will be stored on the right. No duplicates are allowed.
    /*fn _ins(&mut self, node_index: Option<AvlNodeId>, value: T) -> AvlNodeId {
        let node =
            match node_index {
                Some(node) => {
                    // Node exists, check which way to branch.
                    if n == node->val {
                        return node;
                    else if (n < node->val)
                        _ins(n, node->left);
                    else if (n > node->val)
                        _ins(n, node->right);
                },
                None => {
                    // The node doesn't exist, create it here.
                    self.allocate_node(value)
                },
            };

        rebalance(node)
    }*/

    // _rebalance rebalances the provided node
    fn rebalance(&mut self, node: AvlNodeId) -> AvlNodeId {
        let balance = self.height(node.get(self).left) - self.height(node.get(self).right);
        if balance == 2 { // left
            let lbalance = self.height(node.get(self).left.unwrap().get(self).left) -
                           self.height(node.get(self).left.unwrap().get(self).right);
            if lbalance == 0 || lbalance == 1 { // left left - need to rotate right
                return self.rotate_right(node);
            } else if lbalance == -1 { // left right
                return self.rotate_leftright(node); // function name is just a coincidence
            }
        } else if balance == -2 { // right
            let rbalance = self.height(node.get(self).right.unwrap().get(self).left) -
                           self.height(node.get(self).right.unwrap().get(self).right);
            if rbalance == 1 { // right left
                return self.rotate_rightleft(node); // function name is just a coincidence
            } else if rbalance == 0 || rbalance == -1 { // right right - need to rotate left
                return self.rotate_left(node);
            }
        }

        node
    }

    // height gets the height of a tree or subtree
    fn height(&self, node: Option<AvlNodeId>) -> i64 {
        match node {
            Some(node) => {
                let left_height = self.height(node.get(self).left);
                let right_height = self.height(node.get(self).right);

                if left_height > right_height {
                    left_height+1
                } else {
                    right_height+1
                }
            },
            None => { -1 },
        }
    }

    fn allocate_node(&mut self, value: T) -> AvlNodeId {
        match self.free_list.pop() {
            Some(index) => {
                AvlNodeId { time_stamp: self.nodes[index].time_stamp+1, index: index }
            },
            None => {
                // No free slots, create a new one
                let id = AvlNodeId { index: self.nodes.len(), time_stamp: 0 };
                self.nodes.push(AvlSlot { time_stamp: 0,
                                          node: Some(AvlNode { value: value, left: None, right: None }) });
                id
            },
        }
    }

    fn free_node(&mut self, id: AvlNodeId) -> AvlNode<T> {
        self.free_list.push(id.index);

        // NOTE: We unwrap here, because we trust that `id` points to a valid node, because
        // only we can create and free AvlNodes and their AvlNodeIds
        self.nodes[id.index].node.take().unwrap()
    }
}

struct AvlSlot<T> {
    time_stamp: u64,
    node: Option<AvlNode<T>>,
}
<commit_msg>AvlTree::insert compiles...<commit_after>use redox::Vec;

pub struct AvlNode<T> {
    value: T,
    left: Option<AvlNodeId>, // ID for left node
    right: Option<AvlNodeId>, // ID for right node
}

#[derive(Copy, Clone)]
pub struct AvlNodeId {
    index: usize,
    time_stamp: u64,
}

impl AvlNodeId {
    pub fn get<'a, T: PartialOrd>(&self, avl: &'a Avl<T>) -> &'a AvlNode<T> {
        let ref slot = avl.nodes[self.index];
        if slot.time_stamp == self.time_stamp {
            slot.node.as_ref().unwrap()
        } else {
            panic!("AvlNodeId had invalid time_stamp");
        }
    }

    pub fn try_get<'a, T: PartialOrd>(&self, avl: &'a Avl<T>) -> Option<&'a AvlNode<T>> {
        avl.nodes
           .get(self.index)
           .and_then(|slot| {
               if slot.time_stamp == self.time_stamp {
                   slot.node.as_ref()
               } else {
                   None
               }
           })
    }

    pub fn get_mut<'a, T: PartialOrd>(&self, avl: &'a mut Avl<T>) -> &'a mut AvlNode<T> {
        let ref mut slot = avl.nodes[self.index];
        if slot.time_stamp == self.time_stamp {
            slot.node.as_mut().unwrap()
        } else {
            panic!("AvlNodeId had invalid time_stamp");
        }
    }

    pub fn try_get_mut<'a, T: PartialOrd>(&self, avl: &'a mut Avl<T>) -> Option<&'a mut AvlNode<T>> {
        avl.nodes
           .get_mut(self.index)
           .and_then(|slot| {
               if slot.time_stamp == self.time_stamp {
                   slot.node.as_mut()
               } else {
                   None
               }
           })
    }
}

pub struct Avl<T: PartialOrd> {
    root: usize, // Index of the root node
    nodes: Vec<AvlSlot<T>>,
    free_list: Vec<usize>,
}

impl<T: PartialOrd> Avl<T> {
    pub fn new() -> Self {
        Avl {
            root: 0,
            nodes: Vec::new(),
            free_list: Vec::new(),
        }
    }

    // Inserts a value into the tree, keeping it balanced. Lesser values will be stored on
    // the left, while greater values will be stored on the right. No duplicates are allowed.
    fn insert(&mut self, value: T, node_index: Option<AvlNodeId>) -> AvlNodeId {
        let node =
            match node_index {
                Some(node) => {
                    // Node exists, check which way to branch.
                    if value == node.get(self).value {
                        return node;
                    } else if value < node.get(self).value {
                        let l = node.get(self).left;
                        node.get_mut(self).left = Some(self.insert(value, l));
                    } else if value > node.get(self).value {
                        let r = node.get(self).right;
                        node.get_mut(self).right = Some(self.insert(value, r));
                    }

                    node
                },
                None => {
                    // The node doesn't exist, create it here.
                    self.allocate_node(value)
                },
            };

        self.rebalance(node)
    }

    // Performs a left rotation on a tree/subtree.
    // Returns the replace the specified node with
    fn rotate_left(&mut self, node: AvlNodeId) -> AvlNodeId {
        // Keep track of the original node positions
        // For a rotate left, the right child node must exist
        let r = node.get(self).right.unwrap();
        let rl = r.get(self).left;

        let ret = r;
        node.get_mut(self).right = rl;
        ret.get_mut(self).left = Some(node);

        ret
    }

    // Performs a right rotation on a tree/subtree.
    // Returns the replace the specified node with
    fn rotate_right(&mut self, node: AvlNodeId) -> AvlNodeId {
        // Keep track of the original node positions
        // For a rotate right, the left child node must exist
        let l = node.get(self).left.unwrap();
        let lr = l.get(self).right;

        let ret = l;
        node.get_mut(self).left = lr;
        ret.get_mut(self).right = Some(node);

        ret
    }

    // performs a left-right double rotation on a tree/subtree.
    fn rotate_leftright(&mut self, node: AvlNodeId) -> AvlNodeId {
        let l = node.get(self).left.unwrap();
        let new_l = self.rotate_left(l); // Left node needs to exist
        node.get_mut(self).left = Some(new_l);
        self.rotate_right(node)
    }

    // performs a right-left double rotation on a tree/subtree.
    fn rotate_rightleft(&mut self, node: AvlNodeId) -> AvlNodeId {
        let r = node.get(self).right.unwrap();
        let new_r = self.rotate_right(r); // Right node needs to exist
        node.get_mut(self).right = Some(new_r);
        self.rotate_left(node)
    }

    // _rebalance rebalances the provided node
    fn rebalance(&mut self, node: AvlNodeId) -> AvlNodeId {
        let balance = self.height(node.get(self).left) - self.height(node.get(self).right);
        if balance == 2 { // left
            let lbalance = self.height(node.get(self).left.unwrap().get(self).left) -
                           self.height(node.get(self).left.unwrap().get(self).right);
            if lbalance == 0 || lbalance == 1 { // left left - need to rotate right
                return self.rotate_right(node);
            } else if lbalance == -1 { // left right
                return self.rotate_leftright(node); // function name is just a coincidence
            }
        } else if balance == -2 { // right
            let rbalance = self.height(node.get(self).right.unwrap().get(self).left) -
                           self.height(node.get(self).right.unwrap().get(self).right);
            if rbalance == 1 { // right left
                return self.rotate_rightleft(node); // function name is just a coincidence
            } else if rbalance == 0 || rbalance == -1 { // right right - need to rotate left
                return self.rotate_left(node);
            }
        }

        node
    }

    // height gets the height of a tree or subtree
    fn height(&self, node: Option<AvlNodeId>) -> i64 {
        match node {
            Some(node) => {
                let left_height = self.height(node.get(self).left);
                let right_height = self.height(node.get(self).right);

                if left_height > right_height {
                    left_height+1
                } else {
                    right_height+1
                }
            },
            None => { -1 },
        }
    }

    fn allocate_node(&mut self, value: T) -> AvlNodeId {
        match self.free_list.pop() {
            Some(index) => {
                AvlNodeId { time_stamp: self.nodes[index].time_stamp+1, index: index }
            },
            None => {
                // No free slots, create a new one
                let id = AvlNodeId { index: self.nodes.len(), time_stamp: 0 };
                self.nodes.push(AvlSlot { time_stamp: 0,
                                          node: Some(AvlNode { value: value, left: None, right: None }) });
                id
            },
        }
    }

    fn free_node(&mut self, id: AvlNodeId) -> AvlNode<T> {
        self.free_list.push(id.index);

        // NOTE: We unwrap here, because we trust that `id` points to a valid node, because
        // only we can create and free AvlNodes and their AvlNodeIds
        self.nodes[id.index].node.take().unwrap()
    }
}

struct AvlSlot<T> {
    time_stamp: u64,
    node: Option<AvlNode<T>>,
}
<|endoftext|>


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

// ignore-android FIXME #17520
// ignore-emscripten spawning processes is not supported
// ignore-openbsd no support for libbacktrace without filename
// compile-flags:-g

use std::env;
use std::process::{Command, Stdio};
use std::str;

#[inline(never)]
fn foo() {
    let _v = vec![1, 2, 3];
    if env::var_os("IS_TEST").is_some() {
        panic!()
    }
}

#[inline(never)]
fn double() {
    struct Double;

    impl Drop for Double {
        fn drop(&mut self) { panic!("twice") }
    }

    let _d = Double;

    panic!("once");
}

fn template(me: &str) -> Command {
    let mut m = Command::new(me);
    m.env("IS_TEST", "1")
     .stdout(Stdio::piped())
     .stderr(Stdio::piped());
    return m;
}

fn expected(fn_name: &str) -> String {
    format!(" backtrace::{}", fn_name)
}

fn runtest(me: &str) {
    // Make sure that the stack trace is printed
    let p = template(me).arg("fail").env("RUST_BACKTRACE", "1").spawn().unwrap();
    let out = p.wait_with_output().unwrap();
    assert!(!out.status.success());
    let s = str::from_utf8(&out.stderr).unwrap();
    assert!(s.contains("stack backtrace") && s.contains(&expected("foo")),
            "bad output: {}", s);

    // Make sure than the short version cleans the backtrace.
    let p = template(me).arg("fail").env("RUST_BACKTRACE", "1").spawn().unwrap();
    let out = p.wait_with_output().unwrap();
    assert!(!out.status.success());
    let s = str::from_utf8(&out.stderr).unwrap();
    let removed_symbols = &[
        "std::sys::imp::backtrace",
        "std::sys_common::backtrace",
        "std::panicking",
        "core::panicking",
        "rust_begin_unwind",
        "code::result::unwrap_failed",
        "std::panicking::try::do_call",
        "__rust_maybe_catch_panic",
        "__libc_start_main",
        "__rust_try",
        "_start",
    ];
    for symbol in removed_symbols {
        assert!(!s.contains(symbol),
                "{} should be removed from the backtrace\n{}",
                symbol, s);
    }
    assert!(s.contains(" 0:"), "the frame number should start at 0");

    // Only on linux for _start and __libc_start_main
    #[cfg(target_os="linux")]
    {
        // Make sure than the short version cleans the backtrace.
        let p = template(me).arg("fail").env("RUST_BACKTRACE", "full").spawn().unwrap();
        let out = p.wait_with_output().unwrap();
        assert!(!out.status.success());
        let s = str::from_utf8(&out.stderr).unwrap();
        let should_be_present = &[
            "std::panicking",
            "__rust_maybe_catch_panic",
            "__libc_start_main",
            "_start",
        ];
        for symbol in should_be_present {
            // May give false positive due to inlining.
            assert!(s.contains(symbol),
            "the full version of the backtrace should contain {}",
            symbol);
        }
    }

    // Make sure the stack trace is *not* printed
    // (Remove RUST_BACKTRACE from our own environment, in case developer
    // is running `make check` with it on.)
    let p = template(me).arg("fail").env_remove("RUST_BACKTRACE").spawn().unwrap();
    let out = p.wait_with_output().unwrap();
    assert!(!out.status.success());
    let s = str::from_utf8(&out.stderr).unwrap();
    assert!(!s.contains("stack backtrace") && !s.contains(&expected("foo")),
            "bad output2: {}", s);

    // Make sure the stack trace is *not* printed
    // (RUST_BACKTRACE=0 acts as if it were unset from our own environment,
    // in case developer is running `make check` with it set.)
    let p = template(me).arg("fail").env("RUST_BACKTRACE","0").spawn().unwrap();
    let out = p.wait_with_output().unwrap();
    assert!(!out.status.success());
    let s = str::from_utf8(&out.stderr).unwrap();
    assert!(!s.contains("stack backtrace") && !s.contains(" - foo"),
            "bad output3: {}", s);

    // Make sure a stack trace is printed
    let p = template(me).arg("double-fail").spawn().unwrap();
    let out = p.wait_with_output().unwrap();
    assert!(!out.status.success());
    let s = str::from_utf8(&out.stderr).unwrap();
    // loosened the following from double::h to double:: due to
    // spurious failures on mac, 32bit, optimized
    assert!(s.contains("stack backtrace") && s.contains(&expected("double")),
            "bad output3: {}", s);

    // Make sure a stack trace isn't printed too many times
    let p = template(me).arg("double-fail")
                                .env("RUST_BACKTRACE", "1").spawn().unwrap();
    let out = p.wait_with_output().unwrap();
    assert!(!out.status.success());
    let s = str::from_utf8(&out.stderr).unwrap();
    let mut i = 0;
    for _ in 0..2 {
        i += s[i + 10..].find("stack backtrace").unwrap() + 10;
    }
    assert!(s[i + 10..].find("stack backtrace").is_none(),
            "bad output4: {}", s);
}

fn main() {
    let args: Vec<String> = env::args().collect();
    if args.len() >= 2 && args[1] == "fail" {
        foo();
    } else if args.len() >= 2 && args[1] == "double-fail" {
        double();
    } else {
        runtest(&args[0]);
    }
}
<commit_msg>This test is too hard to maintain cross-platform<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// ignore-android FIXME #17520
// ignore-emscripten spawning processes is not supported
// ignore-openbsd no support for libbacktrace without filename
// compile-flags:-g

use std::env;
use std::process::{Command, Stdio};
use std::str;

#[inline(never)]
fn foo() {
    let _v = vec![1, 2, 3];
    if env::var_os("IS_TEST").is_some() {
        panic!()
    }
}

#[inline(never)]
fn double() {
    struct Double;

    impl Drop for Double {
        fn drop(&mut self) { panic!("twice") }
    }

    let _d = Double;

    panic!("once");
}

fn template(me: &str) -> Command {
    let mut m = Command::new(me);
    m.env("IS_TEST", "1")
     .stdout(Stdio::piped())
     .stderr(Stdio::piped());
    return m;
}

fn expected(fn_name: &str) -> String {
    format!(" backtrace::{}", fn_name)
}

fn runtest(me: &str) {
    // Make sure that the stack trace is printed
    let p = template(me).arg("fail").env("RUST_BACKTRACE", "1").spawn().unwrap();
    let out = p.wait_with_output().unwrap();
    assert!(!out.status.success());
    let s = str::from_utf8(&out.stderr).unwrap();
    assert!(s.contains("stack backtrace") && s.contains(&expected("foo")),
            "bad output: {}", s);
    assert!(s.contains(" 0:"), "the frame number should start at 0");

    // Make sure the stack trace is *not* printed
    // (Remove RUST_BACKTRACE from our own environment, in case developer
    // is running `make check` with it on.)
    let p = template(me).arg("fail").env_remove("RUST_BACKTRACE").spawn().unwrap();
    let out = p.wait_with_output().unwrap();
    assert!(!out.status.success());
    let s = str::from_utf8(&out.stderr).unwrap();
    assert!(!s.contains("stack backtrace") && !s.contains(&expected("foo")),
            "bad output2: {}", s);

    // Make sure the stack trace is *not* printed
    // (RUST_BACKTRACE=0 acts as if it were unset from our own environment,
    // in case developer is running `make check` with it set.)
    let p = template(me).arg("fail").env("RUST_BACKTRACE","0").spawn().unwrap();
    let out = p.wait_with_output().unwrap();
    assert!(!out.status.success());
    let s = str::from_utf8(&out.stderr).unwrap();
    assert!(!s.contains("stack backtrace") && !s.contains(" - foo"),
            "bad output3: {}", s);

    // Make sure a stack trace is printed
    let p = template(me).arg("double-fail").spawn().unwrap();
    let out = p.wait_with_output().unwrap();
    assert!(!out.status.success());
    let s = str::from_utf8(&out.stderr).unwrap();
    // loosened the following from double::h to double:: due to
    // spurious failures on mac, 32bit, optimized
    assert!(s.contains("stack backtrace") && s.contains(&expected("double")),
            "bad output3: {}", s);

    // Make sure a stack trace isn't printed too many times
    let p = template(me).arg("double-fail")
                                .env("RUST_BACKTRACE", "1").spawn().unwrap();
    let out = p.wait_with_output().unwrap();
    assert!(!out.status.success());
    let s = str::from_utf8(&out.stderr).unwrap();
    let mut i = 0;
    for _ in 0..2 {
        i += s[i + 10..].find("stack backtrace").unwrap() + 10;
    }
    assert!(s[i + 10..].find("stack backtrace").is_none(),
            "bad output4: {}", s);
}

fn main() {
    let args: Vec<String> = env::args().collect();
    if args.len() >= 2 && args[1] == "fail" {
        foo();
    } else if args.len() >= 2 && args[1] == "double-fail" {
        double();
    } else {
        runtest(&args[0]);
    }
}
<|endoftext|>


<commit_before><commit_msg>Add regression test for #81289<commit_after>// Rustdoc shouldn't display `mut` in function arguments, which are
// implementation details. Regression test for #81289.

#![crate_name = "foo"]

pub struct Foo;

// @count foo/struct.Foo.html '//*[@class="impl-items"]//*[@class="method"]' 2
// @!has - '//*[@class="impl-items"]//*[@class="method"]' 'mut'
impl Foo {
    pub fn foo(mut self) {}

    pub fn bar(mut bar: ()) {}
}

// @count foo/fn.baz.html '//*[@class="rust fn"]' 1
// @!has - '//*[@class="rust fn"]' 'mut'
pub fn baz(mut foo: Foo) {}
<|endoftext|>


<commit_before><commit_msg>Remove "test_" prefix on tests.<commit_after><|endoftext|>


<commit_before><commit_msg>Add percent-encoding convienience wrappers.<commit_after><|endoftext|>


<commit_before><commit_msg>more flexible processing context<commit_after><|endoftext|>


<commit_before><commit_msg>correct nyaa order and limit new messages<commit_after><|endoftext|>


<commit_before><commit_msg>commands: add SURB reply command<commit_after><|endoftext|>


<commit_before><commit_msg>added vector normals<commit_after><|endoftext|>


<commit_before><commit_msg>beginnings of a route parser with parameter support<commit_after>extern crate regex;

#[cfg(test)]
mod tests;

use regex::Regex;
use std::io::{self, Read};
use std::collections::HashMap;
use std::net::{TcpListener, TcpStream};
use std::thread;

#[derive(PartialEq, Debug)]
enum Method {
    Get,
    Put,
    Post,
    Delete,
    NoImpl,
}

#[derive(Debug)]
struct Request {
    method:  Method,
    path:    String,
    headers: HashMap<String, String>,
    payload: String,
}

impl Request {
    fn new() -> Request {
        Request {
            method:  Method::NoImpl,
            path:    String::new(),
            headers: HashMap::new(),
            payload: String::new(),
        }
    }

    pub fn from_str(rqstr: &str) -> Request {
        let mut req = Request::new();
        req.parse(rqstr);
        req
    }

    pub fn parse(&mut self, rqstr: &str) {
        let mut chunks: Vec<&str> = rqstr.splitn(2, "\r\n\r\n").collect();
        let mut header: Vec<&str> = chunks.pop().unwrap().split("\r\n").collect();
        let ask: Vec<&str> = header.pop().unwrap().splitn(3, ' ').collect();

        self.method = match ask[0] {
            "GET"           => Method::Get,
            "PUT" | "PATCH" => Method::Put,
            "POST"          => Method::Post,
            "DELETE"        => Method::Delete,
            _               => Method::NoImpl,
        };
        self.path = String::from(ask[1]);

        for line in header {
            let hdr: Vec<&str> = line.splitn(2, ": ").collect();

            if hdr.len() == 2 {
                self.headers.insert(String::from(hdr[0]), String::from(hdr[1]));
            }
        }
    }
}

#[derive(Debug)]
pub struct Route {
    pathdef: String,
    matcher: Regex,
    params:  HashMap<String, String>,
}

impl Route {
    fn new(path: &str) -> Route {
        let re = Regex::new(r"^<(?:(int|str):)?([\w_][a-zA-Z0-9_]*)>$").unwrap();
        let mut parts: Vec<&str> = path.split('/').filter(|&s| s != "").collect();
        let mut matcher: String = String::from(r"^");
        let mut params: HashMap<String, String> = HashMap::new();

        for part in parts {
            let chunk: String = match re.is_match(part) {
                true  => {
                    let mut rc = String::new();
                    let caps = re.captures(part).unwrap();
                    let param = caps.at(2).unwrap().clone();
                    let ptype: String = match caps.at(1) {
                        Some(x)     => String::from(x),
                        None        => String::from("str"),
                    };

                    let mstr: String = match ptype.as_ref() {
                        "str" => String::from("(?:[^/])+"),
                        "int" => String::from("[0-9]+"),
                        _     => String::from("(?:[^/])+"),
                    };

                    rc.push_str("/(?P<");
                    rc.push_str(&param);
                    rc.push_str(">");
                    rc.push_str(&mstr);
                    rc.push_str(")");
                    params.insert(String::from(param), mstr.clone());

                    rc
                },
                false => String::from("/") + part,
            };

            matcher.push_str(&chunk);
        }

        /* end the regex with an optional final slash and a string terminator */
        matcher.push_str("/?$");

        Route {
            pathdef: String::from(path),
            matcher: Regex::new(&matcher).unwrap(),
            params:  params,
        }
    }

    fn is_match(&self, path: &str) -> bool {
        self.matcher.is_match(&path)
    }

    fn parse(&self, path: &str) -> Option<HashMap<String, String>> {
        let mut params: HashMap<String, String> = HashMap::new();

        return match self.matcher.is_match(&path) {
            true  => {
                let caps = self.matcher.captures(path).unwrap();
                for (param, _) in &self.params {
                    params.insert(param.clone(), String::from(caps.name(&param).unwrap()));
                }

                Some(params)
            },
            false => None,
        }
    }
}

fn handle_client(mut stream: TcpStream) {
    let mut rqstr: String = String::new();
    let mut buf: String = String::new();

    while stream.read_to_string(&mut buf).unwrap() > 0 {
        rqstr.push_str(&buf);
    }

    println!("{}", rqstr);
    println!("");

    let req = Request::from_str(&rqstr);
}

fn main() {
    let rt = Route::new("/api/v1/foo/<foo_stuff>");
    assert_eq!("blahblahblah", rt.parse("/api/v1/foo/blahblahblah").unwrap().get("foo_stuff").unwrap());
    /*
    let listener = TcpListener::bind("127.0.0.1:8080").unwrap();

    for stream in listener.incoming() {
        match stream {
            Ok(stream)  => {
                thread::spawn(move || {
                    handle_client(stream)
                });
            },
            Err(e)      => {},
        }
    }

    drop(listener);
    */
}
<|endoftext|>


<commit_before>use layout::{AnonymousBlock, BlockNode, InlineNode, LayoutBox, Rect};
use css::{ColorValue, Color};
use std::iter::range;

/// Paint a tree of LayoutBoxes to an array of pixels.
pub fn paint(layout_root: &LayoutBox, bounds: Rect) -> Canvas {
    let display_list = build_display_list(layout_root);
    let mut canvas = Canvas::new(bounds.width as uint, bounds.height as uint);
    for item in display_list.iter() {
        canvas.paint_item(item);
    }
    return canvas;
}

#[deriving(Show)]
enum DisplayItem {
    SolidColor(Color, Rect),
}

type DisplayList = Vec<DisplayItem>;

pub fn build_display_list(layout_root: &LayoutBox) -> DisplayList {
    let mut list = Vec::new();
    render_layout_box(&mut list, layout_root);
    return list;
}

fn render_layout_box(list: &mut DisplayList, layout_box: &LayoutBox) {
    render_background(list, layout_box);
    render_borders(list, layout_box);
    for child in layout_box.children.iter() {
        render_layout_box(list, child);
    }
}

fn render_background(list: &mut DisplayList, layout_box: &LayoutBox) {
    get_color(layout_box, "background").map(|color|
        list.push(SolidColor(color, layout_box.dimensions.padding_box())));
}

fn render_borders(list: &mut DisplayList, layout_box: &LayoutBox) {
    let color = match get_color(layout_box, "border-color") {
        Some(color) => color,
        _ => return
    };

    let d = &layout_box.dimensions;
    let border_box = d.border_box();

    // Left border
    list.push(SolidColor(color, Rect {
        x: border_box.x,
        y: border_box.y,
        width: d.border.left,
        height: border_box.height,
    }));

    // Right border
    list.push(SolidColor(color, Rect {
        x: border_box.x + border_box.width - d.border.right,
        y: border_box.y,
        width: d.border.right,
        height: border_box.height,
    }));

    // Top border
    list.push(SolidColor(color, Rect {
        x: border_box.x,
        y: border_box.y,
        width: border_box.width,
        height: d.border.top,
    }));

    // Bottom border
    list.push(SolidColor(color, Rect {
        x: border_box.x,
        y: border_box.y + border_box.height - d.border.bottom,
        width: border_box.width,
        height: d.border.bottom,
    }));
}

fn get_color(layout_box: &LayoutBox, name: &str) -> Option<Color> {
    match layout_box.box_type {
        BlockNode(style) | InlineNode(style) => match style.value(name) {
            Some(ColorValue(color)) => Some(color),
            _ => None
        },
        AnonymousBlock => None
    }
}

pub struct Canvas {
    pub pixels: Vec<Color>,
    pub width: uint,
    pub height: uint,
}

impl Canvas {
    fn new(width: uint, height: uint) -> Canvas {
        let white = Color { r: 255, g: 255, b: 255, a: 255 };
        return Canvas {
            pixels: Vec::from_elem(width * height, white),
            width: width,
            height: height,
        }
    }

    fn paint_item(&mut self, item: &DisplayItem) {
        match item {
            &SolidColor(color, rect) => {
                // Clip the rectangle to the canvas boundaries.
                let x0 = rect.x.clamp(0.0, self.width as f32) as uint;
                let y0 = rect.y.clamp(0.0, self.height as f32) as uint;
                let x1 = (rect.x + rect.width).clamp(0.0, self.width as f32) as uint;
                let y1 = (rect.y + rect.height).clamp(0.0, self.height as f32) as uint;

                for x in range(x0, x1) {
                    for y in range(y0, y1) {
                        // TODO: alpha compositing with existing pixel
                        self.pixels[x + y * self.width] = color;
                    }
                }
            }
        }
    }
}

trait FloatClamp : FloatMath {
    fn clamp(self, lower: Self, upper: Self) -> Self {
        self.max(lower).min(upper)
    }
}
impl<T: FloatMath> FloatClamp for T {}
<commit_msg>Background should cover the border-box<commit_after>use layout::{AnonymousBlock, BlockNode, InlineNode, LayoutBox, Rect};
use css::{ColorValue, Color};
use std::iter::range;

/// Paint a tree of LayoutBoxes to an array of pixels.
pub fn paint(layout_root: &LayoutBox, bounds: Rect) -> Canvas {
    let display_list = build_display_list(layout_root);
    let mut canvas = Canvas::new(bounds.width as uint, bounds.height as uint);
    for item in display_list.iter() {
        canvas.paint_item(item);
    }
    return canvas;
}

#[deriving(Show)]
enum DisplayItem {
    SolidColor(Color, Rect),
}

type DisplayList = Vec<DisplayItem>;

fn build_display_list(layout_root: &LayoutBox) -> DisplayList {
    let mut list = Vec::new();
    render_layout_box(&mut list, layout_root);
    return list;
}

fn render_layout_box(list: &mut DisplayList, layout_box: &LayoutBox) {
    render_background(list, layout_box);
    render_borders(list, layout_box);
    for child in layout_box.children.iter() {
        render_layout_box(list, child);
    }
}

fn render_background(list: &mut DisplayList, layout_box: &LayoutBox) {
    get_color(layout_box, "background").map(|color|
        list.push(SolidColor(color, layout_box.dimensions.border_box())));
}

fn render_borders(list: &mut DisplayList, layout_box: &LayoutBox) {
    let color = match get_color(layout_box, "border-color") {
        Some(color) => color,
        _ => return
    };

    let d = &layout_box.dimensions;
    let border_box = d.border_box();

    // Left border
    list.push(SolidColor(color, Rect {
        x: border_box.x,
        y: border_box.y,
        width: d.border.left,
        height: border_box.height,
    }));

    // Right border
    list.push(SolidColor(color, Rect {
        x: border_box.x + border_box.width - d.border.right,
        y: border_box.y,
        width: d.border.right,
        height: border_box.height,
    }));

    // Top border
    list.push(SolidColor(color, Rect {
        x: border_box.x,
        y: border_box.y,
        width: border_box.width,
        height: d.border.top,
    }));

    // Bottom border
    list.push(SolidColor(color, Rect {
        x: border_box.x,
        y: border_box.y + border_box.height - d.border.bottom,
        width: border_box.width,
        height: d.border.bottom,
    }));
}

fn get_color(layout_box: &LayoutBox, name: &str) -> Option<Color> {
    match layout_box.box_type {
        BlockNode(style) | InlineNode(style) => match style.value(name) {
            Some(ColorValue(color)) => Some(color),
            _ => None
        },
        AnonymousBlock => None
    }
}

pub struct Canvas {
    pub pixels: Vec<Color>,
    pub width: uint,
    pub height: uint,
}

impl Canvas {
    fn new(width: uint, height: uint) -> Canvas {
        let white = Color { r: 255, g: 255, b: 255, a: 255 };
        return Canvas {
            pixels: Vec::from_elem(width * height, white),
            width: width,
            height: height,
        }
    }

    fn paint_item(&mut self, item: &DisplayItem) {
        match item {
            &SolidColor(color, rect) => {
                // Clip the rectangle to the canvas boundaries.
                let x0 = rect.x.clamp(0.0, self.width as f32) as uint;
                let y0 = rect.y.clamp(0.0, self.height as f32) as uint;
                let x1 = (rect.x + rect.width).clamp(0.0, self.width as f32) as uint;
                let y1 = (rect.y + rect.height).clamp(0.0, self.height as f32) as uint;

                for x in range(x0, x1) {
                    for y in range(y0, y1) {
                        // TODO: alpha compositing with existing pixel
                        self.pixels[x + y * self.width] = color;
                    }
                }
            }
        }
    }
}

trait FloatClamp : FloatMath {
    fn clamp(self, lower: Self, upper: Self) -> Self {
        self.max(lower).min(upper)
    }
}
impl<T: FloatMath> FloatClamp for T {}
<|endoftext|>


<commit_before><commit_msg>Add problem #134<commit_after>//! Problem 134 (https://projecteuler.net/problem=134)
//!
//! # 解析
//!
//! 連続する素数 `p1=19`, `p2=23` の場合を例にして考える。
//!
//! `23n が `10k + 9` と書ける場合、
//!
//! ```math
//! 3 * n = 9 (mod 10)
//! => 23n = 23(10k + 3) = 230k + 69
//! ```
//!
//! である。
//!
//! `230k + 69` が `100m + 19` と書ける場合、
//!
//! ```math
//! 3 * k + 6 = 1 (mod 10)
//! => 230k + 69 = 230(10m + 5) + 69 = 2300m + 1219
//! ```
//!
//! よって、`S = 1219` である。
//!
//! # 解法
//!
//! `n`, `m` について以下を満たす `x` を、`x(n, m)` と書く。
//!
//! ```math
//! n * x = m (mod 10)
//! ```
//!
//! `x_i` は `x` の `i` 桁目を表すとする。
//! 以下の漸化式により、`S` を求めることができる。
//! ここで、 `n` は `p1` の桁数である。
//!
//! ```math
//! a[1] = x(p2, p1_1)
//! b[1] = a[1] * p2
//! a[i] = x(p2, p1_i - b[i-1]_i)
//! b[i] = a[i] * p2 * 10^(i-1) + b[i-1]
//! S = b[n]
//! ```
//!
//! ## 例 `p1=19` と `p2=23` の場合
//!
//! ```math
//! a[1] = x(23, 9) = 3
//! b[1] = 3*23 = 69
//! a[2] = x(23, 1 - 6) = 5
//! b[2] = 50*23 + 69 = 1219
//! S = b[2] = 1219
//! ```
//!
//! ## 例 `p1=11` と `p2=13` の場合
//!
//! ```math
//! a[1] = x(13, 1) = 7
//! b[1] = 7*13 = 91
//! a[2] = x(13, 1 - 9) = 4
//! b[2] = 40*13 + 91 = 611
//! S = b[2] = 611
//! ```
//!
//! ## 例 `p1=97` と `p2=101` の場合
//!
//! ```math
//! a[1] = x(101, 7) = 7
//! b[1] = 7*101 = 707
//! a[2] = x(101, 9 - 0) = 9
//! b[2] = 90*101 + 707 = 9797
//! S = b[2] = 9797
//! ```
//!
//! ## 例 `p1=101` と `p2=103` の場合
//!
//! ```math
//! a[1] = x(103, 1) = 7
//! b[1] = 7*103 = 1751
//! a[2] = x(103, 0 - 5) = 5
//! b[2] = 50*103 + 1751 = 6901
//! a[3] = x(103, 1 - 9) = 4
//! b[3] = 400*103 + 6901 = 48101
//! S = b[3] = 48101
//! ```

#[crate_id = "prob0134"];
#[crate_type = "rlib"];

extern mod math;

use std::vec;
use math::prime::Prime;

pub static EXPECTED_ANSWER: &'static str = "18613426663617118";

pub fn solve() -> ~str {
    let min_limit = 5;
    let max_limit = 1000000;

    let mut mod_map = vec::from_fn(10, |_| vec::from_elem(10, 0u));
    for &b in [1u, 3, 7, 9].iter() {
        for n in range(1u, 10) {
            mod_map[b][(b * n) % 10] = n;
        }
    }

    let mut sum = 0;
    let ps = Prime::new();
    let mut pairs = ps.iter()
        .zip(ps.iter().skip(1))
        .skip_while(|&(p1, _p2)| p1 < min_limit)
        .take_while(|&(p1, _p2)| p1 <= max_limit);

    for (p1, p2) in pairs {
        if p1 == 3 { continue }
        let xmap = &mod_map[p2 % 10];
        let mut a = 0;
        let mut b = 0;
        let mut p1_digit = p1;
        let mut coef = 1;
        p1.to_str().len().times(|| {
                let (d, m) = p1_digit.div_rem(&10);
                p1_digit = d;
                a = xmap[(10 + m - (b / coef) % 10) % 10];
                b += a * p2 * coef;
                coef *= 10;
            });
        sum += b;
    }
    sum.to_str()
}
<|endoftext|>


<commit_before><commit_msg>Added a few hdf5 tests<commit_after>#[allow(unused_imports)] use tensor::Tensor;
#[allow(unused_imports)] use io;
#[allow(unused_imports)] use std::path::Path;
#[allow(unused_imports)] use std::env;
#[allow(unused_imports)] use std::fs;

#[test]
fn hdf5() {
    // We can't have multiple HDF5 tests, since these functions are not thread-safe!
    // This is why we have to string all of this together in serial, since otherwise the tests
    // might run concurrently. This is in other words the only test that is allowed to interract
    // with with libhdf5.

    let mut path = env::temp_dir();
    path.push("numeric.h5");
    if path.exists() {
        assert!(fs::remove_file(&path).is_ok());
    }

    {
        let t: Tensor<f64> = Tensor::range(10);

        let res = t.save_hdf5(&path);
        assert!(res.is_ok());
        assert!(path.exists());

        let t2 = io::load_hdf5_as_f64(&path, "/data").unwrap();

        assert!(t == t2);
        assert!(fs::remove_file(&path).is_ok());
    }

    {
        let t: Tensor<i16> = Tensor::range(1000).reshape(&[50, 20]);

        let res = t.save_hdf5(&path);
        assert!(res.is_ok());
        assert!(path.exists());

        let t2 = io::load_hdf5_as_i16(&path, "/data").unwrap();

        assert!(t == t2);
        assert!(fs::remove_file(&path).is_ok());
    }
}

<|endoftext|>


<commit_before><commit_msg>error: add time::ParserError<commit_after><|endoftext|>


<commit_before><commit_msg>Fix the parser.<commit_after><|endoftext|>


<commit_before><commit_msg>Add the brute force broad phase.<commit_after>use na::Identity;
use utils::data::uid_remap::{UidRemap, FastKey};
use geometry::bounding_volume::BoundingVolume;
use geometry::ray::{Ray, RayCast};
use geometry::point::PointQuery;
use broad_phase::BroadPhase;
use math::{Point, Vector};

/// A broad phase testing explicitly all bounding volume pairs.
///
/// Use this for debugging purposes only.
pub struct BruteForceBroadPhase<BV, T> {
    proxies:   UidRemap<(BV, T)>,
    to_remove: Vec<usize>,
    to_add:    Vec<(usize, BV, T)>,
    to_update: Vec<(FastKey, BV)>
}

impl<P: Point, BV, T> BroadPhase<P, BV, T> for BruteForceBroadPhase<BV, T> where
    BV: 'static + BoundingVolume<<P::Vect as Vector>::Scalar> +
        RayCast<P, Identity> + PointQuery<P, Identity> + Clone {
    fn deferred_add(&mut self, uid: usize, bv: BV, data: T) {
        // XXX: should not be inserted now!
        let (key, _) = self.proxies.insert(uid, (bv.clone(), data));

        self.to_update.push((key, bv))
    }

    fn deferred_remove(&mut self, uid: usize) {
        if self.proxies.get_fast_key(uid).is_some() {
            self.to_remove.push(uid);
        }
    }

    fn deferred_set_bounding_volume(&mut self, uid: usize, bv: BV) {
        if let Some(key) = self.proxies.get_fast_key(uid) {
            self.to_update.push((key, bv));
        }
    }

    fn deferred_recompute_all_proximities(&mut self) {
        for proxy in self.proxies.iter() {
            self.to_update.push((proxy.0, (proxy.1).0.clone()));
        }
    }

    fn update(&mut self, allow_proximity: &mut FnMut(&T, &T) -> bool, proximity_handler: &mut FnMut(&T, &T, bool)) {
        for (uid, bv, data) in self.to_add.drain(..) {
            let key = self.proxies.insert(uid, (bv.clone(), data));
            self.to_update.push((key.0, bv))
        }

        for rm in self.to_remove.drain(..) {
            let _ = self.proxies.remove(rm);
        }

        for new_proxy in self.to_update.iter() {
            if let Some(proxy) = self.proxies.get_fast_mut(&new_proxy.0) {
                proxy.0 = new_proxy.1.clone();
            }
        }

        for proxy1_key in self.to_update.drain(..) {
            if let Some(proxy1) = self.proxies.get_fast(&proxy1_key.0) {
                for proxy2 in self.proxies.values() {
                    if allow_proximity(&proxy1.1, &proxy2.1) {
                        proximity_handler(&proxy1.1, &proxy2.1, proxy1.0.intersects(&proxy2.0))
                    }
                }
            }
        }
    }

    fn interferences_with_bounding_volume<'a>(&'a self, bv: &BV, out: &mut Vec<&'a T>) {
        for proxy in self.proxies.values() {
            if proxy.0.intersects(bv) {
                out.push(&proxy.1)
            }
        }
    }

    fn interferences_with_ray<'a>(&'a self, ray: &Ray<P>, out: &mut Vec<&'a T>) {
        for proxy in self.proxies.values() {
            if proxy.0.intersects_ray(&Identity::new(), ray) {
                out.push(&proxy.1)
            }
        }
    }

    fn interferences_with_point<'a>(&'a self, point: &P, out: &mut Vec<&'a T>) {
        for proxy in self.proxies.values() {
            if proxy.0.contains_point(&Identity::new(), point) {
                out.push(&proxy.1)
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>docs(Argon2PasswordHasher): explains why `new` might fail<commit_after><|endoftext|>


<commit_before><commit_msg>added closureinputs<commit_after>use std::mem;

fn apply<F>(f: F)
    where F: FnOnce() {
  f();
}

fn apply_2<F>(f: F) -> i32
    where F: Fn(i32) -> i32 {
    f(3)
}

fn main() {
    let greeting = "Hello";

    let mut farewell = "Goodbye".to_owned();

    let display = || {

        // Fn
        println!("{}", greeting);

        // FnMut
        farewell.push_str("!!!!");
        println!("{}", farewell);

        // FnOnce
        mem::drop(farewell)
    };

    let simple = |x| x+2;

    apply(display);

    println!("2 Added to 3 is: {}", apply_2(simple));

}<|endoftext|>


<commit_before><commit_msg>Add serialization impl's for `response::Response`<commit_after><|endoftext|>