<commit_before>use std::hash::{Hash};
use std::collections::HashMap;
use std::collections::hash_map::Hasher;
use std::iter::Map;
use std::collections::hash_map::{
    Keys,
};
use std::collections::hash_map::Entry::{
    Occupied,
    Vacant,
};
use std::slice::{
    Iter,
};
use std::fmt;

/// **GraphMap\<N, E\>** is an undirected graph, with generic node values **N** and edge weights **E**.
///
/// It uses an combined adjacency list and sparse adjacency matrix representation, using *O(|N|
/// + |E|)* space, and allows testing for edge existance in constant time.
///
/// The node type **N** must implement Copy and will be used as node identifier, duplicated
/// into several places in the data structure.
/// It must be suitable as a hash table key (implementing **Eq + Hash**).
/// The node type must also implement **PartialOrd** so that the implementation can
/// order the pair (**a**, **b**) for an edge connecting any two nodes **a** and **b**.
///
/// **GraphMap** does not allow parallel edges, but self loops are allowed.
#[derive(Clone)]
pub struct GraphMap<N: Eq + Hash<Hasher>, E> {
    nodes: HashMap<N, Vec<N>>,
    edges: HashMap<(N, N), E>,
}

impl<N: Eq + Hash<Hasher> + fmt::Show, E: fmt::Show> fmt::Show for GraphMap<N, E>
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.nodes.fmt(f)
    }
}

#[inline]
fn edge_key<N: Copy + PartialOrd>(a: N, b: N) -> (N, N)
{
    if a <= b { (a, b) } else { (b, a) }
}

#[inline]
fn copy<N: Copy>(n: &N) -> N { *n }

impl<N, E> GraphMap<N, E> where N: Copy + PartialOrd + Eq + Hash<Hasher>
{
    /// Create a new **GraphMap**.
    pub fn new() -> Self
    {
        GraphMap {
            nodes: HashMap::new(),
            edges: HashMap::new(),
        }
    }

    /// Create a new **GraphMap** with estimated capacity.
    pub fn with_capacity(nodes: usize, edges: usize) -> Self
    {
        GraphMap {
            nodes: HashMap::with_capacity(nodes),
            edges: HashMap::with_capacity(edges),
        }
    }

    /// Return the number of nodes in the graph.
    pub fn node_count(&self) -> usize
    {
        self.nodes.len()
    }

    /// Return the number of edges in the graph.
    pub fn edge_count(&self) -> usize
    {
        self.edges.len()
    }

    /// Add node **n** to the graph.
    pub fn add_node(&mut self, n: N) -> N {
        match self.nodes.entry(n) {
            Occupied(_) => {}
            Vacant(ent) => { ent.insert(Vec::new()); }
        }
        n
    }

    /// Return **true** if node **n** was removed.
    pub fn remove_node(&mut self, n: N) -> bool {
        let successors = match self.nodes.remove(&n) {
            None => return false,
            Some(sus) => sus,
        };
        for succ in successors.into_iter() {
            // remove all successor links
            self.remove_single_edge(&succ, &n);
            // Remove all edge values
            self.edges.remove(&edge_key(n, succ));
        }
        true
    }

    /// Return **true** if the node is contained in the graph.
    pub fn contains_node(&self, n: N) -> bool {
        self.nodes.contains_key(&n)
    }

    /// Add an edge connecting **a** and **b** to the graph.
    ///
    /// Inserts nodes **a** and/or **b** if they aren't already part of the graph.
    ///
    /// Return **true** if edge did not previously exist.
    ///
    /// ## Example
    /// ```
    /// use petgraph::GraphMap;
    ///
    /// let mut g = GraphMap::new();
    /// g.add_edge(1, 2, -1);
    /// assert_eq!(g.node_count(), 2);
    /// assert_eq!(g.edge_count(), 1);
    /// ```
    pub fn add_edge(&mut self, a: N, b: N, edge: E) -> bool
    {
        // Use PartialOrd to order the edges
        match self.nodes.entry(a) {
            Occupied(ent) => { ent.into_mut().push(b); }
            Vacant(ent) => { ent.insert(vec![b]); }
        }
        match self.nodes.entry(b) {
            Occupied(ent) => { ent.into_mut().push(a); }
            Vacant(ent) => { ent.insert(vec![a]); }
        }
        self.edges.insert(edge_key(a, b), edge).is_none()
    }

    /// Remove successor relation from a to b
    fn remove_single_edge(&mut self, a: &N, b: &N) {
        match self.nodes.get_mut(a) {
            None => {}
            Some(sus) => {
                match sus.iter().position(|elt| elt == b) {
                    Some(index) => { sus.swap_remove(index); }
                    None => {}
                }
            }
        }
    }

    /// Remove edge from **a** to **b** from the graph.
    ///
    /// Return **None** if the edge didn't exist.
    ///
    /// ## Example
    ///
    /// ```
    /// use petgraph::GraphMap;
    ///
    /// let mut g = GraphMap::new();
    /// g.add_node(1);
    /// g.add_node(2);
    /// g.add_edge(1, 2, -1);
    ///
    /// let edge = g.remove_edge(2, 1);
    /// assert_eq!(edge, Some(-1));
    /// assert_eq!(g.edge_count(), 0);
    /// ```
    pub fn remove_edge(&mut self, a: N, b: N) -> Option<E>
    {
        self.remove_single_edge(&a, &b);
        self.remove_single_edge(&b, &a);
        self.edges.remove(&edge_key(a, b))
    }

    /// Return **true** if the edge connecting **a** with **b** is contained in the graph.
    pub fn contains_edge(&self, a: N, b: N) -> bool {
        self.edges.contains_key(&edge_key(a, b))
    }

    /// Return an iterator over the nodes of the graph.
    ///
    /// Iterator element type is **N**.
    pub fn nodes<'a>(&'a self) -> Nodes<'a, N>
    {
        Nodes{iter: self.nodes.keys().map(copy as fn(&N) -> N)}
    }

    /// Return an iterator over the nodes that are connected with **from** by edges.
    ///
    /// If the node **from** does not exist in the graph, return an empty iterator.
    ///
    /// Iterator element type is **N**.
    pub fn neighbors<'a>(&'a self, from: N) -> Neighbors<'a, N>
    {
        Neighbors{iter:
            match self.nodes.get(&from) {
                Some(neigh) => neigh.iter(),
                None => [].iter(),
            }.map(copy as fn(&N) -> N)
        }
    }

    /// Return an iterator over the nodes that are connected with **from** by edges,
    /// paired with the edge weight.
    ///
    /// If the node **from** does not exist in the graph, return an empty iterator.
    ///
    /// Iterator element type is **(N, &'a E)**.
    pub fn edges<'a>(&'a self, from: N) -> Edges<'a, N, E>
    {
        Edges {
            from: from,
            iter: self.neighbors(from),
            edges: &self.edges,
        }
    }

    /// Return a reference to the edge weight connecting **a** with **b**, or
    /// **None** if the edge does not exist in the graph.
    pub fn edge_weight<'a>(&'a self, a: N, b: N) -> Option<&'a E>
    {
        self.edges.get(&edge_key(a, b))
    }

    /// Return a mutable reference to the edge weight connecting **a** with **b**, or
    /// **None** if the edge does not exist in the graph.
    pub fn edge_weight_mut<'a>(&'a mut self, a: N, b: N) -> Option<&'a mut E>
    {
        self.edges.get_mut(&edge_key(a, b))
    }
}

macro_rules! iterator_methods {
    () => (
        #[inline]
        fn next(&mut self) -> Option<<Self as Iterator>::Item>
        {
            self.iter.next()
        }

        #[inline]
        fn size_hint(&self) -> (usize, Option<usize>)
        {
            self.iter.size_hint()
        }
    )
}

pub struct Nodes<'a, N: 'a> {
    iter: Map<&'a N, N, Keys<'a, N, Vec<N>>, fn(&N) -> N>,
}

impl<'a, N> Iterator for Nodes<'a, N>
{
    type Item = N;
    iterator_methods!();
}

pub struct Neighbors<'a, N: 'a> {
    iter: Map<&'a N, N, Iter<'a, N>, fn(&N) -> N>,
}

impl<'a, N> Iterator for Neighbors<'a, N>
{
    type Item = N;
    iterator_methods!();
}

pub struct Edges<'a, N: 'a + Copy + PartialOrd + Eq + Hash<Hasher>, E: 'a> {
    pub from: N,
    pub edges: &'a HashMap<(N, N), E>,
    pub iter: Neighbors<'a, N>,
}

impl<'a, N, E> Iterator for Edges<'a, N, E>
    where N: 'a + Copy + PartialOrd + Eq + Hash<Hasher>, E: 'a
{
    type Item = (N, &'a E);
    fn next(&mut self) -> Option<(N, &'a E)>
    {
        match self.iter.next() {
            None => None,
            Some(b) => {
                let a = self.from;
                match self.edges.get(&edge_key(a, b)) {
                    None => unreachable!(),
                    Some(edge) => {
                        Some((b, edge))
                    }
                }
            }
        }
    }
}
<commit_msg>impl Index for GraphMap<commit_after>use std::hash::{Hash};
use std::collections::HashMap;
use std::collections::hash_map::Hasher;
use std::iter::Map;
use std::collections::hash_map::{
    Keys,
};
use std::collections::hash_map::Entry::{
    Occupied,
    Vacant,
};
use std::slice::{
    Iter,
};
use std::fmt;
use std::ops::{Index, IndexMut};

/// **GraphMap\<N, E\>** is an undirected graph, with generic node values **N** and edge weights **E**.
///
/// It uses an combined adjacency list and sparse adjacency matrix representation, using *O(|N|
/// + |E|)* space, and allows testing for edge existance in constant time.
///
/// The node type **N** must implement Copy and will be used as node identifier, duplicated
/// into several places in the data structure.
/// It must be suitable as a hash table key (implementing **Eq + Hash**).
/// The node type must also implement **PartialOrd** so that the implementation can
/// order the pair (**a**, **b**) for an edge connecting any two nodes **a** and **b**.
///
/// **GraphMap** does not allow parallel edges, but self loops are allowed.
#[derive(Clone)]
pub struct GraphMap<N: Eq + Hash<Hasher>, E> {
    nodes: HashMap<N, Vec<N>>,
    edges: HashMap<(N, N), E>,
}

impl<N: Eq + Hash<Hasher> + fmt::Show, E: fmt::Show> fmt::Show for GraphMap<N, E>
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.nodes.fmt(f)
    }
}

#[inline]
fn edge_key<N: Copy + PartialOrd>(a: N, b: N) -> (N, N)
{
    if a <= b { (a, b) } else { (b, a) }
}

#[inline]
fn copy<N: Copy>(n: &N) -> N { *n }

impl<N, E> GraphMap<N, E> where N: Copy + PartialOrd + Eq + Hash<Hasher>
{
    /// Create a new **GraphMap**.
    pub fn new() -> Self
    {
        GraphMap {
            nodes: HashMap::new(),
            edges: HashMap::new(),
        }
    }

    /// Create a new **GraphMap** with estimated capacity.
    pub fn with_capacity(nodes: usize, edges: usize) -> Self
    {
        GraphMap {
            nodes: HashMap::with_capacity(nodes),
            edges: HashMap::with_capacity(edges),
        }
    }

    /// Return the number of nodes in the graph.
    pub fn node_count(&self) -> usize
    {
        self.nodes.len()
    }

    /// Return the number of edges in the graph.
    pub fn edge_count(&self) -> usize
    {
        self.edges.len()
    }

    /// Add node **n** to the graph.
    pub fn add_node(&mut self, n: N) -> N {
        match self.nodes.entry(n) {
            Occupied(_) => {}
            Vacant(ent) => { ent.insert(Vec::new()); }
        }
        n
    }

    /// Return **true** if node **n** was removed.
    pub fn remove_node(&mut self, n: N) -> bool {
        let successors = match self.nodes.remove(&n) {
            None => return false,
            Some(sus) => sus,
        };
        for succ in successors.into_iter() {
            // remove all successor links
            self.remove_single_edge(&succ, &n);
            // Remove all edge values
            self.edges.remove(&edge_key(n, succ));
        }
        true
    }

    /// Return **true** if the node is contained in the graph.
    pub fn contains_node(&self, n: N) -> bool {
        self.nodes.contains_key(&n)
    }

    /// Add an edge connecting **a** and **b** to the graph.
    ///
    /// Inserts nodes **a** and/or **b** if they aren't already part of the graph.
    ///
    /// Return **true** if edge did not previously exist.
    ///
    /// ## Example
    /// ```
    /// use petgraph::GraphMap;
    ///
    /// let mut g = GraphMap::new();
    /// g.add_edge(1, 2, -1);
    /// assert_eq!(g.node_count(), 2);
    /// assert_eq!(g.edge_count(), 1);
    /// ```
    pub fn add_edge(&mut self, a: N, b: N, edge: E) -> bool
    {
        // Use PartialOrd to order the edges
        match self.nodes.entry(a) {
            Occupied(ent) => { ent.into_mut().push(b); }
            Vacant(ent) => { ent.insert(vec![b]); }
        }
        match self.nodes.entry(b) {
            Occupied(ent) => { ent.into_mut().push(a); }
            Vacant(ent) => { ent.insert(vec![a]); }
        }
        self.edges.insert(edge_key(a, b), edge).is_none()
    }

    /// Remove successor relation from a to b
    fn remove_single_edge(&mut self, a: &N, b: &N) {
        match self.nodes.get_mut(a) {
            None => {}
            Some(sus) => {
                match sus.iter().position(|elt| elt == b) {
                    Some(index) => { sus.swap_remove(index); }
                    None => {}
                }
            }
        }
    }

    /// Remove edge from **a** to **b** from the graph.
    ///
    /// Return **None** if the edge didn't exist.
    ///
    /// ## Example
    ///
    /// ```
    /// use petgraph::GraphMap;
    ///
    /// let mut g = GraphMap::new();
    /// g.add_node(1);
    /// g.add_node(2);
    /// g.add_edge(1, 2, -1);
    ///
    /// let edge = g.remove_edge(2, 1);
    /// assert_eq!(edge, Some(-1));
    /// assert_eq!(g.edge_count(), 0);
    /// ```
    pub fn remove_edge(&mut self, a: N, b: N) -> Option<E>
    {
        self.remove_single_edge(&a, &b);
        self.remove_single_edge(&b, &a);
        self.edges.remove(&edge_key(a, b))
    }

    /// Return **true** if the edge connecting **a** with **b** is contained in the graph.
    pub fn contains_edge(&self, a: N, b: N) -> bool {
        self.edges.contains_key(&edge_key(a, b))
    }

    /// Return an iterator over the nodes of the graph.
    ///
    /// Iterator element type is **N**.
    pub fn nodes<'a>(&'a self) -> Nodes<'a, N>
    {
        Nodes{iter: self.nodes.keys().map(copy as fn(&N) -> N)}
    }

    /// Return an iterator over the nodes that are connected with **from** by edges.
    ///
    /// If the node **from** does not exist in the graph, return an empty iterator.
    ///
    /// Iterator element type is **N**.
    pub fn neighbors<'a>(&'a self, from: N) -> Neighbors<'a, N>
    {
        Neighbors{iter:
            match self.nodes.get(&from) {
                Some(neigh) => neigh.iter(),
                None => [].iter(),
            }.map(copy as fn(&N) -> N)
        }
    }

    /// Return an iterator over the nodes that are connected with **from** by edges,
    /// paired with the edge weight.
    ///
    /// If the node **from** does not exist in the graph, return an empty iterator.
    ///
    /// Iterator element type is **(N, &'a E)**.
    pub fn edges<'a>(&'a self, from: N) -> Edges<'a, N, E>
    {
        Edges {
            from: from,
            iter: self.neighbors(from),
            edges: &self.edges,
        }
    }

    /// Return a reference to the edge weight connecting **a** with **b**, or
    /// **None** if the edge does not exist in the graph.
    pub fn edge_weight<'a>(&'a self, a: N, b: N) -> Option<&'a E>
    {
        self.edges.get(&edge_key(a, b))
    }

    /// Return a mutable reference to the edge weight connecting **a** with **b**, or
    /// **None** if the edge does not exist in the graph.
    pub fn edge_weight_mut<'a>(&'a mut self, a: N, b: N) -> Option<&'a mut E>
    {
        self.edges.get_mut(&edge_key(a, b))
    }
}

macro_rules! iterator_methods {
    () => (
        #[inline]
        fn next(&mut self) -> Option<<Self as Iterator>::Item>
        {
            self.iter.next()
        }

        #[inline]
        fn size_hint(&self) -> (usize, Option<usize>)
        {
            self.iter.size_hint()
        }
    )
}

pub struct Nodes<'a, N: 'a> {
    iter: Map<&'a N, N, Keys<'a, N, Vec<N>>, fn(&N) -> N>,
}

impl<'a, N> Iterator for Nodes<'a, N>
{
    type Item = N;
    iterator_methods!();
}

pub struct Neighbors<'a, N: 'a> {
    iter: Map<&'a N, N, Iter<'a, N>, fn(&N) -> N>,
}

impl<'a, N> Iterator for Neighbors<'a, N>
{
    type Item = N;
    iterator_methods!();
}

pub struct Edges<'a, N: 'a + Copy + PartialOrd + Eq + Hash<Hasher>, E: 'a> {
    pub from: N,
    pub edges: &'a HashMap<(N, N), E>,
    pub iter: Neighbors<'a, N>,
}

impl<'a, N, E> Iterator for Edges<'a, N, E>
    where N: 'a + Copy + PartialOrd + Eq + Hash<Hasher>, E: 'a
{
    type Item = (N, &'a E);
    fn next(&mut self) -> Option<(N, &'a E)>
    {
        match self.iter.next() {
            None => None,
            Some(b) => {
                let a = self.from;
                match self.edges.get(&edge_key(a, b)) {
                    None => unreachable!(),
                    Some(edge) => {
                        Some((b, edge))
                    }
                }
            }
        }
    }
}

impl<N: Copy + PartialOrd + Eq + Hash<Hasher>, E> Index<(N, N)> for GraphMap<N, E>
{
    type Output = E;
    /// Index **GraphMap** by node pairs to access edge weights.
    fn index(&self, index: &(N, N)) -> &E
    {
        self.edge_weight(index.0, index.1).unwrap()
    }
}

impl<N: Copy + PartialOrd + Eq + Hash<Hasher>, E> IndexMut<(N, N)> for GraphMap<N, E>
{
    type Output = E;
    /// Index **GraphMap** by node pairs to access edge weights.
    fn index_mut(&mut self, index: &(N, N)) -> &mut E
    {
        self.edge_weight_mut(index.0, index.1).unwrap()
    }
}
<|endoftext|>


<commit_before>use gui::*;
use gui::div;

use std::cell::{Ref, RefCell};
use std::time::Instant;
use std::collections::HashMap;

struct CachedDiv {
    /// Node id of the cached div.
    id: it::NodeId,
    /// Visibility of the cached div.
    visibility: div::ComputedVisibility,
    /// The parent id and bbox of the cached div.
    parent: Option<(it::NodeId, Bbox)>,
}

pub struct View<'a> {
    bbox: Bbox,
    arena: it::Arena<div::SpaceDiv<'a>>,
    root_div: it::NodeId,
    children: Vec<it::NodeId>,
    cache: RefCell<Option<Vec<CachedDiv>>>,
    time_start: Instant,
    /// The scrollbars which need to be drawn per div.
    pending_scrollbars: RefCell<HashMap<it::NodeId, (Option<Bbox>, Option<Bbox>)>>,
}

impl<'a> View<'a> {
    pub fn new(bbox: Bbox) -> Self {
        let mut arena = it::Arena::new();
        let root_div = arena.new_node(
            div::SpaceDiv::full()
                .vertical()
                .vert_align(div::Alignment::Min)
                .build(),
        );
        Self {
            bbox,
            arena,
            root_div,
            children: Vec::new(),
            cache: RefCell::new(None),
            time_start: Instant::now(),
            pending_scrollbars: RefCell::new(HashMap::new()),
        }
    }

    pub fn without_bbox() -> Self {
        let zero = Point::new(0, 0);
        Self::new(Bbox::new(zero, zero))
    }

    pub fn add_div(&mut self, parent: Option<it::NodeId>, div: div::SpaceDiv<'a>) -> it::NodeId {
        let node = self.arena.new_node(div);
        parent
            .unwrap_or(self.root_div)
            .append(node, &mut self.arena);
        self.children.push(node);
        *self.cache.borrow_mut() = None;
        node
    }

    pub fn bbox(&self) -> &Bbox {
        &self.bbox
    }

    pub fn set_bbox(&mut self, bbox: Bbox) {
        if bbox != self.bbox {
            *self.cache.borrow_mut() = None;
        }

        self.bbox = bbox;
    }

    /// Returns the root space div of this view.
    pub fn space_div(&self) -> &div::SpaceDiv<'a> {
        &self.arena[self.root_div].data
    }

    /// Draw the entire frame.
    pub fn draw(&self, frame: &nanovg::Frame) {
        self.pending_scrollbars.borrow_mut().clear();

        if let Some(ref divs) = *self.divs() {
            for cached_div in divs.iter() {
                self.draw_div(
                    &self.arena[cached_div.id].data,
                    cached_div.visibility,
                    cached_div.parent,
                    frame,
                );
            }
        }

        self.draw_scrollbars(frame);
    }

    fn draw_scrollbars(&self, frame: &nanovg::Frame) {
        let draw_bbox = |bbox: Bbox| {
            frame.path(
                |path| {
                    let origin = (bbox.min.x as f32, bbox.min.y as f32);
                    let size = (bbox.size().x as f32, bbox.size().y as f32);
                    path.rect(origin, size);
                    path.fill(nanovg::FillStyle {
                        coloring_style: nanovg::ColoringStyle::Color(
                            Color::rgba(0.0, 1.0, 0.0, 0.4).into(),
                        ),
                        ..Default::default()
                    });
                },
                Default::default(),
            );
        };

        for &(hori_bbox, vert_bbox) in self.pending_scrollbars.borrow().values() {
            if let Some(hori_bbox) = hori_bbox {
                draw_bbox(hori_bbox);
            }
            if let Some(vert_bbox) = vert_bbox {
                draw_bbox(vert_bbox);
            }
        }
    }

    /// Draw a single div.
    fn draw_div(
        &self,
        div: &div::SpaceDiv,
        div_visibility: div::ComputedVisibility,
        parent_bbox: Option<(it::NodeId, Bbox)>,
        frame: &nanovg::Frame,
    ) {
        let (div_bbox, x, y) = match div_visibility {
            div::ComputedVisibility::Invisible => return,
            div::ComputedVisibility::Visible { bbox, x, y } => (bbox, x, y),
        };

        // Build clip bbox
        let clip = {
            let mut clip = div_bbox;
            if let Some((min_val, max_val)) = x.min_max() {
                clip.min.x = min_val;
                clip.max.x = max_val;
            }
            if let Some((min_val, max_val)) = y.min_max() {
                clip.min.y = min_val;
                clip.max.y = max_val;
            }
            clip
        };

        // Draw background color if we have one
        if let Some(color) = div.background_color {
            frame.path(
                |path| {
                    let origin = (clip.min.x as f32, clip.min.y as f32);
                    let size = (clip.size().x as f32, clip.size().y as f32);
                    path.rect(origin, size);
                    path.fill(nanovg::FillStyle {
                        coloring_style: nanovg::ColoringStyle::Color(color.into()),
                        ..Default::default()
                    });
                },
                Default::default(),
            );
        }

        // Generate scrollbars
        if let Some((parent, parent_bbox)) = parent_bbox {
            if let Some(sx) = x.scroll() {
                let width = max(parent_bbox.size().x - sx, 8);
                let height = 16;
                let origin = Point::new(
                    parent_bbox.min.x + div.scroll.get().x,
                    parent_bbox.max.y - height,
                );
                let size = Point::new(width, height);
                let bbox = Bbox::with_size(origin, size);
                let mut bars = self.pending_scrollbars.borrow_mut();
                bars.entry(parent).or_insert((None, None)).0 = Some(bbox);
            }
            if let Some(sy) = y.scroll() {
                let width = 16;
                let height = max(parent_bbox.size().y - sy, 8);
                let origin = Point::new(
                    parent_bbox.max.x - width,
                    parent_bbox.min.y + div.scroll.get().y,
                );
                let size = Point::new(width, height);
                let bbox = Bbox::with_size(origin, size);
                let mut bars = self.pending_scrollbars.borrow_mut();
                bars.entry(parent).or_insert((None, None)).1 = Some(bbox);
            }
        }

        let scrolled_div_bbox = {
            let mut bbox = div_bbox;
            let scroll = div.scroll.get();
            if let div::AxisOverflowBehaviour::Scroll { .. } = x {
                bbox.min.x -= scroll.x;
                bbox.max.x -= scroll.x;
            }
            if let div::AxisOverflowBehaviour::Scroll { .. } = y {
                bbox.min.y -= scroll.y;
                bbox.max.y -= scroll.y;
            }
            bbox
        };

        // Draw the widget
        if let Some(ref widget) = div.widget {
            let mut widget = widget.borrow_mut();
            widget.update();
            widget.draw(scrolled_div_bbox, clip, frame);
        }

        let max_scroll = {
            let x = x.scroll().unwrap_or(0);
            let y = y.scroll().unwrap_or(0);
            Point::new(x, y)
        };

        // Scroll right 1 pixel per frame for testing the scrolling.
        let delta = self.time_start.elapsed();
        let delta = (delta.as_secs() * 1000 + delta.subsec_millis() as u64) as f32 / 1000.0;
        let delta = ((delta.sin() * 0.5 + 0.5) * max_scroll.x as f32) as i32;
        div.scroll.set(point_min(Point::new(delta, 0), max_scroll));
    }

    /// Recursively visit all space divs of this view.
    fn visit_divs<F>(
        &self,
        id: it::NodeId,
        visibility: div::ComputedVisibility,
        parent: Option<(it::NodeId, Bbox)>,
        visitor: &mut F,
    ) where
        F: FnMut(CachedDiv),
    {
        if let div::ComputedVisibility::Visible { bbox, .. } = visibility {
            visitor(CachedDiv {
                id,
                visibility,
                parent,
            });

            let visible_children = self.arena[id].data.children(&self.arena, id, bbox).filter(
                |&(_, vis)| match vis {
                    div::ComputedVisibility::Visible { .. } => true,
                    div::ComputedVisibility::Invisible => false,
                },
            );

            for (c, vis) in visible_children {
                self.visit_divs(c, vis, Some((id, bbox)), visitor);
            }
        }
    }

    fn divs(&self) -> Ref<Option<Vec<CachedDiv>>> {
        let is_none = { self.cache.borrow().is_none() };
        if is_none {
            // Build the cache
            let mut vec = self.cache.borrow_mut();
            let vec = vec.get_or_insert_with(|| Vec::with_capacity(32));
            vec.clear();
            self.visit_divs(
                self.root_div,
                div::ComputedVisibility::Visible {
                    bbox: self.bbox,
                    x: div::AxisOverflowBehaviour::Overflow,
                    y: div::AxisOverflowBehaviour::Overflow,
                },
                None,
                &mut |cached_div| vec.push(cached_div),
            );
        }
        self.cache.borrow()
    }
}
<commit_msg>Don't filter invisible children, the if catches it<commit_after>use gui::*;
use gui::div;

use std::cell::{Ref, RefCell};
use std::time::Instant;
use std::collections::HashMap;

struct CachedDiv {
    /// Node id of the cached div.
    id: it::NodeId,
    /// Visibility of the cached div.
    visibility: div::ComputedVisibility,
    /// The parent id and bbox of the cached div.
    parent: Option<(it::NodeId, Bbox)>,
}

pub struct View<'a> {
    bbox: Bbox,
    arena: it::Arena<div::SpaceDiv<'a>>,
    root_div: it::NodeId,
    children: Vec<it::NodeId>,
    cache: RefCell<Option<Vec<CachedDiv>>>,
    time_start: Instant,
    /// The scrollbars which need to be drawn per div.
    pending_scrollbars: RefCell<HashMap<it::NodeId, (Option<Bbox>, Option<Bbox>)>>,
}

impl<'a> View<'a> {
    pub fn new(bbox: Bbox) -> Self {
        let mut arena = it::Arena::new();
        let root_div = arena.new_node(
            div::SpaceDiv::full()
                .vertical()
                .vert_align(div::Alignment::Min)
                .build(),
        );
        Self {
            bbox,
            arena,
            root_div,
            children: Vec::new(),
            cache: RefCell::new(None),
            time_start: Instant::now(),
            pending_scrollbars: RefCell::new(HashMap::new()),
        }
    }

    pub fn without_bbox() -> Self {
        let zero = Point::new(0, 0);
        Self::new(Bbox::new(zero, zero))
    }

    pub fn add_div(&mut self, parent: Option<it::NodeId>, div: div::SpaceDiv<'a>) -> it::NodeId {
        let node = self.arena.new_node(div);
        parent
            .unwrap_or(self.root_div)
            .append(node, &mut self.arena);
        self.children.push(node);
        *self.cache.borrow_mut() = None;
        node
    }

    pub fn bbox(&self) -> &Bbox {
        &self.bbox
    }

    pub fn set_bbox(&mut self, bbox: Bbox) {
        if bbox != self.bbox {
            *self.cache.borrow_mut() = None;
        }

        self.bbox = bbox;
    }

    /// Returns the root space div of this view.
    pub fn space_div(&self) -> &div::SpaceDiv<'a> {
        &self.arena[self.root_div].data
    }

    /// Draw the entire frame.
    pub fn draw(&self, frame: &nanovg::Frame) {
        self.pending_scrollbars.borrow_mut().clear();

        if let Some(ref divs) = *self.divs() {
            for cached_div in divs.iter() {
                self.draw_div(
                    &self.arena[cached_div.id].data,
                    cached_div.visibility,
                    cached_div.parent,
                    frame,
                );
            }
        }

        self.draw_scrollbars(frame);
    }

    fn draw_scrollbars(&self, frame: &nanovg::Frame) {
        let draw_bbox = |bbox: Bbox| {
            frame.path(
                |path| {
                    let origin = (bbox.min.x as f32, bbox.min.y as f32);
                    let size = (bbox.size().x as f32, bbox.size().y as f32);
                    path.rect(origin, size);
                    path.fill(nanovg::FillStyle {
                        coloring_style: nanovg::ColoringStyle::Color(
                            Color::rgba(0.0, 1.0, 0.0, 0.4).into(),
                        ),
                        ..Default::default()
                    });
                },
                Default::default(),
            );
        };

        for &(hori_bbox, vert_bbox) in self.pending_scrollbars.borrow().values() {
            if let Some(hori_bbox) = hori_bbox {
                draw_bbox(hori_bbox);
            }
            if let Some(vert_bbox) = vert_bbox {
                draw_bbox(vert_bbox);
            }
        }
    }

    /// Draw a single div.
    fn draw_div(
        &self,
        div: &div::SpaceDiv,
        div_visibility: div::ComputedVisibility,
        parent_bbox: Option<(it::NodeId, Bbox)>,
        frame: &nanovg::Frame,
    ) {
        let (div_bbox, x, y) = match div_visibility {
            div::ComputedVisibility::Invisible => return,
            div::ComputedVisibility::Visible { bbox, x, y } => (bbox, x, y),
        };

        // Build clip bbox
        let clip = {
            let mut clip = div_bbox;
            if let Some((min_val, max_val)) = x.min_max() {
                clip.min.x = min_val;
                clip.max.x = max_val;
            }
            if let Some((min_val, max_val)) = y.min_max() {
                clip.min.y = min_val;
                clip.max.y = max_val;
            }
            clip
        };

        // Draw background color if we have one
        if let Some(color) = div.background_color {
            frame.path(
                |path| {
                    let origin = (clip.min.x as f32, clip.min.y as f32);
                    let size = (clip.size().x as f32, clip.size().y as f32);
                    path.rect(origin, size);
                    path.fill(nanovg::FillStyle {
                        coloring_style: nanovg::ColoringStyle::Color(color.into()),
                        ..Default::default()
                    });
                },
                Default::default(),
            );
        }

        // Generate scrollbars
        if let Some((parent, parent_bbox)) = parent_bbox {
            if let Some(sx) = x.scroll() {
                let width = max(parent_bbox.size().x - sx, 8);
                let height = 16;
                let origin = Point::new(
                    parent_bbox.min.x + div.scroll.get().x,
                    parent_bbox.max.y - height,
                );
                let size = Point::new(width, height);
                let bbox = Bbox::with_size(origin, size);
                let mut bars = self.pending_scrollbars.borrow_mut();
                bars.entry(parent).or_insert((None, None)).0 = Some(bbox);
            }
            if let Some(sy) = y.scroll() {
                let width = 16;
                let height = max(parent_bbox.size().y - sy, 8);
                let origin = Point::new(
                    parent_bbox.max.x - width,
                    parent_bbox.min.y + div.scroll.get().y,
                );
                let size = Point::new(width, height);
                let bbox = Bbox::with_size(origin, size);
                let mut bars = self.pending_scrollbars.borrow_mut();
                bars.entry(parent).or_insert((None, None)).1 = Some(bbox);
            }
        }

        let scrolled_div_bbox = {
            let mut bbox = div_bbox;
            let scroll = div.scroll.get();
            if let div::AxisOverflowBehaviour::Scroll { .. } = x {
                bbox.min.x -= scroll.x;
                bbox.max.x -= scroll.x;
            }
            if let div::AxisOverflowBehaviour::Scroll { .. } = y {
                bbox.min.y -= scroll.y;
                bbox.max.y -= scroll.y;
            }
            bbox
        };

        // Draw the widget
        if let Some(ref widget) = div.widget {
            let mut widget = widget.borrow_mut();
            widget.update();
            widget.draw(scrolled_div_bbox, clip, frame);
        }

        let max_scroll = {
            let x = x.scroll().unwrap_or(0);
            let y = y.scroll().unwrap_or(0);
            Point::new(x, y)
        };

        // Scroll right 1 pixel per frame for testing the scrolling.
        let delta = self.time_start.elapsed();
        let delta = (delta.as_secs() * 1000 + delta.subsec_millis() as u64) as f32 / 1000.0;
        let delta = ((delta.sin() * 0.5 + 0.5) * max_scroll.x as f32) as i32;
        div.scroll.set(point_min(Point::new(delta, 0), max_scroll));
    }

    /// Recursively visit all space divs of this view.
    fn visit_divs<F>(
        &self,
        id: it::NodeId,
        visibility: div::ComputedVisibility,
        parent: Option<(it::NodeId, Bbox)>,
        visitor: &mut F,
    ) where
        F: FnMut(CachedDiv),
    {
        if let div::ComputedVisibility::Visible { bbox, .. } = visibility {
            visitor(CachedDiv {
                id,
                visibility,
                parent,
            });

            let visible_children = self.arena[id].data.children(&self.arena, id, bbox);

            for (c, vis) in visible_children {
                self.visit_divs(c, vis, Some((id, bbox)), visitor);
            }
        }
    }

    fn divs(&self) -> Ref<Option<Vec<CachedDiv>>> {
        let is_none = { self.cache.borrow().is_none() };
        if is_none {
            // Build the cache
            let mut vec = self.cache.borrow_mut();
            let vec = vec.get_or_insert_with(|| Vec::with_capacity(32));
            vec.clear();
            self.visit_divs(
                self.root_div,
                div::ComputedVisibility::Visible {
                    bbox: self.bbox,
                    x: div::AxisOverflowBehaviour::Overflow,
                    y: div::AxisOverflowBehaviour::Overflow,
                },
                None,
                &mut |cached_div| vec.push(cached_div),
            );
        }
        self.cache.borrow()
    }
}
<|endoftext|>


<commit_before>extern crate hyper;

// use std::io::Read;

// use hyper::header::Connection;
// use hyper::header::ConnectionOption;

struct Request;
// struct Response;

pub struct Client<'a> {
    client: hyper::Client<hyper::net::HttpConnector<'a>>
}

impl<'a> Client<'a> {
    pub fn new() -> Client<'a> {
        Client {
            client: hyper::Client::new()
        }
    }

//     pub fn get(&mut self, url: &str) -> Response {
//         let req = self.client.get(&url).send().unwrap();
//     }
}

#[test]
fn client_wrapper_works() {
    let client = Client::new();
}
<commit_msg>Partial implementation of http client wrapper<commit_after>extern crate hyper;

use std::option::Option;
use std::collections::HashMap;

// use std::io::Read;

// use hyper::header::Connection;
// use hyper::header::ConnectionOption;
//
struct Response;
struct HTTPError;

struct Request<'a> {
    client: hyper::Client<hyper::net::HttpConnector<'a>>
}

impl<'a> Request<'a> {
    fn new() -> Request {
        Request { client: hyper::Client::new() }
    }

    fn exec() -> Result<Response, HTTPError> {
        Ok(Response);
    }
}

// struct Response;

pub struct Builder {
    method: Method,
    url: Option<String>,
    body: Option<String>,
    headers: HashMap<String, String>
}

impl Builder {
    fn new() -> Builder {
        Builder {
            method: Method::GET,
            url: None,
            body: None,
            headers: HashMap::new()
        }
    }

    fn method(&mut self, method: Method) -> &mut Builder {
        self.method = method;
        self
    }

    fn url(&mut self, url: &str) -> &mut Builder {
        self.url = Some(url.to_string());
        self
    }

    fn body(&mut self, body: &str) -> &mut Builder {
        self.body = Some(body.to_string());
        self
    }

    fn header(&mut self, header: &str, value: &str) -> &mut Builder {
        self.headers.insert(header.to_string(), value.to_string());
        self
    }

    fn build(&self) -> Request {
        let req = Request::new();
    }
}

pub enum Method {
    GET,
    POST,
    PUT,
    DELETE
}

impl Method {
    fn to_str(&self) -> &str {
        match *self {
            Method::GET => { "GET" },
            Method::POST => { "POST" },
            Method::PUT => { "PUT" },
            Method::DELETE => { "DELETE" }
        }
    }
}

#[test]
fn request_builder() {

}
<|endoftext|>


<commit_before>use super::{Open, Sink};
use alsa::device_name::HintIter;
use alsa::pcm::{Access, Format, HwParams, PCM};
use alsa::{Direction, Error, ValueOr};
use std::ffi::CString;
use std::io;
use std::process::exit;

pub struct AlsaSink(Option<PCM>, String);

fn list_outputs() {
    for t in &["pcm", "ctl", "hwdep"] {
        println!("{} devices:", t);
        let i = HintIter::new(None, &*CString::new(*t).unwrap()).unwrap();
        for a in i {
            if let Some(Direction::Playback) = a.direction {
                // mimic aplay -L
                println!(
                    "{}\n\t{}\n",
                    a.name.unwrap(),
                    a.desc.unwrap().replace("\n", "\n\t")
                );
            }
        }
    }
}

fn open_device(dev_name: &str) -> Result<(PCM), Box<Error>> {
    let pcm = PCM::new(dev_name, Direction::Playback, false)?;
    // http://www.linuxjournal.com/article/6735?page=0,1#N0x19ab2890.0x19ba78d8
    // latency = period_size * periods / (rate * bytes_per_frame)
    // For 16 Bit stereo data, one frame has a length of four bytes.
    // 500ms  = buffer_size / (44100 * 4)
    // buffer_size_bytes = 0.5 * 44100 / 4
    // buffer_size_frames = 0.5 * 44100 = 22050
    {
        // Set hardware parameters: 44100 Hz / Stereo / 16 bit
        let hwp = HwParams::any(&pcm)?;

        hwp.set_access(Access::RWInterleaved)?;
        hwp.set_format(Format::s16())?;
        hwp.set_rate(44100, ValueOr::Nearest)?;
        hwp.set_channels(2)?;
        hwp.set_period_size_near(5512, ValueOr::Nearest)?; // Period of roughly 125ms
        hwp.set_buffer_size_near(22048)?; // ~ 0.5s latency
        pcm.hw_params(&hwp)?;

        let swp = pcm.sw_params_current()?;
        swp.set_start_threshold(hwp.get_buffer_size()? - hwp.get_period_size()?)?;
        pcm.sw_params(&swp)?;
    }

    Ok(pcm)
}

impl Open for AlsaSink {
    fn open(device: Option<String>) -> AlsaSink {
        info!("Using alsa sink");

        let name = match device.as_ref().map(AsRef::as_ref) {
            Some("?") => {
                println!("Listing available alsa outputs");
                list_outputs();
                exit(0)
            }
            Some(device) => device,
            None => "default",
        }
        .to_string();

        AlsaSink(None, name)
    }
}

impl Sink for AlsaSink {
    fn start(&mut self) -> io::Result<()> {
        if self.0.is_none() {
            let pcm = open_device(&self.1);
            match pcm {
                Ok(p) => self.0 = Some(p),
                Err(e) => {
                    error!("Alsa error PCM open {}", e);
                    return Err(io::Error::new(
                        io::ErrorKind::Other,
                        "Alsa error: PCM open failed",
                    ));
                }
            }
        }

        Ok(())
    }

    fn stop(&mut self) -> io::Result<()> {
        {
            let pcm = self.0.as_ref().unwrap();
            pcm.drain().unwrap();
        }
        self.0 = None;
        Ok(())
    }

    fn write(&mut self, data: &[i16]) -> io::Result<()> {
        let pcm = self.0.as_mut().unwrap();
        let io = pcm.io_i16().unwrap();

        match io.writei(&data) {
            Ok(_) => (),
            Err(err) => pcm.try_recover(err, false).unwrap(),
        }

        Ok(())
    }
}
<commit_msg>Introduce a buffer for a full period<commit_after>use super::{Open, Sink};
use alsa::device_name::HintIter;
use alsa::pcm::{Access, Format, Frames, HwParams, PCM};
use alsa::{Direction, Error, ValueOr};
use std::cmp::min;
use std::ffi::CString;
use std::io;
use std::process::exit;

const PERIOD_SIZE: usize = 5512; // Period of roughly 125ms
const BUFFERED_PERIODS: usize = 4; // ~ 0.5s latency

pub struct AlsaSink {
    pcm: Option<PCM>,
    device: String,
    buffer: [i16; PERIOD_SIZE as usize],
    buffered_data: usize,
}

fn list_outputs() {
    for t in &["pcm", "ctl", "hwdep"] {
        println!("{} devices:", t);
        let i = HintIter::new(None, &*CString::new(*t).unwrap()).unwrap();
        for a in i {
            if let Some(Direction::Playback) = a.direction {
                // mimic aplay -L
                println!(
                    "{}\n\t{}\n",
                    a.name.unwrap(),
                    a.desc.unwrap().replace("\n", "\n\t")
                );
            }
        }
    }
}

fn open_device(dev_name: &str) -> Result<(PCM), Box<Error>> {
    let pcm = PCM::new(dev_name, Direction::Playback, false)?;
    // http://www.linuxjournal.com/article/6735?page=0,1#N0x19ab2890.0x19ba78d8
    // latency = period_size * periods / (rate * bytes_per_frame)
    // For 16 Bit stereo data, one frame has a length of four bytes.
    // 500ms  = buffer_size / (44100 * 4)
    // buffer_size_bytes = 0.5 * 44100 / 4
    // buffer_size_frames = 0.5 * 44100 = 22050
    {
        // Set hardware parameters: 44100 Hz / Stereo / 16 bit
        let hwp = HwParams::any(&pcm)?;

        hwp.set_access(Access::RWInterleaved)?;
        hwp.set_format(Format::s16())?;
        hwp.set_rate(44100, ValueOr::Nearest)?;
        hwp.set_channels(2)?;
        hwp.set_period_size_near(PERIOD_SIZE as Frames, ValueOr::Nearest)?;
        hwp.set_buffer_size_near((PERIOD_SIZE * BUFFERED_PERIODS) as Frames)?;
        pcm.hw_params(&hwp)?;

        let swp = pcm.sw_params_current()?;
        swp.set_start_threshold(hwp.get_buffer_size()? - hwp.get_period_size()?)?;
        pcm.sw_params(&swp)?;
    }

    Ok(pcm)
}

impl Open for AlsaSink {
    fn open(device: Option<String>) -> AlsaSink {
        info!("Using alsa sink");

        let name = match device.as_ref().map(AsRef::as_ref) {
            Some("?") => {
                println!("Listing available alsa outputs");
                list_outputs();
                exit(0)
            }
            Some(device) => device,
            None => "default",
        }
        .to_string();

        AlsaSink {
            pcm: None,
            device: name,
            buffer: [0; PERIOD_SIZE],
            buffered_data: 0,
        }
    }
}

impl Sink for AlsaSink {
    fn start(&mut self) -> io::Result<()> {
        if self.pcm.is_none() {
            let pcm = open_device(&self.device);
            match pcm {
                Ok(p) => self.pcm = Some(p),
                Err(e) => {
                    error!("Alsa error PCM open {}", e);
                    return Err(io::Error::new(
                        io::ErrorKind::Other,
                        "Alsa error: PCM open failed",
                    ));
                }
            }
        }

        Ok(())
    }

    fn stop(&mut self) -> io::Result<()> {
        {
            let pcm = self.pcm.as_ref().unwrap();
            pcm.drain().unwrap();
        }
        self.pcm = None;
        Ok(())
    }

    fn write(&mut self, data: &[i16]) -> io::Result<()> {
        let mut processed_data = 0;
        while processed_data < data.len() {
            let data_to_buffer = min(
                PERIOD_SIZE - self.buffered_data,
                data.len() - processed_data,
            );
            let buffer_slice =
                &mut self.buffer[self.buffered_data..self.buffered_data + data_to_buffer];
            buffer_slice.copy_from_slice(&data[processed_data..processed_data + data_to_buffer]);
            self.buffered_data += data_to_buffer;
            processed_data += data_to_buffer;
            if self.buffered_data == PERIOD_SIZE {
                self.buffered_data = 0;
                let pcm = self.pcm.as_mut().unwrap();
                let io = pcm.io_i16().unwrap();
                match io.writei(&self.buffer) {
                    Ok(_) => (),
                    Err(err) => pcm.try_recover(err, false).unwrap(),
                }
            }
        }

        Ok(())
    }
}
<|endoftext|>


<commit_before>use crate::core::*;
use crate::geometry::Space;
use crate::policies::{FinitePolicy, Policy};
use rand::{
    distributions::{Distribution, Normal},
    rngs::ThreadRng,
    Rng,
    thread_rng,
};
use std::ops::Add;

pub struct PerturbedPolicy<P, D, R = ThreadRng> {
    pub base_policy: P,
    pub noise_dist: D,

    rng: R,
}

impl<P, D> PerturbedPolicy<P, D> {
    pub fn new(base_policy: P, noise_dist: D) -> Self {
        PerturbedPolicy::with_rng(base_policy, noise_dist, thread_rng())
    }
}

impl<P> PerturbedPolicy<P, Normal> {
    pub fn normal(base_policy: P, std_dev: f64) -> Self {
        PerturbedPolicy::with_rng(base_policy, Normal::new(0.0, std_dev), thread_rng())
    }
}

impl<P, D, R> PerturbedPolicy<P, D, R> {
    pub fn with_rng(base_policy: P, noise_dist: D, rng: R) -> Self {
        PerturbedPolicy {
            base_policy,
            noise_dist,
            rng,
        }
    }
}

impl<P, D, R> Algorithm for PerturbedPolicy<P, D, R> {}

impl<S, P, D, R> Policy<S> for PerturbedPolicy<P, D, R>
where
    P: Policy<S>,
    D: Distribution<P::Action>,
    R: Rng,
    P::Action: Add<P::Action, Output = P::Action>,
{
    type Action = P::Action;

    fn sample(&mut self, s: &S) -> P::Action {
        let base_action = self.base_policy.sample(s);
        let perturbation = self.noise_dist.sample(&mut self.rng);

        base_action + perturbation
    }

    fn probability(&mut self, _: &S, _: P::Action) -> f64 {
        unimplemented!()
    }
}

impl<S, P, D, R> FinitePolicy<S> for PerturbedPolicy<P, D, R>
where
    P: FinitePolicy<S>,
    D: Distribution<P::Action>,
    R: Rng,
{
    fn n_actions(&self) -> P::Action {
        self.base_policy.n_actions()
    }

    fn probabilities(&mut self, _: &S) -> Vector<f64> {
        unimplemented!()
    }
}
<commit_msg>refactor(policies): use Shared<P> policy instance in PerturbedPolicy<commit_after>use crate::core::*;
use crate::geometry::Space;
use crate::policies::{FinitePolicy, Policy};
use rand::{
    distributions::{Distribution, Normal},
    rngs::ThreadRng,
    Rng,
    thread_rng,
};
use std::ops::Add;

pub struct PerturbedPolicy<P, D, R = ThreadRng> {
    pub base_policy: Shared<P>,
    pub noise_dist: D,

    rng: R,
}

impl<P, D> PerturbedPolicy<P, D> {
    pub fn new(base_policy: Shared<P>, noise_dist: D) -> Self {
        PerturbedPolicy::with_rng(base_policy, noise_dist, thread_rng())
    }
}

impl<P> PerturbedPolicy<P, Normal> {
    pub fn normal(base_policy: Shared<P>, std_dev: f64) -> Self {
        PerturbedPolicy::with_rng(base_policy, Normal::new(0.0, std_dev), thread_rng())
    }
}

impl<P, D, R> PerturbedPolicy<P, D, R> {
    pub fn with_rng(base_policy: Shared<P>, noise_dist: D, rng: R) -> Self {
        PerturbedPolicy {
            base_policy,
            noise_dist,
            rng,
        }
    }
}

impl<P, D, R> Algorithm for PerturbedPolicy<P, D, R> {}

impl<S, P, D, R> Policy<S> for PerturbedPolicy<P, D, R>
where
    P: Policy<S>,
    D: Distribution<P::Action>,
    R: Rng,
    P::Action: Add<P::Action, Output = P::Action>,
{
    type Action = P::Action;

    fn sample(&mut self, s: &S) -> P::Action {
        let base_action = self.base_policy.borrow_mut().sample(s);
        let perturbation = self.noise_dist.sample(&mut self.rng);

        base_action + perturbation
    }

    fn probability(&mut self, _: &S, _: P::Action) -> f64 {
        unimplemented!()
    }
}

impl<S, P, D, R> FinitePolicy<S> for PerturbedPolicy<P, D, R>
where
    P: FinitePolicy<S>,
    D: Distribution<P::Action>,
    R: Rng,
{
    fn n_actions(&self) -> P::Action {
        self.base_policy.n_actions()
    }

    fn probabilities(&mut self, _: &S) -> Vector<f64> {
        unimplemented!()
    }
}
<|endoftext|>


<commit_before>#[crate_type = "bin"];
#[feature(globs)];

extern mod protobuf;
extern mod extra;

use std::io;
use std::path::Path;
use std::os;
use extra::getopts;

use protobuf::*;
use protobuf::descriptor::*;
use protobuf::codegen::*;

fn write_file(bin: &str, gen_options: &GenOptions) {
    let is: @Reader = io::file_reader(&Path(bin)).unwrap();
    let fds = parse_from_reader::<FileDescriptorSet>(is);

    let results = gen(fds.file, gen_options);

    for r in results.iter() {
        let file_writer = io::file_writer(~Path(r.name), [io::Create, io::Truncate]).unwrap();
        file_writer.write(r.content);
    }
}

fn main() {
    let args = os::args();
    let opts: ~[getopts::Opt] = ~[
    ];
    let matches = getopts::getopts(args.tail(), opts).unwrap();
    let pb_bin = match matches.free {
        [ref pb_bin] => pb_bin.to_owned(),
        _ => fail!("must have exactly one argument")
    };
    let gen_options = GenOptions {
        dummy: false,
    };
    write_file(pb_bin, &gen_options);
}
<commit_msg>Use Path::new()<commit_after>#[crate_type = "bin"];
#[feature(globs)];

extern mod protobuf;
extern mod extra;

use std::io;
use std::path::Path;
use std::os;
use extra::getopts;

use protobuf::*;
use protobuf::descriptor::*;
use protobuf::codegen::*;

fn write_file(bin: &str, gen_options: &GenOptions) {
    let is: @Reader = io::file_reader(&Path::new(bin)).unwrap();
    let fds = parse_from_reader::<FileDescriptorSet>(is);

    let results = gen(fds.file, gen_options);

    for r in results.iter() {
        let file_writer = io::file_writer(&Path::new(r.name.to_owned()), [io::Create, io::Truncate]).unwrap();
        file_writer.write(r.content);
    }
}

fn main() {
    let args = os::args();
    let opts: ~[getopts::Opt] = ~[
    ];
    let matches = getopts::getopts(args.tail(), opts).unwrap();
    let pb_bin = match matches.free {
        [ref pb_bin] => pb_bin.to_owned(),
        _ => fail!("must have exactly one argument")
    };
    let gen_options = GenOptions {
        dummy: false,
    };
    write_file(pb_bin, &gen_options);
}
<|endoftext|>


<commit_before><commit_msg>Kakuro: use delayed application for min-max method to avoid errors<commit_after><|endoftext|>


<commit_before>use time;
use std::mem;
use std::num::{Float};
use image::{GenericImage, SubImage, Pixel};
use image::{ImageBuffer, Rgba};
use image;
use glutin;
use glium::{self, DisplayBuild};
use util::{self, AtlasBuilder, Atlas, AtlasItem, V2, Rect, Rgb, Color};
use event::{Event, MouseButton};
use renderer::{Renderer, Vertex};
use scancode;

pub static FONT_W: u32 = 8;
pub static FONT_H: u32 = 8;

/// The first font image in the atlas image set.
static FONT_IDX: usize = 0;

/// Image index of the solid color texture block.
static SOLID_IDX: usize = 96;

pub struct CanvasBuilder {
    title: String,
    dim: V2<i32>,
    frame_interval: Option<f64>,
    builder: AtlasBuilder,
}

/// Toplevel graphics drawing and input reading context.
impl CanvasBuilder {
    pub fn new() -> CanvasBuilder {
        let mut ret = CanvasBuilder {
            title: "window".to_string(),
            dim: V2(640, 360),
            frame_interval: None,
            builder: AtlasBuilder::new(),
        };
        ret.init_font();
        ret.init_solid();
        ret
    }

    pub fn set_title(mut self, title: &str) -> CanvasBuilder {
        self.title = title.to_string();
        self
    }

    /// Set the frame rate.
    pub fn set_frame_interval(mut self, interval_s: f64) -> CanvasBuilder {
        assert!(interval_s > 0.00001);
        self.frame_interval = Some(interval_s);
        self
    }

    /// Set the resolution.
    pub fn set_dim(mut self, dim: V2<i32>) -> CanvasBuilder {
        self.dim = dim;
        self
    }

    pub fn add_image<P: Pixel<u8> + 'static, I: GenericImage<P>>(
        &mut self, offset: V2<i32>, image: I) -> Image {
        Image(self.builder.push(offset, image))
    }

    /// Start running the engine, return an event iteration.
    pub fn run(&mut self) -> Canvas {
        Canvas::new(
            self.dim,
            self.title.as_slice(),
            self.frame_interval,
            Atlas::new(&self.builder))
    }

    /// Load the default font into the texture atlas.
    fn init_font(&mut self) {
        let mut font_sheet = util::color_key(
            &image::load_from_memory(include_bytes!("../assets/font.png")).unwrap(),
            &Rgb::new(0x80u8, 0x80u8, 0x80u8));
        for i in 0..96 {
            let x = 8u32 * (i % 16u32);
            let y = 8u32 * (i / 16u32);
            let Image(idx) = self.add_image(V2(0, -8), SubImage::new(&mut font_sheet, x, y, 8, 8));
            assert!(idx - i as usize == FONT_IDX);
        }
    }

    /// Load a solid color element into the texture atlas.
    fn init_solid(&mut self) {
        let image: ImageBuffer<Vec<u8>, u8, Rgba<u8>> = ImageBuffer::from_fn(1, 1, Box::new(|&: _, _| Rgba([0xffu8, 0xffu8, 0xffu8, 0xffu8])));
        let Image(idx) = self.add_image(V2(0, 0), image);
        assert!(idx == SOLID_IDX);
    }
}

/// Interface to render to a live display.
pub struct Canvas {
    display: glium::Display,
    events: Vec<glutin::Event>,
    renderer: Renderer,

    atlas: Atlas,

    state: State,
    frame_interval: Option<f64>,
    last_render_time: f64,
    resolution: V2<i32>,
    window_resolution: V2<i32>,

    vertices: Vec<Vertex>,
    indices: Vec<u16>,

    /// Time in seconds it took to render the last frame.
    pub render_duration: f64,
}

#[derive(PartialEq)]
enum State {
    Normal,
    EndFrame,
}

impl Canvas {
    fn new(
        dim: V2<i32>,
        title: &str,
        frame_interval: Option<f64>,
        atlas: Atlas) -> Canvas {

        let display = glutin::WindowBuilder::new()
            .with_title(title.to_string())
            .with_dimensions(dim.0 as u32, dim.1 as u32)
            .build_glium().unwrap();

        let (w, h) = display.get_framebuffer_dimensions();

        let tex_image = image::imageops::flip_vertical(&atlas.image);
        let renderer = Renderer::new(&display, tex_image);

        Canvas {
            display: display,
            events: Vec::new(),
            renderer: renderer,

            atlas: atlas,

            state: State::Normal,
            frame_interval: frame_interval,
            last_render_time: time::precise_time_s(),
            resolution: dim,
            window_resolution: V2(w as i32, h as i32),

            vertices: Vec::new(),
            indices: Vec::new(),

            render_duration: 0.1f64,
        }
    }

    /// Clear the screen.
    pub fn clear(&mut self) {
        // TODO: use the color.
        self.vertices.clear();
        self.indices.clear();
    }

    /// Transform screen coordinates from the scaled-up window into
    /// pixel-perfect coordinates of the actual graphics.
    fn screen_to_pixel(&self, V2(sx, sy): V2<i32>) -> V2<i32> {
        let Rect(V2(rx, ry), V2(rw, rh)) = pixel_perfect(self.resolution, self.window_resolution);

        V2(((sx - rx) as f32 * self.resolution.0 as f32 / rw as f32) as i32,
           ((sy - ry) as f32 * self.resolution.1 as f32 / rh as f32) as i32)
    }

    #[inline(always)]
    fn window_to_device(&self, window_pos: V2<f32>, z: f32) -> [f32; 3] {
        let V2(w, h) = self.window_resolution;
        let Rect(V2(rx, ry), V2(rw, _)) = pixel_perfect(self.resolution, self.window_resolution);
        let zoom = (rw as f32) / (self.resolution.0 as f32);
        [-1.0 + (2.0 * (rx as f32 + window_pos.0 * zoom) / w as f32),
          1.0 - (2.0 * (ry as f32 + window_pos.1 * zoom) / h as f32),
         z]
    }

    /// Add a vertex to the geometry data of the current frame.
    pub fn push_vertex<C: Color, C2: Color>(&mut self, pos: V2<f32>, layer: f32, tex_coord: V2<f32>,
                                 color: &C, back_color: &C2) {
        let pos = self.window_to_device(pos, layer);

        self.vertices.push(Vertex {
            pos: pos,
            tex_coord: [tex_coord.0, tex_coord.1],
            color: color.to_rgba(),
            back_color: back_color.to_rgba(),
        });
    }

    /// Return the current vertex count, important for determining the indices
    /// for newly inserted vertices.
    pub fn num_vertices(&self) -> u16 { self.vertices.len() as u16 }

    /// Add a triangle defined by index values into the list of vertices
    /// inserted with push_vertex.
    pub fn push_triangle(&mut self, p0: u16, p1: u16, p2: u16) {
        self.indices.push(p0);
        self.indices.push(p1);
        self.indices.push(p2);
    }

    /// Return the image corresponding to a char in the built-in font.
    pub fn font_image(&self, c: char) -> Option<Image> {
        let idx = c as usize;
        // Hardcoded limiting of the font to printable ASCII.
        if idx >= 32 && idx < 128 {
            Some(Image((idx - 32) as usize + FONT_IDX))
        } else {
            None
        }
    }

    /// Return a texture coordinate to a #FFFFFFFF texel for solid color
    /// graphics.
    pub fn solid_tex_coord(&self) -> V2<f32> { self.atlas.items[SOLID_IDX].tex.0 }

    pub fn image_data<'a>(&'a self, Image(idx): Image) -> &'a AtlasItem {
        &self.atlas.items[idx]
    }
}

impl<'a> Iterator for Canvas {
    type Item=Event<'a>;

    fn next(&mut self) -> Option<Event<'a>> {
        // After a render event, control will return here on a new
        // iter call. Do post-render work here.
        if self.state == State::EndFrame {
            self.state = State::Normal;

            let mut target = self.display.draw();

            // Move out the accumulated geometry data.
            let vertices = mem::replace(&mut self.vertices, Vec::new());
            let indices = mem::replace(&mut self.indices, Vec::new());
            self.renderer.draw(&self.display, &mut target, vertices, indices);

            target.finish();
        }

        loop {
            self.events.push_all(self.display.poll_events().as_slice());

            if !self.events.is_empty() {
                match self.events.remove(0) {
                    glutin::Event::ReceivedCharacter(ch) => {
                        return Some(Event::Char(ch));
                    }
                    glutin::Event::KeyboardInput(action, scan, _vko) => {
                        if (scan as usize) < scancode::MAP.len() {
                            if let Some(key) = scancode::MAP[scan as usize] {
                                return Some(if action == glutin::ElementState::Pressed {
                                    Event::KeyPressed(key)
                                }
                                else {
                                    Event::KeyReleased(key)
                                });
                            }
                        }
                    }
                    glutin::Event::MouseMoved((x, y)) => {
                        let pixel_pos = self.screen_to_pixel(V2(x, y));
                        return Some(Event::MouseMoved((pixel_pos.0, pixel_pos.1)));
                    }
                    glutin::Event::MouseWheel(x) => {
                        return Some(Event::MouseWheel(x));
                    }
                    glutin::Event::MouseInput(state, button) => {
                        let button = match button {
                            glutin::MouseButton::LeftMouseButton => MouseButton::Left,
                            glutin::MouseButton::RightMouseButton => MouseButton::Right,
                            glutin::MouseButton::MiddleMouseButton => MouseButton::Middle,
                            glutin::MouseButton::OtherMouseButton(x) => MouseButton::Other(x),
                        };
                        match state {
                            glutin::ElementState::Pressed => {
                                return Some(Event::MousePressed(button));
                            }
                            glutin::ElementState::Released => {
                                return Some(Event::MouseReleased(button));
                            }
                        }
                    }
                    glutin::Event::Focused(b) => {
                        return Some(Event::FocusChanged(b));
                    }
                    glutin::Event::Closed => {
                        return None;
                    }
                    _ => ()
                }
            }

            let t = time::precise_time_s();
            if self.frame_interval.map_or(true,
                |x| t - self.last_render_time >= x) {
                let delta = t - self.last_render_time;
                let sensitivity = 0.25f64;
                self.render_duration = (1f64 - sensitivity) * self.render_duration + sensitivity * delta;

                self.last_render_time = t;

                // Time to render, must return a handle to self.
                // XXX: Need unsafe hackery to get around lifetimes check.
                self.state = State::EndFrame;

                let (w, h) = self.display.get_framebuffer_dimensions();
                self.window_resolution = V2(w as i32, h as i32);

                unsafe {
                    return Some(Event::Render(mem::transmute(self)))
                }
            }
        }
    }
}

/// Drawable images stored in the Canvas.
#[derive(Copy, Clone, PartialEq)]
pub struct Image(usize);

/// A pixel perfect centered and scaled rectangle of resolution dim in a
/// window of size area.
#[inline(always)]
fn pixel_perfect(canvas: V2<i32>, window: V2<i32>) -> Rect<i32> {
    let mut scale = (window.0 as f32 / canvas.0 as f32)
        .min(window.1 as f32 / canvas.1 as f32);

    if scale > 1.0 {
        // Snap to pixel scale if more than 1 window pixel per canvas pixel.
        scale = scale.floor();
    }

    let dim = V2((scale * canvas.0 as f32) as i32, (scale * canvas.1 as f32) as i32);
    let offset = (window - dim) / 2;
    Rect(offset, dim)
}
<commit_msg>API tweaks<commit_after>use time;
use std::mem;
use std::num::{Float};
use image::{GenericImage, SubImage, Pixel};
use image::{ImageBuffer, Rgba};
use image;
use glutin;
use glium::{self, DisplayBuild};
use util::{self, AtlasBuilder, Atlas, AtlasItem, V2, Rect, Rgb, Color};
use event::{Event, MouseButton};
use renderer::{Renderer, Vertex};
use scancode;

pub static FONT_W: u32 = 8;
pub static FONT_H: u32 = 8;

/// The first font image in the atlas image set.
static FONT_IDX: usize = 0;

/// Image index of the solid color texture block.
static SOLID_IDX: usize = 96;

pub struct CanvasBuilder {
    title: String,
    dim: V2<i32>,
    frame_interval: Option<f64>,
    builder: AtlasBuilder,
}

/// Toplevel graphics drawing and input reading context.
impl CanvasBuilder {
    pub fn new() -> CanvasBuilder {
        let mut ret = CanvasBuilder {
            title: "".to_string(),
            dim: V2(640, 360),
            frame_interval: None,
            builder: AtlasBuilder::new(),
        };
        ret.init_font();
        ret.init_solid();
        ret
    }

    /// Set the window title.
    pub fn set_title(mut self, title: &str) -> CanvasBuilder {
        self.title = title.to_string();
        self
    }

    /// Set the frame rate.
    pub fn set_frame_interval(mut self, interval_s: f64) -> CanvasBuilder {
        assert!(interval_s > 0.00001);
        self.frame_interval = Some(interval_s);
        self
    }

    /// Set the size of the logical canvas.
    pub fn set_size(mut self, width: i32, height: i32) -> CanvasBuilder {
        assert!(width > 0 && height > 0);
        self.dim = V2(width, height);
        self
    }

    /// Add an image into the canvas image atlas.
    pub fn add_image<P: Pixel<u8> + 'static, I: GenericImage<P>>(
        &mut self, offset: V2<i32>, image: I) -> Image {
        Image(self.builder.push(offset, image))
    }

    /// Start running the engine, return an event iteration.
    pub fn run(&mut self) -> Canvas {
        Canvas::new(
            self.dim,
            self.title.as_slice(),
            self.frame_interval,
            Atlas::new(&self.builder))
    }

    /// Load the default font into the texture atlas.
    fn init_font(&mut self) {
        let mut font_sheet = util::color_key(
            &image::load_from_memory(include_bytes!("../assets/font.png")).unwrap(),
            &Rgb::new(0x80u8, 0x80u8, 0x80u8));
        for i in 0..96 {
            let x = 8u32 * (i % 16u32);
            let y = 8u32 * (i / 16u32);
            let Image(idx) = self.add_image(V2(0, -8), SubImage::new(&mut font_sheet, x, y, 8, 8));
            assert!(idx - i as usize == FONT_IDX);
        }
    }

    /// Load a solid color element into the texture atlas.
    fn init_solid(&mut self) {
        let image: ImageBuffer<Vec<u8>, u8, Rgba<u8>> = ImageBuffer::from_fn(1, 1, Box::new(|&: _, _| Rgba([0xffu8, 0xffu8, 0xffu8, 0xffu8])));
        let Image(idx) = self.add_image(V2(0, 0), image);
        assert!(idx == SOLID_IDX);
    }
}

/// Interface to render to a live display.
pub struct Canvas {
    display: glium::Display,
    events: Vec<glutin::Event>,
    renderer: Renderer,

    atlas: Atlas,

    state: State,
    frame_interval: Option<f64>,
    last_render_time: f64,
    resolution: V2<i32>,
    window_resolution: V2<i32>,

    vertices: Vec<Vertex>,
    indices: Vec<u16>,

    /// Time in seconds it took to render the last frame.
    pub render_duration: f64,
}

#[derive(PartialEq)]
enum State {
    Normal,
    EndFrame,
}

impl Canvas {
    fn new(
        dim: V2<i32>,
        title: &str,
        frame_interval: Option<f64>,
        atlas: Atlas) -> Canvas {

        let display = glutin::WindowBuilder::new()
            .with_title(title.to_string())
            .with_dimensions(dim.0 as u32, dim.1 as u32)
            .build_glium().unwrap();

        let (w, h) = display.get_framebuffer_dimensions();

        let tex_image = image::imageops::flip_vertical(&atlas.image);
        let renderer = Renderer::new(&display, tex_image);

        Canvas {
            display: display,
            events: Vec::new(),
            renderer: renderer,

            atlas: atlas,

            state: State::Normal,
            frame_interval: frame_interval,
            last_render_time: time::precise_time_s(),
            resolution: dim,
            window_resolution: V2(w as i32, h as i32),

            vertices: Vec::new(),
            indices: Vec::new(),

            render_duration: 0.1f64,
        }
    }

    /// Clear the screen.
    pub fn clear(&mut self) {
        // TODO: use the color.
        self.vertices.clear();
        self.indices.clear();
    }

    /// Transform screen coordinates from the scaled-up window into
    /// pixel-perfect coordinates of the actual graphics.
    fn screen_to_pixel(&self, V2(sx, sy): V2<i32>) -> V2<i32> {
        let Rect(V2(rx, ry), V2(rw, rh)) = pixel_perfect(self.resolution, self.window_resolution);

        V2(((sx - rx) as f32 * self.resolution.0 as f32 / rw as f32) as i32,
           ((sy - ry) as f32 * self.resolution.1 as f32 / rh as f32) as i32)
    }

    #[inline(always)]
    fn window_to_device(&self, window_pos: V2<f32>, z: f32) -> [f32; 3] {
        let V2(w, h) = self.window_resolution;
        let Rect(V2(rx, ry), V2(rw, _)) = pixel_perfect(self.resolution, self.window_resolution);
        let zoom = (rw as f32) / (self.resolution.0 as f32);
        [-1.0 + (2.0 * (rx as f32 + window_pos.0 * zoom) / w as f32),
          1.0 - (2.0 * (ry as f32 + window_pos.1 * zoom) / h as f32),
         z]
    }

    /// Add a vertex to the geometry data of the current frame.
    pub fn push_vertex<C: Color, C2: Color>(&mut self, pos: V2<f32>, layer: f32, tex_coord: V2<f32>,
                                 color: &C, back_color: &C2) {
        let pos = self.window_to_device(pos, layer);

        self.vertices.push(Vertex {
            pos: pos,
            tex_coord: [tex_coord.0, tex_coord.1],
            color: color.to_rgba(),
            back_color: back_color.to_rgba(),
        });
    }

    /// Return the current vertex count, important for determining the indices
    /// for newly inserted vertices.
    pub fn num_vertices(&self) -> u16 { self.vertices.len() as u16 }

    /// Add a triangle defined by index values into the list of vertices
    /// inserted with push_vertex.
    pub fn push_triangle(&mut self, p0: u16, p1: u16, p2: u16) {
        self.indices.push(p0);
        self.indices.push(p1);
        self.indices.push(p2);
    }

    /// Return the image corresponding to a char in the built-in font.
    pub fn font_image(&self, c: char) -> Option<Image> {
        let idx = c as usize;
        // Hardcoded limiting of the font to printable ASCII.
        if idx >= 32 && idx < 128 {
            Some(Image((idx - 32) as usize + FONT_IDX))
        } else {
            None
        }
    }

    /// Return a texture coordinate to a #FFFFFFFF texel for solid color
    /// graphics.
    pub fn solid_tex_coord(&self) -> V2<f32> { self.atlas.items[SOLID_IDX].tex.0 }

    pub fn image_data<'a>(&'a self, Image(idx): Image) -> &'a AtlasItem {
        &self.atlas.items[idx]
    }
}

impl<'a> Iterator for Canvas {
    type Item=Event<'a>;

    fn next(&mut self) -> Option<Event<'a>> {
        // After a render event, control will return here on a new
        // iter call. Do post-render work here.
        if self.state == State::EndFrame {
            self.state = State::Normal;

            let mut target = self.display.draw();

            // Move out the accumulated geometry data.
            let vertices = mem::replace(&mut self.vertices, Vec::new());
            let indices = mem::replace(&mut self.indices, Vec::new());
            self.renderer.draw(&self.display, &mut target, vertices, indices);

            target.finish();
        }

        loop {
            self.events.push_all(self.display.poll_events().as_slice());

            if !self.events.is_empty() {
                match self.events.remove(0) {
                    glutin::Event::ReceivedCharacter(ch) => {
                        return Some(Event::Char(ch));
                    }
                    glutin::Event::KeyboardInput(action, scan, _vko) => {
                        if (scan as usize) < scancode::MAP.len() {
                            if let Some(key) = scancode::MAP[scan as usize] {
                                return Some(if action == glutin::ElementState::Pressed {
                                    Event::KeyPressed(key)
                                }
                                else {
                                    Event::KeyReleased(key)
                                });
                            }
                        }
                    }
                    glutin::Event::MouseMoved((x, y)) => {
                        let pixel_pos = self.screen_to_pixel(V2(x, y));
                        return Some(Event::MouseMoved((pixel_pos.0, pixel_pos.1)));
                    }
                    glutin::Event::MouseWheel(x) => {
                        return Some(Event::MouseWheel(x));
                    }
                    glutin::Event::MouseInput(state, button) => {
                        let button = match button {
                            glutin::MouseButton::LeftMouseButton => MouseButton::Left,
                            glutin::MouseButton::RightMouseButton => MouseButton::Right,
                            glutin::MouseButton::MiddleMouseButton => MouseButton::Middle,
                            glutin::MouseButton::OtherMouseButton(x) => MouseButton::Other(x),
                        };
                        match state {
                            glutin::ElementState::Pressed => {
                                return Some(Event::MousePressed(button));
                            }
                            glutin::ElementState::Released => {
                                return Some(Event::MouseReleased(button));
                            }
                        }
                    }
                    glutin::Event::Focused(b) => {
                        return Some(Event::FocusChanged(b));
                    }
                    glutin::Event::Closed => {
                        return None;
                    }
                    _ => ()
                }
            }

            let t = time::precise_time_s();
            if self.frame_interval.map_or(true,
                |x| t - self.last_render_time >= x) {
                let delta = t - self.last_render_time;
                let sensitivity = 0.25f64;
                self.render_duration = (1f64 - sensitivity) * self.render_duration + sensitivity * delta;

                self.last_render_time = t;

                // Time to render, must return a handle to self.
                // XXX: Need unsafe hackery to get around lifetimes check.
                self.state = State::EndFrame;

                let (w, h) = self.display.get_framebuffer_dimensions();
                self.window_resolution = V2(w as i32, h as i32);

                unsafe {
                    return Some(Event::Render(mem::transmute(self)))
                }
            }
        }
    }
}

/// Drawable images stored in the Canvas.
#[derive(Copy, Clone, PartialEq)]
pub struct Image(usize);

/// A pixel perfect centered and scaled rectangle of resolution dim in a
/// window of size area.
#[inline(always)]
fn pixel_perfect(canvas: V2<i32>, window: V2<i32>) -> Rect<i32> {
    let mut scale = (window.0 as f32 / canvas.0 as f32)
        .min(window.1 as f32 / canvas.1 as f32);

    if scale > 1.0 {
        // Snap to pixel scale if more than 1 window pixel per canvas pixel.
        scale = scale.floor();
    }

    let dim = V2((scale * canvas.0 as f32) as i32, (scale * canvas.1 as f32) as i32);
    let offset = (window - dim) / 2;
    Rect(offset, dim)
}
<|endoftext|>


<commit_before>#![feature(test)]
#![deny(warnings)]

extern crate futures;
extern crate hyper;
extern crate pretty_env_logger;
extern crate test;
extern crate tokio;

use std::net::SocketAddr;

use futures::{Future, Stream};
use tokio::runtime::current_thread::Runtime;
use tokio::net::TcpListener;

use hyper::{Body, Method, Request, Response, Version};
use hyper::client::HttpConnector;
use hyper::server::conn::Http;

#[bench]
fn http1_get(b: &mut test::Bencher) {
    bench_with(b, Version::HTTP_11, || {
        Request::new(Body::empty())
    });
}

#[bench]
fn http1_post(b: &mut test::Bencher) {
    bench_with(b, Version::HTTP_11, || {
        let mut req = Request::new("foo bar baz quux".into());
        *req.method_mut() = Method::POST;
        req
    });
}

#[bench]
fn http1_get_parallel(b: &mut test::Bencher) {
    bench_parallel_with(b, Version::HTTP_11, || {
        Request::new(Body::empty())
    });
}

#[bench]
fn http2_get(b: &mut test::Bencher) {
    bench_with(b, Version::HTTP_2, || {
        Request::new(Body::empty())
    });
}

#[bench]
fn http2_post(b: &mut test::Bencher) {
    bench_with(b, Version::HTTP_2, || {
        let mut req = Request::new("foo bar baz quux".into());
        *req.method_mut() = Method::POST;
        req
    });
}

#[bench]
fn http2_get_parallel(b: &mut test::Bencher) {
    bench_parallel_with(b, Version::HTTP_2, || {
        Request::new(Body::empty())
    });
}

fn bench_with<F>(b: &mut test::Bencher, version: Version, make_request: F)
where
    F: Fn() -> Request<Body>,
{
    let _ = pretty_env_logger::try_init();
    let mut rt = Runtime::new().unwrap();
    let body = b"Hello";
    let addr = spawn_hello(&mut rt, body);

    let connector = HttpConnector::new(1);
    let client = hyper::Client::builder()
        .http2_only(version == Version::HTTP_2)
        .build::<_, Body>(connector);

    let url: hyper::Uri = format!("http://{}/hello", addr).parse().unwrap();

    b.bytes = body.len() as u64;
    b.iter(move || {
        let mut req = make_request();
        *req.uri_mut() = url.clone();
        rt.block_on(client.request(req).and_then(|res| {
            res.into_body().for_each(|_chunk| {
                Ok(())
            })
        })).expect("client wait");
    });
}

fn bench_parallel_with<F>(b: &mut test::Bencher, version: Version, make_request: F)
where
    F: Fn() -> Request<Body>,
{
    let _ = pretty_env_logger::try_init();
    let mut rt = Runtime::new().unwrap();
    let body = b"Hello";
    let addr = spawn_hello(&mut rt, body);

    let connector = HttpConnector::new(1);
    let client = hyper::Client::builder()
        .http2_only(version == Version::HTTP_2)
        .build::<_, Body>(connector);

    let url: hyper::Uri = format!("http://{}/hello", addr).parse().unwrap();

    b.bytes = body.len() as u64;
    b.iter(move || {
        let futs = (0..10)
            .into_iter()
            .map(|_| {
                let mut req = make_request();
                *req.uri_mut() = url.clone();
                client.request(req).and_then(|res| {
                    res.into_body().for_each(|_chunk| {
                        Ok(())
                    })
                }).map_err(|_e| ())
            });
        let _ = rt.block_on(::futures::future::join_all(futs));
    });
}

fn spawn_hello(rt: &mut Runtime, body: &'static [u8]) -> SocketAddr {
    use hyper::service::{service_fn};
    let addr = "127.0.0.1:0".parse().unwrap();
    let listener = TcpListener::bind(&addr).unwrap();
    let addr = listener.local_addr().unwrap();

    let http = Http::new();

    let service = service_fn(move |req: Request<Body>| {
        req.into_body()
            .concat2()
            .map(move |_| {
                Response::new(Body::from(body))
            })
    });

    // Specifically only accept 1 connection.
    let srv = listener.incoming()
        .into_future()
        .map_err(|(e, _inc)| panic!("accept error: {}", e))
        .and_then(move |(accepted, _inc)| {
            let socket = accepted.expect("accepted socket");
            http.serve_connection(socket, service)
                .map_err(|_| ())
        });
    rt.spawn(srv);
    return addr
}
<commit_msg>test(benches): clean up end_to_end benchmark configuration<commit_after>#![feature(test)]
#![deny(warnings)]

extern crate futures;
extern crate hyper;
extern crate pretty_env_logger;
extern crate test;
extern crate tokio;

use std::net::SocketAddr;

use futures::{Future, Stream};
use tokio::runtime::current_thread::Runtime;

use hyper::{Body, Method, Request, Response, Server};
use hyper::client::HttpConnector;

#[bench]
fn http1_get(b: &mut test::Bencher) {
    opts()
        .bench(b)
}

#[bench]
fn http1_post(b: &mut test::Bencher) {
    opts()
        .method(Method::POST)
        .request_body(b"foo bar baz quux")
        .bench(b)
}

#[bench]
fn http1_get_parallel(b: &mut test::Bencher) {
    opts()
        .parallel(10)
        .bench(b)
}

#[bench]
fn http2_get(b: &mut test::Bencher) {
    opts()
        .http2()
        .bench(b)
}

#[bench]
fn http2_post(b: &mut test::Bencher) {
    opts()
        .http2()
        .method(Method::POST)
        .request_body(b"foo bar baz quux")
        .bench(b)
}

#[bench]
fn http2_get_parallel(b: &mut test::Bencher) {
    opts()
        .http2()
        .parallel(10)
        .bench(b)
}

// ==== Benchmark Options =====

struct Opts {
    http2: bool,
    parallel_cnt: u32,
    request_method: Method,
    request_body: Option<&'static [u8]>,
    response_body: &'static [u8],
}

fn opts() -> Opts {
    Opts {
        http2: false,
        parallel_cnt: 1,
        request_method: Method::GET,
        request_body: None,
        response_body: b"Hello",
    }
}

impl Opts {
    fn http2(mut self) -> Self {
        self.http2 = true;
        self
    }

    fn method(mut self, m: Method) -> Self {
        self.request_method = m;
        self
    }

    fn request_body(mut self, body: &'static [u8]) -> Self {
        self.request_body = Some(body);
        self
    }

    fn parallel(mut self, cnt: u32) -> Self {
        assert!(cnt > 0, "parallel count must be larger than 0");
        self.parallel_cnt = cnt;
        self
    }

    fn bench(self, b: &mut test::Bencher) {
        let _ = pretty_env_logger::try_init();
        let mut rt = Runtime::new().unwrap();
        let addr = spawn_hello(&mut rt, self.response_body);

        let connector = HttpConnector::new(1);
        let client = hyper::Client::builder()
            .http2_only(self.http2)
            .build::<_, Body>(connector);

        let url: hyper::Uri = format!("http://{}/hello", addr).parse().unwrap();

        let make_request = || {
            let body = self
                .request_body
                .map(Body::from)
                .unwrap_or_else(|| Body::empty());
            let mut req = Request::new(body);
            *req.method_mut() = self.request_method.clone();
            req
        };

        if self.parallel_cnt == 1 {
            b.iter(move || {
                let mut req = make_request();
                *req.uri_mut() = url.clone();
                rt.block_on(client.request(req).and_then(|res| {
                    res.into_body().for_each(|_chunk| {
                        Ok(())
                    })
                })).expect("client wait");
            });
        } else {
            b.iter(|| {
                let futs = (0..self.parallel_cnt)
                    .into_iter()
                    .map(|_| {
                        let mut req = make_request();
                        *req.uri_mut() = url.clone();
                        client.request(req).and_then(|res| {
                            res.into_body().for_each(|_chunk| {
                                Ok(())
                            })
                        }).map_err(|e| panic!("client error: {}", e))
                    });
                let _ = rt.block_on(::futures::future::join_all(futs));
            });
        }
    }
}

fn spawn_hello(rt: &mut Runtime, body: &'static [u8]) -> SocketAddr {
    use hyper::service::{service_fn};
    let addr = "127.0.0.1:0".parse().unwrap();

    let srv = Server::bind(&addr)
        .serve(move || {
            service_fn(move |req: Request<Body>| {
                req.into_body()
                    .concat2()
                    .map(move |_| {
                        Response::new(Body::from(body))
                    })
            })
        });
    let addr = srv.local_addr();
    let fut = srv.map_err(|err| panic!("server error: {}", err));
    rt.spawn(fut);
    return addr
}
<|endoftext|>


<commit_before>use std::fmt;
use std::ops::Range;
use std::usize;

#[derive(Clone, Hash)]
pub struct BitsVec {
    inner: Vec<usize>,
    units: usize,
    bits: usize,
    max_bits: usize,
    leftover: usize,
}

impl BitsVec {
    pub fn new(bits: usize) -> BitsVec {
        let max = usize::MAX.count_ones() as usize;
        // We can store more bits, but then we might need BigInt to get them out!
        assert!(bits < max, "cannot hold more than {} bits at a time", max - 1);

        BitsVec {
            inner: vec![0],
            units: 0,
            bits: bits,
            max_bits: max,
            leftover: max,
        }
    }

    pub fn push(&mut self, mut value: usize) {
        assert!(value >> self.bits == 0,
                "input size is more than allowed size ({} >= {})", value, 2usize.pow(self.bits as u32));

        let mut idx = self.inner.len() - 1;
        let shift_amount;

        if self.leftover < self.bits {
            let left = self.bits - self.leftover;
            self.inner[idx] |= value >> left;
            if self.leftover != 0 {     // special case, in which masking would result in zero!
                value &= (1 << left) - 1;
            }

            self.inner.push(0);
            self.leftover = self.max_bits - left;
            shift_amount = self.max_bits - left;
            idx += 1;
        } else {
            shift_amount = self.leftover - self.bits;
            self.leftover -= self.bits;
        }

        value <<= shift_amount;
        self.inner[idx] |= value;
        self.units += 1;
    }

    pub fn get(&self, i: usize) -> Option<usize> {
        if i >= self.units {
            return None
        }

        let idx = i * self.bits / self.max_bits;
        let bits = (i * self.bits) % self.max_bits;
        let mut val = self.inner[idx];
        if bits != 0 {
            val &= (1 << (self.max_bits - bits)) - 1;
        }

        let diff = self.max_bits - bits;
        if diff >= self.bits {
            Some(val >> (diff - self.bits))
        } else {
            let shift = self.bits - diff;
            Some((val << shift) | (self.inner[idx + 1] >> (self.max_bits - shift)))
        }
    }

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

    pub fn inner_len(&self) -> usize {
        self.inner.len()
    }

    pub fn iter(&self) -> Iter {
        Iter { vec: self, range: 0..self.units }
    }

    pub fn into_iter(self) -> IntoIter {
        IntoIter { range: 0..self.units, vec: self }
    }
}

impl fmt::Debug for BitsVec {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_list().entries(self.iter()).finish()
    }
}

pub struct Iter<'a> {
    vec: &'a BitsVec,
    range: Range<usize>,
}

impl<'a> IntoIterator for &'a BitsVec {
    type Item = usize;
    type IntoIter = Iter<'a>;

    fn into_iter(self) -> Iter<'a> {
        self.iter()
    }
}

impl<'a> Iterator for Iter<'a> {
    type Item = usize;

    fn next(&mut self) -> Option<usize> {
        self.range.next().and_then(|i| self.vec.get(i))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.range.size_hint()
    }
}

impl<'a> DoubleEndedIterator for Iter<'a> {
    fn next_back(&mut self) -> Option<usize> {
        self.range.next_back().and_then(|i| self.vec.get(i))
    }
}

impl<'a> ExactSizeIterator for Iter<'a> {}

pub struct IntoIter {
    vec: BitsVec,
    range: Range<usize>,
}

impl IntoIterator for BitsVec {
    type Item = usize;
    type IntoIter = IntoIter;

    fn into_iter(self) -> IntoIter {
        self.into_iter()
    }
}

impl Iterator for IntoIter {
    type Item = usize;

    fn next(&mut self) -> Option<usize> {
        self.range.next().and_then(|i| self.vec.get(i))
    }
}

impl DoubleEndedIterator for IntoIter {
    fn next_back(&mut self) -> Option<usize> {
        self.range.next_back().and_then(|i| self.vec.get(i))
    }
}

impl ExactSizeIterator for IntoIter {}
<commit_msg>Basic setter (and some minor fixes)<commit_after>use std::fmt;
use std::ops::Range;
use std::usize;

#[derive(Clone, Hash)]
pub struct BitsVec {
    inner: Vec<usize>,
    units: usize,
    bits: usize,
    max_bits: usize,
    leftover: usize,
}

impl BitsVec {
    pub fn new(bits: usize) -> BitsVec {
        let max = usize::MAX.count_ones() as usize;
        // We can store more bits, but then we might need BigInt to get them out!
        assert!(bits < max, "cannot hold more than {} bits at a time", max - 1);

        BitsVec {
            inner: vec![0],
            units: 0,
            bits: bits,
            max_bits: max,
            leftover: max,
        }
    }

    pub fn push(&mut self, mut value: usize) {
        assert!(value >> self.bits == 0,
                "input size is more than allowed size ({} >= {})", value, 2usize.pow(self.bits as u32));

        let mut idx = self.inner.len() - 1;
        let shift_amount;

        if self.leftover < self.bits {
            let left = self.bits - self.leftover;
            self.inner[idx] |= value >> left;
            if self.leftover != 0 {     // special case, in which masking would result in zero!
                value &= (1 << left) - 1;
            }

            self.inner.push(0);
            self.leftover = self.max_bits - left;
            shift_amount = self.max_bits - left;
            idx += 1;
        } else {
            shift_amount = self.leftover - self.bits;
            self.leftover -= self.bits;
        }

        value <<= shift_amount;
        self.inner[idx] |= value;
        self.units += 1;
    }

    pub fn get(&self, i: usize) -> Option<usize> {
        if i >= self.units {
            return None
        }

        let idx = i * self.bits / self.max_bits;
        let bits = (i * self.bits) % self.max_bits;
        let diff = self.max_bits - bits;
        let mut val = self.inner[idx];
        if bits != 0 {
            val &= (1 << diff) - 1;
        }

        if diff >= self.bits {
            Some(val >> (diff - self.bits))
        } else {
            let shift = self.bits - diff;
            Some((val << shift) | (self.inner[idx + 1] >> (self.max_bits - shift)))
        }
    }

    pub fn set(&mut self, i: usize, value: usize) {
        assert!(i < self.units, "index out of bounds ({} >= {})", i, self.units);
        assert!(value >> self.bits == 0,
                "input size is more than allowed size ({} >= {})", value, 2usize.pow(self.bits as u32));

        let idx = i * self.bits / self.max_bits;
        let bits = (i * self.bits) % self.max_bits;
        let diff = self.max_bits - bits;
        let mut val = self.inner[idx];

        if diff >= self.bits {
            let shift = diff - self.bits;
            let last = val & ((1 << shift) - 1);
            let mask = if bits == 0 { 0 } else { ((1 << bits) - 1) << diff };   // prevent overflow
            val &= mask;
            val |= value << shift;
            self.inner[idx] = val | last;
        } else {
            let shift = self.bits - diff;
            self.inner[idx] >>= diff;
            self.inner[idx] <<= diff;
            self.inner[idx] |= value >> shift;
            let last = value & ((1 << shift) - 1);
            self.inner[idx + 1] &= (1 << (self.max_bits - shift)) - 1;
            self.inner[idx + 1] |= last << (self.max_bits - shift);
        }
    }

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

    pub fn inner_len(&self) -> usize {
        self.inner.len()
    }

    pub fn iter(&self) -> Iter {
        Iter { vec: self, range: 0..self.units }
    }

    pub fn into_iter(self) -> IntoIter {
        IntoIter { range: 0..self.units, vec: self }
    }
}

impl fmt::Debug for BitsVec {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_list().entries(self.iter()).finish()
    }
}

pub struct Iter<'a> {
    vec: &'a BitsVec,
    range: Range<usize>,
}

impl<'a> IntoIterator for &'a BitsVec {
    type Item = usize;
    type IntoIter = Iter<'a>;

    fn into_iter(self) -> Iter<'a> {
        self.iter()
    }
}

impl<'a> Iterator for Iter<'a> {
    type Item = usize;

    fn next(&mut self) -> Option<usize> {
        self.range.next().and_then(|i| self.vec.get(i))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.range.size_hint()
    }
}

impl<'a> DoubleEndedIterator for Iter<'a> {
    fn next_back(&mut self) -> Option<usize> {
        self.range.next_back().and_then(|i| self.vec.get(i))
    }
}

impl<'a> ExactSizeIterator for Iter<'a> {}

pub struct IntoIter {
    vec: BitsVec,
    range: Range<usize>,
}

impl IntoIterator for BitsVec {
    type Item = usize;
    type IntoIter = IntoIter;

    fn into_iter(self) -> IntoIter {
        self.into_iter()
    }
}

impl Iterator for IntoIter {
    type Item = usize;

    fn next(&mut self) -> Option<usize> {
        self.range.next().and_then(|i| self.vec.get(i))
    }
}

impl DoubleEndedIterator for IntoIter {
    fn next_back(&mut self) -> Option<usize> {
        self.range.next_back().and_then(|i| self.vec.get(i))
    }
}

impl ExactSizeIterator for IntoIter {}
<|endoftext|>