<commit_before>use super::BareDoomMap;
use super::geom::{Coord, Point, Rect};

use std::collections::HashMap;
use std::marker::PhantomData;

use std;

// TODO
// map diagnostics
// - error:
// - info: unused vertex
// - info: unused side
// - info: sector with no sides
// - info: thing not in the map (polyobjs excluded)

/// A fully-fledged map, independent (more or less) of any particular underlying format.
// TODO actually i'm not so sure about that!  should i, say, have different map impls that use
// different types...
pub struct Map {
    /*
    lines: Vec<Rc<RefCell<Line>>>,
    sides: Vec<Rc<RefCell<Side>>>,
    sectors: Vec<Rc<RefCell<Sector>>>,
    things: Vec<Rc<RefCell<Thing>>>,
    vertices: Vec<Rc<RefCell<Vertex>>>,
    */
    lines: Vec<Line>,
    sides: Vec<Side>,
    sectors: Vec<Sector>,
    things: Vec<Thing>,
    vertices: Vec<Vertex>,

    bbox: Option<Rect>,
}

impl Map {
    pub fn new() -> Self {
        Map {
            lines: Vec::new(),
            sides: Vec::new(),
            sectors: Vec::new(),
            things: Vec::new(),
            vertices: Vec::new(),

            bbox: None,
        }
    }
    pub fn from_bare(bare_map: &BareDoomMap) -> Self {
        let mut map = Map::new();
        for bare_sector in bare_map.sectors.iter() {
            let sectorh = map.add_sector();
            let sector = &mut map.sectors[sectorh.0];
            sector.tag = bare_sector.sector_tag as u32;
            sector.special = bare_sector.sector_type as u32;
            sector.floor_height = bare_sector.floor_height as i32;
            sector.ceiling_height = bare_sector.ceiling_height as i32;
        }
        for bare_vertex in bare_map.vertices.iter() {
            map.add_vertex(bare_vertex.x as f64, bare_vertex.y as f64);
        }
        for bare_side in bare_map.sides.iter() {
            let handle = map.add_side((bare_side.sector as usize).into());
            let side = map.side_mut(handle);
            side.lower_texture = bare_side.lower_texture.into();
            side.middle_texture = bare_side.middle_texture.into();
            side.upper_texture = bare_side.upper_texture.into();
        }
        for bare_line in bare_map.lines.iter() {
            let handle = map.add_line((bare_line.v0 as usize).into(), (bare_line.v1 as usize).into());
            let line = map.line_mut(handle);
            line.flags = bare_line.flags as u32;
            // FIXME and here's where we start to go awry -- this should use a method.  so should
            // new side w/ sector
            if bare_line.front_sidedef != -1 {
                line.front = Some((bare_line.front_sidedef as usize).into());
            }
            if bare_line.back_sidedef != -1 {
                line.back = Some((bare_line.back_sidedef as usize).into());
            }
        }
        for bare_thing in bare_map.things.iter() {
            map.things.push(Thing{
                point: Point::new(bare_thing.x as Coord, bare_thing.y as Coord),
                doomednum: bare_thing.doomednum as u32,
            });
        }

        map
    }

    fn side_mut(&mut self, handle: Handle<Side>) -> &mut Side {
        &mut self.sides[handle.0]
    }
    fn line_mut(&mut self, handle: Handle<Line>) -> &mut Line {
        &mut self.lines[handle.0]
    }

    fn add_sector(&mut self) -> Handle<Sector> {
        self.sectors.push(Sector{ special: 0, tag: 0, floor_height: 0, ceiling_height: 0 });
        (self.sectors.len() - 1).into()
    }
    fn add_side(&mut self, sector: Handle<Sector>) -> Handle<Side> {
        self.sides.push(Side{
            id: 0,
            lower_texture: "".into(),
            middle_texture: "".into(),
            upper_texture: "".into(),
            sector: sector,
        });
        (self.sides.len() - 1).into()
    }
    fn add_vertex(&mut self, x: f64, y: f64) {
        self.vertices.push(Vertex{ x, y });
        //self.vertices.push(vertex);
        //return vertex;
    }
    fn add_line(&mut self, start: Handle<Vertex>, end: Handle<Vertex>) -> Handle<Line> {
        self.lines.push(Line{
            start,
            end,
            flags: 0,
            special: 0,
            front: None,
            back: None,
        });
        (self.lines.len() - 1).into()
    }

    pub fn iter_lines(&self) -> <Vec<BoundLine> as IntoIterator>::IntoIter {
        let bound: Vec<_> = self.lines.iter().map(|a| BoundLine(a, self)).collect();
        bound.into_iter()
//        return self.lines.iter().map(|a| BoundLine(a, self));
    }
    pub fn iter_sectors(&self) -> std::slice::Iter<Sector> {
        self.sectors.iter()
    }
    pub fn iter_things(&self) -> std::slice::Iter<Thing> {
        self.things.iter()
    }

    pub fn vertex(&self, handle: Handle<Vertex>) -> &Vertex {
        &self.vertices[handle.0]
    }

    pub fn side(&self, handle: Handle<Side>) -> &Side {
        &self.sides[handle.0]
    }

    pub fn sector(&self, handle: Handle<Sector>) -> &Sector {
        &self.sectors[handle.0]
    }

    pub fn bbox(&self) -> Rect {
        // TODO ah heck, should include Things too
        let points: Vec<_> = self.vertices.iter().map(|v| Point::new(v.x, v.y)).collect();
        Rect::from_points(points.iter())
    }

    pub fn find_player_start(&self) -> Option<Point> {
        for thing in &self.things {
            if thing.doomednum() == 1 {
                return Some(thing.point());
            }
        }
        None
    }

    pub fn sector_to_polygons(&self, s: usize) -> Vec<Vec<Point>> {
        struct Edge<'a> {
            line: &'a Line,
            side: &'a Side,
            facing: Facing,
            v0: &'a Vertex,
            v1: &'a Vertex,
            done: bool,
        }
        // This is just to convince HashMap to hash on the actual reference, not the underlying
        // BareVertex value
        struct VertexRef<'a>(&'a Vertex);
        impl<'a> PartialEq for VertexRef<'a> {
            fn eq(&self, other: &VertexRef) -> bool {
                (self.0 as *const _) == (other.0 as *const _)
            }
        }
        impl<'a> Eq for VertexRef<'a> {}
        impl<'a> std::hash::Hash for VertexRef<'a> {
            fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
                (self.0 as *const Vertex).hash(state)
            }
        }

        let mut edges = vec![];
        let mut vertices_to_edges = HashMap::new();
        // TODO linear scan -- would make more sense to turn the entire map into polygons in one go
        for line in &self.lines {
            let (frontid, backid) = line.side_indices();
            // FIXME need to handle self-referencing sectors, but also
            if let Some(front) = line.front.map(|h| &self.sides[h.0]) {
                if let Some(back) = line.back.map(|h| &self.sides[h.0]) {
                    if front.sector == back.sector {
                        continue;
                    }
                }
            }

            // TODO seems like a good case for a custom iterator
            for &(facing, sideid) in [(Facing::Front, frontid), (Facing::Back, backid)].iter() {
                if sideid.is_none() {
                    continue;
                }
                // TODO this and the vertices lookups might be bogus and crash...
                let side = &self.sides[sideid.unwrap().0];
                if side.sector.0 == s {
                    let v0 = &self.vertices[line.start.0];
                    let v1 = &self.vertices[line.end.0];
                    let edge = Edge{
                        line,
                        side,
                        facing,
                        // TODO should these be swapped depending on the line facing?
                        v0,
                        v1,
                        done: false,
                    };
                    edges.push(edge);
                    vertices_to_edges.entry(VertexRef(v0)).or_insert_with(|| Vec::new()).push(edges.len() - 1);
                    vertices_to_edges.entry(VertexRef(v1)).or_insert_with(|| Vec::new()).push(edges.len() - 1);
                }
            }
        }

        // Trace sectors by starting at the first side's first vertex and attempting to walk from
        // there
        let mut outlines = Vec::new();
        let mut seen_vertices = HashMap::new();
        while edges.len() > 0 {
            let mut next_vertices = vec![];
            for edge in edges.iter() {
                // TODO having done-ness for both edges and vertices seems weird, idk
                if !seen_vertices.contains_key(&VertexRef(edge.v0)) {
                    next_vertices.push(edge.v0);
                    break;
                }
                if !seen_vertices.contains_key(&VertexRef(edge.v1)) {
                    next_vertices.push(edge.v1);
                    break;
                }
            }
            if next_vertices.is_empty() {
                break;
            }

            let mut outline = Vec::new();
            while next_vertices.len() > 0 {
                let vertices = next_vertices;
                next_vertices = Vec::new();
                for vertex in vertices.iter() {
                    if seen_vertices.contains_key(&VertexRef(vertex)) {
                        continue;
                    }
                    seen_vertices.insert(VertexRef(vertex), true);
                    outline.push(Point::new(vertex.x, vertex.y));

                    // TODO so, problems occur here if:
                    // - a vertex has more than two edges
                    //   - special case: double-sided edges are OK!  but we have to eliminate
                    //   those, WITHOUT ruining entirely self-referencing sectors
                    // - a vertex has one edge
                    for e in vertices_to_edges.get(&VertexRef(vertex)).unwrap().iter() {
                        let edge = &mut edges[*e];
                        if edge.done {
                            // TODO actually this seems weird?  why would this happen.
                            continue;
                        }
                        edge.done = true;
                        if !seen_vertices.contains_key(&VertexRef(edge.v0)) {
                            next_vertices.push(edge.v0);
                        }
                        else if !seen_vertices.contains_key(&VertexRef(edge.v1)) {
                            next_vertices.push(edge.v1);
                        }
                        // Only add EXACTLY ONE vertex at a time for now -- so, assuming simple
                        // polygons!  Figure out the rest, uh, later.
                        break;
                    }
                }
            }
            if outline.len() > 0 {
                outlines.push(outline);
            }
        }

        outlines
    }
}

#[derive(Copy, Clone, Debug)]
pub enum Facing {
    Front,
    Back,
}

pub struct Handle<T>(usize, PhantomData<*const T>);

// These traits are implemented by hand because #derive'd impls only apply when T implements the
// same trait, but we don't actually own a T, so that bound is unnecessary.
impl<T> Clone for Handle<T> {
    fn clone(&self) -> Self {
        Handle(self.0, PhantomData)
    }
}

impl<T> Copy for Handle<T> {}

impl<T> PartialEq for Handle<T> {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}
impl<T> Eq for Handle<T> {}

impl<T> std::hash::Hash for Handle<T> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.0.hash(state)
    }
}

impl<T> From<usize> for Handle<T> {
    fn from(index: usize) -> Self {
        Handle(index, PhantomData)
    }
}

trait MapComponent {}

pub struct Thing {
    point: Point,
    doomednum: u32,
}

impl Thing {
    pub fn point(&self) -> Point {
        self.point
    }

    pub fn doomednum(&self) -> u32 {
        self.doomednum
    }
}

pub struct Line {
    start: Handle<Vertex>,
    end: Handle<Vertex>,
    flags: u32,
    special: usize,
    //sector_tag -- oops, different in zdoom...
    front: Option<Handle<Side>>,
    back: Option<Handle<Side>>,
}

impl Line {
    pub fn vertex_indices(&self) -> (Handle<Vertex>, Handle<Vertex>) {
        (self.start, self.end)
    }

    pub fn side_indices(&self) -> (Option<Handle<Side>>, Option<Handle<Side>>) {
        (self.front, self.back)
    }

    pub fn has_special(&self) -> bool {
        self.special != 0
    }

    pub fn blocks_player(&self) -> bool {
        self.flags & 1 != 0
    }

    pub fn is_one_sided(&self) -> bool {
        self.front.is_some() != self.back.is_some()
    }

    pub fn is_two_sided(&self) -> bool {
        self.front.is_some() && self.back.is_some()
    }
}

// A Line that knows what map it came from, so it can look up its actual sides and vertices
#[derive(Clone, Copy)]
pub struct BoundLine<'a>(&'a Line, &'a Map);
impl<'a> BoundLine<'a> {
    pub fn start(&self) -> &Vertex {
        self.1.vertex(self.0.start)
    }

    pub fn end(&self) -> &Vertex {
        self.1.vertex(self.0.end)
    }

    pub fn front(&self) -> Option<&Side> {
        self.0.front.map(|s| self.1.side(s))
    }

    pub fn back(&self) -> Option<&Side> {
        self.0.back.map(|s| self.1.side(s))
    }

    // TODO these are all delegates, eugh
    pub fn vertex_indices(&self) -> (Handle<Vertex>, Handle<Vertex>) {
        self.0.vertex_indices()
    }

    pub fn side_indices(&self) -> (Option<Handle<Side>>, Option<Handle<Side>>) {
        self.0.side_indices()
    }

    pub fn has_special(&self) -> bool {
        self.0.has_special()
    }

    pub fn blocks_player(&self) -> bool {
        self.0.blocks_player()
    }

    pub fn is_one_sided(&self) -> bool {
        self.0.is_one_sided()
    }

    pub fn is_two_sided(&self) -> bool {
        self.0.is_two_sided()
    }
}

pub struct Sector {
    tag: u32,
    special: u32,

    floor_height: i32,
    ceiling_height: i32,
}

impl Sector {
    pub fn tag(&self) -> u32 {
        self.tag
    }

    pub fn special(&self) -> u32 {
        self.special
    }

    pub fn floor_height(&self) -> i32 {
        self.floor_height
    }

    pub fn ceiling_height(&self) -> i32 {
        self.ceiling_height
    }
}

pub struct Side {
    //map: Rc<Map>,
    pub id: u32,
    pub upper_texture: String,
    pub lower_texture: String,
    pub middle_texture: String,
    pub sector: Handle<Sector>,
}

#[derive(Clone, Copy)]
pub struct BoundSide<'a>(&'a Side, &'a Map);
impl<'a> BoundSide<'a> {
    //pub fn sector(&self) ->
}

pub struct Vertex {
    pub x: f64,
    pub y: f64,
}
<commit_msg>Prefix unused struct fields with _<commit_after>use super::BareDoomMap;
use super::geom::{Coord, Point, Rect};

use std::collections::HashMap;
use std::marker::PhantomData;

use std;

// TODO
// map diagnostics
// - error:
// - info: unused vertex
// - info: unused side
// - info: sector with no sides
// - info: thing not in the map (polyobjs excluded)

/// A fully-fledged map, independent (more or less) of any particular underlying format.
// TODO actually i'm not so sure about that!  should i, say, have different map impls that use
// different types...
pub struct Map {
    /*
    lines: Vec<Rc<RefCell<Line>>>,
    sides: Vec<Rc<RefCell<Side>>>,
    sectors: Vec<Rc<RefCell<Sector>>>,
    things: Vec<Rc<RefCell<Thing>>>,
    vertices: Vec<Rc<RefCell<Vertex>>>,
    */
    lines: Vec<Line>,
    sides: Vec<Side>,
    sectors: Vec<Sector>,
    things: Vec<Thing>,
    vertices: Vec<Vertex>,

    _bbox: Option<Rect>,
}

impl Map {
    pub fn new() -> Self {
        Map {
            lines: Vec::new(),
            sides: Vec::new(),
            sectors: Vec::new(),
            things: Vec::new(),
            vertices: Vec::new(),

            _bbox: None,
        }
    }
    pub fn from_bare(bare_map: &BareDoomMap) -> Self {
        let mut map = Map::new();
        for bare_sector in bare_map.sectors.iter() {
            let sectorh = map.add_sector();
            let sector = &mut map.sectors[sectorh.0];
            sector.tag = bare_sector.sector_tag as u32;
            sector.special = bare_sector.sector_type as u32;
            sector.floor_height = bare_sector.floor_height as i32;
            sector.ceiling_height = bare_sector.ceiling_height as i32;
        }
        for bare_vertex in bare_map.vertices.iter() {
            map.add_vertex(bare_vertex.x as f64, bare_vertex.y as f64);
        }
        for bare_side in bare_map.sides.iter() {
            let handle = map.add_side((bare_side.sector as usize).into());
            let side = map.side_mut(handle);
            side.lower_texture = bare_side.lower_texture.into();
            side.middle_texture = bare_side.middle_texture.into();
            side.upper_texture = bare_side.upper_texture.into();
        }
        for bare_line in bare_map.lines.iter() {
            let handle = map.add_line((bare_line.v0 as usize).into(), (bare_line.v1 as usize).into());
            let line = map.line_mut(handle);
            line.flags = bare_line.flags as u32;
            // FIXME and here's where we start to go awry -- this should use a method.  so should
            // new side w/ sector
            if bare_line.front_sidedef != -1 {
                line.front = Some((bare_line.front_sidedef as usize).into());
            }
            if bare_line.back_sidedef != -1 {
                line.back = Some((bare_line.back_sidedef as usize).into());
            }
        }
        for bare_thing in bare_map.things.iter() {
            map.things.push(Thing{
                point: Point::new(bare_thing.x as Coord, bare_thing.y as Coord),
                doomednum: bare_thing.doomednum as u32,
            });
        }

        map
    }

    fn side_mut(&mut self, handle: Handle<Side>) -> &mut Side {
        &mut self.sides[handle.0]
    }
    fn line_mut(&mut self, handle: Handle<Line>) -> &mut Line {
        &mut self.lines[handle.0]
    }

    fn add_sector(&mut self) -> Handle<Sector> {
        self.sectors.push(Sector{ special: 0, tag: 0, floor_height: 0, ceiling_height: 0 });
        (self.sectors.len() - 1).into()
    }
    fn add_side(&mut self, sector: Handle<Sector>) -> Handle<Side> {
        self.sides.push(Side{
            id: 0,
            lower_texture: "".into(),
            middle_texture: "".into(),
            upper_texture: "".into(),
            sector: sector,
        });
        (self.sides.len() - 1).into()
    }
    fn add_vertex(&mut self, x: f64, y: f64) {
        self.vertices.push(Vertex{ x, y });
        //self.vertices.push(vertex);
        //return vertex;
    }
    fn add_line(&mut self, start: Handle<Vertex>, end: Handle<Vertex>) -> Handle<Line> {
        self.lines.push(Line{
            start,
            end,
            flags: 0,
            special: 0,
            front: None,
            back: None,
        });
        (self.lines.len() - 1).into()
    }

    pub fn iter_lines(&self) -> <Vec<BoundLine> as IntoIterator>::IntoIter {
        let bound: Vec<_> = self.lines.iter().map(|a| BoundLine(a, self)).collect();
        bound.into_iter()
//        return self.lines.iter().map(|a| BoundLine(a, self));
    }
    pub fn iter_sectors(&self) -> std::slice::Iter<Sector> {
        self.sectors.iter()
    }
    pub fn iter_things(&self) -> std::slice::Iter<Thing> {
        self.things.iter()
    }

    pub fn vertex(&self, handle: Handle<Vertex>) -> &Vertex {
        &self.vertices[handle.0]
    }

    pub fn side(&self, handle: Handle<Side>) -> &Side {
        &self.sides[handle.0]
    }

    pub fn sector(&self, handle: Handle<Sector>) -> &Sector {
        &self.sectors[handle.0]
    }

    pub fn bbox(&self) -> Rect {
        // TODO ah heck, should include Things too
        let points: Vec<_> = self.vertices.iter().map(|v| Point::new(v.x, v.y)).collect();
        Rect::from_points(points.iter())
    }

    pub fn find_player_start(&self) -> Option<Point> {
        for thing in &self.things {
            if thing.doomednum() == 1 {
                return Some(thing.point());
            }
        }
        None
    }

    pub fn sector_to_polygons(&self, s: usize) -> Vec<Vec<Point>> {
        struct Edge<'a> {
            _line: &'a Line,
            _side: &'a Side,
            _facing: Facing,
            v0: &'a Vertex,
            v1: &'a Vertex,
            done: bool,
        }
        // This is just to convince HashMap to hash on the actual reference, not the underlying
        // BareVertex value
        struct VertexRef<'a>(&'a Vertex);
        impl<'a> PartialEq for VertexRef<'a> {
            fn eq(&self, other: &VertexRef) -> bool {
                (self.0 as *const _) == (other.0 as *const _)
            }
        }
        impl<'a> Eq for VertexRef<'a> {}
        impl<'a> std::hash::Hash for VertexRef<'a> {
            fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
                (self.0 as *const Vertex).hash(state)
            }
        }

        let mut edges = vec![];
        let mut vertices_to_edges = HashMap::new();
        // TODO linear scan -- would make more sense to turn the entire map into polygons in one go
        for line in &self.lines {
            let (frontid, backid) = line.side_indices();
            // FIXME need to handle self-referencing sectors, but also
            if let Some(front) = line.front.map(|h| &self.sides[h.0]) {
                if let Some(back) = line.back.map(|h| &self.sides[h.0]) {
                    if front.sector == back.sector {
                        continue;
                    }
                }
            }

            // TODO seems like a good case for a custom iterator
            for &(facing, sideid) in [(Facing::Front, frontid), (Facing::Back, backid)].iter() {
                if sideid.is_none() {
                    continue;
                }
                // TODO this and the vertices lookups might be bogus and crash...
                let side = &self.sides[sideid.unwrap().0];
                if side.sector.0 == s {
                    let v0 = &self.vertices[line.start.0];
                    let v1 = &self.vertices[line.end.0];
                    let edge = Edge{
                        _line: line,
                        _side: side,
                        _facing: facing,
                        // TODO should these be swapped depending on the line facing?
                        v0,
                        v1,
                        done: false,
                    };
                    edges.push(edge);
                    vertices_to_edges.entry(VertexRef(v0)).or_insert_with(|| Vec::new()).push(edges.len() - 1);
                    vertices_to_edges.entry(VertexRef(v1)).or_insert_with(|| Vec::new()).push(edges.len() - 1);
                }
            }
        }

        // Trace sectors by starting at the first side's first vertex and attempting to walk from
        // there
        let mut outlines = Vec::new();
        let mut seen_vertices = HashMap::new();
        while edges.len() > 0 {
            let mut next_vertices = vec![];
            for edge in edges.iter() {
                // TODO having done-ness for both edges and vertices seems weird, idk
                if !seen_vertices.contains_key(&VertexRef(edge.v0)) {
                    next_vertices.push(edge.v0);
                    break;
                }
                if !seen_vertices.contains_key(&VertexRef(edge.v1)) {
                    next_vertices.push(edge.v1);
                    break;
                }
            }
            if next_vertices.is_empty() {
                break;
            }

            let mut outline = Vec::new();
            while next_vertices.len() > 0 {
                let vertices = next_vertices;
                next_vertices = Vec::new();
                for vertex in vertices.iter() {
                    if seen_vertices.contains_key(&VertexRef(vertex)) {
                        continue;
                    }
                    seen_vertices.insert(VertexRef(vertex), true);
                    outline.push(Point::new(vertex.x, vertex.y));

                    // TODO so, problems occur here if:
                    // - a vertex has more than two edges
                    //   - special case: double-sided edges are OK!  but we have to eliminate
                    //   those, WITHOUT ruining entirely self-referencing sectors
                    // - a vertex has one edge
                    for e in vertices_to_edges.get(&VertexRef(vertex)).unwrap().iter() {
                        let edge = &mut edges[*e];
                        if edge.done {
                            // TODO actually this seems weird?  why would this happen.
                            continue;
                        }
                        edge.done = true;
                        if !seen_vertices.contains_key(&VertexRef(edge.v0)) {
                            next_vertices.push(edge.v0);
                        }
                        else if !seen_vertices.contains_key(&VertexRef(edge.v1)) {
                            next_vertices.push(edge.v1);
                        }
                        // Only add EXACTLY ONE vertex at a time for now -- so, assuming simple
                        // polygons!  Figure out the rest, uh, later.
                        break;
                    }
                }
            }
            if outline.len() > 0 {
                outlines.push(outline);
            }
        }

        outlines
    }
}

#[derive(Copy, Clone, Debug)]
pub enum Facing {
    Front,
    Back,
}

pub struct Handle<T>(usize, PhantomData<*const T>);

// These traits are implemented by hand because #derive'd impls only apply when T implements the
// same trait, but we don't actually own a T, so that bound is unnecessary.
impl<T> Clone for Handle<T> {
    fn clone(&self) -> Self {
        Handle(self.0, PhantomData)
    }
}

impl<T> Copy for Handle<T> {}

impl<T> PartialEq for Handle<T> {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}
impl<T> Eq for Handle<T> {}

impl<T> std::hash::Hash for Handle<T> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.0.hash(state)
    }
}

impl<T> From<usize> for Handle<T> {
    fn from(index: usize) -> Self {
        Handle(index, PhantomData)
    }
}

trait MapComponent {}

pub struct Thing {
    point: Point,
    doomednum: u32,
}

impl Thing {
    pub fn point(&self) -> Point {
        self.point
    }

    pub fn doomednum(&self) -> u32 {
        self.doomednum
    }
}

pub struct Line {
    start: Handle<Vertex>,
    end: Handle<Vertex>,
    flags: u32,
    special: usize,
    //sector_tag -- oops, different in zdoom...
    front: Option<Handle<Side>>,
    back: Option<Handle<Side>>,
}

impl Line {
    pub fn vertex_indices(&self) -> (Handle<Vertex>, Handle<Vertex>) {
        (self.start, self.end)
    }

    pub fn side_indices(&self) -> (Option<Handle<Side>>, Option<Handle<Side>>) {
        (self.front, self.back)
    }

    pub fn has_special(&self) -> bool {
        self.special != 0
    }

    pub fn blocks_player(&self) -> bool {
        self.flags & 1 != 0
    }

    pub fn is_one_sided(&self) -> bool {
        self.front.is_some() != self.back.is_some()
    }

    pub fn is_two_sided(&self) -> bool {
        self.front.is_some() && self.back.is_some()
    }
}

// A Line that knows what map it came from, so it can look up its actual sides and vertices
#[derive(Clone, Copy)]
pub struct BoundLine<'a>(&'a Line, &'a Map);
impl<'a> BoundLine<'a> {
    pub fn start(&self) -> &Vertex {
        self.1.vertex(self.0.start)
    }

    pub fn end(&self) -> &Vertex {
        self.1.vertex(self.0.end)
    }

    pub fn front(&self) -> Option<&Side> {
        self.0.front.map(|s| self.1.side(s))
    }

    pub fn back(&self) -> Option<&Side> {
        self.0.back.map(|s| self.1.side(s))
    }

    // TODO these are all delegates, eugh
    pub fn vertex_indices(&self) -> (Handle<Vertex>, Handle<Vertex>) {
        self.0.vertex_indices()
    }

    pub fn side_indices(&self) -> (Option<Handle<Side>>, Option<Handle<Side>>) {
        self.0.side_indices()
    }

    pub fn has_special(&self) -> bool {
        self.0.has_special()
    }

    pub fn blocks_player(&self) -> bool {
        self.0.blocks_player()
    }

    pub fn is_one_sided(&self) -> bool {
        self.0.is_one_sided()
    }

    pub fn is_two_sided(&self) -> bool {
        self.0.is_two_sided()
    }
}

pub struct Sector {
    tag: u32,
    special: u32,

    floor_height: i32,
    ceiling_height: i32,
}

impl Sector {
    pub fn tag(&self) -> u32 {
        self.tag
    }

    pub fn special(&self) -> u32 {
        self.special
    }

    pub fn floor_height(&self) -> i32 {
        self.floor_height
    }

    pub fn ceiling_height(&self) -> i32 {
        self.ceiling_height
    }
}

pub struct Side {
    //map: Rc<Map>,
    pub id: u32,
    pub upper_texture: String,
    pub lower_texture: String,
    pub middle_texture: String,
    pub sector: Handle<Sector>,
}

#[derive(Clone, Copy)]
pub struct BoundSide<'a>(&'a Side, &'a Map);
impl<'a> BoundSide<'a> {
    //pub fn sector(&self) ->
}

pub struct Vertex {
    pub x: f64,
    pub y: f64,
}
<|endoftext|>


<commit_before>//! Tools to retrieve Internet-time using NTP protocol.

use std::num::Float;
use time::Timespec;
use std::io::Cursor;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use std::io::Error as IoError;
use std::io::ErrorKind as IoErrorKind;

const NTP_CLIENT: u8 = 3;
const NTP_HEADER_SIZE: usize = 48; // 12 words
const NTP_TO_UNIX_EPOCH: i64 = 2208988800;

const LEAP_SHIFT: i32 = 6;
const VERSION_SHIFT: i32 = 3;

#[derive(Debug)]
pub struct NTPTimestamp {
    seconds: u32,
    fraction: u32
}

impl NTPTimestamp {
    pub fn as_timespec(&self) -> Timespec {
        Timespec{sec: (self.seconds as i64) - NTP_TO_UNIX_EPOCH,
                 nsec: (((self.fraction as f64) / 2f64.powi(32) ) / 1e-9) as i32}
    }
}

#[derive(Debug)]
pub struct NTPHeader {
    leap: u8,
    version: u8,
    mode: u8,
    stratum: u8,
    poll: u8,
    precision: u8,
    root_delay: u32,
    root_dispersion: u32,
    reference_id: u32,
    reference_timestamp: NTPTimestamp,
    origin_timestamp: NTPTimestamp,
    receive_timestamp: NTPTimestamp,
    pub transmit_timestamp: NTPTimestamp,
}

impl NTPHeader {
    pub fn new() -> NTPHeader {
        NTPHeader {
            leap: 0,
            version: 3,
            mode: NTP_CLIENT,
            stratum: 0,
            poll: 0,
            precision: 0,
            root_delay : 0,
            root_dispersion : 0,
            reference_id : 0,
            reference_timestamp : NTPTimestamp{seconds:0, fraction:0},
            origin_timestamp : NTPTimestamp{seconds:0, fraction:0},
            receive_timestamp : NTPTimestamp{seconds:0, fraction:0},
            transmit_timestamp : NTPTimestamp{seconds:0, fraction:0}
        }
    }

    fn encode_first_word<T>(&self, w: &mut T) -> Result<(), IoError> where T: WriteBytesExt {
        try!(w.write_u8(self.leap << LEAP_SHIFT | self.version << VERSION_SHIFT | self.mode));
        try!(w.write_u8(self.stratum));
        try!(w.write_u8(self.poll));
        try!(w.write_u8(self.precision));
        Ok(())
    }

    pub fn encode(&self) -> Result<Vec<u8>, IoError> {
        let mut vec = Vec::<u8>::new();

        // TODO: since Vec still implements old_io::Write trait the next 4 lines does not compile
        //try!(vec.write_u8(self.leap << LEAP_SHIFT | self.version << VERSION_SHIFT | self.mode));
        //try!(vec.write_u8(self.stratum));
        //try!(vec.write_u8(self.poll));
        //try!(vec.write_u8(self.precision));

        // TODO: remove workaround when possible
        try!(self.encode_first_word(&mut vec));

        try!(vec.write_u32::<BigEndian>(self.root_delay));
        try!(vec.write_u32::<BigEndian>(self.root_dispersion));
        try!(vec.write_u32::<BigEndian>(self.reference_id));
        try!(vec.write_u32::<BigEndian>(self.reference_timestamp.seconds));
        try!(vec.write_u32::<BigEndian>(self.reference_timestamp.fraction));
        try!(vec.write_u32::<BigEndian>(self.origin_timestamp.seconds));
        try!(vec.write_u32::<BigEndian>(self.origin_timestamp.fraction));
        try!(vec.write_u32::<BigEndian>(self.receive_timestamp.seconds));
        try!(vec.write_u32::<BigEndian>(self.receive_timestamp.fraction));
        try!(vec.write_u32::<BigEndian>(self.transmit_timestamp.seconds));
        try!(vec.write_u32::<BigEndian>(self.transmit_timestamp.fraction));
        Ok(vec)
    }

    pub fn decode(size: usize, buf: & [u8]) -> Result<NTPHeader, IoError> {
        let mut reader = Cursor::new(buf);
        let mut header = NTPHeader::new();

        if size < NTP_HEADER_SIZE {
            return Err(IoError::new(IoErrorKind::Other,
                "Unexpected number of bytes in NTP datagram",
                Option::Some(format!("{} bytes expected in NTP header; {} bytes received", NTP_HEADER_SIZE, size))));
        }

        let leap_version_mode = try!(reader.read_u8());
        header.leap = (leap_version_mode >> LEAP_SHIFT) & 0b11;
        header.version = (leap_version_mode >> VERSION_SHIFT) & 0b111;
        header.mode = leap_version_mode & 0b111;
        header.stratum = try!(reader.read_u8());
        header.poll = try!(reader.read_u8());
        header.precision = try!(reader.read_u8());
        header.root_delay = try!(reader.read_u32::<BigEndian>());
        header.root_dispersion = try!(reader.read_u32::<BigEndian>());
        header.reference_id = try!(reader.read_u32::<BigEndian>());
        header.reference_timestamp.seconds = try!(reader.read_u32::<BigEndian>());
        header.reference_timestamp.fraction = try!(reader.read_u32::<BigEndian>());
        header.origin_timestamp.seconds = try!(reader.read_u32::<BigEndian>());
        header.origin_timestamp.fraction = try!(reader.read_u32::<BigEndian>());
        header.receive_timestamp.seconds = try!(reader.read_u32::<BigEndian>());
        header.receive_timestamp.fraction = try!(reader.read_u32::<BigEndian>());
        header.transmit_timestamp.seconds = try!(reader.read_u32::<BigEndian>());
        header.transmit_timestamp.fraction = try!(reader.read_u32::<BigEndian>());

        Ok(header)
    }
}
<commit_msg>Remove some uses<commit_after>//! Tools to retrieve Internet-time using NTP protocol.

use std::num::Float;
use time::Timespec;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use std::io;

const NTP_CLIENT: u8 = 3;
const NTP_HEADER_SIZE: usize = 48; // 12 words
const NTP_TO_UNIX_EPOCH: i64 = 2208988800;

const LEAP_SHIFT: i32 = 6;
const VERSION_SHIFT: i32 = 3;

#[derive(Debug)]
pub struct NTPTimestamp {
    seconds: u32,
    fraction: u32
}

impl NTPTimestamp {
    pub fn as_timespec(&self) -> Timespec {
        Timespec{sec: (self.seconds as i64) - NTP_TO_UNIX_EPOCH,
                 nsec: (((self.fraction as f64) / 2f64.powi(32) ) / 1e-9) as i32}
    }
}

#[derive(Debug)]
pub struct NTPHeader {
    leap: u8,
    version: u8,
    mode: u8,
    stratum: u8,
    poll: u8,
    precision: u8,
    root_delay: u32,
    root_dispersion: u32,
    reference_id: u32,
    reference_timestamp: NTPTimestamp,
    origin_timestamp: NTPTimestamp,
    receive_timestamp: NTPTimestamp,
    pub transmit_timestamp: NTPTimestamp,
}

impl NTPHeader {
    pub fn new() -> NTPHeader {
        NTPHeader {
            leap: 0,
            version: 3,
            mode: NTP_CLIENT,
            stratum: 0,
            poll: 0,
            precision: 0,
            root_delay : 0,
            root_dispersion : 0,
            reference_id : 0,
            reference_timestamp : NTPTimestamp{seconds:0, fraction:0},
            origin_timestamp : NTPTimestamp{seconds:0, fraction:0},
            receive_timestamp : NTPTimestamp{seconds:0, fraction:0},
            transmit_timestamp : NTPTimestamp{seconds:0, fraction:0}
        }
    }

    fn encode_first_word<T>(&self, w: &mut T) -> Result<(), io::Error> where T: WriteBytesExt {
        try!(w.write_u8(self.leap << LEAP_SHIFT | self.version << VERSION_SHIFT | self.mode));
        try!(w.write_u8(self.stratum));
        try!(w.write_u8(self.poll));
        try!(w.write_u8(self.precision));
        Ok(())
    }

    pub fn encode(&self) -> Result<Vec<u8>, io::Error> {
        let mut vec = Vec::<u8>::new();

        // TODO: since Vec still implements old_io::Write trait the next 4 lines does not compile
        //try!(vec.write_u8(self.leap << LEAP_SHIFT | self.version << VERSION_SHIFT | self.mode));
        //try!(vec.write_u8(self.stratum));
        //try!(vec.write_u8(self.poll));
        //try!(vec.write_u8(self.precision));

        // TODO: remove workaround when possible
        try!(self.encode_first_word(&mut vec));

        try!(vec.write_u32::<BigEndian>(self.root_delay));
        try!(vec.write_u32::<BigEndian>(self.root_dispersion));
        try!(vec.write_u32::<BigEndian>(self.reference_id));
        try!(vec.write_u32::<BigEndian>(self.reference_timestamp.seconds));
        try!(vec.write_u32::<BigEndian>(self.reference_timestamp.fraction));
        try!(vec.write_u32::<BigEndian>(self.origin_timestamp.seconds));
        try!(vec.write_u32::<BigEndian>(self.origin_timestamp.fraction));
        try!(vec.write_u32::<BigEndian>(self.receive_timestamp.seconds));
        try!(vec.write_u32::<BigEndian>(self.receive_timestamp.fraction));
        try!(vec.write_u32::<BigEndian>(self.transmit_timestamp.seconds));
        try!(vec.write_u32::<BigEndian>(self.transmit_timestamp.fraction));
        Ok(vec)
    }

    pub fn decode(size: usize, buf: & [u8]) -> Result<NTPHeader, io::Error> {
        let mut reader = io::Cursor::new(buf);
        let mut header = NTPHeader::new();

        if size < NTP_HEADER_SIZE {
            return Err(io::Error::new(io::ErrorKind::Other,
                "Unexpected number of bytes in NTP datagram",
                Option::Some(format!("{} bytes expected in NTP header; {} bytes received", NTP_HEADER_SIZE, size))));
        }

        let leap_version_mode = try!(reader.read_u8());
        header.leap = (leap_version_mode >> LEAP_SHIFT) & 0b11;
        header.version = (leap_version_mode >> VERSION_SHIFT) & 0b111;
        header.mode = leap_version_mode & 0b111;
        header.stratum = try!(reader.read_u8());
        header.poll = try!(reader.read_u8());
        header.precision = try!(reader.read_u8());
        header.root_delay = try!(reader.read_u32::<BigEndian>());
        header.root_dispersion = try!(reader.read_u32::<BigEndian>());
        header.reference_id = try!(reader.read_u32::<BigEndian>());
        header.reference_timestamp.seconds = try!(reader.read_u32::<BigEndian>());
        header.reference_timestamp.fraction = try!(reader.read_u32::<BigEndian>());
        header.origin_timestamp.seconds = try!(reader.read_u32::<BigEndian>());
        header.origin_timestamp.fraction = try!(reader.read_u32::<BigEndian>());
        header.receive_timestamp.seconds = try!(reader.read_u32::<BigEndian>());
        header.receive_timestamp.fraction = try!(reader.read_u32::<BigEndian>());
        header.transmit_timestamp.seconds = try!(reader.read_u32::<BigEndian>());
        header.transmit_timestamp.fraction = try!(reader.read_u32::<BigEndian>());

        Ok(header)
    }
}
<|endoftext|>


<commit_before>use collections::string::ToString;
use core::ops::*;

use abs::Abs;
use approx::Approx;
use bounded::Bounded;
use clamp::Clamp;
use to_degrees::ToDegrees;
use to_radians::ToRadians;
use to_primitive::ToPrimitive;
use from_primitive::FromPrimitive;
use max::Max;
use min::Min;
use one::One;
use round::Round;
use signum::Signum;
use sqrt::Sqrt;
use trig::Trig;
use zero::Zero;

pub trait Num:
    Copy + One + Zero
    + Min + Max + Signum
    + Abs
    + Approx
    + Bounded
    + Clamp
    + ToDegrees
    + ToRadians
    + ToPrimitive
    + FromPrimitive
    + Trig
    + Sqrt
    + Round
    + PartialEq
    + PartialOrd
    + ToString

    + Add<Self, Output = Self>
    + Mul<Self, Output = Self>
    + Sub<Self, Output = Self>
    + Div<Self, Output = Self>
    + Rem<Self, Output = Self>

    + AddAssign<Self>
    + MulAssign<Self>
    + SubAssign<Self>
    + DivAssign<Self>
    + RemAssign<Self> {}

impl<T> Num for T where T:
    Copy + One + Zero
    + Min + Max + Signum
    + Abs
    + Approx
    + Bounded
    + Clamp
    + ToDegrees
    + ToRadians
    + ToPrimitive
    + FromPrimitive
    + Trig
    + Sqrt
    + Round
    + PartialEq
    + PartialOrd
    + ToString

    + Add<T, Output = T>
    + Mul<T, Output = T>
    + Sub<T, Output = T>
    + Div<T, Output = T>
    + Rem<T, Output = T>

    + AddAssign<T>
    + MulAssign<T>
    + SubAssign<T>
    + DivAssign<T>
    + RemAssign<T> {}
<commit_msg>clean up<commit_after>use collections::string::ToString;
use core::ops::*;
use core::cmp::Ord;

use abs::Abs;
use approx::Approx;
use bounded::Bounded;
use clamp::Clamp;
use to_degrees::ToDegrees;
use to_radians::ToRadians;
use to_primitive::ToPrimitive;
use from_primitive::FromPrimitive;
use max::Max;
use min::Min;
use one::One;
use round::Round;
use signum::Signum;
use sqrt::Sqrt;
use trig::Trig;
use zero::Zero;

pub trait Num:
    Copy + One + Zero
    + Min + Max + Signum
    + Abs
    + Approx
    + Bounded
    + Clamp
    + ToDegrees
    + ToRadians
    + ToPrimitive
    + FromPrimitive
    + Trig
    + Sqrt
    + Round
    + Ord
    + PartialEq
    + PartialOrd
    + ToString

    + Add<Self, Output = Self>
    + Mul<Self, Output = Self>
    + Sub<Self, Output = Self>
    + Div<Self, Output = Self>
    + Rem<Self, Output = Self>

    + AddAssign<Self>
    + MulAssign<Self>
    + SubAssign<Self>
    + DivAssign<Self>
    + RemAssign<Self> {}

impl<T> Num for T where T:
    Copy + One + Zero
    + Min + Max + Signum
    + Abs
    + Approx
    + Bounded
    + Clamp
    + ToDegrees
    + ToRadians
    + ToPrimitive
    + FromPrimitive
    + Trig
    + Sqrt
    + Round
    + Ord
    + PartialEq
    + PartialOrd
    + ToString

    + Add<T, Output = T>
    + Mul<T, Output = T>
    + Sub<T, Output = T>
    + Div<T, Output = T>
    + Rem<T, Output = T>

    + AddAssign<T>
    + MulAssign<T>
    + SubAssign<T>
    + DivAssign<T>
    + RemAssign<T> {}
<|endoftext|>


<commit_before>//! The ORC JIT.

use super::prelude::*;
use super::object::LLVMObjectFileRef;
use super::target_machine::LLVMTargetMachineRef;

pub enum LLVMOrcOpaqueJITStack {}
pub type LLVMOrcJITStackRef = *mut LLVMOrcOpaqueJITStack;
pub type LLVMOrcModuleHandle = u32;
pub type LLVMOrcTargetAddress = u64;

pub type LLVMOrcSymbolResolverFn = extern "C" fn(*const ::libc::c_char, *mut ::libc::c_void) -> u64;
pub type LLVMOrcLazyCompileCallbackFn = extern "C" fn(LLVMOrcJITStackRef, *mut ::libc::c_void);
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LLVMOrcErrorCode {
    LLVMOrcErrSuccess = 0,
    LLVMOrcErrGeneric,
}

extern "C" {
    /// Create an ORC JIT stack.
    ///
    /// The client owns the returned stack and must call OrcDisposeInstance
    /// when done with it. The JIT stack takes ownership of the provided
    /// TargetMachine.
    pub fn LLVMOrcCreateInstance(TM: LLVMTargetMachineRef) -> LLVMOrcJITStackRef;

    /// Get the error message for the most recent error (if any).
    ///
    /// The returned message is owned by the ORC JIT stack.
    pub fn LLVMOrcGetErrorMsg(JITStack: LLVMOrcJITStackRef) -> *const ::libc::c_char;

    /// Mangle the given symbol.
    ///
    /// Memory is allocated for the mangled symbol, which will be owned by
    /// the client.
    pub fn LLVMOrcGetMangledSymbol(JITStack: LLVMOrcJITStackRef,
                                   MangledSymbol: *mut *mut ::libc::c_char,
                                   Symbol: *const ::libc::c_char);

    /// Dispose of a mangled symbol.
    pub fn LLVMOrcDisposeMangledSymbol(MangledSymbol: *mut ::libc::c_char);

    /// Create a lazy compile callback.
    pub fn LLVMOrcCreateLazyCompileCallback(JITStack: LLVMOrcJITStackRef,
                                            Callback: LLVMOrcLazyCompileCallbackFn,
                                            CallbackCtx: *mut ::libc::c_void)
                                            -> LLVMOrcTargetAddress;

    /// Create a named indirect call stub.
    pub fn LLVMOrcCreateIndirectStub(JITStack: LLVMOrcJITStackRef,
                                     StubName: *const ::libc::c_char,
                                     InitAddr: LLVMOrcTargetAddress)
                                     -> LLVMOrcErrorCode;

    /// Set the pointer for the given indirect stub.
    pub fn LLVMOrcSetIndirectStubPointer(JITStack: LLVMOrcJITStackRef,
                                         StubName: *const ::libc::c_char,
                                         NewAddr: LLVMOrcTargetAddress)
                                         -> LLVMOrcErrorCode;

    /// Add a module to be eagerly compiled.
    pub fn LLVMOrcAddEagerlyCompiledIR(JITStack: LLVMOrcJITStackRef,
                                       Mod: LLVMModuleRef,
                                       SymbolResolver: LLVMOrcSymbolResolverFn,
                                       SymbolResolverCtx: *mut ::libc::c_void)
                                       -> LLVMOrcModuleHandle;

    /// Add a module to be lazily compiled one function at a time.
    pub fn LLVMOrcAddLazilyCompiledIR(JITStack: LLVMOrcJITStackRef,
                                      Mod: LLVMModuleRef,
                                      SymbolResolver: LLVMOrcSymbolResolverFn,
                                      SymbolResolverCtx: *mut ::libc::c_void)
                                      -> LLVMOrcModuleHandle;

    /// Add an object file.
    pub fn LLVMOrcAddObjectFile(JITStack: LLVMOrcJITStackRef,
                                Obj: LLVMObjectFileRef,
                                SymbolResolver: LLVMOrcSymbolResolverFn,
                                SymbolResolverCtx: *mut ::libc::c_void)
                                -> LLVMOrcModuleHandle;

    /// Remove a module set from the JIT.
    pub fn LLVMRemoveModule(JITStack: LLVMOrcJITStackRef, H: LLVMOrcModuleHandle);

    /// Get symbol address from JIT instance.
    pub fn LLVMOrcGetSymbolAddress(JITStack: LLVMOrcJITStackRef,
                                   SymbolName: *const ::libc::c_char)
                                   -> LLVMOrcTargetAddress;

    /// Dispose of an ORC JIT stack.
    pub fn LLVMOrcDisposeInstance(JITStack: LLVMOrcJITStackRef);
}
<commit_msg>fix spell error<commit_after>//! The ORC JIT.

use super::prelude::*;
use super::object::LLVMObjectFileRef;
use super::target_machine::LLVMTargetMachineRef;

pub enum LLVMOrcOpaqueJITStack {}
pub type LLVMOrcJITStackRef = *mut LLVMOrcOpaqueJITStack;
pub type LLVMOrcModuleHandle = u32;
pub type LLVMOrcTargetAddress = u64;

pub type LLVMOrcSymbolResolverFn = extern "C" fn(*const ::libc::c_char, *mut ::libc::c_void) -> u64;
pub type LLVMOrcLazyCompileCallbackFn = extern "C" fn(LLVMOrcJITStackRef, *mut ::libc::c_void);
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LLVMOrcErrorCode {
    LLVMOrcErrSuccess = 0,
    LLVMOrcErrGeneric,
}

extern "C" {
    /// Create an ORC JIT stack.
    ///
    /// The client owns the returned stack and must call OrcDisposeInstance
    /// when done with it. The JIT stack takes ownership of the provided
    /// TargetMachine.
    pub fn LLVMOrcCreateInstance(TM: LLVMTargetMachineRef) -> LLVMOrcJITStackRef;

    /// Get the error message for the most recent error (if any).
    ///
    /// The returned message is owned by the ORC JIT stack.
    pub fn LLVMOrcGetErrorMsg(JITStack: LLVMOrcJITStackRef) -> *const ::libc::c_char;

    /// Mangle the given symbol.
    ///
    /// Memory is allocated for the mangled symbol, which will be owned by
    /// the client.
    pub fn LLVMOrcGetMangledSymbol(JITStack: LLVMOrcJITStackRef,
                                   MangledSymbol: *mut *mut ::libc::c_char,
                                   Symbol: *const ::libc::c_char);

    /// Dispose of a mangled symbol.
    pub fn LLVMOrcDisposeMangledSymbol(MangledSymbol: *mut ::libc::c_char);

    /// Create a lazy compile callback.
    pub fn LLVMOrcCreateLazyCompileCallback(JITStack: LLVMOrcJITStackRef,
                                            Callback: LLVMOrcLazyCompileCallbackFn,
                                            CallbackCtx: *mut ::libc::c_void)
                                            -> LLVMOrcTargetAddress;

    /// Create a named indirect call stub.
    pub fn LLVMOrcCreateIndirectStub(JITStack: LLVMOrcJITStackRef,
                                     StubName: *const ::libc::c_char,
                                     InitAddr: LLVMOrcTargetAddress)
                                     -> LLVMOrcErrorCode;

    /// Set the pointer for the given indirect stub.
    pub fn LLVMOrcSetIndirectStubPointer(JITStack: LLVMOrcJITStackRef,
                                         StubName: *const ::libc::c_char,
                                         NewAddr: LLVMOrcTargetAddress)
                                         -> LLVMOrcErrorCode;

    /// Add a module to be eagerly compiled.
    pub fn LLVMOrcAddEagerlyCompiledIR(JITStack: LLVMOrcJITStackRef,
                                       Mod: LLVMModuleRef,
                                       SymbolResolver: LLVMOrcSymbolResolverFn,
                                       SymbolResolverCtx: *mut ::libc::c_void)
                                       -> LLVMOrcModuleHandle;

    /// Add a module to be lazily compiled one function at a time.
    pub fn LLVMOrcAddLazilyCompiledIR(JITStack: LLVMOrcJITStackRef,
                                      Mod: LLVMModuleRef,
                                      SymbolResolver: LLVMOrcSymbolResolverFn,
                                      SymbolResolverCtx: *mut ::libc::c_void)
                                      -> LLVMOrcModuleHandle;

    /// Add an object file.
    pub fn LLVMOrcAddObjectFile(JITStack: LLVMOrcJITStackRef,
                                Obj: LLVMObjectFileRef,
                                SymbolResolver: LLVMOrcSymbolResolverFn,
                                SymbolResolverCtx: *mut ::libc::c_void)
                                -> LLVMOrcModuleHandle;

    /// Remove a module set from the JIT.
    pub fn LLVMOrcRemoveModule(JITStack: LLVMOrcJITStackRef, H: LLVMOrcModuleHandle);

    /// Get symbol address from JIT instance.
    pub fn LLVMOrcGetSymbolAddress(JITStack: LLVMOrcJITStackRef,
                                   SymbolName: *const ::libc::c_char)
                                   -> LLVMOrcTargetAddress;

    /// Dispose of an ORC JIT stack.
    pub fn LLVMOrcDisposeInstance(JITStack: LLVMOrcJITStackRef);
}
<|endoftext|>


<commit_before>use core::num::Wrapping;
use core::ops::Mul;
use {CheckedMul, One};

/// Binary operator for raising a value to a power.
pub trait Pow<RHS> {
    /// The result after applying the operator.
    type Output;

    /// Returns `self` to the power `rhs`.
    ///
    /// # Examples
    ///
    /// ```
    /// use num_traits::Pow;
    /// assert_eq!(Pow::pow(10u32, 2u32), 100);
    /// ```
    fn pow(self, rhs: RHS) -> Self::Output;
}

macro_rules! pow_impl {
    ($t:ty) => {
        pow_impl!($t, u8);
        pow_impl!($t, usize);

        // FIXME: these should be possible
        // pow_impl!($t, u16);
        // pow_impl!($t, u32);
        // pow_impl!($t, u64);
    };
    ($t:ty, $rhs:ty) => {
        pow_impl!($t, $rhs, usize, pow);
    };
    ($t:ty, $rhs:ty, $desired_rhs:ty, $method:expr) => {
        impl Pow<$rhs> for $t {
            type Output = $t;
            #[inline]
            fn pow(self, rhs: $rhs) -> $t {
                ($method)(self, <$desired_rhs>::from(rhs))
            }
        }

        impl<'a> Pow<&'a $rhs> for $t {
            type Output = $t;
            #[inline]
            fn pow(self, rhs: &'a $rhs) -> $t {
                ($method)(self, <$desired_rhs>::from(*rhs))
            }
        }

        impl<'a> Pow<$rhs> for &'a $t {
            type Output = $t;
            #[inline]
            fn pow(self, rhs: $rhs) -> $t {
                ($method)(*self, <$desired_rhs>::from(rhs))
            }
        }

        impl<'a, 'b> Pow<&'a $rhs> for &'b $t {
            type Output = $t;
            #[inline]
            fn pow(self, rhs: &'a $rhs) -> $t {
                ($method)(*self, <$desired_rhs>::from(*rhs))
            }
        }
    };
}

pow_impl!(u8, u8, u32, u8::pow);
pow_impl!(u8, u16, u32, u8::pow);
pow_impl!(u8, u32, u32, u8::pow);
pow_impl!(u8, usize);
pow_impl!(i8, u8, u32, i8::pow);
pow_impl!(i8, u16, u32, i8::pow);
pow_impl!(i8, u32, u32, i8::pow);
pow_impl!(i8, usize);
pow_impl!(u16, u8, u32, u16::pow);
pow_impl!(u16, u16, u32, u16::pow);
pow_impl!(u16, u32, u32, u16::pow);
pow_impl!(u16, usize);
pow_impl!(i16, u8, u32, i16::pow);
pow_impl!(i16, u16, u32, i16::pow);
pow_impl!(i16, u32, u32, i16::pow);
pow_impl!(i16, usize);
pow_impl!(u32, u8, u32, u32::pow);
pow_impl!(u32, u16, u32, u32::pow);
pow_impl!(u32, u32, u32, u32::pow);
pow_impl!(u32, usize);
pow_impl!(i32, u8, u32, i32::pow);
pow_impl!(i32, u16, u32, i32::pow);
pow_impl!(i32, u32, u32, i32::pow);
pow_impl!(i32, usize);
pow_impl!(u64, u8, u32, u64::pow);
pow_impl!(u64, u16, u32, u64::pow);
pow_impl!(u64, u32, u32, u64::pow);
pow_impl!(u64, usize);
pow_impl!(i64, u8, u32, i64::pow);
pow_impl!(i64, u16, u32, i64::pow);
pow_impl!(i64, u32, u32, i64::pow);
pow_impl!(i64, usize);

#[cfg(has_i128)]
pow_impl!(u128, u8, u32, u128::pow);
#[cfg(has_i128)]
pow_impl!(u128, u16, u32, u128::pow);
#[cfg(has_i128)]
pow_impl!(u128, u32, u32, u128::pow);
#[cfg(has_i128)]
pow_impl!(u128, usize);

#[cfg(has_i128)]
pow_impl!(i128, u8, u32, i128::pow);
#[cfg(has_i128)]
pow_impl!(i128, u16, u32, i128::pow);
#[cfg(has_i128)]
pow_impl!(i128, u32, u32, i128::pow);
#[cfg(has_i128)]
pow_impl!(i128, usize);

pow_impl!(usize, u8, u32, usize::pow);
pow_impl!(usize, u16, u32, usize::pow);
pow_impl!(usize, u32, u32, usize::pow);
pow_impl!(usize, usize);
pow_impl!(isize, u8, u32, isize::pow);
pow_impl!(isize, u16, u32, isize::pow);
pow_impl!(isize, u32, u32, isize::pow);
pow_impl!(isize, usize);
pow_impl!(Wrapping<u8>);
pow_impl!(Wrapping<i8>);
pow_impl!(Wrapping<u16>);
pow_impl!(Wrapping<i16>);
pow_impl!(Wrapping<u32>);
pow_impl!(Wrapping<i32>);
pow_impl!(Wrapping<u64>);
pow_impl!(Wrapping<i64>);
#[cfg(has_i128)]
pow_impl!(Wrapping<u128>);
#[cfg(has_i128)]
pow_impl!(Wrapping<i128>);
pow_impl!(Wrapping<usize>);
pow_impl!(Wrapping<isize>);

// FIXME: these should be possible
// pow_impl!(u8, u64);
// pow_impl!(i16, u64);
// pow_impl!(i8, u64);
// pow_impl!(u16, u64);
// pow_impl!(u32, u64);
// pow_impl!(i32, u64);
// pow_impl!(u64, u64);
// pow_impl!(i64, u64);
// pow_impl!(usize, u64);
// pow_impl!(isize, u64);

#[cfg(feature = "std")]
mod float_impls {
    use super::Pow;

    pow_impl!(f32, i8, i32, f32::powi);
    pow_impl!(f32, u8, i32, f32::powi);
    pow_impl!(f32, i16, i32, f32::powi);
    pow_impl!(f32, u16, i32, f32::powi);
    pow_impl!(f32, i32, i32, f32::powi);
    pow_impl!(f64, i8, i32, f64::powi);
    pow_impl!(f64, u8, i32, f64::powi);
    pow_impl!(f64, i16, i32, f64::powi);
    pow_impl!(f64, u16, i32, f64::powi);
    pow_impl!(f64, i32, i32, f64::powi);
    pow_impl!(f32, f32, f32, f32::powf);
    pow_impl!(f64, f32, f64, f64::powf);
    pow_impl!(f64, f64, f64, f64::powf);
}

/// Raises a value to the power of exp, using exponentiation by squaring.
///
/// # Example
///
/// ```rust
/// use num_traits::pow;
///
/// assert_eq!(pow(2i8, 4), 16);
/// assert_eq!(pow(6u8, 3), 216);
/// ```
#[inline]
pub fn pow<T: Clone + One + Mul<T, Output = T>>(mut base: T, mut exp: usize) -> T {
    if exp == 0 {
        return T::one();
    }

    while exp & 1 == 0 {
        base = base.clone() * base;
        exp >>= 1;
    }
    if exp == 1 {
        return base;
    }

    let mut acc = base.clone();
    while exp > 1 {
        exp >>= 1;
        base = base.clone() * base;
        if exp & 1 == 1 {
            acc = acc * base.clone();
        }
    }
    acc
}

/// Raises a value to the power of exp, returning `None` if an overflow occurred.
///
/// Otherwise same as the `pow` function.
///
/// # Example
///
/// ```rust
/// use num_traits::checked_pow;
///
/// assert_eq!(checked_pow(2i8, 4), Some(16));
/// assert_eq!(checked_pow(7i8, 8), None);
/// assert_eq!(checked_pow(7u32, 8), Some(5_764_801));
/// ```
#[inline]
pub fn checked_pow<T: Clone + One + CheckedMul>(mut base: T, mut exp: usize) -> Option<T> {
    if exp == 0 {
        return Some(T::one());
    }

    macro_rules! optry {
        ($expr:expr) => {
            if let Some(val) = $expr {
                val
            } else {
                return None;
            }
        };
    }

    while exp & 1 == 0 {
        base = optry!(base.checked_mul(&base));
        exp >>= 1;
    }
    if exp == 1 {
        return Some(base);
    }

    let mut acc = base.clone();
    while exp > 1 {
        exp >>= 1;
        base = optry!(base.checked_mul(&base));
        if exp & 1 == 1 {
            acc = optry!(acc.checked_mul(&base));
        }
    }
    Some(acc)
}
<commit_msg>Updated documentation to note the pow(0, 0) case.<commit_after>use core::num::Wrapping;
use core::ops::Mul;
use {CheckedMul, One};

/// Binary operator for raising a value to a power.
pub trait Pow<RHS> {
    /// The result after applying the operator.
    type Output;

    /// Returns `self` to the power `rhs`.
    ///
    /// # Examples
    ///
    /// ```
    /// use num_traits::Pow;
    /// assert_eq!(Pow::pow(10u32, 2u32), 100);
    /// ```
    fn pow(self, rhs: RHS) -> Self::Output;
}

macro_rules! pow_impl {
    ($t:ty) => {
        pow_impl!($t, u8);
        pow_impl!($t, usize);

        // FIXME: these should be possible
        // pow_impl!($t, u16);
        // pow_impl!($t, u32);
        // pow_impl!($t, u64);
    };
    ($t:ty, $rhs:ty) => {
        pow_impl!($t, $rhs, usize, pow);
    };
    ($t:ty, $rhs:ty, $desired_rhs:ty, $method:expr) => {
        impl Pow<$rhs> for $t {
            type Output = $t;
            #[inline]
            fn pow(self, rhs: $rhs) -> $t {
                ($method)(self, <$desired_rhs>::from(rhs))
            }
        }

        impl<'a> Pow<&'a $rhs> for $t {
            type Output = $t;
            #[inline]
            fn pow(self, rhs: &'a $rhs) -> $t {
                ($method)(self, <$desired_rhs>::from(*rhs))
            }
        }

        impl<'a> Pow<$rhs> for &'a $t {
            type Output = $t;
            #[inline]
            fn pow(self, rhs: $rhs) -> $t {
                ($method)(*self, <$desired_rhs>::from(rhs))
            }
        }

        impl<'a, 'b> Pow<&'a $rhs> for &'b $t {
            type Output = $t;
            #[inline]
            fn pow(self, rhs: &'a $rhs) -> $t {
                ($method)(*self, <$desired_rhs>::from(*rhs))
            }
        }
    };
}

pow_impl!(u8, u8, u32, u8::pow);
pow_impl!(u8, u16, u32, u8::pow);
pow_impl!(u8, u32, u32, u8::pow);
pow_impl!(u8, usize);
pow_impl!(i8, u8, u32, i8::pow);
pow_impl!(i8, u16, u32, i8::pow);
pow_impl!(i8, u32, u32, i8::pow);
pow_impl!(i8, usize);
pow_impl!(u16, u8, u32, u16::pow);
pow_impl!(u16, u16, u32, u16::pow);
pow_impl!(u16, u32, u32, u16::pow);
pow_impl!(u16, usize);
pow_impl!(i16, u8, u32, i16::pow);
pow_impl!(i16, u16, u32, i16::pow);
pow_impl!(i16, u32, u32, i16::pow);
pow_impl!(i16, usize);
pow_impl!(u32, u8, u32, u32::pow);
pow_impl!(u32, u16, u32, u32::pow);
pow_impl!(u32, u32, u32, u32::pow);
pow_impl!(u32, usize);
pow_impl!(i32, u8, u32, i32::pow);
pow_impl!(i32, u16, u32, i32::pow);
pow_impl!(i32, u32, u32, i32::pow);
pow_impl!(i32, usize);
pow_impl!(u64, u8, u32, u64::pow);
pow_impl!(u64, u16, u32, u64::pow);
pow_impl!(u64, u32, u32, u64::pow);
pow_impl!(u64, usize);
pow_impl!(i64, u8, u32, i64::pow);
pow_impl!(i64, u16, u32, i64::pow);
pow_impl!(i64, u32, u32, i64::pow);
pow_impl!(i64, usize);

#[cfg(has_i128)]
pow_impl!(u128, u8, u32, u128::pow);
#[cfg(has_i128)]
pow_impl!(u128, u16, u32, u128::pow);
#[cfg(has_i128)]
pow_impl!(u128, u32, u32, u128::pow);
#[cfg(has_i128)]
pow_impl!(u128, usize);

#[cfg(has_i128)]
pow_impl!(i128, u8, u32, i128::pow);
#[cfg(has_i128)]
pow_impl!(i128, u16, u32, i128::pow);
#[cfg(has_i128)]
pow_impl!(i128, u32, u32, i128::pow);
#[cfg(has_i128)]
pow_impl!(i128, usize);

pow_impl!(usize, u8, u32, usize::pow);
pow_impl!(usize, u16, u32, usize::pow);
pow_impl!(usize, u32, u32, usize::pow);
pow_impl!(usize, usize);
pow_impl!(isize, u8, u32, isize::pow);
pow_impl!(isize, u16, u32, isize::pow);
pow_impl!(isize, u32, u32, isize::pow);
pow_impl!(isize, usize);
pow_impl!(Wrapping<u8>);
pow_impl!(Wrapping<i8>);
pow_impl!(Wrapping<u16>);
pow_impl!(Wrapping<i16>);
pow_impl!(Wrapping<u32>);
pow_impl!(Wrapping<i32>);
pow_impl!(Wrapping<u64>);
pow_impl!(Wrapping<i64>);
#[cfg(has_i128)]
pow_impl!(Wrapping<u128>);
#[cfg(has_i128)]
pow_impl!(Wrapping<i128>);
pow_impl!(Wrapping<usize>);
pow_impl!(Wrapping<isize>);

// FIXME: these should be possible
// pow_impl!(u8, u64);
// pow_impl!(i16, u64);
// pow_impl!(i8, u64);
// pow_impl!(u16, u64);
// pow_impl!(u32, u64);
// pow_impl!(i32, u64);
// pow_impl!(u64, u64);
// pow_impl!(i64, u64);
// pow_impl!(usize, u64);
// pow_impl!(isize, u64);

#[cfg(feature = "std")]
mod float_impls {
    use super::Pow;

    pow_impl!(f32, i8, i32, f32::powi);
    pow_impl!(f32, u8, i32, f32::powi);
    pow_impl!(f32, i16, i32, f32::powi);
    pow_impl!(f32, u16, i32, f32::powi);
    pow_impl!(f32, i32, i32, f32::powi);
    pow_impl!(f64, i8, i32, f64::powi);
    pow_impl!(f64, u8, i32, f64::powi);
    pow_impl!(f64, i16, i32, f64::powi);
    pow_impl!(f64, u16, i32, f64::powi);
    pow_impl!(f64, i32, i32, f64::powi);
    pow_impl!(f32, f32, f32, f32::powf);
    pow_impl!(f64, f32, f64, f64::powf);
    pow_impl!(f64, f64, f64, f64::powf);
}

/// Raises a value to the power of exp, using exponentiation by squaring.
///
/// Note that `0⁰` (`pow(0, 0)`) returnes `1`. Mathematicly this is undefined.
///
/// # Example
///
/// ```rust
/// use num_traits::pow;
///
/// assert_eq!(pow(2i8, 4), 16);
/// assert_eq!(pow(6u8, 3), 216);
/// assert_eq!(pow(0u8, 0), 1); // Be aware if this case affects you
/// ```
#[inline]
pub fn pow<T: Clone + One + Mul<T, Output = T>>(mut base: T, mut exp: usize) -> T {
    if exp == 0 {
        return T::one();
    }

    while exp & 1 == 0 {
        base = base.clone() * base;
        exp >>= 1;
    }
    if exp == 1 {
        return base;
    }

    let mut acc = base.clone();
    while exp > 1 {
        exp >>= 1;
        base = base.clone() * base;
        if exp & 1 == 1 {
            acc = acc * base.clone();
        }
    }
    acc
}

/// Raises a value to the power of exp, returning `None` if an overflow occurred.
///
/// Note that `0⁰` (`checked_pow(0, 0)`) returnes `Some(1)`. Mathematicly this is undefined.
///
/// Otherwise same as the `pow` function.
///
/// # Example
///
/// ```rust
/// use num_traits::checked_pow;
///
/// assert_eq!(checked_pow(2i8, 4), Some(16));
/// assert_eq!(checked_pow(7i8, 8), None);
/// assert_eq!(checked_pow(7u32, 8), Some(5_764_801));
/// assert_eq!(checked_pow(0u32, 0), Some(1)); // Be aware if this case affect you
/// ```
#[inline]
pub fn checked_pow<T: Clone + One + CheckedMul>(mut base: T, mut exp: usize) -> Option<T> {
    if exp == 0 {
        return Some(T::one());
    }

    macro_rules! optry {
        ($expr:expr) => {
            if let Some(val) = $expr {
                val
            } else {
                return None;
            }
        };
    }

    while exp & 1 == 0 {
        base = optry!(base.checked_mul(&base));
        exp >>= 1;
    }
    if exp == 1 {
        return Some(base);
    }

    let mut acc = base.clone();
    while exp > 1 {
        exp >>= 1;
        base = optry!(base.checked_mul(&base));
        if exp & 1 == 1 {
            acc = optry!(acc.checked_mul(&base));
        }
    }
    Some(acc)
}
<|endoftext|>


<commit_before>use ::*;

#[get("/pvp")]
fn pvpindex<'a>() -> ContRes<'a> {
    let conn = lock_database();
    let mut stmt = conn.prepare("SELECT id, name FROM players order by name").unwrap();
    let names: Vec<_> = stmt.query_map(&[], |row| {
            Named {
                id: row.get(0),
                name: row.get(1)
            }
        })
        .unwrap()
        .map(Result::unwrap)
        .collect();

    let mut context = create_context("pvp");
    context.add("names", &names);

    respond_page("pvpindex", context)
}

#[get("/pvp/<p1>/<p2>")]
fn pvp<'a>(p1: i32, p2: i32) -> ContRes<'a> {
    let conn = lock_database();
    let mut stmt =
        conn.prepare("SELECT (SELECT name FROM players p WHERE p.id = g.home_id) AS home, \
                      (SELECT name FROM players p WHERE p.id = g.away_id) AS away, home_score, \
                      away_score, ball_id, (SELECT img FROM balls b WHERE ball_id = b.id), \
                      (SELECT name FROM balls b WHERE ball_id = b.id), dato, home_id FROM games g \
                      WHERE (home_id = ?1 and away_id = ?2) or (home_id = ?2 and away_id = ?1) \
                      and dato > date('now','start of month') ORDER BY dato DESC")
            .unwrap();

    let mut map = ((0, 0, "".to_owned()), (0, 0, "".to_owned()));

    let pvp: Vec<_> = stmt.query_map(&[&p1, &p2], |row| {
            let game = PlayedGame {
                home: row.get(0),
                away: row.get(1),
                home_score: row.get(2),
                away_score: row.get(3),
                ball: row.get(5),
                ball_name: row.get(6),
                dato: row.get(7),
            };
            let home_id: i32 = row.get(8);

            let home_win = game.home_score > game.away_score;
            {
                let home = if home_id == p1 {&mut map.0} else {&mut map.1};
                if home.2.is_empty() {
                    home.2 = game.home.clone();
                }
                home.0 += game.home_score;
                if home_win { home.1 += 1 }
            }
            {
                let away = if home_id == p1 {&mut map.1} else {&mut map.0};
                if away.2.is_empty() {
                    away.2 = game.away.clone();
                }
                away.0 += game.away_score;
                if !home_win { away.1 += 1 }
            }

            game
        })
        .unwrap()
        .map(Result::unwrap)
        .collect();

    print!("{:?}", map);

//      p1  mål     p1 vundne   p1 navn     p1 antal kampe
//      p2  mål     p2 vundne   p2 navn     p2 antal kampe

    let mut context = create_context("pvp");

    context.add("pvp", &pvp);
    context.add("map", &map);
    respond_page("pvp", context)
}
<commit_msg>Fix #49<commit_after>use ::*;

#[get("/pvp")]
fn pvpindex<'a>() -> ContRes<'a> {
    let conn = lock_database();
    let mut stmt = conn.prepare("SELECT id, name FROM players order by name").unwrap();
    let names: Vec<_> = stmt.query_map(&[], |row| {
            Named {
                id: row.get(0),
                name: row.get(1)
            }
        })
        .unwrap()
        .map(Result::unwrap)
        .collect();

    let mut context = create_context("pvp");
    context.add("names", &names);

    respond_page("pvpindex", context)
}

#[get("/pvp/<p1>/<p2>")]
fn pvp<'a>(p1: i32, p2: i32) -> ContRes<'a> {
    let conn = lock_database();
    let mut stmt =
        conn.prepare("SELECT (SELECT name FROM players p WHERE p.id = g.home_id) AS home, \
                      (SELECT name FROM players p WHERE p.id = g.away_id) AS away, home_score, \
                      away_score, ball_id, (SELECT img FROM balls b WHERE ball_id = b.id), \
                      (SELECT name FROM balls b WHERE ball_id = b.id), dato, home_id FROM games g \
                      WHERE (home_id = ?1 and away_id = ?2) and dato > date('now','start of month') \
                      or (home_id = ?2 and away_id = ?1) and dato > date('now','start of month') \
                      ORDER BY dato DESC")
            .unwrap();

    let mut map = ((0, 0, "".to_owned()), (0, 0, "".to_owned()));

    let pvp: Vec<_> = stmt.query_map(&[&p1, &p2], |row| {
            let game = PlayedGame {
                home: row.get(0),
                away: row.get(1),
                home_score: row.get(2),
                away_score: row.get(3),
                ball: row.get(5),
                ball_name: row.get(6),
                dato: row.get(7),
            };
            let home_id: i32 = row.get(8);

            let home_win = game.home_score > game.away_score;
            {
                let home = if home_id == p1 {&mut map.0} else {&mut map.1};
                if home.2.is_empty() {
                    home.2 = game.home.clone();
                }
                home.0 += game.home_score;
                if home_win { home.1 += 1 }
            }
            {
                let away = if home_id == p1 {&mut map.1} else {&mut map.0};
                if away.2.is_empty() {
                    away.2 = game.away.clone();
                }
                away.0 += game.away_score;
                if !home_win { away.1 += 1 }
            }

            game
        })
        .unwrap()
        .map(Result::unwrap)
        .collect();

    print!("{:?}", map);

//      p1  mål     p1 vundne   p1 navn     p1 antal kampe
//      p2  mål     p2 vundne   p2 navn     p2 antal kampe

    let mut context = create_context("pvp");

    context.add("pvp", &pvp);
    context.add("map", &map);
    respond_page("pvp", context)
}
<|endoftext|>


<commit_before>#[allow(dead_code)]
#[allow(unused_variables)]
extern crate mmap;

use std::mem;
use std::ptr;
use std::fs::OpenOptions;
use std::os::unix::fs::OpenOptionsExt;
use mmap::{MemoryMap, MapOption};
use std::os::unix::prelude::AsRawFd;

const BCM2708_PERI_BASE: u32 = 0x20000000;
const GPIO_BASE: u8 = (BCM2708_PERI_BASE + 0x200000) as u8;
const O_SYNC: u32 = 1052672;
const MAP_SHARED: i32 = 0x0001;
const BLOCK_SIZE: usize = (4*1024);
enum Void {} // void type

struct Bcm2835Peripheral {
    addr_p: *const u8,
    mem_fd: i32,
    map: mmap::MemoryMap,
    addr: *mut u8
}

fn main() {
    unsafe {
        let gpio = Bcm2835Peripheral { addr_p: &GPIO_BASE, mem_fd: 0, map: MemoryMap::new(1024, &[]).unwrap(), addr: ptr::null_mut()};
        map_peripheral(gpio);
    }
}

fn map_peripheral(mut foo: Bcm2835Peripheral) {
    let file = match OpenOptions::new()
                    .read(true)
                    .write(true)
                    .mode(O_SYNC)
                    .open("/dev/mem") {
      Ok(file) => file,
      Err(e) => panic!("Unable to open /dev/mem, Are you root?")
    };

    let map_opts = &[
        MapOption::MapNonStandardFlags(MAP_SHARED),
        MapOption::MapReadable,
        MapOption::MapWritable,
       // MapOption::MapAddr(foo.addr_p),
        MapOption::MapFd(file.as_raw_fd())
    ];

   let mmap = match MemoryMap::new(BLOCK_SIZE, map_opts) {
     Ok(mmap) => mmap,
     Err(e) => panic!("ERR: {}", e)
    };
    foo.map = mmap;
    foo.addr = foo.map.data();
    println!("{:?}", foo.map.data());
}
<commit_msg>remove unused unsafe block<commit_after>extern crate mmap;

use std::ptr;
use std::fs::OpenOptions;
use std::os::unix::fs::OpenOptionsExt;
use mmap::{MemoryMap, MapOption};
use std::os::unix::prelude::AsRawFd;

const BCM2708_PERI_BASE: u32 = 0x20000000;
const GPIO_BASE: u8 = (BCM2708_PERI_BASE + 0x200000) as u8;
const O_SYNC: u32 = 1052672;
const MAP_SHARED: i32 = 0x0001;
const BLOCK_SIZE: usize = (4*1024);

#[allow(dead_code)]
struct Bcm2835Peripheral {
    addr_p: *const u8,
    mem_fd: i32,
    map: mmap::MemoryMap,
    addr: *mut u8
}

fn main() {
    let gpio = Bcm2835Peripheral { addr_p: &GPIO_BASE, mem_fd: 0, map: MemoryMap::new(1024, &[]).unwrap(), addr: ptr::null_mut()};
    map_peripheral(gpio);
}

fn map_peripheral(mut foo: Bcm2835Peripheral) {
    let file = match OpenOptions::new()
                    .read(true)
                    .write(true)
                    .mode(O_SYNC)
                    .open("/dev/mem") {
      Ok(file) => file,
      Err(_e) => panic!("Unable to open /dev/mem, Are you root?")
    };

    let map_opts = &[
        MapOption::MapNonStandardFlags(MAP_SHARED),
        MapOption::MapReadable,
        MapOption::MapWritable,
       // MapOption::MapAddr(foo.addr_p),
        MapOption::MapFd(file.as_raw_fd())
    ];

   let mmap = match MemoryMap::new(BLOCK_SIZE, map_opts) {
     Ok(mmap) => mmap,
     Err(e) => panic!("ERR: {}", e)
    };
    foo.map = mmap;
    foo.addr = foo.map.data();
    println!("{:?}", foo.map.data());
}
<|endoftext|>


<commit_before>use LDAPResult;
use ber::{Tag, Type, Class, Payload};

pub trait LDAPTag
{
    fn into_tag(self) -> Tag;
    fn from_tag(tag: Tag) -> LDAPResult<Self>;
}

impl LDAPTag for Tag
{
    fn into_tag(self) -> Tag
    {
        self
    }

    fn from_tag(tag: Tag) -> LDAPResult<Self>
    {
        Ok(tag)
    }
}

impl<T> LDAPTag for Vec<T> where T: LDAPTag
{
    fn into_tag(self) -> Tag
    {
        let tagvec = self.into_iter().map(|x| x.into_tag()).collect();
        Tag::new(Class::Universal(Type::Sequence), Payload::Constructed(tagvec))
    }

    fn from_tag(tag: Tag) -> LDAPResult<Self>
    {
        let tags = try!(tag.into_payload().into_inner_constructed());
        let mut values = Vec::<T>::new();
        for tag in tags
        {
            let value: T = try!(LDAPTag::from_tag(tag));
            values.push(value);
        }
        Ok(values)
    }
}

impl LDAPTag for String
{
    fn into_tag(self) -> Tag
    {
        Tag::new(Class::Universal(Type::OctetString), Payload::Primitive(self.into_bytes()))
    }

    fn from_tag(tag: Tag) -> LDAPResult<Self>
    {
        let payload = try!(tag.into_payload().into_inner_primitive());
        Ok(try!(String::from_utf8(payload)))
    }
}

impl LDAPTag for bool
{
    fn into_tag(self) -> Tag
    {
        let pl: u8;
        if self {pl = 0xFF} else {pl = 0x00}
        Tag::new(Class::Universal(Type::Boolean), Payload::Primitive(vec![pl]))
    }

    fn from_tag(tag: Tag) -> LDAPResult<Self>
    {
        let byte = try!(tag.into_payload().into_inner_primitive())[0];
        Ok(byte == 0xFF)
    }
}

impl LDAPTag for i32
{
    fn into_tag(self) -> Tag
    {
        let mut count: u8 = 0;
        let mut clone = self;
        while {count += 1; clone >>= 8; clone > 0 }{}
        let mut bytes = Vec::<u8>::new();
        for i in (0..count).rev()
        {
            bytes.push(((self & (0xFF << i * 8)) >> i * 8) as u8);
        }
        Tag::new(Class::Universal(Type::Integer), Payload::Primitive(bytes))
    }

    fn from_tag(tag: Tag) -> LDAPResult<Self>
    {
        let bytes = try!(tag.into_payload().into_inner_primitive());
        let mut res = 0i32;
        let mut i = 0u8;
        for byte in bytes
        {
            res = byte as i32 >> (32 - i * 8);
            i += 1;
        }
        Ok(res)
    }
}
<commit_msg>Fix for RFC 1214<commit_after>use LDAPResult;
use ber::{Tag, Type, Class, Payload};

pub trait LDAPTag: Sized
{
    fn into_tag(self) -> Tag;
    fn from_tag(tag: Tag) -> LDAPResult<Self>;
}

impl LDAPTag for Tag
{
    fn into_tag(self) -> Tag
    {
        self
    }

    fn from_tag(tag: Tag) -> LDAPResult<Self>
    {
        Ok(tag)
    }
}

impl<T> LDAPTag for Vec<T> where T: LDAPTag
{
    fn into_tag(self) -> Tag
    {
        let tagvec = self.into_iter().map(|x| x.into_tag()).collect();
        Tag::new(Class::Universal(Type::Sequence), Payload::Constructed(tagvec))
    }

    fn from_tag(tag: Tag) -> LDAPResult<Self>
    {
        let tags = try!(tag.into_payload().into_inner_constructed());
        let mut values = Vec::<T>::new();
        for tag in tags
        {
            let value: T = try!(LDAPTag::from_tag(tag));
            values.push(value);
        }
        Ok(values)
    }
}

impl LDAPTag for String
{
    fn into_tag(self) -> Tag
    {
        Tag::new(Class::Universal(Type::OctetString), Payload::Primitive(self.into_bytes()))
    }

    fn from_tag(tag: Tag) -> LDAPResult<Self>
    {
        let payload = try!(tag.into_payload().into_inner_primitive());
        Ok(try!(String::from_utf8(payload)))
    }
}

impl LDAPTag for bool
{
    fn into_tag(self) -> Tag
    {
        let pl: u8;
        if self {pl = 0xFF} else {pl = 0x00}
        Tag::new(Class::Universal(Type::Boolean), Payload::Primitive(vec![pl]))
    }

    fn from_tag(tag: Tag) -> LDAPResult<Self>
    {
        let byte = try!(tag.into_payload().into_inner_primitive())[0];
        Ok(byte == 0xFF)
    }
}

impl LDAPTag for i32
{
    fn into_tag(self) -> Tag
    {
        let mut count: u8 = 0;
        let mut clone = self;
        while {count += 1; clone >>= 8; clone > 0 }{}
        let mut bytes = Vec::<u8>::new();
        for i in (0..count).rev()
        {
            bytes.push(((self & (0xFF << i * 8)) >> i * 8) as u8);
        }
        Tag::new(Class::Universal(Type::Integer), Payload::Primitive(bytes))
    }

    fn from_tag(tag: Tag) -> LDAPResult<Self>
    {
        let bytes = try!(tag.into_payload().into_inner_primitive());
        let mut res = 0i32;
        let mut i = 0u8;
        for byte in bytes
        {
            res = byte as i32 >> (32 - i * 8);
            i += 1;
        }
        Ok(res)
    }
}
<|endoftext|>


<commit_before>use std::io::prelude::*;
use std::net;
use std::io;
use std::convert::From;

extern crate rustc_serialize;
use rustc_serialize::json;
use rustc_serialize::Encodable;

extern crate time;

pub struct Fluentd<'a, A: net::ToSocketAddrs> {
    pub address: A,
    pub tag: &'a str,
}

#[derive(Debug)]
pub enum FluentError {
    DecodeError(json::EncoderError),
    IoError(io::Error),
}

impl From<io::Error> for FluentError {
    fn from(err: io::Error) -> FluentError {
        FluentError::IoError(err)
    }
}

impl From<json::EncoderError> for FluentError {
    fn from(err: json::EncoderError) -> FluentError {
        FluentError::DecodeError(err)
    }
}

impl <'a, A: net::ToSocketAddrs> Fluentd<'a, A> {
    pub fn new(address: A, tag: &'a str) -> Fluentd<'a, A> {
        Fluentd {
            address: address,
            tag: tag
        }
    }

    pub fn write<B: Encodable>(&self, object: &B) -> Result<(), FluentError> {
        let tag = try!(json::encode(&self.tag));
        let now = time::now();
        let record = try!(json::encode(object));
        let message = format!("[{},{},{}]", tag, now.to_timespec().sec, record);

        let mut stream = try!(net::TcpStream::connect(&self.address));
        let _ = stream.write(&message.into_bytes());
        drop(stream);

        Ok(())
    }
}
<commit_msg>tcp: Return result explicitly<commit_after>use std::io::prelude::*;
use std::net;
use std::io;
use std::convert::From;

extern crate rustc_serialize;
use rustc_serialize::json;
use rustc_serialize::Encodable;

extern crate time;

pub struct Fluentd<'a, A: net::ToSocketAddrs> {
    pub address: A,
    pub tag: &'a str,
}

#[derive(Debug)]
pub enum FluentError {
    DecodeError(json::EncoderError),
    IoError(io::Error),
}

impl From<io::Error> for FluentError {
    fn from(err: io::Error) -> FluentError {
        FluentError::IoError(err)
    }
}

impl From<json::EncoderError> for FluentError {
    fn from(err: json::EncoderError) -> FluentError {
        FluentError::DecodeError(err)
    }
}

impl <'a, A: net::ToSocketAddrs> Fluentd<'a, A> {
    pub fn new(address: A, tag: &'a str) -> Fluentd<'a, A> {
        Fluentd {
            address: address,
            tag: tag
        }
    }

    pub fn write<B: Encodable>(&self, object: &B) -> Result<(), FluentError> {
        let tag = try!(json::encode(&self.tag));
        let now = time::now();
        let record = try!(json::encode(object));
        let message = format!("[{},{},{}]", tag, now.to_timespec().sec, record);

        let mut stream = try!(net::TcpStream::connect(&self.address));
        let result = stream.write(&message.into_bytes());
        drop(stream);

        match result {
            Ok(_) => Ok(()),
            Err(v) => Err(From::from(v)),
        }
    }
}
<|endoftext|>