<commit_before>extern crate puck;
#[macro_use]
extern crate puck_core;
extern crate cgmath;
extern crate rand;

#[macro_use]
extern crate serde_derive;
extern crate serde;

use cgmath::{Zero, InnerSpace, vec3, vec2, Rad};
use std::f64::consts::PI;

use puck_core::{Vec2f, Vec3f, Vec3, Tick, HashMap, TreeMap, Color};
use puck_core::app::{App, Event, SimSettings};

use puck::app::{RenderedApp, RenderSettings};
use puck::{FileResources, RenderTick, Input, Dimensions, Camera};
use puck::audio::{SoundRender, Listener, SoundEvent};
use puck::render::gfx::OpenGLRenderer;
use puck::render::*;

use std::collections::Bound;
use std::collections::Bound::*;

use std::hash::Hash;

#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
pub enum Id {
    Game,
    Player,
    Rock(u64),
    Shot(u64),
}

#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
pub enum ActorKind {
    Player,
    Rock,
    Shot
}

#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
pub enum Entity {
    Game { level: u64, score: u64 },
    Actor(Actor),
}

#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
pub struct Actor {
    pub kind: ActorKind,
    pub pos: Vec2f,
    pub facing: f32,
    pub velocity: Vec2f,
    pub rvel: f32,
    pub bbox_size: f32,
    pub life: f32, // for shots, times alive, for players/rocks hp
    pub thrust: bool,
}

const PLAYER_LIFE: f32 = 1.0;
const SHOT_LIFE: f32 = 2.0;
const ROCK_LIFE: f32 = 1.0;

const PLAYER_BBOX: f32 = 12.0;
const ROCK_BBOX: f32 = 12.0;
const SHOT_BBOX: f32 = 6.0;

const MAX_ROCK_VEL: f32 = 50.0;

const SHOT_SPEED: f32 = 200.0;
const SHOT_RVEL: f32 = 0.1;
const SPRITE_SIZE: u32 = 32;

// Acceleration in pixels per second, more or less.
const PLAYER_THRUST: f32 = 100.0;
// Rotation in radians per second.
const PLAYER_TURN_RATE: f32 = 3.05;
// Seconds between shots
const PLAYER_SHOT_TIME: f32 = 0.5;

const MAX_PHYSICS_VEL: f32 = 250.0;

#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
pub enum EntityEvent {
    UpdateShipControls { rvel: f32, thrust: bool },
    UpdatePhysics { velocity : Vec2f, facing: f32, position: Vec2f },
    AdjustLife { life: f32 },
    IncreaseLevel,
    IncreaseScore,
}

fn create_player() -> Actor {
    Actor {
        kind: ActorKind::Player,
        pos: Vec2f::zero(),
        facing: 0.,
        velocity: Vec2f::zero(),
        rvel: 0.,
        bbox_size: PLAYER_BBOX,
        life: PLAYER_LIFE,
        thrust: false,
    }
}

fn create_rock() -> Actor {
    Actor {
        kind: ActorKind::Rock,
        pos: Vec2f::zero(),
        facing: 0.,
        velocity: Vec2f::zero(),
        rvel: 0.,
        bbox_size: ROCK_BBOX,
        life: ROCK_LIFE,
        thrust: false,
    }
}

fn create_shot() -> Actor {
    Actor {
        kind: ActorKind::Shot,
        pos: Vec2f::zero(),
        facing: 0.,
        velocity: Vec2f::zero(),
        rvel: SHOT_RVEL,
        bbox_size: SHOT_BBOX,
        life: SHOT_LIFE,
        thrust: false,
    }
}

fn random_vec(max_magnitude: f32) -> Vec2f {
    let angle = rand::random::<f32>() * 2.0 * std::f32::consts::PI;
    let mag = rand::random::<f32>() * max_magnitude;
    vec_from_angle(angle) * (mag)
}

fn vec_from_angle(angle: f32) -> Vec2f {
    let vx = angle.sin();
    let vy = angle.cos();
    Vec2f::new(vx, vy)
}

fn create_rocks(num: u64, exclusion: Vec2f, min_radius: f32, max_radius: f32) -> Vec<(Id, Entity)> {
    assert!(max_radius > min_radius);
    let new_rock = |n| {
        let mut rock = create_rock();
        let r_angle = rand::random::<f32>() * 2.0 * std::f32::consts::PI;
        let r_distance = rand::random::<f32>() * (max_radius - min_radius) + min_radius;
        rock.pos = exclusion + vec_from_angle(r_angle) * r_distance;
        rock.velocity = random_vec(MAX_ROCK_VEL);
        (Id::Rock(n), Entity::Actor(rock))
    };
    (0..num).map(new_rock).collect()
}

fn wrapped_position(pos:Vec2f, wrap_x:f32, wrap_y:f32) -> Vec2f {
    let mut wrapped_pos = pos;

    if pos.x > wrap_x {
        wrapped_pos.x -= wrap_x;
    } else if pos.x < 0. {
        wrapped_pos.x += wrap_x;
    };
    if pos.y > wrap_y {
        wrapped_pos.y -= wrap_y;
    } else if pos.y < 0. {
        wrapped_pos.y += wrap_y;
    }
    wrapped_pos
}

fn update_physics(actor:&Actor, time:f32, wrap_x:f32, wrap_y: f32) -> EntityEvent {
    // Clamp the velocity to the max efficiently

    let norm = actor.velocity.magnitude();
    let vel = if norm > MAX_PHYSICS_VEL {
        actor.velocity / norm * MAX_PHYSICS_VEL
    } else {
        actor.velocity
    };

    let accel = if actor.thrust {
        let v = vec_from_angle(-actor.facing + PI as f32);
        v * PLAYER_THRUST
    } else {
        vec2(0., 0.)
    };

    EntityEvent::UpdatePhysics {
        velocity : vel + accel * time,
        facing: actor.facing + actor.rvel * time,
        position: wrapped_position(actor.pos + actor.velocity * time, wrap_x, wrap_y),
    }
}

pub fn main() {
    println!("astroblasto");
    let file_resources = FileResources::default_relative();
    let sim_settings = SimSettings { tick_rate: 60 };
    let render_settings = RenderSettings { dimensions: (640, 480), vsync: false, title: "Astroblasto!".into() };

    let init_state = treemap![Id::Game => Entity::Game { level: 0, score: 0 }];

    let run_result = puck::app::runner::run::<AstroApp>(file_resources, sim_settings, render_settings, Vec::new(), init_state);
}

struct AstroApp();

pub type IdRange = (Bound<Id>, Bound<Id>);

pub const ALL_ROCKS : IdRange = (Included(Id::Rock(0)), Included(Id::Rock(100)));
pub const ALL_SHOTS : IdRange = (Included(Id::Shot(0)), Included(Id::Shot(100)));

pub fn no_events<A, B>() -> (Vec<A>, Vec<B>) {
    (Vec::new(), Vec::new())
}

//struct RenderState {
//    pub sound_events: Vec<SoundEvent>,
//
//}

impl App for AstroApp {
    type Id = Id;
    type Entity = Entity; // do we need Eq?
    type EntityEvent = EntityEvent;
    type RenderEvent = SoundEvent;

    fn handle_entity_event(event:&Self::EntityEvent, id: &Self::Id, entity: &mut Self::Entity) -> Vec<Event<Self::Id, Self::Entity, Self::EntityEvent, Self::RenderEvent>> {
        use Entity::*;
        use EntityEvent::*;

        match (event, entity) {
            (&IncreaseLevel, &mut Game { mut level, .. }) => { level += 1; vec![] },
            (&IncreaseScore, &mut Game { mut score, ..}) => { score += 1; vec![] },
            (&UpdateShipControls { rvel, thrust }, &mut Actor(ref mut actor)) => {
                actor.rvel = rvel;
                actor.thrust = thrust;
                vec![]
            }
            (&UpdatePhysics { velocity, facing, position }, &mut Actor(ref mut actor)) => {
                actor.velocity = velocity;
                actor.facing = facing;
                actor.pos = position;
                vec![]
            }
            (&AdjustLife { life }, &mut Actor(ref mut actor)) => {
                actor.life = life;
                vec![]
            },
            (ev, ent) => {
                println!("uhhh, dont recognize {:?} with {:?}", ev, ent);
                vec![]
            },
        }
    }

    fn simulate(time:Tick, entities:&TreeMap<Self::Id, Self::Entity>, id: &Self::Id, entity: &Self::Entity) -> (Vec<Self::EntityEvent>, Vec<Event<Self::Id, Self::Entity, Self::EntityEvent, Self::RenderEvent>>) {
        use puck_core::app::Event::*;
        use Entity::*;
        use EntityEvent::*;
        match entity {
            &Game { score, level } => {
                if let Some(&Entity::Actor(player)) = entities.get(&Id::Player) {
                    let rock_count = entities.range(ALL_ROCKS).count();
                    if rock_count == 0 {
                        let spawn_rocks = create_rocks(level + 6, player.pos, 100.0, 250.0).into_iter().map(|(id, entity)| {
                            Event::SpawnEvent(id, entity)
                        }).collect();
                        (vec![IncreaseLevel], spawn_rocks)
                    } else {
                        no_events()
                    }
                } else {
                    // no player
                    (vec![], vec![SpawnEvent(Id::Player, Entity::Actor(create_player()))])
                }
            },
            &Actor(ref actor) => {
//                println!("simulate -> {:?} for {:?}", actor, time.tick_duration);

                (vec![update_physics(actor, time.tick_duration as f32, 640.0, 480.0)], vec![] )
            },
        }
    }
}

impl RenderedApp for AstroApp {
    type RenderState = Vec<SoundEvent>;

    fn handle_input(input:&Input, dimensions: &Dimensions, entities: &TreeMap<Self::Id, Self::Entity>) -> Vec<Event<Self::Id, Self::Entity, Self::EntityEvent, Self::RenderEvent>> {

        if let Some(&Entity::Actor(actor)) = entities.get(&Id::Player) {
           let rvel = if input.keys.down.contains(&puck::input::VirtualKeyCode::A) {
               -PLAYER_TURN_RATE
           } else if input.keys.down.contains(&puck::input::VirtualKeyCode::D) {
                PLAYER_TURN_RATE
           } else {
               0.0
           };
           let thrust = input.keys.down.contains(&puck::input::VirtualKeyCode::W);
           vec![Event::EntityEvent(Id::Player, EntityEvent::UpdateShipControls { rvel, thrust})]
        } else {
           vec![]
        }
    }

    fn handle_render_event(event: &Self::RenderEvent, render_state: &mut Self::RenderState) {
        render_state.push(event.clone());
    }

    fn render(time: RenderTick, dimensions: &Dimensions, entities:&TreeMap<Self::Id, Self::Entity>, render_state: &mut Self::RenderState, renderer: &mut OpenGLRenderer) -> SoundRender {
        use Entity::*;
        use ActorKind::*;

        renderer.clear_depth_and_color(Color::BLACK);

        let tesselator = GeometryTesselator::new(Vec3::new(1.0, 1.0, 1.0));
        let mut verticies = Vec::new();

        let atlas = TextureAtlas {
            texture_size: 512,
            tile_size: 32,
        };
        let rock = atlas.at(0, 0);
        let shot = atlas.at(1, 0);
        let player = atlas.at(2, 0);

        for (id, e) in entities {
            match e {
                &Game { level, score } => {

                },
                &Actor(actor) => {
                    let tex = match actor.kind {
                        Shot => shot,
                        Player => player,
                        Rock => rock,
                    };

                    tesselator.draw_floor_centre_anchored_rotated_at(&mut verticies, &tex, vec3(actor.pos.x as f64, 0.0, actor.pos.y as f64), actor.facing as f64, 0.0);
                },
            }
        }

        let (w, h) = dimensions.points;
        let camera = Camera {
            at: vec3(w as f64 / 2.0, 0., h as f64 / 2.0),
            pitch: Rad(PI / 4.0_f64),
            viewport: *dimensions,
            points_per_unit: 1.0,
            near_far: (-1000., 1000.),
        };

        renderer.draw_vertices(&verticies, Uniforms {
            transform : camera.view_projection(),
            color: Color::WHITE,
        }, Blend::None).expect("the ability to draw");
        renderer.finish_frame().expect("finished frame");

        let out = render_state.split_off(0);
        SoundRender::non_positional_effects(Vec::new())
    }
}

<commit_msg>Puckin<commit_after>extern crate puck;
#[macro_use]
extern crate puck_core;
extern crate cgmath;
extern crate rand;

#[macro_use]
extern crate serde_derive;
extern crate serde;

use cgmath::{Zero, InnerSpace, vec3, vec2, Rad};
use std::f64::consts::PI;

use puck_core::{Vec2f, Vec3f, Vec3, Tick, HashMap, TreeMap, Color, clamp};
use puck_core::app::{App, Event, SimSettings};

use puck::app::{RenderedApp, RenderSettings};
use puck::{FileResources, RenderTick, Input, Dimensions, Camera};
use puck::audio::{SoundRender, Listener, SoundEvent};
use puck::render::gfx::OpenGLRenderer;
use puck::render::*;

use std::collections::Bound;
use std::collections::Bound::*;

use std::hash::Hash;

#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
pub enum Id {
    Game,
    Player,
    Rock(u64),
    Shot(u64),
}

#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
pub enum ActorKind {
    Player,
    Rock,
    Shot
}

#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
pub enum Entity {
    Game { level: u64, score: u64 },
    Actor(Actor),
}

#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
pub struct Actor {
    pub kind: ActorKind,
    pub pos: Vec2f,
    pub facing: f32,
    pub velocity: Vec2f,
    pub rvel: f32,
    pub bbox_size: f32,
    pub life: f32, // for shots, times alive, for players/rocks hp
    pub thrust: bool,
}

const PLAYER_LIFE: f32 = 1.0;
const SHOT_LIFE: f32 = 2.0;
const ROCK_LIFE: f32 = 1.0;

const PLAYER_BBOX: f32 = 12.0;
const ROCK_BBOX: f32 = 12.0;
const SHOT_BBOX: f32 = 6.0;

const MAX_ROCK_VEL: f32 = 50.0;

const SHOT_SPEED: f32 = 200.0;
const SHOT_RVEL: f32 = 0.1;
const SPRITE_SIZE: u32 = 32;

// Acceleration in pixels per second, more or less.
const PLAYER_THRUST: f32 = 100.0;
// Rotation in radians per second.
const PLAYER_TURN_RATE: f32 = 3.05;
// Seconds between shots
const PLAYER_SHOT_TIME: f32 = 0.5;

const MAX_PHYSICS_VEL: f32 = 250.0;

#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
pub enum EntityEvent {
    UpdateShipControls { rvel: f32, thrust: bool },
    UpdatePhysics { velocity : Vec2f, facing: f32, position: Vec2f },
    SetLife(f32),
    IncreaseLevel,
    IncreaseScore,
}

fn create_player() -> Actor {
    Actor {
        kind: ActorKind::Player,
        pos: Vec2f::zero(),
        facing: 0.,
        velocity: Vec2f::zero(),
        rvel: 0.,
        bbox_size: PLAYER_BBOX,
        life: PLAYER_LIFE,
        thrust: false,
    }
}

fn create_rock() -> Actor {
    Actor {
        kind: ActorKind::Rock,
        pos: Vec2f::zero(),
        facing: 0.,
        velocity: Vec2f::zero(),
        rvel: 0.,
        bbox_size: ROCK_BBOX,
        life: ROCK_LIFE,
        thrust: false,
    }
}

fn create_shot() -> Actor {
    Actor {
        kind: ActorKind::Shot,
        pos: Vec2f::zero(),
        facing: 0.,
        velocity: Vec2f::zero(),
        rvel: SHOT_RVEL,
        bbox_size: SHOT_BBOX,
        life: SHOT_LIFE,
        thrust: false,
    }
}

fn random_vec(max_magnitude: f32) -> Vec2f {
    let angle = rand::random::<f32>() * 2.0 * std::f32::consts::PI;
    let mag = rand::random::<f32>() * max_magnitude;
    vec_from_angle(angle) * (mag)
}

fn vec_from_angle(angle: f32) -> Vec2f {
    let vx = angle.sin();
    let vy = angle.cos();
    Vec2f::new(vx, vy)
}

fn create_rocks(num: u64, exclusion: Vec2f, min_radius: f32, max_radius: f32) -> Vec<(Id, Entity)> {
    assert!(max_radius > min_radius);
    let new_rock = |n| {
        let mut rock = create_rock();
        let r_angle = rand::random::<f32>() * 2.0 * std::f32::consts::PI;
        let r_distance = rand::random::<f32>() * (max_radius - min_radius) + min_radius;
        rock.pos = exclusion + vec_from_angle(r_angle) * r_distance;
        rock.velocity = random_vec(MAX_ROCK_VEL);
        (Id::Rock(n), Entity::Actor(rock))
    };
    (0..num).map(new_rock).collect()
}

fn wrapped_position(pos:Vec2f, wrap_x:f32, wrap_y:f32) -> Vec2f {
    let mut wrapped_pos = pos;

    if pos.x > wrap_x {
        wrapped_pos.x -= wrap_x;
    } else if pos.x < 0. {
        wrapped_pos.x += wrap_x;
    };
    if pos.y > wrap_y {
        wrapped_pos.y -= wrap_y;
    } else if pos.y < 0. {
        wrapped_pos.y += wrap_y;
    }
    wrapped_pos
}

fn update_life(actor:&Actor, time:f32) -> EntityEvent {
    let new_life = if actor.life > 0.0 {
        clamp(actor.life - time, 0.0, 1000.0)
    } else {
        actor.life
    };
    EntityEvent::SetLife(actor.life)
}

fn update_physics(actor:&Actor, time:f32, wrap_x:f32, wrap_y: f32) -> EntityEvent {
    // Clamp the velocity to the max efficiently

    let norm = actor.velocity.magnitude();
    let vel = if norm > MAX_PHYSICS_VEL {
        actor.velocity / norm * MAX_PHYSICS_VEL
    } else {
        actor.velocity
    };

    let accel = if actor.thrust {
        let v = vec_from_angle(-actor.facing + PI as f32);
        v * PLAYER_THRUST
    } else {
        vec2(0., 0.)
    };

    EntityEvent::UpdatePhysics {
        velocity : vel + accel * time,
        facing: actor.facing + actor.rvel * time,
        position: wrapped_position(actor.pos + actor.velocity * time, wrap_x, wrap_y),
    }
}

pub fn main() {
    println!("astroblasto");
    let file_resources = FileResources::default_relative();
    let sim_settings = SimSettings { tick_rate: 60 };
    let render_settings = RenderSettings { dimensions: (640, 480), vsync: false, title: "Astroblasto!".into() };

    let init_state = treemap![Id::Game => Entity::Game { level: 0, score: 0 }];

    let run_result = puck::app::runner::run::<AstroApp>(file_resources, sim_settings, render_settings, Vec::new(), init_state);
}

struct AstroApp();

pub type IdRange = (Bound<Id>, Bound<Id>);

pub const ALL_ROCKS : IdRange = (Included(Id::Rock(0)), Included(Id::Rock(100)));
pub const ALL_SHOTS : IdRange = (Included(Id::Shot(0)), Included(Id::Shot(100)));

pub fn no_events<A, B>() -> (Vec<A>, Vec<B>) {
    (Vec::new(), Vec::new())
}

//struct RenderState {
//    pub sound_events: Vec<SoundEvent>,
//
//}

impl App for AstroApp {
    type Id = Id;
    type Entity = Entity; // do we need Eq?
    type EntityEvent = EntityEvent;
    type RenderEvent = SoundEvent;

    fn handle_entity_event(event:&Self::EntityEvent, id: &Self::Id, entity: &mut Self::Entity) -> Vec<Event<Self::Id, Self::Entity, Self::EntityEvent, Self::RenderEvent>> {
        use Entity::*;
        use EntityEvent::*;

        match (event, entity) {
            (&IncreaseLevel, &mut Game { mut level, .. }) => { level += 1; vec![] },
            (&IncreaseScore, &mut Game { mut score, ..}) => { score += 1; vec![] },
            (&UpdateShipControls { rvel, thrust }, &mut Actor(ref mut actor)) => {
                actor.rvel = rvel;
                actor.thrust = thrust;
                vec![]
            }
            (&UpdatePhysics { velocity, facing, position }, &mut Actor(ref mut actor)) => {
                actor.velocity = velocity;
                actor.facing = facing;
                actor.pos = position;
                vec![]
            }
            (&SetLife(life), &mut Actor(ref mut actor)) => {
                actor.life = life;
                vec![]
            },
            (ev, ent) => {
                println!("uhhh, dont recognize {:?} with {:?}", ev, ent);
                vec![]
            },
        }
    }

    fn simulate(time:Tick, entities:&TreeMap<Self::Id, Self::Entity>, id: &Self::Id, entity: &Self::Entity) -> (Vec<Self::EntityEvent>, Vec<Event<Self::Id, Self::Entity, Self::EntityEvent, Self::RenderEvent>>) {
        use puck_core::app::Event::*;
        use Entity::*;
        use EntityEvent::*;
        use ActorKind::*;
        match entity {
            &Game { level, .. } => {
                if let Some(&Entity::Actor(player)) = entities.get(&Id::Player) {
                    let rock_count = entities.range(ALL_ROCKS).count();
                    if rock_count == 0 {
                        let spawn_rocks = create_rocks(level + 6, player.pos, 100.0, 250.0).into_iter().map(|(id, entity)| {
                            Event::SpawnEvent(id, entity)
                        }).collect();
                        (vec![IncreaseLevel], spawn_rocks)
                    } else {
                        no_events()
                    }
                } else {
                    // no player
                    (vec![], vec![SpawnEvent(Id::Player, Entity::Actor(create_player()))])
                }
            },
            &Actor(ref actor) => {
                let physics = update_physics(actor, time.tick_duration as f32, 640.0, 480.0);
//                println!("simulate -> {:?} for {:?}", actor, time.tick_duration);
                match actor.kind {
                    Player => (vec![physics, update_life(actor, time.tick_duration as f32)], vec![]),
                    Rock => (vec![physics], vec![]),
                    Shot => (vec![physics, update_life(actor, time.tick_duration as f32)], vec![]),
                }
            },
        }
    }
}

impl RenderedApp for AstroApp {
    type RenderState = Vec<SoundEvent>;

    fn handle_input(input:&Input, dimensions: &Dimensions, entities: &TreeMap<Self::Id, Self::Entity>) -> Vec<Event<Self::Id, Self::Entity, Self::EntityEvent, Self::RenderEvent>> {

        if let Some(&Entity::Actor(actor)) = entities.get(&Id::Player) {
           let rvel = if input.keys.down.contains(&puck::input::VirtualKeyCode::A) {
               -PLAYER_TURN_RATE
           } else if input.keys.down.contains(&puck::input::VirtualKeyCode::D) {
                PLAYER_TURN_RATE
           } else {
               0.0
           };
           let thrust = input.keys.down.contains(&puck::input::VirtualKeyCode::W);
           vec![Event::EntityEvent(Id::Player, EntityEvent::UpdateShipControls { rvel, thrust})]
        } else {
           vec![]
        }
    }

    fn handle_render_event(event: &Self::RenderEvent, render_state: &mut Self::RenderState) {
        render_state.push(event.clone());
    }

    fn render(time: RenderTick, dimensions: &Dimensions, entities:&TreeMap<Self::Id, Self::Entity>, render_state: &mut Self::RenderState, renderer: &mut OpenGLRenderer) -> SoundRender {
        use Entity::*;
        use ActorKind::*;

        renderer.clear_depth_and_color(Color::BLACK);

        let tesselator = GeometryTesselator::new(Vec3::new(1.0, 1.0, 1.0));
        let mut verticies = Vec::new();

        let atlas = TextureAtlas {
            texture_size: 512,
            tile_size: 32,
        };
        let rock = atlas.at(0, 0);
        let shot = atlas.at(1, 0);
        let player = atlas.at(2, 0);

        for (id, e) in entities {
            match e {
                &Game { level, score } => {

                },
                &Actor(actor) => {
                    let tex = match actor.kind {
                        Shot => shot,
                        Player => player,
                        Rock => rock,
                    };

                    tesselator.draw_floor_centre_anchored_rotated_at(&mut verticies, &tex, vec3(actor.pos.x as f64, 0.0, actor.pos.y as f64), actor.facing as f64, 0.0);
                },
            }
        }

        let (w, h) = dimensions.points;
        let camera = Camera {
            at: vec3(w as f64 / 2.0, 0., h as f64 / 2.0),
            pitch: Rad(PI / 4.0_f64),
            viewport: *dimensions,
            points_per_unit: 1.0,
            near_far: (-1000., 1000.),
        };

        renderer.draw_vertices(&verticies, Uniforms {
            transform : camera.view_projection(),
            color: Color::WHITE,
        }, Blend::None).expect("the ability to draw");
        renderer.finish_frame().expect("finished frame");

        let out = render_state.split_off(0);
        SoundRender::non_positional_effects(Vec::new())
    }
}

<|endoftext|>


<commit_before>fn kth<'a, T>(k:uint, list: &'a ~[T]) -> Option<&'a T> {
    if list.len() >= k && k > 0{
        Some(&list[k-1])
    } else {
        None
    }
}

fn main() {
    let list = ~['a', 'b', 'c', 'd', 'e'];
    println!("{:?}", kth(3, &list));

    let list = ~['a'];
    println!("{:?}", kth(3, &list));
}
<commit_msg>Clean up Problem 03<commit_after>fn kth<'a, T>(k:uint, list: &'a [T]) -> Option<&'a T> {
    if list.len() >= k && k > 0{
        Some(&list[k-1])
    } else {
        None
    }
}

fn main() {
    let list = ~['a', 'b', 'c', 'd', 'e'];
    println!("{:?}", kth(3, list));

    let list = ~['a'];
    println!("{:?}", kth(3, list));
}
<|endoftext|>


<commit_before>use futures::sync::mpsc::UnboundedSender;

use super::inputs::Input;
use super::token::Token;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum TokenDestination {
    Stream,
    Queue,
    Ignore
}

/// A `struct` which contains the complete state of a `Parser`.
pub struct ParserState<'a, Rule> {
    input:     &'a Input,
    pos:       usize,
    sender:    UnboundedSender<Token<Rule>>,
    queue:     Vec<Token<Rule>>,
    dest:      TokenDestination,
    is_atomic: bool
}

impl<'a, Rule> ParserState<'a, Rule> {
    /// Creates a new `ParserState` from an `Input` and an `UnboundedSender`.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate futures;
    /// # extern crate pest;
    /// # use futures::sync::mpsc::unbounded;
    /// # use pest::{ParserState, StringInput, Token};
    /// # fn main() {
    /// let (s, _) = unbounded::<Token<()>>();
    /// let input = StringInput::new("a");
    ///
    /// let state = ParserState::new(&input, s);
    /// # }
    /// ```
    pub fn new(input: &'a Input, sender: UnboundedSender<Token<Rule>>) -> ParserState<'a, Rule> {
        ParserState {
            input:     input,
            pos:       0,
            sender:    sender,
            queue:     vec![],
            dest:      TokenDestination::Stream,
            is_atomic: false
        }
    }

    /// Sends `token` according to the state's destination. The `Token` will get sent to the
    /// `TokenStream`, queued up to be sent later, or ignored.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # extern crate futures;
    /// # extern crate pest;
    /// # use futures::sync::mpsc::unbounded;
    /// # use pest::{ParserState, StringInput, Token};
    /// # fn main() {
    /// let (s, _) = unbounded::<Token<()>>();
    /// let input = StringInput::new("");
    /// let mut state = ParserState::new(&input, s);
    ///
    /// state.send(Token::Start((), 0));
    /// # }
    /// ```
    #[inline]
    pub fn send(&mut self, token: Token<Rule>) {
        match self.dest {
            TokenDestination::Stream => self.sender.send(token).unwrap(),
            TokenDestination::Queue  => self.queue.push(token),
            TokenDestination::Ignore => ()
        };
    }

    /// Matches `string`, returns whether it matched, and advances the position with `string.len()`
    /// in case it did.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate futures;
    /// # extern crate pest;
    /// # use futures::sync::mpsc::unbounded;
    /// # use pest::{ParserState, StringInput, Token};
    /// # fn main() {
    /// let (s, _) = unbounded::<Token<()>>();
    /// let input = StringInput::new("abcd");
    /// let mut state = ParserState::new(&input, s);
    ///
    /// assert!(state.match_string("ab"));
    /// assert!(state.match_string("cd"));
    /// # }
    /// ```
    #[inline]
    pub fn match_string(&mut self, string: &str) -> bool {
        let result = self.input.match_string(string, self.pos);

        if result {
            self.pos += string.len();
        }

        result
    }

    /// Matches `string` case insensitively, returns whether it matched, and advances the position
    /// with `string.len()` in case it did.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate futures;
    /// # extern crate pest;
    /// # use futures::sync::mpsc::unbounded;
    /// # use pest::{ParserState, StringInput, Token};
    /// # fn main() {
    /// let (s, _) = unbounded::<Token<()>>();
    /// let input = StringInput::new("AbcD");
    /// let mut state = ParserState::new(&input, s);
    ///
    /// assert!(state.match_insensitive("ab"));
    /// assert!(state.match_insensitive("cd"));
    /// # }
    /// ```
    #[inline]
    pub fn match_insensitive(&mut self, string: &str) -> bool {
        let result = self.input.match_insensitive(string, self.pos);

        if result {
            self.pos += string.len();
        }

        result
    }

    /// Matches if the current `char` is between `left` and `right`, and advances the position with
    /// one `char` length in case it did.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate futures;
    /// # extern crate pest;
    /// # use futures::sync::mpsc::unbounded;
    /// # use pest::{ParserState, StringInput, Token};
    /// # fn main() {
    /// let (s, _) = unbounded::<Token<()>>();
    /// let input = StringInput::new("Cd");
    /// let mut state = ParserState::new(&input, s);
    ///
    /// assert!(state.match_range('A', 'Z'));
    /// assert!(state.match_range('a', 'z'));
    /// # }
    /// ```
    #[inline]
    pub fn match_range(&mut self, left: char, right: char) -> bool {
        let result = self.input.match_range(left, right, self.pos);

        if result {
            self.pos += left.len_utf8();
        }

        result
    }

    /// Matches the current `rule`, queues up all generated `Token`s, and reverts the state if the
    /// `rule` fails.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate futures;
    /// # extern crate pest;
    /// # use futures::sync::mpsc::unbounded;
    /// # use pest::{ParserState, StringInput, Token};
    /// # fn main() {
    /// let (s, _) = unbounded::<Token<()>>();
    /// let input = StringInput::new("abacad");
    /// let mut state = ParserState::new(&input, s);
    ///
    /// assert!(state.queued(|state| {
    ///     state.match_string("a") && state.match_string("b")
    /// }));
    /// assert!(state.queued(|state| {
    ///     state.match_string("a") && state.match_string("c")
    /// }));
    /// assert!(!state.queued(|state| {
    ///     state.match_string("a") && state.match_string("c")
    /// }));
    /// # }
    /// ```
    #[inline]
    pub fn queued<F>(&mut self, rule: F) -> bool
        where F: FnOnce(&mut ParserState<'a, Rule>) -> bool {

        let initial_pos = self.pos;
        let should_toggle = self.dest == TokenDestination::Stream;

        if should_toggle {
            self.dest = TokenDestination::Queue;
        }

        let result = rule(self);

        if should_toggle {
            self.dest = TokenDestination::Stream;

            if result {
                for token in self.queue.drain(..) {
                    self.sender.send(token).unwrap();
                }
            } else {
                self.queue.clear();
            }
        }

        if !result {
            self.pos = initial_pos;
        }

        result
    }

    /// Matches the current `rule`, ignores all `Token`s, and reverts the state.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate futures;
    /// # extern crate pest;
    /// # use futures::sync::mpsc::unbounded;
    /// # use pest::{ParserState, StringInput, Token};
    /// # fn main() {
    /// let (s, _) = unbounded::<Token<()>>();
    /// let input = StringInput::new("ab");
    /// let mut state = ParserState::new(&input, s);
    ///
    /// assert!(state.ignored(|state| {
    ///     state.send(Token::Start((), 0));
    ///     state.match_string("a") && state.match_string("b")
    /// }));
    /// assert!(state.ignored(|state| {
    ///     state.send(Token::Start((), 0));
    ///     state.match_string("a") && state.match_string("b")
    /// }));
    /// assert!(!state.ignored(|state| {
    ///     state.send(Token::Start((), 0));
    ///     state.match_string("a") && state.match_string("c")
    /// }));
    /// # }
    /// ```
    #[inline]
    pub fn ignored<F>(&mut self, rule: F) -> bool
        where F: FnOnce(&mut ParserState<'a, Rule>) -> bool {

        let initial_pos = self.pos;
        let should_toggle = self.dest != TokenDestination::Ignore;
        let initial_dest = self.dest;

        if should_toggle {
            self.dest = TokenDestination::Ignore;
        }

        let result = rule(self);

        if should_toggle {
            self.dest = initial_dest;
        }

        self.pos = initial_pos;

        result
    }
}
<commit_msg>Added atomics and attempts.<commit_after>use futures::sync::mpsc::UnboundedSender;

use super::inputs::Input;
use super::token::Token;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum TokenDestination {
    Stream,
    Queue,
    Ignore
}

/// A `struct` which contains the complete state of a `Parser`.
pub struct ParserState<'a, Rule> {
    input:       &'a Input,
    pos:         usize,
    sender:      UnboundedSender<Token<Rule>>,
    queue:       Vec<Token<Rule>>,
    dest:        TokenDestination,
    is_atomic:   bool,
    attempts:    Vec<Rule>,
    attempt_pos: usize
}

impl<'a, Rule: Clone + Ord> ParserState<'a, Rule> {
    /// Creates a new `ParserState` from an `Input` and an `UnboundedSender`.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate futures;
    /// # extern crate pest;
    /// # use futures::sync::mpsc::unbounded;
    /// # use pest::{ParserState, StringInput, Token};
    /// # fn main() {
    /// let (s, _) = unbounded::<Token<()>>();
    /// let input = StringInput::new("a");
    ///
    /// let state = ParserState::new(&input, s);
    /// # }
    /// ```
    pub fn new(input: &'a Input, sender: UnboundedSender<Token<Rule>>) -> ParserState<'a, Rule> {
        ParserState {
            input:       input,
            pos:         0,
            sender:      sender,
            queue:       vec![],
            dest:        TokenDestination::Stream,
            is_atomic:   false,
            attempts:    vec![],
            attempt_pos: 0
        }
    }

    /// Sends `token` according to the state's destination. The `Token` will get sent to the
    /// `TokenStream`, queued up to be sent later, or ignored.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # extern crate futures;
    /// # extern crate pest;
    /// # use futures::sync::mpsc::unbounded;
    /// # use pest::{ParserState, StringInput, Token};
    /// # fn main() {
    /// let (s, _) = unbounded::<Token<()>>();
    /// let input = StringInput::new("");
    /// let mut state = ParserState::new(&input, s);
    ///
    /// state.send(Token::Start((), 0));
    /// # }
    /// ```
    #[inline]
    pub fn send(&mut self, token: Token<Rule>) {
        match self.dest {
            TokenDestination::Stream => self.sender.send(token).unwrap(),
            TokenDestination::Queue  => self.queue.push(token),
            TokenDestination::Ignore => ()
        };
    }

    /// Matches `string`, returns whether it matched, and advances the position with `string.len()`
    /// in case it did.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate futures;
    /// # extern crate pest;
    /// # use futures::sync::mpsc::unbounded;
    /// # use pest::{ParserState, StringInput, Token};
    /// # fn main() {
    /// let (s, _) = unbounded::<Token<()>>();
    /// let input = StringInput::new("abcd");
    /// let mut state = ParserState::new(&input, s);
    ///
    /// assert!(state.match_string("ab"));
    /// assert!(state.match_string("cd"));
    /// # }
    /// ```
    #[inline]
    pub fn match_string(&mut self, string: &str) -> bool {
        let result = self.input.match_string(string, self.pos);

        if result {
            self.pos += string.len();
        }

        result
    }

    /// Matches `string` case insensitively, returns whether it matched, and advances the position
    /// with `string.len()` in case it did.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate futures;
    /// # extern crate pest;
    /// # use futures::sync::mpsc::unbounded;
    /// # use pest::{ParserState, StringInput, Token};
    /// # fn main() {
    /// let (s, _) = unbounded::<Token<()>>();
    /// let input = StringInput::new("AbcD");
    /// let mut state = ParserState::new(&input, s);
    ///
    /// assert!(state.match_insensitive("ab"));
    /// assert!(state.match_insensitive("cd"));
    /// # }
    /// ```
    #[inline]
    pub fn match_insensitive(&mut self, string: &str) -> bool {
        let result = self.input.match_insensitive(string, self.pos);

        if result {
            self.pos += string.len();
        }

        result
    }

    /// Matches if the current `char` is between `left` and `right`, and advances the position with
    /// one `char` length in case it did.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate futures;
    /// # extern crate pest;
    /// # use futures::sync::mpsc::unbounded;
    /// # use pest::{ParserState, StringInput, Token};
    /// # fn main() {
    /// let (s, _) = unbounded::<Token<()>>();
    /// let input = StringInput::new("Cd");
    /// let mut state = ParserState::new(&input, s);
    ///
    /// assert!(state.match_range('A', 'Z'));
    /// assert!(state.match_range('a', 'z'));
    /// # }
    /// ```
    #[inline]
    pub fn match_range(&mut self, left: char, right: char) -> bool {
        let result = self.input.match_range(left, right, self.pos);

        if result {
            self.pos += left.len_utf8();
        }

        result
    }

    /// Matches the current `rule`, queues up all generated `Token`s, and reverts the state if the
    /// `rule` fails.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate futures;
    /// # extern crate pest;
    /// # use futures::sync::mpsc::unbounded;
    /// # use pest::{ParserState, StringInput, Token};
    /// # fn main() {
    /// let (s, _) = unbounded::<Token<()>>();
    /// let input = StringInput::new("abacad");
    /// let mut state = ParserState::new(&input, s);
    ///
    /// assert!(state.queued(|state| {
    ///     state.match_string("a") && state.match_string("b")
    /// }));
    /// assert!(state.queued(|state| {
    ///     state.match_string("a") && state.match_string("c")
    /// }));
    /// assert!(!state.queued(|state| {
    ///     state.match_string("a") && state.match_string("c")
    /// }));
    /// # }
    /// ```
    #[inline]
    pub fn queued<F>(&mut self, rule: F) -> bool
        where F: FnOnce(&mut ParserState<'a, Rule>) -> bool {

        let initial_pos = self.pos;
        let should_toggle = self.dest == TokenDestination::Stream;

        if should_toggle {
            self.dest = TokenDestination::Queue;
        }

        let result = rule(self);

        if should_toggle {
            self.dest = TokenDestination::Stream;

            if result {
                for token in self.queue.drain(..) {
                    self.sender.send(token).unwrap();
                }
            } else {
                self.queue.clear();
            }
        }

        if !result {
            self.pos = initial_pos;
        }

        result
    }

    /// Matches the current `rule`, ignores all `Token`s, and reverts the state.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate futures;
    /// # extern crate pest;
    /// # use futures::sync::mpsc::unbounded;
    /// # use pest::{ParserState, StringInput, Token};
    /// # fn main() {
    /// let (s, _) = unbounded::<Token<()>>();
    /// let input = StringInput::new("ab");
    /// let mut state = ParserState::new(&input, s);
    ///
    /// assert!(state.ignored(|state| {
    ///     state.send(Token::Start((), 0));
    ///     state.match_string("a") && state.match_string("b")
    /// }));
    /// assert!(state.ignored(|state| {
    ///     state.send(Token::Start((), 0));
    ///     state.match_string("a") && state.match_string("b")
    /// }));
    /// assert!(!state.ignored(|state| {
    ///     state.send(Token::Start((), 0));
    ///     state.match_string("a") && state.match_string("c")
    /// }));
    /// # }
    /// ```
    #[inline]
    pub fn ignored<F>(&mut self, rule: F) -> bool
        where F: FnOnce(&mut ParserState<'a, Rule>) -> bool {

        let initial_pos = self.pos;
        let should_toggle = self.dest != TokenDestination::Ignore;
        let initial_dest = self.dest;

        if should_toggle {
            self.dest = TokenDestination::Ignore;
        }

        let result = rule(self);

        if should_toggle {
            self.dest = initial_dest;
        }

        self.pos = initial_pos;

        result
    }

    /// Matches the current `rule` while toggling atomicity.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate futures;
    /// # extern crate pest;
    /// # use futures::sync::mpsc::unbounded;
    /// # use pest::{ParserState, StringInput, Token};
    /// # fn main() {
    /// let (s, _) = unbounded::<Token<()>>();
    /// let input = StringInput::new("");
    /// let mut state = ParserState::new(&input, s);
    ///
    /// assert!(!state.is_atomic());
    /// state.atomic(true, |state| {
    ///     assert!(state.is_atomic());
    ///     true
    /// });
    /// assert!(!state.is_atomic());
    /// # }
    /// ```
    #[inline]
    pub fn atomic<F>(&mut self, is_atomic: bool, rule: F) -> bool
        where F: FnOnce(&mut ParserState<'a, Rule>) -> bool {

        let should_toggle = self.is_atomic != is_atomic;

        if should_toggle {
            self.is_atomic = is_atomic;
        }

        let result = rule(self);

        if should_toggle {
            self.is_atomic = !is_atomic;
        }

        result
    }

    /// Returns the state's current atomicity.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate futures;
    /// # extern crate pest;
    /// # use futures::sync::mpsc::unbounded;
    /// # use pest::{ParserState, StringInput, Token};
    /// # fn main() {
    /// let (s, _) = unbounded::<Token<()>>();
    /// let input = StringInput::new("");
    /// let mut state = ParserState::new(&input, s);
    ///
    /// assert!(!state.is_atomic());
    /// # }
    /// ```
    #[inline]
    pub fn is_atomic(&self) -> bool {
        self.is_atomic
    }

    /// Keeps track of failed rule attempts. It should be called when a `Rule` fails at current
    /// `pos`.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate futures;
    /// # extern crate pest;
    /// # use futures::sync::mpsc::unbounded;
    /// # use pest::{ParserState, StringInput, Token};
    /// # fn main() {
    /// #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
    /// enum Rule {
    ///     a,
    ///     b
    /// }
    ///
    /// let (s, _) = unbounded::<Token<Rule>>();
    /// let input = StringInput::new("a");
    /// let mut state = ParserState::new(&input, s);
    ///
    /// state.track(Rule::a);
    /// assert_eq!(state.attempts(), (vec![Rule::a], 0));
    ///
    /// state.match_string("a");
    ///
    /// state.track(Rule::b);
    /// assert_eq!(state.attempts(), (vec![Rule::b], 1));
    /// # }
    /// ```
    #[inline]
    pub fn track(&mut self, rule: Rule) {
        if self.is_atomic || self.dest == TokenDestination::Ignore {
            return
        }

        if self.attempts.is_empty() {
            self.attempts.push(rule);

            self.attempt_pos = self.pos;
        } else {
            if self.pos == self.attempt_pos {
                self.attempts.push(rule);
            } else if self.pos > self.attempt_pos {
                self.attempts.clear();
                self.attempts.push(rule);

                self.attempt_pos = self.pos;
            }
        }
    }

    /// Returns a `Vec` of all attempted `Rule`s at the deepest position where the parsing last
    /// stopped. It only returns leaves from the rule tree.
    ///
    /// It is commonly used for error reporting and debugging grammars.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate futures;
    /// # extern crate pest;
    /// # use futures::sync::mpsc::unbounded;
    /// # use pest::{ParserState, StringInput, Token};
    /// # fn main() {
    /// let (s, _) = unbounded::<Token<()>>();
    /// let input = StringInput::new("");
    /// let mut state = ParserState::new(&input, s);
    ///
    /// state.track(());
    /// assert_eq!(state.attempts(), (vec![()], 0));
    /// # }
    /// ```
    #[inline]
    pub fn attempts(&mut self) -> (Vec<Rule>, usize) {
        self.attempts.sort();
        self.attempts.dedup();

        (self.attempts.iter().cloned().collect(), self.attempt_pos)
    }
}
<|endoftext|>


<commit_before>fn complex_number_multiply<'a>(x: &'a str, y: &'a str) -> String {}

fn main() {}
<commit_msg>a bit<commit_after>fn complex_number_multiply<'a>(x: &'a str, y: &'a str) -> String {
    let mut x_temp: Vec<&str> = x.split('+').collect();
    let mut y_temp: Vec<&str> = y.split('+').collect();

    println!("{:?}", x_temp);
    println!("{:?}", y_temp);
    println!("{:?}", y_temp[1].as_bytes()[1]);

    let ins = x_temp[0].parse::<u32>().unwrap() * y_temp[0].parse::<u32>().unwrap();
    //let com = y_temp
    println!("{:?}", ins);

    return String::from("aa");
}

fn main() {
    complex_number_multiply("2+1i", "3+1i");
}
<|endoftext|>


<commit_before>use crate::{CompileError, Config, Syntax};

use std::path::PathBuf;
use std::str::FromStr;

use quote::ToTokens;

pub struct TemplateInput<'a> {
    pub ast: &'a syn::DeriveInput,
    pub config: &'a Config<'a>,
    pub syntax: &'a Syntax<'a>,
    pub source: Source,
    pub print: Print,
    pub escaper: &'a str,
    pub ext: Option<String>,
    pub parent: Option<&'a syn::Type>,
    pub path: PathBuf,
}

impl<'a> TemplateInput<'a> {
    /// Extract the template metadata from the `DeriveInput` structure. This
    /// mostly recovers the data for the `TemplateInput` fields from the
    /// `template()` attribute list fields; it also finds the of the `_parent`
    /// field, if any.
    pub fn new<'n>(
        ast: &'n syn::DeriveInput,
        config: &'n Config,
    ) -> Result<TemplateInput<'n>, CompileError> {
        // Check that an attribute called `template()` exists and that it is
        // the proper type (list).
        let meta = ast
            .attrs
            .iter()
            .find_map(|attr| match attr.parse_meta() {
                Ok(m) => {
                    if m.path().is_ident("template") {
                        Some(Ok(m))
                    } else {
                        None
                    }
                }
                Err(e) => Some(Err(format!("unable to parse attribute: {}", e).into())),
            })
            .unwrap_or(Err(CompileError::Static("no attribute 'template' found")))?;

        let meta_list = match meta {
            syn::Meta::List(inner) => inner,
            _ => return Err("attribute 'template' has incorrect type".into()),
        };

        // Loop over the meta attributes and find everything that we
        // understand. Raise panics if something is not right.
        // `source` contains an enum that can represent `path` or `source`.
        let mut source = None;
        let mut print = Print::None;
        let mut escaping = None;
        let mut ext = None;
        let mut syntax = None;
        for item in meta_list.nested {
            let pair = match item {
                syn::NestedMeta::Meta(syn::Meta::NameValue(ref pair)) => pair,
                _ => {
                    return Err(format!(
                        "unsupported attribute argument {:?}",
                        item.to_token_stream()
                    )
                    .into())
                }
            };

            if pair.path.is_ident("path") {
                if let syn::Lit::Str(ref s) = pair.lit {
                    if source.is_some() {
                        return Err("must specify 'source' or 'path', not both".into());
                    }
                    source = Some(Source::Path(s.value()));
                } else {
                    return Err("template path must be string literal".into());
                }
            } else if pair.path.is_ident("source") {
                if let syn::Lit::Str(ref s) = pair.lit {
                    if source.is_some() {
                        return Err("must specify 'source' or 'path', not both".into());
                    }
                    source = Some(Source::Source(s.value()));
                } else {
                    return Err("template source must be string literal".into());
                }
            } else if pair.path.is_ident("print") {
                if let syn::Lit::Str(ref s) = pair.lit {
                    print = s.value().parse()?;
                } else {
                    return Err("print value must be string literal".into());
                }
            } else if pair.path.is_ident("escape") {
                if let syn::Lit::Str(ref s) = pair.lit {
                    escaping = Some(s.value());
                } else {
                    return Err("escape value must be string literal".into());
                }
            } else if pair.path.is_ident("ext") {
                if let syn::Lit::Str(ref s) = pair.lit {
                    ext = Some(s.value());
                } else {
                    return Err("ext value must be string literal".into());
                }
            } else if pair.path.is_ident("syntax") {
                if let syn::Lit::Str(ref s) = pair.lit {
                    syntax = Some(s.value())
                } else {
                    return Err("syntax value must be string literal".into());
                }
            } else {
                return Err(format!(
                    "unsupported attribute key '{}' found",
                    pair.path.to_token_stream()
                )
                .into());
            }
        }

        // Validate the `source` and `ext` value together, since they are
        // related. In case `source` was used instead of `path`, the value
        // of `ext` is merged into a synthetic `path` value here.
        let source = source.expect("template path or source not found in attributes");
        let path = match (&source, &ext) {
            (&Source::Path(ref path), None) => config.find_template(path, None)?,
            (&Source::Source(_), Some(ext)) => PathBuf::from(format!("{}.{}", ast.ident, ext)),
            (&Source::Path(_), Some(_)) => {
                return Err("'ext' attribute cannot be used with 'path' attribute".into())
            }
            (&Source::Source(_), None) => {
                return Err("must include 'ext' attribute when using 'source' attribute".into())
            }
        };

        // Check to see if a `_parent` field was defined on the context
        // struct, and store the type for it for use in the code generator.
        let parent = match ast.data {
            syn::Data::Struct(syn::DataStruct {
                fields: syn::Fields::Named(ref fields),
                ..
            }) => fields
                .named
                .iter()
                .find(|f| f.ident.as_ref().filter(|name| *name == "_parent").is_some())
                .map(|f| &f.ty),
            _ => None,
        };

        if parent.is_some() {
            eprint!(
                "   --> in struct {}\n   = use of deprecated field '_parent'\n",
                ast.ident
            );
        }

        // Validate syntax
        let syntax = syntax.map_or_else(
            || Ok(config.syntaxes.get(config.default_syntax).unwrap()),
            |s| {
                config.syntaxes.get(&s).ok_or_else(|| {
                    CompileError::String(format!("attribute syntax {} not exist", s))
                })
            },
        )?;

        // Match extension against defined output formats

        let extension = escaping.unwrap_or_else(|| {
            path.extension()
                .map(|s| s.to_str().unwrap())
                .unwrap_or("")
                .to_string()
        });

        let mut escaper = None;
        for (extensions, path) in &config.escapers {
            if extensions.contains(&extension) {
                escaper = Some(path);
                break;
            }
        }

        let escaper = escaper.ok_or_else(|| {
            CompileError::String(format!("no escaper defined for extension '{}'", extension,))
        })?;

        Ok(TemplateInput {
            ast,
            config,
            source,
            print,
            escaper,
            ext,
            parent,
            path,
            syntax,
        })
    }
}

pub enum Source {
    Path(String),
    Source(String),
}

#[derive(PartialEq)]
pub enum Print {
    All,
    Ast,
    Code,
    None,
}

impl FromStr for Print {
    type Err = CompileError;

    fn from_str(s: &str) -> Result<Print, Self::Err> {
        use self::Print::*;
        Ok(match s {
            "all" => All,
            "ast" => Ast,
            "code" => Code,
            "none" => None,
            v => return Err(format!("invalid value for print option: {}", v,).into()),
        })
    }
}
<commit_msg>Fix style suggestion per nightly clippy<commit_after>use crate::{CompileError, Config, Syntax};

use std::path::PathBuf;
use std::str::FromStr;

use quote::ToTokens;

pub struct TemplateInput<'a> {
    pub ast: &'a syn::DeriveInput,
    pub config: &'a Config<'a>,
    pub syntax: &'a Syntax<'a>,
    pub source: Source,
    pub print: Print,
    pub escaper: &'a str,
    pub ext: Option<String>,
    pub parent: Option<&'a syn::Type>,
    pub path: PathBuf,
}

impl<'a> TemplateInput<'a> {
    /// Extract the template metadata from the `DeriveInput` structure. This
    /// mostly recovers the data for the `TemplateInput` fields from the
    /// `template()` attribute list fields; it also finds the of the `_parent`
    /// field, if any.
    pub fn new<'n>(
        ast: &'n syn::DeriveInput,
        config: &'n Config,
    ) -> Result<TemplateInput<'n>, CompileError> {
        // Check that an attribute called `template()` exists and that it is
        // the proper type (list).
        let meta = ast
            .attrs
            .iter()
            .find_map(|attr| match attr.parse_meta() {
                Ok(m) => {
                    if m.path().is_ident("template") {
                        Some(Ok(m))
                    } else {
                        None
                    }
                }
                Err(e) => Some(Err(format!("unable to parse attribute: {}", e).into())),
            })
            .unwrap_or(Err(CompileError::Static("no attribute 'template' found")))?;

        let meta_list = match meta {
            syn::Meta::List(inner) => inner,
            _ => return Err("attribute 'template' has incorrect type".into()),
        };

        // Loop over the meta attributes and find everything that we
        // understand. Raise panics if something is not right.
        // `source` contains an enum that can represent `path` or `source`.
        let mut source = None;
        let mut print = Print::None;
        let mut escaping = None;
        let mut ext = None;
        let mut syntax = None;
        for item in meta_list.nested {
            let pair = match item {
                syn::NestedMeta::Meta(syn::Meta::NameValue(ref pair)) => pair,
                _ => {
                    return Err(format!(
                        "unsupported attribute argument {:?}",
                        item.to_token_stream()
                    )
                    .into())
                }
            };

            if pair.path.is_ident("path") {
                if let syn::Lit::Str(ref s) = pair.lit {
                    if source.is_some() {
                        return Err("must specify 'source' or 'path', not both".into());
                    }
                    source = Some(Source::Path(s.value()));
                } else {
                    return Err("template path must be string literal".into());
                }
            } else if pair.path.is_ident("source") {
                if let syn::Lit::Str(ref s) = pair.lit {
                    if source.is_some() {
                        return Err("must specify 'source' or 'path', not both".into());
                    }
                    source = Some(Source::Source(s.value()));
                } else {
                    return Err("template source must be string literal".into());
                }
            } else if pair.path.is_ident("print") {
                if let syn::Lit::Str(ref s) = pair.lit {
                    print = s.value().parse()?;
                } else {
                    return Err("print value must be string literal".into());
                }
            } else if pair.path.is_ident("escape") {
                if let syn::Lit::Str(ref s) = pair.lit {
                    escaping = Some(s.value());
                } else {
                    return Err("escape value must be string literal".into());
                }
            } else if pair.path.is_ident("ext") {
                if let syn::Lit::Str(ref s) = pair.lit {
                    ext = Some(s.value());
                } else {
                    return Err("ext value must be string literal".into());
                }
            } else if pair.path.is_ident("syntax") {
                if let syn::Lit::Str(ref s) = pair.lit {
                    syntax = Some(s.value())
                } else {
                    return Err("syntax value must be string literal".into());
                }
            } else {
                return Err(format!(
                    "unsupported attribute key '{}' found",
                    pair.path.to_token_stream()
                )
                .into());
            }
        }

        // Validate the `source` and `ext` value together, since they are
        // related. In case `source` was used instead of `path`, the value
        // of `ext` is merged into a synthetic `path` value here.
        let source = source.expect("template path or source not found in attributes");
        let path = match (&source, &ext) {
            (&Source::Path(ref path), None) => config.find_template(path, None)?,
            (&Source::Source(_), Some(ext)) => PathBuf::from(format!("{}.{}", ast.ident, ext)),
            (&Source::Path(_), Some(_)) => {
                return Err("'ext' attribute cannot be used with 'path' attribute".into())
            }
            (&Source::Source(_), None) => {
                return Err("must include 'ext' attribute when using 'source' attribute".into())
            }
        };

        // Check to see if a `_parent` field was defined on the context
        // struct, and store the type for it for use in the code generator.
        let parent = match ast.data {
            syn::Data::Struct(syn::DataStruct {
                fields: syn::Fields::Named(ref fields),
                ..
            }) => fields
                .named
                .iter()
                .find(|f| f.ident.as_ref().filter(|name| *name == "_parent").is_some())
                .map(|f| &f.ty),
            _ => None,
        };

        if parent.is_some() {
            eprint!(
                "   --> in struct {}\n   = use of deprecated field '_parent'\n",
                ast.ident
            );
        }

        // Validate syntax
        let syntax = syntax.map_or_else(
            || Ok(config.syntaxes.get(config.default_syntax).unwrap()),
            |s| {
                config.syntaxes.get(&s).ok_or_else(|| {
                    CompileError::String(format!("attribute syntax {} not exist", s))
                })
            },
        )?;

        // Match extension against defined output formats

        let extension = escaping.unwrap_or_else(|| {
            path.extension()
                .map(|s| s.to_str().unwrap())
                .unwrap_or("")
                .to_string()
        });

        let mut escaper = None;
        for (extensions, path) in &config.escapers {
            if extensions.contains(&extension) {
                escaper = Some(path);
                break;
            }
        }

        let escaper = escaper.ok_or_else(|| {
            CompileError::String(format!("no escaper defined for extension '{}'", extension,))
        })?;

        Ok(TemplateInput {
            ast,
            config,
            syntax,
            source,
            print,
            escaper,
            ext,
            parent,
            path,
        })
    }
}

pub enum Source {
    Path(String),
    Source(String),
}

#[derive(PartialEq)]
pub enum Print {
    All,
    Ast,
    Code,
    None,
}

impl FromStr for Print {
    type Err = CompileError;

    fn from_str(s: &str) -> Result<Print, Self::Err> {
        use self::Print::*;
        Ok(match s {
            "all" => All,
            "ast" => Ast,
            "code" => Code,
            "none" => None,
            v => return Err(format!("invalid value for print option: {}", v,).into()),
        })
    }
}
<|endoftext|>


<commit_before>// Copyright 2015 Pierre Talbot (IRCAM)

// 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.

use kernel::*;
use kernel::Trilean::*;
use propagators::cmp::x_neq_y::*;
use solver::fd::event::*;
use variable::ops::*;
use interval::ncollections::ops::*;

#[derive(Clone)]
pub struct Distinct<V>
{
  props: Vec<XNeqY<V,V>>
}

impl<V> Distinct<V> where
  V: Clone
{
  pub fn new(vars: Vec<V>) -> Distinct<V> {
    let mut props = vec![];
    for i in 0..vars.len()-1 {
      for j in i+1..vars.len() {
        let i_neq_j = XNeqY::new(vars[i].clone(), vars[j].clone());
        props.push(i_neq_j);
      }
    }
    Distinct { props: props }
  }
}

impl<Store, Domain, V> Subsumption<Store> for Distinct<V> where
  V: StoreRead<Store, Value=Domain> + Clone,
  Domain: Bounded + Disjoint
{
  fn is_subsumed(&self, store: &Store) -> Trilean {
    let mut all_entailed = true;
    for p in &self.props {
      match p.is_subsumed(store) {
        False => return False,
        Unknown => all_entailed = false,
        _ => ()
      }
    }
    if all_entailed { True }
    else { Unknown }
  }
}

impl<Store, Domain, V> Propagator<Store> for Distinct<V> where
  V: StoreRead<Store, Value=Domain> + StoreMonotonicUpdate<Store, Domain>,
  Domain: Bounded + Cardinality,
  Domain: Difference<<Domain as Bounded>::Bound, Output=Domain>
{
  fn propagate(&mut self, store: &mut Store) -> bool {
    for p in &mut self.props {
      if !p.propagate(store) {
        return false;
      }
    }
    true
  }
}

impl<V> PropagatorDependencies<FDEvent> for Distinct<V> where
  V: ViewDependencies<FDEvent> + Clone
{
  fn dependencies(&self) -> Vec<(usize, FDEvent)> {
    self.props.iter().flat_map(|p| p.dependencies()).collect()
  }
}

impl<V> DeepClone for Distinct<V> where
  V: Clone
{
  fn deep_clone(&self) -> Distinct<V> {
    Distinct {
      props: self.props.iter().map(|p| p.deep_clone()).collect()
    }
  }
}

#[cfg(test)]
mod test {
  use super::*;
  use kernel::*;
  use kernel::Trilean::*;
  use solver::fd::event::*;
  use solver::fd::event::FDEvent::*;
  use interval::interval::*;
  use propagators::test::*;

  #[test]
  fn distinct_test() {
    let zero = (0,0).to_interval();
    let one = (1,1).to_interval();
    let two = (2,2).to_interval();
    let dom0_1 = (0,1).to_interval();
    let dom0_2 = (0,2).to_interval();
    let dom0_3 = (0,3).to_interval();

    distinct_test_one(1, vec![zero,one,two], True, True, vec![], true);
    distinct_test_one(2, vec![zero,zero,two], False, False, vec![], false);
    distinct_test_one(3, vec![zero,one,dom0_3], Unknown, True, vec![(2, Bound)], true);
    distinct_test_one(4, vec![zero,one,dom0_2], Unknown, True, vec![(2, Assignment)], true);
    distinct_test_one(5, vec![zero,one,dom0_1], Unknown, False, vec![], false);
    distinct_test_one(6, vec![zero,dom0_3,dom0_3], Unknown, Unknown, vec![(1, Bound),(2, Bound)], true);
    distinct_test_one(7, vec![dom0_3], True, True, vec![], true);
  }

  fn distinct_test_one(test_num: u32, doms: Vec<Interval<i32>>,
    before: Trilean, after: Trilean,
    delta_expected: Vec<(usize, FDEvent)>, propagate_success: bool)
  {
    nary_propagator_test(test_num, Distinct::new, doms, before, after, delta_expected, propagate_success);
  }
}
<commit_msg>Fix a bug on the dependencies, it was subscribing more than once to the same dependency.<commit_after>// Copyright 2015 Pierre Talbot (IRCAM)

// 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.

use kernel::*;
use kernel::Trilean::*;
use propagators::cmp::x_neq_y::*;
use solver::fd::event::*;
use variable::ops::*;
use interval::ncollections::ops::*;

#[derive(Clone)]
pub struct Distinct<V>
{
  props: Vec<XNeqY<V,V>>,
  vars: Vec<V>
}

impl<V> Distinct<V> where
  V: Clone
{
  pub fn new(vars: Vec<V>) -> Distinct<V> {
    let mut props = vec![];
    for i in 0..vars.len()-1 {
      for j in i+1..vars.len() {
        let i_neq_j = XNeqY::new(vars[i].clone(), vars[j].clone());
        props.push(i_neq_j);
      }
    }
    Distinct {
      props: props,
      vars: vars
    }
  }
}

impl<Store, Domain, V> Subsumption<Store> for Distinct<V> where
  V: StoreRead<Store, Value=Domain> + Clone,
  Domain: Bounded + Disjoint
{
  fn is_subsumed(&self, store: &Store) -> Trilean {
    let mut all_entailed = true;
    for p in &self.props {
      match p.is_subsumed(store) {
        False => return False,
        Unknown => all_entailed = false,
        _ => ()
      }
    }
    if all_entailed { True }
    else { Unknown }
  }
}

impl<Store, Domain, V> Propagator<Store> for Distinct<V> where
  V: StoreRead<Store, Value=Domain> + StoreMonotonicUpdate<Store, Domain>,
  Domain: Bounded + Cardinality,
  Domain: Difference<<Domain as Bounded>::Bound, Output=Domain>
{
  fn propagate(&mut self, store: &mut Store) -> bool {
    for p in &mut self.props {
      if !p.propagate(store) {
        return false;
      }
    }
    true
  }
}

impl<V> PropagatorDependencies<FDEvent> for Distinct<V> where
  V: ViewDependencies<FDEvent> + Clone
{
  fn dependencies(&self) -> Vec<(usize, FDEvent)> {
    self.vars.iter().flat_map(|v| v.dependencies(FDEvent::Inner)).collect()
  }
}

impl<V> DeepClone for Distinct<V> where
  V: Clone
{
  fn deep_clone(&self) -> Distinct<V> {
    Distinct {
      props: self.props.iter().map(|p| p.deep_clone()).collect(),
      vars: self.vars.clone()
    }
  }
}

#[cfg(test)]
mod test {
  use super::*;
  use kernel::*;
  use kernel::Trilean::*;
  use solver::fd::event::*;
  use solver::fd::event::FDEvent::*;
  use interval::interval::*;
  use propagators::test::*;

  #[test]
  fn distinct_test() {
    let zero = (0,0).to_interval();
    let one = (1,1).to_interval();
    let two = (2,2).to_interval();
    let dom0_1 = (0,1).to_interval();
    let dom0_2 = (0,2).to_interval();
    let dom0_3 = (0,3).to_interval();

    distinct_test_one(1, vec![zero,one,two], True, True, vec![], true);
    distinct_test_one(2, vec![zero,zero,two], False, False, vec![], false);
    distinct_test_one(3, vec![zero,one,dom0_3], Unknown, True, vec![(2, Bound)], true);
    distinct_test_one(4, vec![zero,one,dom0_2], Unknown, True, vec![(2, Assignment)], true);
    distinct_test_one(5, vec![zero,one,dom0_1], Unknown, False, vec![], false);
    distinct_test_one(6, vec![zero,dom0_3,dom0_3], Unknown, Unknown, vec![(1, Bound),(2, Bound)], true);
    distinct_test_one(7, vec![dom0_3], True, True, vec![], true);
  }

  fn distinct_test_one(test_num: u32, doms: Vec<Interval<i32>>,
    before: Trilean, after: Trilean,
    delta_expected: Vec<(usize, FDEvent)>, propagate_success: bool)
  {
    nary_propagator_test(test_num, Distinct::new, doms, before, after, delta_expected, propagate_success);
  }
}
<|endoftext|>


<commit_before>use crate::spec::{LinkArgs, LinkerFlavor, PanicStrategy, RelocModel, RelroLevel, TargetOptions};

pub fn opts() -> TargetOptions {
    let mut pre_link_args = LinkArgs::new();
    pre_link_args.insert(
        LinkerFlavor::Gcc,
        vec!["-Wl,--as-needed".to_string(), "-Wl,-z,noexecstack".to_string()],
    );

    TargetOptions {
        disable_redzone: true,
        panic_strategy: PanicStrategy::Abort,
        stack_probes: true,
        eliminate_frame_pointer: false,
        linker_is_gnu: true,
        position_independent_executables: true,
        needs_plt: true,
        relro_level: RelroLevel::Full,
        relocation_model: RelocModel::Static,
        target_family: Some("unix".to_string()),
        pre_link_args,

        ..Default::default()
    }
}
<commit_msg>don't mark linux kernel module targets as a unix environment<commit_after>use crate::spec::{LinkArgs, LinkerFlavor, PanicStrategy, RelocModel, RelroLevel, TargetOptions};

pub fn opts() -> TargetOptions {
    let mut pre_link_args = LinkArgs::new();
    pre_link_args.insert(
        LinkerFlavor::Gcc,
        vec!["-Wl,--as-needed".to_string(), "-Wl,-z,noexecstack".to_string()],
    );

    TargetOptions {
        disable_redzone: true,
        panic_strategy: PanicStrategy::Abort,
        stack_probes: true,
        eliminate_frame_pointer: false,
        linker_is_gnu: true,
        position_independent_executables: true,
        needs_plt: true,
        relro_level: RelroLevel::Full,
        relocation_model: RelocModel::Static,
        pre_link_args,

        ..Default::default()
    }
}
<|endoftext|>


<commit_before>
extern mod sax;

use self::sax::*;

pub struct Registry {
    enum_nss: ~[EnumNs],
    cmd_nss: ~[CmdNs],
}

impl Registry {
    pub fn from_xml(data: &str) -> Registry {
        RegistryBuilder::parse(data)
    }
}

pub struct EnumNs {
    ns: ~str,
    enums: ~[Enum],
}

pub struct Enum {
    ident: ~str,
    value: ~str,
}

pub struct ReturnType(Option<~str>);

pub struct CmdNs {
    ns: ~str,
    cmds: ~[Cmd],
}

pub struct Cmd {
    ident: ~str,
    ty: ReturnType,
    params: ~[Param]
}

pub struct Param {
    ptype: ~str,
    ident: ~str,
}

struct RegistryBuilder {
    priv port: SaxPort,
}

impl<'self> RegistryBuilder {
    fn recv(&self) -> ParseEvent {
        match self.port.recv() {
            Ok(msg) => msg,
            Err(err) => fail!("XML error: %s", err.to_str())
        }
    }

    fn parse(data: &str) -> Registry {
        let builder = RegistryBuilder {
            port: parse_xml(data)
        };
        match builder.recv() {
            StartDocument => (),
            msg => fail!("Expected start of document, found: %?", msg.to_str()),
        }
        match builder.recv() {
            StartElement(~"registry", _) => builder.consume_registry(),
            msg => fail!("Expected <registry>, found: %?", msg.to_str()),
        }
    }

    fn skip_until(&self, event: ParseEvent) {
        loop {
            let msg = self.recv();
            if msg == event || msg == EndDocument { break }
        }
    }

    fn consume_registry(&self) -> Registry {
        let mut registry = Registry { enum_nss: ~[], cmd_nss: ~[] };
        loop {
            match self.recv() {
                // ignores
                Characters(_) | Comment(_) | IgnorableWhitespace(_) => (),
                StartElement(~"comment", _) => self.skip_until(EndElement(~"comment")),
                StartElement(~"types", _) => self.skip_until(EndElement(~"types")),
                StartElement(~"groups", _) => self.skip_until(EndElement(~"groups")),
                StartElement(~"feature", _) => self.skip_until(EndElement(~"feature")),
                StartElement(~"extensions", _) => self.skip_until(EndElement(~"extensions")),

                // add enum namespace
                StartElement(~"enums", ref atts) => {
                    match atts.find(&~"namespace") {
                        Some(ns) => {
                            registry.enum_nss.push(
                                self.consume_enum_ns(ns.clone())
                            );
                        }
                        _ => fail!("Unexpected enum namespace attributes, found: %?", atts),
                    }
                }
                // add command namespace
                StartElement(~"commands", _) => self.skip_until(EndElement(~"commands")),

                // finished building the registry
                EndElement(~"registry") => break,

                // error handling
                msg => fail!("Expected </registry>, found: %?", msg.to_str()),
            }
        }
        registry
    }

    fn consume_enum_ns(&self, ns: ~str) -> EnumNs {
        let mut enum_ns = EnumNs { ns: ns, enums: ~[] };
        loop {
            match self.recv() {
                // ignores
                Characters(_) | Comment(_) | IgnorableWhitespace(_) => (),
                StartElement(~"unused", _) => self.skip_until(EndElement(~"unused")),
                // add enum definition
                StartElement(~"enum", ref atts) => {
                    match (atts.find(&~"name"), atts.find(&~"value")){
                        (Some(ident), Some(value)) => {
                            enum_ns.enums.push(
                                self.consume_enum(ident.clone(), value.clone())
                            )
                        }
                        _ => fail!("Unexpected enum attributes, found: %?", atts),
                    }
                }
                // finished building the namespace
                EndElement(~"enums") => break,
                // error handling
                msg => fail!("Expected </enums>, found: %?", msg.to_str()),
            }
        }
        enum_ns
    }

    fn consume_enum(&self, ident: ~str, value: ~str) -> Enum {
        match self.recv() {
            EndElement(~"enum") => Enum { ident: ident, value: value },
            msg => fail!("Expected </enum>, found: %?", msg.to_str()),
        }
    }

    // TODO: Consume command namespaces
}<commit_msg>Add extra attributes to EnumNs<commit_after>
extern mod sax;

use self::sax::*;

pub struct Registry {
    enum_nss: ~[EnumNs],
    cmd_nss: ~[CmdNs],
}

impl Registry {
    pub fn from_xml(data: &str) -> Registry {
        RegistryBuilder::parse(data)
    }
}

pub struct EnumNs {
    namespace: ~str,
    enums: ~[Enum],
    group: Option<~str>,
    ty: Option<~str>,
    start: Option<~str>,
    end: Option<~str>,
    vendor: Option<~str>,
    comment: Option<~str>,
}

pub struct Enum {
    ident: ~str,
    value: ~str,
}

pub struct ReturnType(Option<~str>);

pub struct CmdNs {
    namespace: ~str,
    cmds: ~[Cmd],
}

pub struct Cmd {
    ident: ~str,
    ty: ReturnType,
    params: ~[Param]
}

pub struct Param {
    ptype: ~str,
    ident: ~str,
}

struct RegistryBuilder {
    priv port: SaxPort,
}

impl<'self> RegistryBuilder {
    fn recv(&self) -> ParseEvent {
        match self.port.recv() {
            Ok(msg) => msg,
            Err(err) => fail!("XML error: %s", err.to_str())
        }
    }

    fn parse(data: &str) -> Registry {
        let builder = RegistryBuilder {
            port: parse_xml(data)
        };
        match builder.recv() {
            StartDocument => (),
            msg => fail!("Expected start of document, found: %?", msg.to_str()),
        }
        match builder.recv() {
            StartElement(~"registry", _) => builder.consume_registry(),
            msg => fail!("Expected <registry>, found: %?", msg.to_str()),
        }
    }

    fn skip_until(&self, event: ParseEvent) {
        loop {
            let msg = self.recv();
            if msg == event || msg == EndDocument { break }
        }
    }

    fn consume_registry(&self) -> Registry {
        let mut registry = Registry { enum_nss: ~[], cmd_nss: ~[] };
        loop {
            match self.recv() {
                // ignores
                Characters(_) | Comment(_) | IgnorableWhitespace(_) => (),
                StartElement(~"comment", _) => self.skip_until(EndElement(~"comment")),
                StartElement(~"types", _) => self.skip_until(EndElement(~"types")),
                StartElement(~"groups", _) => self.skip_until(EndElement(~"groups")),
                StartElement(~"feature", _) => self.skip_until(EndElement(~"feature")),
                StartElement(~"extensions", _) => self.skip_until(EndElement(~"extensions")),

                // add enum namespace
                StartElement(~"enums", ref atts) => {
                    registry.enum_nss.push(
                        EnumNs {
                            namespace:  atts.get_copy(&~"namespace"),
                            enums:      self.consume_enums(),
                            group:      atts.find_copy(&~"group"),
                            ty:         atts.find_copy(&~"type"),
                            start:      atts.find_copy(&~"start"),
                            end:        atts.find_copy(&~"end"),
                            vendor:     atts.find_copy(&~"vendor"),
                            comment:    atts.find_copy(&~"comment"),
                        }
                    )
                }
                // add command namespace
                StartElement(~"commands", _) => self.skip_until(EndElement(~"commands")),

                // finished building the registry
                EndElement(~"registry") => break,

                // error handling
                msg => fail!("Expected </registry>, found: %?", msg.to_str()),
            }
        }
        registry
    }

    fn consume_enums(&self) -> ~[Enum] {
        let mut enums = ~[];
        loop {
            match self.recv() {
                // ignores
                Characters(_) | Comment(_) | IgnorableWhitespace(_) => (),
                StartElement(~"unused", _) => self.skip_until(EndElement(~"unused")),
                // add enum definition
                StartElement(~"enum", ref atts) => {
                    enums.push(
                        Enum {
                            ident:  atts.get_copy(&~"name"),
                            value:  atts.get_copy(&~"value"),
                        }
                    );
                    match self.recv() {
                        EndElement(~"enum") => (),
                        msg => fail!("Expected </enum>, found: %?", msg.to_str()),
                    }
                }
                // finished building the namespace
                EndElement(~"enums") => break,
                // error handling
                msg => fail!("Expected </enums>, found: %?", msg.to_str()),
            }
        }
        enums
    }

    // TODO: Consume command namespaces
}<|endoftext|>


<commit_before>use master_smasher::drawable::{Asset, Drawable};
use super::MeteorState;
use super::interpolate::State;
use super::launched_meteor::LaunchedMeteor;

use glm;
use glm::ext::normalize_to;
use sdl2::rect;

pub struct UnlaunchedMeteor {
    asset: Asset,
    target: State<glm::IVec2>,
}

impl UnlaunchedMeteor {
    pub fn new(asset: Asset) -> Self {
        UnlaunchedMeteor {
            asset: asset,
            target: State::new(glm::ivec2(0, 0)),
        }
    }

    pub fn update(&mut self, target: glm::IVec2) {
        self.target.update(target);
    }

    pub fn drawables(&self, interpolation: f64) -> Vec<Drawable> {
        const NUM_RECTS: u32 = 10;
        const SIDE_LEN: u32 = 5;

        let target = glm::to_dvec2(self.target.interpolated(interpolation));
        let center = glm::to_dvec2(self.asset.center());
        let distance = target - center;
        let offset = self.asset.dst_rect.z / 2 + 10;
        let offset_vector = normalize_to(distance, offset as f64);
        let anchor_point = center + offset_vector;
        let step = (target - anchor_point) / NUM_RECTS as f64;

        let rects = (0..NUM_RECTS)
            .map(|i| anchor_point + (step * i as f64))
            .map(|p| (p.x as i32, p.y as i32))
            .map(|p| rect::Rect::from_center(p, SIDE_LEN, SIDE_LEN))
            .collect();

        vec![Drawable::Asset(self.asset), Drawable::Rectangles(rects)]
    }

    pub fn launch(&self, max_coords: glm::UVec2) -> MeteorState {
        const FACTOR: f64 = 50.;
        let offset = self.target.current - glm::to_ivec2(self.asset.center());
        let velocity = glm::to_dvec2(offset) / FACTOR;
        MeteorState::LAUNCHED(LaunchedMeteor::new(self.asset, max_coords, velocity))
    }
}
<commit_msg>split getting drawable rectangles of unlaunched meteor<commit_after>use master_smasher::drawable::{Asset, Drawable};
use super::MeteorState;
use super::interpolate::State;
use super::launched_meteor::LaunchedMeteor;

use glm;
use glm::ext::normalize_to;
use sdl2::rect;

pub struct UnlaunchedMeteor {
    asset: Asset,
    target: State<glm::IVec2>,
}

impl UnlaunchedMeteor {
    pub fn new(asset: Asset) -> Self {
        UnlaunchedMeteor {
            asset: asset,
            target: State::new(glm::ivec2(0, 0)),
        }
    }

    pub fn update(&mut self, target: glm::IVec2) {
        self.target.update(target);
    }

    pub fn drawables(&self, interpolation: f64) -> Vec<Drawable> {
        let target = glm::to_dvec2(self.target.interpolated(interpolation));
        let center = glm::to_dvec2(self.asset.center());
        let rects = self.target_rects(target, center);
        vec![Drawable::Asset(self.asset), Drawable::Rectangles(rects)]
    }

    fn target_rects(&self, target: glm::DVec2, center: glm::DVec2) -> Vec<rect::Rect> {
        const NUM_RECTS: u32 = 10;
        const SIDE_LEN: u32 = 5;

        let distance = target - center;
        let offset = self.asset.dst_rect.z / 2 + 10;
        let offset_vector = normalize_to(distance, offset as f64);
        let anchor_point = center + offset_vector;
        let step = (target - anchor_point) / NUM_RECTS as f64;

        (0..NUM_RECTS)
            .map(|i| anchor_point + (step * i as f64))
            .map(|p| (p.x as i32, p.y as i32))
            .map(|p| rect::Rect::from_center(p, SIDE_LEN, SIDE_LEN))
            .collect()
    }

    pub fn launch(&self, max_coords: glm::UVec2) -> MeteorState {
        const FACTOR: f64 = 50.;
        let offset = self.target.current - glm::to_ivec2(self.asset.center());
        let velocity = glm::to_dvec2(offset) / FACTOR;
        MeteorState::LAUNCHED(LaunchedMeteor::new(self.asset, max_coords, velocity))
    }
}
<|endoftext|>


<commit_before>use indy::WalletHandle;
use indy::did;
use indy::IndyError;
use indy::future::Future;
use indy::WalletHandle;

pub struct Did {}

impl Did {
    pub fn new(wallet_handle: WalletHandle, my_did_json: &str) -> Result<(String, String), IndyError> {
        did::create_and_store_my_did(wallet_handle, my_did_json).wait()
    }

    pub fn replace_keys_start(wallet_handle: WalletHandle, did: &str, identity_json: &str) -> Result<String, IndyError> {
        did::replace_keys_start(wallet_handle, did, identity_json).wait()
    }

    pub fn replace_keys_apply(wallet_handle: WalletHandle, did: &str) -> Result<(), IndyError> {
        did::replace_keys_apply(wallet_handle, did).wait()
    }

    pub fn set_metadata(wallet_handle: WalletHandle, did: &str, metadata: &str) -> Result<(), IndyError> {
        did::set_did_metadata(wallet_handle, did, metadata).wait()
    }

    pub fn get_did_with_meta(wallet_handle: WalletHandle, did: &str) -> Result<String, IndyError> {
        did::get_my_did_with_metadata(wallet_handle, did).wait()
    }

    pub fn list_dids_with_meta(wallet_handle: WalletHandle) -> Result<String, IndyError> {
        did::list_my_dids_with_metadata(wallet_handle).wait()
    }

    pub fn abbreviate_verkey(did: &str, verkey: &str) -> Result<String, IndyError> {
        did::abbreviate_verkey(did, verkey).wait()
    }

    pub fn qualify_did(wallet_handle: WalletHandle, did: &str, method: &str) -> Result<String, IndyError> {
        did::qualify_did(wallet_handle, did, method).wait()
    }
}<commit_msg>fix merge conflicts<commit_after>use indy::did;
use indy::IndyError;
use indy::future::Future;
use indy::WalletHandle;

pub struct Did {}

impl Did {
    pub fn new(wallet_handle: WalletHandle, my_did_json: &str) -> Result<(String, String), IndyError> {
        did::create_and_store_my_did(wallet_handle, my_did_json).wait()
    }

    pub fn replace_keys_start(wallet_handle: WalletHandle, did: &str, identity_json: &str) -> Result<String, IndyError> {
        did::replace_keys_start(wallet_handle, did, identity_json).wait()
    }

    pub fn replace_keys_apply(wallet_handle: WalletHandle, did: &str) -> Result<(), IndyError> {
        did::replace_keys_apply(wallet_handle, did).wait()
    }

    pub fn set_metadata(wallet_handle: WalletHandle, did: &str, metadata: &str) -> Result<(), IndyError> {
        did::set_did_metadata(wallet_handle, did, metadata).wait()
    }

    pub fn get_did_with_meta(wallet_handle: WalletHandle, did: &str) -> Result<String, IndyError> {
        did::get_my_did_with_metadata(wallet_handle, did).wait()
    }

    pub fn list_dids_with_meta(wallet_handle: WalletHandle) -> Result<String, IndyError> {
        did::list_my_dids_with_metadata(wallet_handle).wait()
    }

    pub fn abbreviate_verkey(did: &str, verkey: &str) -> Result<String, IndyError> {
        did::abbreviate_verkey(did, verkey).wait()
    }

    pub fn qualify_did(wallet_handle: WalletHandle, did: &str, method: &str) -> Result<String, IndyError> {
        did::qualify_did(wallet_handle, did, method).wait()
    }
}
<|endoftext|>


<commit_before>pub use self::imp::read2;

#[cfg(unix)]
mod imp {
    use std::io::prelude::*;
    use std::io;
    use std::mem;
    use std::os::unix::prelude::*;
    use std::process::{ChildStdout, ChildStderr};
    use libc;

    pub fn read2(mut out_pipe: ChildStdout,
                 mut err_pipe: ChildStderr,
                 data: &mut FnMut(bool, &mut Vec<u8>, bool)) -> io::Result<()> {
        unsafe {
            libc::fcntl(out_pipe.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK);
            libc::fcntl(err_pipe.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK);
        }

        let mut out_done = false;
        let mut err_done = false;
        let mut out = Vec::new();
        let mut err = Vec::new();

        let mut fds: [libc::pollfd; 2] = unsafe { mem::zeroed() };
        fds[0].fd = out_pipe.as_raw_fd();
        fds[0].events = libc::POLLIN;
        fds[1].fd = err_pipe.as_raw_fd();
        fds[1].events = libc::POLLIN;
        loop {
            // wait for either pipe to become readable using `select`
            let r = unsafe { libc::poll(fds.as_mut_ptr(), 2, -1) };
            if r == -1 {
                let err = io::Error::last_os_error();
                if err.kind() == io::ErrorKind::Interrupted {
                    continue
                }
                return Err(err)
            }

            // Read as much as we can from each pipe, ignoring EWOULDBLOCK or
            // EAGAIN. If we hit EOF, then this will happen because the underlying
            // reader will return Ok(0), in which case we'll see `Ok` ourselves. In
            // this case we flip the other fd back into blocking mode and read
            // whatever's leftover on that file descriptor.
            let handle = |res: io::Result<_>| {
                match res {
                    Ok(_) => Ok(true),
                    Err(e) => {
                        if e.kind() == io::ErrorKind::WouldBlock {
                            Ok(false)
                        } else {
                            Err(e)
                        }
                    }
                }
            };
            if !out_done && fds[0].revents != 0 && handle(out_pipe.read_to_end(&mut out))? {
                out_done = true;
            }
            data(true, &mut out, out_done);
            if !err_done && fds[1].revents != 0 && handle(err_pipe.read_to_end(&mut err))? {
                err_done = true;
            }
            data(false, &mut err, err_done);

            if out_done && err_done {
                return Ok(())
            }
        }
    }
}

#[cfg(windows)]
mod imp {
    extern crate miow;
    extern crate winapi;

    use std::io;
    use std::os::windows::prelude::*;
    use std::process::{ChildStdout, ChildStderr};
    use std::slice;

    use self::miow::iocp::{CompletionPort, CompletionStatus};
    use self::miow::pipe::NamedPipe;
    use self::miow::Overlapped;
    use self::winapi::shared::winerror::ERROR_BROKEN_PIPE;

    struct Pipe<'a> {
        dst: &'a mut Vec<u8>,
        overlapped: Overlapped,
        pipe: NamedPipe,
        done: bool,
    }

    pub fn read2(out_pipe: ChildStdout,
                 err_pipe: ChildStderr,
                 data: &mut FnMut(bool, &mut Vec<u8>, bool)) -> io::Result<()> {
        let mut out = Vec::new();
        let mut err = Vec::new();

        let port = CompletionPort::new(1)?;
        port.add_handle(0, &out_pipe)?;
        port.add_handle(1, &err_pipe)?;

        unsafe {
            let mut out_pipe = Pipe::new(out_pipe, &mut out);
            let mut err_pipe = Pipe::new(err_pipe, &mut err);

            out_pipe.read()?;
            err_pipe.read()?;

            let mut status = [CompletionStatus::zero(), CompletionStatus::zero()];

            while !out_pipe.done || !err_pipe.done {
                for status in port.get_many(&mut status, None)? {
                    if status.token() == 0 {
                        out_pipe.complete(status);
                        data(true, out_pipe.dst, out_pipe.done);
                        out_pipe.read()?;
                    } else {
                        err_pipe.complete(status);
                        data(false, err_pipe.dst, err_pipe.done);
                        err_pipe.read()?;
                    }
                }
            }

            Ok(())
        }
    }

    impl<'a> Pipe<'a> {
        unsafe fn new<P: IntoRawHandle>(p: P, dst: &'a mut Vec<u8>) -> Pipe<'a> {
            Pipe {
                dst: dst,
                pipe: NamedPipe::from_raw_handle(p.into_raw_handle()),
                overlapped: Overlapped::zero(),
                done: false,
            }
        }

        unsafe fn read(&mut self) -> io::Result<()> {
            let dst = slice_to_end(self.dst);
            match self.pipe.read_overlapped(dst, self.overlapped.raw()) {
                Ok(_) => Ok(()),
                Err(e) => {
                    if e.raw_os_error() == Some(ERROR_BROKEN_PIPE as i32) {
                        self.done = true;
                        Ok(())
                    } else {
                        Err(e)
                    }
                }
            }
        }

        unsafe fn complete(&mut self, status: &CompletionStatus) {
            let prev = self.dst.len();
            self.dst.set_len(prev + status.bytes_transferred() as usize);
            if status.bytes_transferred() == 0 {
                self.done = true;
            }
        }
    }

    unsafe fn slice_to_end(v: &mut Vec<u8>) -> &mut [u8] {
        if v.capacity() == 0 {
            v.reserve(16);
        }
        if v.capacity() == v.len() {
            v.reserve(1);
        }
        slice::from_raw_parts_mut(v.as_mut_ptr().offset(v.len() as isize),
                                  v.capacity() - v.len())
    }
}
<commit_msg>Don't spin on empty fds in `read2` on Unix<commit_after>pub use self::imp::read2;

#[cfg(unix)]
mod imp {
    use std::io::prelude::*;
    use std::io;
    use std::mem;
    use std::os::unix::prelude::*;
    use std::process::{ChildStdout, ChildStderr};
    use libc;

    pub fn read2(mut out_pipe: ChildStdout,
                 mut err_pipe: ChildStderr,
                 data: &mut FnMut(bool, &mut Vec<u8>, bool)) -> io::Result<()> {
        unsafe {
            libc::fcntl(out_pipe.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK);
            libc::fcntl(err_pipe.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK);
        }

        let mut out_done = false;
        let mut err_done = false;
        let mut out = Vec::new();
        let mut err = Vec::new();

        let mut fds: [libc::pollfd; 2] = unsafe { mem::zeroed() };
        fds[0].fd = out_pipe.as_raw_fd();
        fds[0].events = libc::POLLIN;
        fds[1].fd = err_pipe.as_raw_fd();
        fds[1].events = libc::POLLIN;
        let mut nfds = 2;
        let mut errfd = 1;

        while nfds > 0 {
            // wait for either pipe to become readable using `select`
            let r = unsafe { libc::poll(fds.as_mut_ptr(), nfds, -1) };
            if r == -1 {
                let err = io::Error::last_os_error();
                if err.kind() == io::ErrorKind::Interrupted {
                    continue
                }
                return Err(err)
            }

            // Read as much as we can from each pipe, ignoring EWOULDBLOCK or
            // EAGAIN. If we hit EOF, then this will happen because the underlying
            // reader will return Ok(0), in which case we'll see `Ok` ourselves. In
            // this case we flip the other fd back into blocking mode and read
            // whatever's leftover on that file descriptor.
            let handle = |res: io::Result<_>| {
                match res {
                    Ok(_) => Ok(true),
                    Err(e) => {
                        if e.kind() == io::ErrorKind::WouldBlock {
                            Ok(false)
                        } else {
                            Err(e)
                        }
                    }
                }
            };
            if !err_done && fds[errfd].revents != 0 && handle(err_pipe.read_to_end(&mut err))? {
                err_done = true;
                nfds -= 1;
            }
            data(false, &mut err, err_done);
            if !out_done && fds[0].revents != 0 && handle(out_pipe.read_to_end(&mut out))? {
                out_done = true;
                fds[0].fd = err_pipe.as_raw_fd();
                errfd = 0;
                nfds -= 1;
            }
            data(true, &mut out, out_done);
        }
        Ok(())
    }
}

#[cfg(windows)]
mod imp {
    extern crate miow;
    extern crate winapi;

    use std::io;
    use std::os::windows::prelude::*;
    use std::process::{ChildStdout, ChildStderr};
    use std::slice;

    use self::miow::iocp::{CompletionPort, CompletionStatus};
    use self::miow::pipe::NamedPipe;
    use self::miow::Overlapped;
    use self::winapi::shared::winerror::ERROR_BROKEN_PIPE;

    struct Pipe<'a> {
        dst: &'a mut Vec<u8>,
        overlapped: Overlapped,
        pipe: NamedPipe,
        done: bool,
    }

    pub fn read2(out_pipe: ChildStdout,
                 err_pipe: ChildStderr,
                 data: &mut FnMut(bool, &mut Vec<u8>, bool)) -> io::Result<()> {
        let mut out = Vec::new();
        let mut err = Vec::new();

        let port = CompletionPort::new(1)?;
        port.add_handle(0, &out_pipe)?;
        port.add_handle(1, &err_pipe)?;

        unsafe {
            let mut out_pipe = Pipe::new(out_pipe, &mut out);
            let mut err_pipe = Pipe::new(err_pipe, &mut err);

            out_pipe.read()?;
            err_pipe.read()?;

            let mut status = [CompletionStatus::zero(), CompletionStatus::zero()];

            while !out_pipe.done || !err_pipe.done {
                for status in port.get_many(&mut status, None)? {
                    if status.token() == 0 {
                        out_pipe.complete(status);
                        data(true, out_pipe.dst, out_pipe.done);
                        out_pipe.read()?;
                    } else {
                        err_pipe.complete(status);
                        data(false, err_pipe.dst, err_pipe.done);
                        err_pipe.read()?;
                    }
                }
            }

            Ok(())
        }
    }

    impl<'a> Pipe<'a> {
        unsafe fn new<P: IntoRawHandle>(p: P, dst: &'a mut Vec<u8>) -> Pipe<'a> {
            Pipe {
                dst: dst,
                pipe: NamedPipe::from_raw_handle(p.into_raw_handle()),
                overlapped: Overlapped::zero(),
                done: false,
            }
        }

        unsafe fn read(&mut self) -> io::Result<()> {
            let dst = slice_to_end(self.dst);
            match self.pipe.read_overlapped(dst, self.overlapped.raw()) {
                Ok(_) => Ok(()),
                Err(e) => {
                    if e.raw_os_error() == Some(ERROR_BROKEN_PIPE as i32) {
                        self.done = true;
                        Ok(())
                    } else {
                        Err(e)
                    }
                }
            }
        }

        unsafe fn complete(&mut self, status: &CompletionStatus) {
            let prev = self.dst.len();
            self.dst.set_len(prev + status.bytes_transferred() as usize);
            if status.bytes_transferred() == 0 {
                self.done = true;
            }
        }
    }

    unsafe fn slice_to_end(v: &mut Vec<u8>) -> &mut [u8] {
        if v.capacity() == 0 {
            v.reserve(16);
        }
        if v.capacity() == v.len() {
            v.reserve(1);
        }
        slice::from_raw_parts_mut(v.as_mut_ptr().offset(v.len() as isize),
                                  v.capacity() - v.len())
    }
}
<|endoftext|>