<commit_before>use std::marker::PhantomData;
use std::vec::Vec;

pub use automata::*;
pub use approximation::*;

pub use util::*;

pub use tree_stack::*;
pub use push_down::*;

//Strategy Element for mapping pushdown to its top most k elements
#[derive(Clone)]
pub struct PDTopKElement<A>{
    pub dummy: PhantomData<A>,
    pub size: usize,
}

impl <A : Ord + PartialEq + Debug + Clone + Hash,
      T: Eq + Clone +Hash,
      W: Ord + Eq + Clone + Add<Output=W> + Mul<Output = W> + Div<f64, Output=W> + Add<f64, Output = f64> + Zero + One> ApproximationStrategy<PushDown<A>, PushDown<A>,
        automata::Transition<PushDown<A>, PushDownInstruction<A>, T, W>,
        automata::Transition<PushDown<A>, PushDownInstruction<A>, T, W>>
      for PDTopKElement<A>{

    fn approximate_initial(self, a : PushDown<A>)-> PushDown<A>{
        let mut b = a.elements.clone();
        b.remove(0);
        let pushdown = PushDown::new(b[0].clone(), a.empty.clone());
        println!("{:?}", pushdown);
        let ps=pushdown.replacek(&b[0], &b, &self.size.clone());
                println!("{:?}", ps[0]);
        ps[0].clone()

    }

    fn approximate_transition(self, t :  automata::Transition<PushDown<A>, PushDownInstruction<A>, T, W>) ->
        automata::Transition<PushDown<A>, PushDownInstruction<A>, T, W>{
        match t.instruction{
            PushDownInstruction::Replace {ref current_val, ref new_val} => {
                automata::Transition {
                    _dummy: PhantomData,
                    word: t.word.clone(),
                    weight: t.weight.clone(),
                    instruction: PushDownInstruction::ReplaceK {
                        current_val: current_val.clone(),
                        new_val: new_val.clone(),
                        limit: self.size.clone(),
                    }
                }
            },
            PushDownInstruction::ReplaceK {ref current_val, ref new_val, ref limit} => {
                automata::Transition {
                    _dummy: PhantomData,
                    word: t.word.clone(),
                    weight: t.weight.clone(),
                    instruction: PushDownInstruction::ReplaceK {
                        current_val: current_val.clone(),
                        new_val: new_val.clone(),
                        limit: self.size.clone(),
                    }
                }
            },
        }
    }
}
<commit_msg>Small additional change<commit_after>use std::marker::PhantomData;

pub use automata::*;
pub use approximation::*;

pub use util::*;

pub use tree_stack::*;
pub use push_down::*;

//Strategy Element for mapping pushdown to its top most k elements
#[derive(Clone)]
pub struct PDTopKElement<A>{
    pub dummy: PhantomData<A>,
    pub size: usize,
}

impl <A : Ord + PartialEq + Debug + Clone + Hash,
      T: Eq + Clone +Hash,
      W: Ord + Eq + Clone + Add<Output=W> + Mul<Output = W> + Div<f64, Output=W> + Add<f64, Output = f64> + Zero + One> ApproximationStrategy<PushDown<A>, PushDown<A>,
        automata::Transition<PushDown<A>, PushDownInstruction<A>, T, W>,
        automata::Transition<PushDown<A>, PushDownInstruction<A>, T, W>>
      for PDTopKElement<A>{

    fn approximate_initial(self, a : PushDown<A>)-> PushDown<A>{
        let mut b = a.elements.clone();
        b.remove(0);
        let pushdown = PushDown::new(b[0].clone(), a.empty.clone());
        let ps=pushdown.replacek(&b[0], &b, &self.size.clone());
        ps[0].clone()

    }

    fn approximate_transition(self, t :  automata::Transition<PushDown<A>, PushDownInstruction<A>, T, W>) ->
        automata::Transition<PushDown<A>, PushDownInstruction<A>, T, W>{
        match t.instruction{
            PushDownInstruction::Replace {ref current_val, ref new_val} => {
                automata::Transition {
                    _dummy: PhantomData,
                    word: t.word.clone(),
                    weight: t.weight.clone(),
                    instruction: PushDownInstruction::ReplaceK {
                        current_val: current_val.clone(),
                        new_val: new_val.clone(),
                        limit: self.size.clone(),
                    }
                }
            },
            PushDownInstruction::ReplaceK {ref current_val, ref new_val, ..} => {
                automata::Transition {
                    _dummy: PhantomData,
                    word: t.word.clone(),
                    weight: t.weight.clone(),
                    instruction: PushDownInstruction::ReplaceK {
                        current_val: current_val.clone(),
                        new_val: new_val.clone(),
                        limit: self.size.clone(),
                    }
                }
            },
        }
    }
}
<|endoftext|>


<commit_before>
extern crate debug;
extern crate lab;

use lab::units::Per;
use lab::units::Comp;

pub enum L1Cache {}
#[deriving(PartialEq)]
pub enum F32 {}
#[deriving(PartialEq)]
pub enum Byte {}
pub enum XY<T> {}
pub enum XYZ<T> {}
pub enum RGB<T> {}
pub enum RGBA<T> {}
pub enum Triangle<T> {}
pub enum Quad<T> {}

impl Comp<Byte> for L1Cache {
    fn comp() -> Per<Byte, L1Cache> {
        Per::kibi(32.0)
    }
}

impl<T> Comp<XY<T>> for Triangle<XY<T>> {
    fn comp() -> Per<XY<T>, Triangle<XY<T>>> {
        Per::new(3.0)
    }
}

impl<T> Comp<XYZ<T>> for Triangle<XYZ<T>> {
    fn comp() -> Per<XYZ<T>, Triangle<XYZ<T>>> {
        Per::new(3.0)
    }
}

impl<T> Comp<Triangle<T>> for Quad<Triangle<T>> {
    fn comp() -> Per<Triangle<T>, Quad<Triangle<T>>> {
        Per::new(2.0)
    }
}

impl<T> Comp<XY<T>> for Quad<XY<T>> {
    fn comp() -> Per<XY<T>, Quad<XY<T>>> {
        Per::new(4.0)
    }
}

impl<T> Comp<XYZ<T>> for Quad<XYZ<T>> {
    fn comp() -> Per<XYZ<T>, Quad<XYZ<T>>> {
        Per::new(4.0)
    }
}

impl Comp<Byte> for F32 {
    fn comp() -> Per<Byte, F32> {
        Per::new(4.0)
    }
}

impl<T> Comp<T> for XY<T> {
    fn comp() -> Per<T, XY<T>> {
        Per::new(2.0)
    }
}

impl<T> Comp<T> for XYZ<T> {
    fn comp() -> Per<T, XYZ<T>> {
        Per::new(3.0)
    }
}

impl<T> Comp<T> for RGB<T> {
    fn comp() -> Per<T, RGB<T>> {
        Per::new(3.0)
    }
}

impl<T> Comp<T> for RGBA<T> {
    fn comp() -> Per<T, RGBA<T>> {
        Per::new(4.0)
    }
}

fn product<T: Comp<U>, U, V: Comp<T>>() -> Per<U, V> {
    let u_per_t: Per<U, T> = Comp::comp();
    let t_per_v: Per<T, V> = Comp::comp();
    u_per_t * t_per_v
}

fn main() {
    let bytes_per_xy: Per<Byte, XY<F32>> = product();
    println!("{:?}", bytes_per_xy);

    let bytes_per_xyz: Per<Byte, XYZ<F32>> = product();
    println!("{:?}", bytes_per_xyz);

    let bytes_per_triangle: Per<Byte, Triangle<XY<F32>>>
        = bytes_per_xy * Comp::comp();
    println!("{:?}", bytes_per_triangle);

    let bytes_per_l1cache: Per<Byte, L1Cache> = Comp::comp();
    println!("{:?}", bytes_per_l1cache);

    let triangles_per_l1cache = bytes_per_l1cache / bytes_per_triangle;
    println!("{:?}", triangles_per_l1cache);
}

<commit_msg>Testing new stuff<commit_after>
extern crate debug;
extern crate lab;

use lab::units::Per;
use lab::units::Comp;

pub enum Sum<A, B> {}
pub enum L1Cache {}
pub enum F32 {}
pub enum F64 {}
pub enum Byte {}
pub enum XY<T> {}
pub enum XYZ<T> {}
pub enum RGB<T> {}
pub enum RGBA<T> {}
pub enum Triangle<T> {}
pub enum Quad<T> {}

impl Comp<Byte> for L1Cache {
    fn comp() -> Per<Byte, L1Cache> {
        Per::kibi(32.0)
    }
}

impl<T> Comp<XY<T>> for Triangle<XY<T>> {
    fn comp() -> Per<XY<T>, Triangle<XY<T>>> {
        Per::new(3.0)
    }
}

impl<T> Comp<XYZ<T>> for Triangle<XYZ<T>> {
    fn comp() -> Per<XYZ<T>, Triangle<XYZ<T>>> {
        Per::new(3.0)
    }
}

impl<T> Comp<Triangle<T>> for Quad<Triangle<T>> {
    fn comp() -> Per<Triangle<T>, Quad<Triangle<T>>> {
        Per::new(2.0)
    }
}

impl<T> Comp<XY<T>> for Quad<XY<T>> {
    fn comp() -> Per<XY<T>, Quad<XY<T>>> {
        Per::new(4.0)
    }
}

impl<T> Comp<XYZ<T>> for Quad<XYZ<T>> {
    fn comp() -> Per<XYZ<T>, Quad<XYZ<T>>> {
        Per::new(4.0)
    }
}

impl Comp<Byte> for Byte {
    fn comp() -> Per<Byte, Byte> {
        Per::new(1.0)
    }
}

impl Comp<Byte> for F32 {
    fn comp() -> Per<Byte, F32> {
        Per::new(4.0)
    }
}

impl Comp<Byte> for F64 {
    fn comp() -> Per<Byte, F64> {
        Per::new(8.0)
    }
}

impl<T> Comp<T> for XY<T> {
    fn comp() -> Per<T, XY<T>> {
        Per::new(2.0)
    }
}

impl<T> Comp<T> for XYZ<T> {
    fn comp() -> Per<T, XYZ<T>> {
        Per::new(3.0)
    }
}

impl<T> Comp<T> for RGB<T> {
    fn comp() -> Per<T, RGB<T>> {
        Per::new(3.0)
    }
}

impl<T> Comp<T> for RGBA<T> {
    fn comp() -> Per<T, RGBA<T>> {
        Per::new(4.0)
    }
}

fn product<T: Comp<U>, U, V: Comp<T>>() -> Per<U, V> {
    let u_per_t: Per<U, T> = Comp::comp();
    let t_per_v: Per<T, V> = Comp::comp();
    u_per_t * t_per_v
}

impl<T: Comp<Byte>, U: Comp<T>, V: Comp<Byte>, W: Comp<V>>
Comp<Byte> for Sum<U, W> {
    fn comp() -> Per<Byte, Sum<U, W>> {
        let Per(a): Per<Byte, W> = product();
        let Per(b): Per<Byte, W> = product();
        Per(a + b)
    }
}

fn bytes_per_triangle<T: Comp<Byte>>() -> Per<Byte, Triangle<XY<T>>> {
    let bytes_per_xy: Per<Byte, XY<T>> = product();
    bytes_per_xy * Comp::comp()
}

fn bytes_per_xy<T: Comp<Byte>>() -> Per<Byte, XY<T>> {
    product()
}

fn bytes_per_xyz<T: Comp<Byte>>() -> Per<Byte, XYZ<T>> {
    product()
}

fn bytes_per_l1cache() -> Per<Byte, L1Cache> {
    Comp::comp()
}

fn bytes_per_rgba<T: Comp<Byte>>() -> Per<Byte, RGBA<T>> {
    product()
}

fn bytes_per_rgb<T: Comp<Byte>>() -> Per<Byte, RGB<T>> {
    product()
}

fn main() {
    let bytes_per_xy: Per<Byte, XY<F32>> = bytes_per_xy();
    println!("{:?}", bytes_per_xy);

    let bytes_per_xyz: Per<Byte, XYZ<F32>> = bytes_per_xyz();
    println!("{:?}", bytes_per_xyz);

    let bytes_per_triangle: Per<Byte, Triangle<XY<F32>>>
        = bytes_per_triangle();
    println!("{:?}", bytes_per_triangle);

    let bytes_per_l1cache: Per<Byte, L1Cache> = bytes_per_l1cache();
    println!("{:?}", bytes_per_l1cache);

    let triangles_per_l1cache = bytes_per_l1cache / bytes_per_triangle;
    println!("{:?}", triangles_per_l1cache);

    let bytes_per_rgba: Per<Byte, RGBA<F32>> = bytes_per_rgba();
    println!("{:?}", bytes_per_rgba);

    let bytes_per_rgb: Per<Byte, RGB<F32>> = bytes_per_rgb();
    println!("{:?}", bytes_per_rgb);
}

<|endoftext|>


<commit_before>use std::vec;
use std::num;
use std::iter;

fn int_sqrt(n: uint) -> uint {
    num::sqrt(n as f64) as uint
}

fn simple_sieve(limit: uint) -> ~[uint] {
    if limit < 2 {
        return ~[];
    }

    let mut primes = vec::from_elem(limit + 1, true);

    for prime in iter::range_inclusive(2, int_sqrt(limit) + 1) {
        if primes[prime] {
            for multiple in iter::range_step(prime * prime, limit + 1, prime) {
                primes[multiple] = false
            }
        }
    }
    iter::range_inclusive(2, limit).filter(|&n| primes[n]).collect()
}

fn main() {
    println!("{:?}", simple_sieve(100))
}
<commit_msg>Fix Sieve of Eratosthenes<commit_after>use std::slice;
use std::num;
use std::iter;

fn int_sqrt(n: uint) -> uint {
    num::sqrt(n as f64) as uint
}

fn simple_sieve(limit: uint) -> ~[uint] {
    if limit < 2 {
        return ~[];
    }

    let mut primes = slice::from_elem(limit + 1, true);

    for prime in iter::range_inclusive(2, int_sqrt(limit) + 1) {
        if primes[prime] {
            for multiple in iter::range_step(prime * prime, limit + 1, prime) {
                primes[multiple] = false
            }
        }
    }
    iter::range_inclusive(2, limit).filter(|&n| primes[n]).collect()
}

fn main() {
    println!("{:?}", simple_sieve(100))
}
<|endoftext|>


<commit_before>extern crate polydraw;

use std::cmp::max;

use polydraw::{Application, Renderer, RenderFrame};
use polydraw::geom::line::{LineSegment, LineIntersection};
use polydraw::geom::point::Point;
use polydraw::draw::{RGB, bresenham, hline, vline};

const HALF_RECT: i32 = 12;

#[derive (Debug)]
enum ActivePoint {
   Line1Point1,
   Line1Point2,
   Line2Point1,
   Line2Point2,
}

struct IntersectionRenderer {
   intersection: Option<Point<f64>>,

   l1: LineSegment<f64>,
   l2: LineSegment<f64>,

   mouse_x: i32,
   mouse_y: i32,

   width: u32,
   height: u32,

   line_color: RGB,
   default_color: RGB,
   hover_color: RGB,
   intersection_color: RGB,

   dragged_point: Option<ActivePoint>,
}

impl IntersectionRenderer {
   fn new() -> Self {
      IntersectionRenderer {
         intersection: None,

         l1: LineSegment::default(),
         l2: LineSegment::default(),

         mouse_x: -10000,
         mouse_y: -10000,

         width: 0,
         height: 0,

         line_color: RGB::new(93, 181, 241),
         default_color: RGB::new(127, 191, 63),
         hover_color: RGB::new(255, 255, 255),
         intersection_color: RGB::new(127, 127, 255),

         dragged_point: None,
      }
   }

   fn line_point_rect(&self, frame: &mut RenderFrame, x: i32, y: i32) {
      self.point_rect(frame, x, y, self.hit_test_color(x, y));
   }

   fn point_rect(&self, frame: &mut RenderFrame, x: i32, y: i32, color: &RGB) {
      let right_x = x + HALF_RECT;
      let left_x = x - HALF_RECT;
      let top_y = y + HALF_RECT;
      let bottom_y = y - HALF_RECT;

      hline(frame, left_x, right_x, top_y, color);
      hline(frame, left_x, right_x, bottom_y, color);

      vline(frame, left_x, bottom_y, top_y, color);
      vline(frame, right_x, bottom_y, top_y, color);
   }

   fn hit_test_color(&self, x: i32, y: i32) -> &RGB {
      if self.hit_test(x, y) {
         &self.hover_color
      } else {
         &self.default_color
      }
   }

   fn hit_test(&self, x: i32, y: i32) -> bool {
      let distance = max((x - self.mouse_x).abs(), (y - self.mouse_y).abs());
      distance <= HALF_RECT
   }

   fn active_point(&self) -> Option<ActivePoint> {
      let l1_p1_x = self.l1.x1() as i32;
      let l1_p1_y = self.l1.y1() as i32;

      if self.hit_test(l1_p1_x, l1_p1_y) {
         return Some(ActivePoint::Line1Point1);
      }

      let l1_p2_x = self.l1.x2() as i32;
      let l1_p2_y = self.l1.y2() as i32;

      if self.hit_test(l1_p2_x, l1_p2_y) {
         return Some(ActivePoint::Line1Point2);
      }

      let l2_p1_x = self.l2.x1() as i32;
      let l2_p1_y = self.l2.y1() as i32;

      if self.hit_test(l2_p1_x, l2_p1_y) {
         return Some(ActivePoint::Line2Point1);
      }

      let l2_p2_x = self.l2.x2() as i32;
      let l2_p2_y = self.l2.y2() as i32;

      if self.hit_test(l2_p2_x, l2_p2_y) {
         return Some(ActivePoint::Line2Point2);
      }

      None
   }

   fn recalc_intersection(&mut self) {
      let intersection = self.l1.line().intersect(self.l2.line());
      match intersection {
         LineIntersection::Point(p) => {
            self.intersection = Some(p);
         },
         _ => {
            self.intersection = None;
         }
      }
   }
}

impl Renderer for IntersectionRenderer {
   fn init(&mut self, width: u32, height: u32) {
      self.l1.update(
         100_f64, 120_f64,
         width as f64 - 100_f64, height as f64 - 100_f64
      );

      self.l2.update(
         140_f64, height as f64 - 90_f64,
         width as f64 - 140_f64, 100_f64
      );

      self.width = width;
      self.height = height;

      self.recalc_intersection();
   }

   fn resized(&mut self, width: u32, height: u32) {
      let dx: f64 = width as f64 - self.width as f64;
      let dy: f64 = height as f64 - self.height as f64;

      let l1_p1_x = self.l1.x1();
      let l1_p1_y = self.l1.y1();

      let l1_p2_x = self.l1.x2();
      let l1_p2_y = self.l1.y2();

      let l2_p1_x = self.l2.x1();
      let l2_p1_y = self.l2.y1();

      let l2_p2_x = self.l2.x2();
      let l2_p2_y = self.l2.y2();

      self.l1.update(l1_p1_x, l1_p1_y, l1_p2_x + dx, l1_p2_y + dy);

      self.l2.update(l2_p1_x, l2_p1_y + dy, l2_p2_x + dx, l2_p2_y);

      self.width = width;
      self.height = height;

      self.recalc_intersection();
   }

   fn mouse_moved(&mut self, x: i32, y: i32) {
      self.mouse_x = x;
      self.mouse_y = y;

      let x_f64 = x as f64;
      let y_f64 = y as f64;

      match self.dragged_point {
         Some(ActivePoint::Line1Point1) => {
            let x2 = self.l1.x2();
            let y2 = self.l1.y2();
            self.l1.update(x_f64, y_f64, x2, y2);
         },

         Some(ActivePoint::Line1Point2) => {
            let x1 = self.l1.x1();
            let y1 = self.l1.y1();
            self.l1.update(x1, y1, x_f64, y_f64);
         },

         Some(ActivePoint::Line2Point1) => {
            let x2 = self.l2.x2();
            let y2 = self.l2.y2();
            self.l2.update(x_f64, y_f64, x2, y2);
         },

         Some(ActivePoint::Line2Point2) => {
            let x1 = self.l2.x1();
            let y1 = self.l2.y1();
            self.l2.update(x1, y1, x_f64, y_f64);
         },

         _ => {
            return;
         }
      }

      self.recalc_intersection();
   }

   fn mouse_left_button_pressed(&mut self) {
      self.dragged_point = self.active_point();
   }

   fn mouse_left_button_released(&mut self) {
      self.dragged_point = None;
   }

   fn render(&mut self, frame: &mut RenderFrame) {
      frame.clear();

      let l1_p1_x = self.l1.x1() as i32;
      let l1_p1_y = self.l1.y1() as i32;

      let l1_p2_x = self.l1.x2() as i32;
      let l1_p2_y = self.l1.y2() as i32;

      let l2_p1_x = self.l2.x1() as i32;
      let l2_p1_y = self.l2.y1() as i32;

      let l2_p2_x = self.l2.x2() as i32;
      let l2_p2_y = self.l2.y2() as i32;

      bresenham(frame, l1_p1_x, l1_p1_y, l1_p2_x, l1_p2_y, &self.line_color);
      bresenham(frame, l2_p1_x, l2_p1_y, l2_p2_x, l2_p2_y, &self.line_color);

      self.line_point_rect(frame, l1_p1_x, l1_p1_y);
      self.line_point_rect(frame, l1_p2_x, l1_p2_y);
      self.line_point_rect(frame, l2_p1_x, l2_p1_y);
      self.line_point_rect(frame, l2_p2_x, l2_p2_y);

      match self.intersection {
         Some(ref p) => {
            self.point_rect(frame, p.x as i32, p.y as i32, &self.intersection_color);
         },
         _ => {}
      }
   }
}

fn main() {
   let mut renderer = IntersectionRenderer::new();

   Application::new()
      .renderer(&mut renderer)
      .title("Intersection")
      .run();
}
<commit_msg>The intersection example using the line segment intersection algorithm<commit_after>extern crate polydraw;

use std::cmp::max;

use polydraw::{Application, Renderer, RenderFrame};
use polydraw::geom::line::{LineSegment, LineSegmentIntersection};
use polydraw::geom::point::Point;
use polydraw::draw::{RGB, bresenham, hline, vline};

const HALF_RECT: i32 = 12;

#[derive (Debug)]
enum ActivePoint {
   Line1Point1,
   Line1Point2,
   Line2Point1,
   Line2Point2,
}

struct IntersectionRenderer {
   intersection: Option<Point<f64>>,

   l1: LineSegment<f64>,
   l2: LineSegment<f64>,

   mouse_x: i32,
   mouse_y: i32,

   width: u32,
   height: u32,

   line_color: RGB,
   default_color: RGB,
   hover_color: RGB,
   intersection_color: RGB,

   dragged_point: Option<ActivePoint>,
}

impl IntersectionRenderer {
   fn new() -> Self {
      IntersectionRenderer {
         intersection: None,

         l1: LineSegment::default(),
         l2: LineSegment::default(),

         mouse_x: -10000,
         mouse_y: -10000,

         width: 0,
         height: 0,

         line_color: RGB::new(93, 181, 241),
         default_color: RGB::new(127, 191, 63),
         hover_color: RGB::new(255, 255, 255),
         intersection_color: RGB::new(127, 127, 255),

         dragged_point: None,
      }
   }

   fn line_point_rect(&self, frame: &mut RenderFrame, x: i32, y: i32) {
      self.point_rect(frame, x, y, self.hit_test_color(x, y));
   }

   fn point_rect(&self, frame: &mut RenderFrame, x: i32, y: i32, color: &RGB) {
      let right_x = x + HALF_RECT;
      let left_x = x - HALF_RECT;
      let top_y = y + HALF_RECT;
      let bottom_y = y - HALF_RECT;

      hline(frame, left_x, right_x, top_y, color);
      hline(frame, left_x, right_x, bottom_y, color);

      vline(frame, left_x, bottom_y, top_y, color);
      vline(frame, right_x, bottom_y, top_y, color);
   }

   fn hit_test_color(&self, x: i32, y: i32) -> &RGB {
      if self.hit_test(x, y) {
         &self.hover_color
      } else {
         &self.default_color
      }
   }

   fn hit_test(&self, x: i32, y: i32) -> bool {
      let distance = max((x - self.mouse_x).abs(), (y - self.mouse_y).abs());
      distance <= HALF_RECT
   }

   fn active_point(&self) -> Option<ActivePoint> {
      let l1_p1_x = self.l1.x1() as i32;
      let l1_p1_y = self.l1.y1() as i32;

      if self.hit_test(l1_p1_x, l1_p1_y) {
         return Some(ActivePoint::Line1Point1);
      }

      let l1_p2_x = self.l1.x2() as i32;
      let l1_p2_y = self.l1.y2() as i32;

      if self.hit_test(l1_p2_x, l1_p2_y) {
         return Some(ActivePoint::Line1Point2);
      }

      let l2_p1_x = self.l2.x1() as i32;
      let l2_p1_y = self.l2.y1() as i32;

      if self.hit_test(l2_p1_x, l2_p1_y) {
         return Some(ActivePoint::Line2Point1);
      }

      let l2_p2_x = self.l2.x2() as i32;
      let l2_p2_y = self.l2.y2() as i32;

      if self.hit_test(l2_p2_x, l2_p2_y) {
         return Some(ActivePoint::Line2Point2);
      }

      None
   }

   fn recalc_intersection(&mut self) {
      let intersection = self.l1.intersect(&self.l2);
      match intersection {
         LineSegmentIntersection::Point(p) => {
            self.intersection = Some(p);
         },
         _ => {
            self.intersection = None;
         }
      }
   }
}

impl Renderer for IntersectionRenderer {
   fn init(&mut self, width: u32, height: u32) {
      self.l1.update(
         100_f64, 120_f64,
         width as f64 - 100_f64, height as f64 - 100_f64
      );

      self.l2.update(
         140_f64, height as f64 - 90_f64,
         width as f64 - 140_f64, 100_f64
      );

      self.width = width;
      self.height = height;

      self.recalc_intersection();
   }

   fn resized(&mut self, width: u32, height: u32) {
      let dx: f64 = width as f64 - self.width as f64;
      let dy: f64 = height as f64 - self.height as f64;

      let l1_p1_x = self.l1.x1();
      let l1_p1_y = self.l1.y1();

      let l1_p2_x = self.l1.x2();
      let l1_p2_y = self.l1.y2();

      let l2_p1_x = self.l2.x1();
      let l2_p1_y = self.l2.y1();

      let l2_p2_x = self.l2.x2();
      let l2_p2_y = self.l2.y2();

      self.l1.update(l1_p1_x, l1_p1_y, l1_p2_x + dx, l1_p2_y + dy);

      self.l2.update(l2_p1_x, l2_p1_y + dy, l2_p2_x + dx, l2_p2_y);

      self.width = width;
      self.height = height;

      self.recalc_intersection();
   }

   fn mouse_moved(&mut self, x: i32, y: i32) {
      self.mouse_x = x;
      self.mouse_y = y;

      let x_f64 = x as f64;
      let y_f64 = y as f64;

      match self.dragged_point {
         Some(ActivePoint::Line1Point1) => {
            let x2 = self.l1.x2();
            let y2 = self.l1.y2();
            self.l1.update(x_f64, y_f64, x2, y2);
         },

         Some(ActivePoint::Line1Point2) => {
            let x1 = self.l1.x1();
            let y1 = self.l1.y1();
            self.l1.update(x1, y1, x_f64, y_f64);
         },

         Some(ActivePoint::Line2Point1) => {
            let x2 = self.l2.x2();
            let y2 = self.l2.y2();
            self.l2.update(x_f64, y_f64, x2, y2);
         },

         Some(ActivePoint::Line2Point2) => {
            let x1 = self.l2.x1();
            let y1 = self.l2.y1();
            self.l2.update(x1, y1, x_f64, y_f64);
         },

         _ => {
            return;
         }
      }

      self.recalc_intersection();
   }

   fn mouse_left_button_pressed(&mut self) {
      self.dragged_point = self.active_point();
   }

   fn mouse_left_button_released(&mut self) {
      self.dragged_point = None;
   }

   fn render(&mut self, frame: &mut RenderFrame) {
      frame.clear();

      let l1_p1_x = self.l1.x1() as i32;
      let l1_p1_y = self.l1.y1() as i32;

      let l1_p2_x = self.l1.x2() as i32;
      let l1_p2_y = self.l1.y2() as i32;

      let l2_p1_x = self.l2.x1() as i32;
      let l2_p1_y = self.l2.y1() as i32;

      let l2_p2_x = self.l2.x2() as i32;
      let l2_p2_y = self.l2.y2() as i32;

      bresenham(frame, l1_p1_x, l1_p1_y, l1_p2_x, l1_p2_y, &self.line_color);
      bresenham(frame, l2_p1_x, l2_p1_y, l2_p2_x, l2_p2_y, &self.line_color);

      self.line_point_rect(frame, l1_p1_x, l1_p1_y);
      self.line_point_rect(frame, l1_p2_x, l1_p2_y);
      self.line_point_rect(frame, l2_p1_x, l2_p1_y);
      self.line_point_rect(frame, l2_p2_x, l2_p2_y);

      match self.intersection {
         Some(ref p) => {
            self.point_rect(frame, p.x as i32, p.y as i32, &self.intersection_color);
         },
         _ => {}
      }
   }
}

fn main() {
   let mut renderer = IntersectionRenderer::new();

   Application::new()
      .renderer(&mut renderer)
      .title("Intersection")
      .run();
}
<|endoftext|>


<commit_before>//! Implementation of a simple uTP client and server.
#![feature(macro_rules)]

extern crate utp;
use std::io::net::ip::{Ipv4Addr, SocketAddr};

macro_rules! iotry(
    ($e:expr) => (match $e { Ok(v) => v, Err(e) => panic!("{}", e), })
)

fn usage() {
    println!("Usage: utp [-s|-c] <address> <port>");
}

fn main() {
    use utp::UtpStream;
    use std::from_str::FromStr;
    use std::io::{stdin, stdout, stderr};

    // Defaults
    let mut addr = SocketAddr { ip: Ipv4Addr(127,0,0,1), port: 8080 };

    let args = std::os::args();

    if args.len() != 2 && args.len() != 4 {
        usage();
        return;
    }

    if args.len() == 4 {
        addr = SocketAddr {
            ip:   FromStr::from_str(args[2].as_slice()).expect("Invalid address"),
            port: FromStr::from_str(args[3].as_slice()).expect("Invalid port"),
        };
    }

    match args[1].as_slice() {
        "-s" => {
            let mut stream = UtpStream::bind(addr);
            let mut writer = stdout();
            let _ = writeln!(stderr(), "Serving on {}", addr);

            let payload = iotry!(stream.read_to_end());
            iotry!(writer.write(payload.as_slice()));
        }
        "-c" => {
            let mut stream = iotry!(UtpStream::connect(addr));
            let mut reader = stdin();

            let payload = iotry!(reader.read_to_end());
            iotry!(stream.write(payload.as_slice()));
            iotry!(stream.close());
            drop(stream);
        }
        _ => usage(),
    }
}
<commit_msg>Make argument handling clearer in example code.<commit_after>//! Implementation of a simple uTP client and server.
#![feature(macro_rules)]

extern crate utp;
use std::io::net::ip::{Ipv4Addr, SocketAddr};

macro_rules! iotry(
    ($e:expr) => (match $e { Ok(v) => v, Err(e) => panic!("{}", e), })
)

fn usage() {
    println!("Usage: utp [-s|-c] <address> <port>");
}

fn main() {
    use utp::UtpStream;
    use std::from_str::FromStr;
    use std::io::{stdin, stdout, stderr};

    enum Mode {
        Server,
        Client
    }
    let mut mode: Mode;

    // Provide a default address
    let mut addr = SocketAddr { ip: Ipv4Addr(127,0,0,1), port: 8080 };

    let args = std::os::args();
    let mut args = args.iter().map(|arg| arg.as_slice());

    // Skip program name
    args.next();

    match args.next() {
        Some("-s") => mode = Server,
        Some("-c") => mode = Client,
        _ => { usage(); return; }
    }

    match args.collect::<Vec<_>>().as_slice() {
        [] => (),
        [ip, port] => {
            addr = SocketAddr {
                ip:   FromStr::from_str(ip).expect("Invalid address"),
                port: FromStr::from_str(port).expect("Invalid port"),
            };
        }
        _ => { usage(); return; }
    }

    match mode {
        Server => {
            let mut stream = UtpStream::bind(addr);
            let mut writer = stdout();
            let _ = writeln!(stderr(), "Serving on {}", addr);

            let payload = iotry!(stream.read_to_end());
            iotry!(writer.write(payload.as_slice()));
        }
        Client => {
            let mut stream = iotry!(UtpStream::connect(addr));
            let mut reader = stdin();

            let payload = iotry!(reader.read_to_end());
            iotry!(stream.write(payload.as_slice()));
            iotry!(stream.close());
            drop(stream);
        }
    }
}
<|endoftext|>


<commit_before>// Administrative functions.

+ shutdown{weight=10000}
* <id> eq <bot master> => Shutting down... <call>shutdown</call>
- {@botmaster only}

+ botmaster only
- This command can only be used by my botmaster. <id> != <bot master>

> object shutdown perl
	my ($rs) = @_;

	# Shut down.
	exit(0);
< object
<commit_msg>Update admin.rs with Python shutdown object<commit_after>// Administrative functions.

+ shutdown{weight=10000}
* <id> eq <bot master> => Shutting down... <call>shutdown</call>
- {@botmaster only}

+ botmaster only
- This command can only be used by my botmaster. <id> != <bot master>

> object shutdown perl
	my ($rs) = @_;

	# Shut down.
	exit(0);
< object

> object shutdown python
	# Shut down
	exit(0)
< object
<|endoftext|>


<commit_before>use std::{cmp, mem, ptr};
use stash::Stash;

pub struct BatchedVecRef<'a, T: 'a> {
    tail: &'a mut Vec<T>,
    batches: &'a mut Vec<Vec<T>>
}

impl<'a, T> BatchedVecRef<'a, T> {
    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        // It is sufficent to only check the tail for emptiness, since any time we flush
        // the tail (in .reserve), we also push some elements.
        self.tail.is_empty()
    }

    #[inline(always)]
    fn reserve(&mut self, stash: &mut Stash<T>) {
        if self.tail.len() == self.tail.capacity() {
            let complete = mem::replace(self.tail, stash.get());
            if !complete.is_empty() {
                self.batches.push(complete);
            }
        }
    }

    #[inline(always)]
    pub fn push(&mut self, element: T, stash: &mut Stash<T>) {
        self.reserve(stash);

        // The reserve call already ensured we have space. For
        // efficiency, use an unchecked push.
        unsafe {
            let len = self.tail.len();
            ptr::write(self.tail.get_unchecked_mut(len), element);
            self.tail.set_len(len + 1);
        }
    }

    pub fn push_vec(&mut self, mut elements: Vec<T>, stash: &mut Stash<T>) {
        // Fill up tail so that we keep the batches fully filled (we don't
        // want to waste memory).
        let available = self.tail.capacity() - self.tail.len();
        let to_move = cmp::min(available, elements.len());
        self.tail.extend(elements.drain(..to_move)); // This ought to compile to just 2 memcpys

        if elements.is_empty() {
            stash.give(elements);
        } else {
            let tail = mem::replace(self.tail, elements);
            if !tail.is_empty() {
                self.batches.push(tail);
            }
        }
    }

    #[inline(always)]
    pub unsafe fn push_all(&mut self, elements: &[T], stash: &mut Stash<T>) {
        self.reserve(stash);

        if !(self.tail.capacity() - self.tail.len() >= elements.len()) {
            panic!("cap: {:?}, len: {:?}, pcl: {:?}", self.tail.capacity(), self.tail.len(), elements.len());
        }

        let len = self.tail.len();
        ptr::copy_nonoverlapping(elements.as_ptr(), self.tail.as_mut_ptr().offset(len as isize), elements.len());
        self.tail.set_len(len + elements.len());
    }

    #[inline(always)]
    pub fn finish_into(&mut self, target: &mut Vec<Vec<T>>, stash: &mut Stash<T>) {
        target.extend(self.batches.drain(..));
        if !self.tail.is_empty() {
            target.push(mem::replace(&mut self.tail, stash.get()));
        }
    }

    #[inline(always)]
    pub fn finish(&mut self, stash: &mut Stash<T>) -> Vec<Vec<T>> {
        if !self.tail.is_empty() {
            self.batches.push(mem::replace(&mut self.tail, stash.get()));
        }
        mem::replace(&mut self.batches, Vec::new())
    }
}

pub struct BatchedVec<T> {
    tail: Vec<T>,
    batches: Vec<Vec<T>>
}

impl<T> BatchedVec<T> {
    pub fn new() -> BatchedVec<T> {
        BatchedVec {
            tail: Vec::new(),
            batches: Vec::new()
        }
    }

    pub fn ref_mut(&mut self) -> BatchedVecRef<T> {
        BatchedVecRef {
            tail: &mut self.tail,
            batches: &mut self.batches
        }
    }
}

pub struct BatchedVecX256<T> {
    tails: Vec<Vec<T>>,
    batches: Vec<Vec<Vec<T>>>
}

impl<T> BatchedVecX256<T> {
    pub fn new() -> BatchedVecX256<T> {
        let mut tails = Vec::with_capacity(256);
        let mut batches = Vec::with_capacity(256);
        for _byte in 0..256 {
            tails.push(Vec::new());
            batches.push(Vec::new());
        }

        BatchedVecX256 {
            tails: tails,
            batches: batches
        }
    }

    #[inline(always)]
    pub fn get_mut(&mut self, byte: u8) -> BatchedVecRef<T> {
        unsafe {
            BatchedVecRef {
                tail: self.tails.get_unchecked_mut(byte as usize),
                batches: self.batches.get_unchecked_mut(byte as usize)
            }
        }
    }
}
<commit_msg>Add some documentation to BatchedVec.<commit_after>use std::{cmp, mem, ptr};
use stash::Stash;

pub struct BatchedVecRef<'a, T: 'a> {
    tail: &'a mut Vec<T>,
    batches: &'a mut Vec<Vec<T>>
}

impl<'a, T> BatchedVecRef<'a, T> {
    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        // It is sufficent to only check the tail for emptiness, since any time we flush
        // the tail (in .reserve), we also push some elements.
        self.tail.is_empty()
    }

    #[inline(always)]
    fn reserve(&mut self, stash: &mut Stash<T>) {
        if self.tail.len() == self.tail.capacity() {
            let complete = mem::replace(self.tail, stash.get());
            if !complete.is_empty() {
                self.batches.push(complete);
            }
        }
    }

    #[inline(always)]
    pub fn push(&mut self, element: T, stash: &mut Stash<T>) {
        self.reserve(stash);

        // The reserve call already ensured we have space. For
        // efficiency, use an unchecked push.
        unsafe {
            let len = self.tail.len();
            ptr::write(self.tail.get_unchecked_mut(len), element);
            self.tail.set_len(len + 1);
        }
    }

    pub fn push_vec(&mut self, mut elements: Vec<T>, stash: &mut Stash<T>) {
        // Fill up tail so that we keep the batches fully filled (we don't
        // want to waste memory).
        let available = self.tail.capacity() - self.tail.len();
        let to_move = cmp::min(available, elements.len());
        self.tail.extend(elements.drain(..to_move)); // This ought to compile to just 2 memcpys

        if elements.is_empty() {
            stash.give(elements);
        } else {
            let tail = mem::replace(self.tail, elements);
            if !tail.is_empty() {
                self.batches.push(tail);
            }
        }
    }

    #[inline(always)]
    pub unsafe fn push_all(&mut self, elements: &[T], stash: &mut Stash<T>) {
        self.reserve(stash);

        if !(self.tail.capacity() - self.tail.len() >= elements.len()) {
            panic!("cap: {:?}, len: {:?}, pcl: {:?}", self.tail.capacity(), self.tail.len(), elements.len());
        }

        let len = self.tail.len();
        ptr::copy_nonoverlapping(elements.as_ptr(), self.tail.as_mut_ptr().offset(len as isize), elements.len());
        self.tail.set_len(len + elements.len());
    }

    #[inline(always)]
    pub fn finish_into(&mut self, target: &mut Vec<Vec<T>>, stash: &mut Stash<T>) {
        target.extend(self.batches.drain(..));
        if !self.tail.is_empty() {
            target.push(mem::replace(&mut self.tail, stash.get()));
        }
    }

    #[inline(always)]
    pub fn finish(&mut self, stash: &mut Stash<T>) -> Vec<Vec<T>> {
        if !self.tail.is_empty() {
            self.batches.push(mem::replace(&mut self.tail, stash.get()));
        }
        mem::replace(&mut self.batches, Vec::new())
    }
}

/// An efficiently-appendable collection of `T`s. Unlike `Vec<T>`, which stores all elements contiguously,
/// `BatchedVec<T>` stores elements in a bunch of independent batches, avoiding the need to periodically
/// copy lots of elements.
pub struct BatchedVec<T> {
    tail: Vec<T>,
    batches: Vec<Vec<T>>
}

impl<T> BatchedVec<T> {
    /// Create an empty `BatchedVec<T>`
    pub fn new() -> BatchedVec<T> {
        BatchedVec {
            tail: Vec::new(),
            batches: Vec::new()
        }
    }

    /// Actually access this `BatchedVec<T>`. Because of the `BatchedVecX256` optimization,
    /// we don't want to implement all the methods on `&mut BatchedVec<T>`, since `BatchedVecX256`
    /// has no way of getting those thin references. Instead, we have a custom "fat pointer" type
    /// that all access is done through, generalizing `BatchedVec` and `BatchedVecX256`.
    pub fn ref_mut(&mut self) -> BatchedVecRef<T> {
        BatchedVecRef {
            tail: &mut self.tail,
            batches: &mut self.batches
        }
    }
}

/// An optimized equivalent of `Box<[BatchedVec<T>; 256]>`. Since the tails are the most
/// commonly used parts of `BatchedVec`s, it is advantageous to store them in a separate,
/// parallel array.
pub struct BatchedVecX256<T> {
    tails: Vec<Vec<T>>,
    batches: Vec<Vec<Vec<T>>>
}

impl<T> BatchedVecX256<T> {
    /// Create a new set of 256 empty `BatchedVec`s.
    pub fn new() -> BatchedVecX256<T> {
        let mut tails = Vec::with_capacity(256);
        let mut batches = Vec::with_capacity(256);
        for _byte in 0..256 {
            tails.push(Vec::new());
            batches.push(Vec::new());
        }

        BatchedVecX256 {
            tails: tails,
            batches: batches
        }
    }

    /// Access the `BatchedVec` at the `byte` position.
    #[inline(always)]
    pub fn get_mut(&mut self, byte: u8) -> BatchedVecRef<T> {
        unsafe {
            BatchedVecRef {
                tail: self.tails.get_unchecked_mut(byte as usize),
                batches: self.batches.get_unchecked_mut(byte as usize)
            }
        }
    }
}
<|endoftext|>


<commit_before>#![feature(globs)]
extern crate rdb;
use rdb::*;
use std::io::MemReader;

#[test]
fn test_read_length() {
    assert_eq!(
        (0, false),
        read_length_with_encoding(&mut MemReader::new(vec!(0x0)))
        );

    assert_eq!(
        (16383, false),
        read_length_with_encoding(&mut MemReader::new(vec!(0x7f, 0xff)))
        );

    assert_eq!(
        (4294967295, false),
        read_length_with_encoding(&mut MemReader::new(
                vec!(0x80, 0xff, 0xff, 0xff, 0xff)))
        );

    assert_eq!(
        (0, true),
        read_length_with_encoding(&mut MemReader::new(vec!(0xC0))));
}

#[test]
fn test_read_blob() {
    assert_eq!(
        vec!(0x61, 0x62, 0x63, 0x64),
        read_blob(&mut MemReader::new(vec!(4, 0x61, 0x62, 0x63, 0x64))));
}

#[test]
fn test_verify_version() {
    assert_eq!(
        true,
        verify_version(&mut MemReader::new(vec!(0x30, 0x30, 0x30, 0x33))));

    assert_eq!(
        false,
        verify_version(&mut MemReader::new(vec!(0x30, 0x30, 0x30, 0x3a))));
}

#[test]
fn test_verify_magic() {
    assert_eq!(
        true,
        verify_magic(&mut MemReader::new(vec!(0x52, 0x45, 0x44, 0x49, 0x53))));

    assert_eq!(
        false,
        verify_magic(&mut MemReader::new(vec!(0x51, 0x0, 0x0, 0x0, 0x0))));
}
<commit_msg>Test that read_length works as expected<commit_after>#![feature(globs)]
extern crate rdb;
use rdb::*;
use std::io::MemReader;

#[test]
fn test_read_length() {
    assert_eq!(
        (0, false),
        read_length_with_encoding(&mut MemReader::new(vec!(0x0)))
        );

    assert_eq!(
        (16383, false),
        read_length_with_encoding(&mut MemReader::new(vec!(0x7f, 0xff)))
        );

    assert_eq!(
        (4294967295, false),
        read_length_with_encoding(&mut MemReader::new(
                vec!(0x80, 0xff, 0xff, 0xff, 0xff)))
        );

    assert_eq!(
        (0, true),
        read_length_with_encoding(&mut MemReader::new(vec!(0xC0))));

    assert_eq!(
        16383,
        read_length(&mut MemReader::new(vec!(0x7f, 0xff)))
        );
}

#[test]
fn test_read_blob() {
    assert_eq!(
        vec!(0x61, 0x62, 0x63, 0x64),
        read_blob(&mut MemReader::new(vec!(4, 0x61, 0x62, 0x63, 0x64))));
}

#[test]
fn test_verify_version() {
    assert_eq!(
        true,
        verify_version(&mut MemReader::new(vec!(0x30, 0x30, 0x30, 0x33))));

    assert_eq!(
        false,
        verify_version(&mut MemReader::new(vec!(0x30, 0x30, 0x30, 0x3a))));
}

#[test]
fn test_verify_magic() {
    assert_eq!(
        true,
        verify_magic(&mut MemReader::new(vec!(0x52, 0x45, 0x44, 0x49, 0x53))));

    assert_eq!(
        false,
        verify_magic(&mut MemReader::new(vec!(0x51, 0x0, 0x0, 0x0, 0x0))));
}
<|endoftext|>


<commit_before>extern crate generator;

use generator::*;

#[test]
fn generator_is_done() {
    let mut g = Gn::<()>::new(|| {
        yield_with(());
    });

    g.next();
    assert!(!g.is_done());
    g.next();
    assert!(g.is_done());
}

#[test]
fn test_yield_a() {
    let mut g = Gn::<i32>::new(|| {
        let r: i32 = yield_(10).unwrap();
        r * 2
    });

    // first start the generator
    let i = g.raw_send(None).unwrap();
    assert_eq!(i, 10);
    let i = g.send(3);
    assert_eq!(i, 6);
    assert!(g.is_done());
}

#[test]
fn test_yield_with() {
    let mut g = Gn::new(|| {
        yield_with(10);
        20
    });

    // the para type could be deduced here
    let i = g.send(());
    assert!(i == 10);

    let j = g.next();
    assert!(j.unwrap() == 20);
}

#[test]
#[should_panic]
fn test_yield_with_type_error() {
    let mut g = Gn::<()>::new(|| {
        // yield_with::<i32>(10);
        yield_with(10u32);
        20i32
    });

    g.next();
}

#[test]
#[should_panic]
fn test_get_yield_type_error() {
    let mut g = Gn::<u32>::new(|| {
        get_yield::<i32>();
    });

    g.send(10);
}

#[test]
#[should_panic]
fn test_deep_yield_with_type_error() {
    let mut g = Gn::<()>::new(|| {
        let mut g = Gn::<()>::new(|| {
            yield_with(0);
        });
        g.next();
    });

    g.next();
}

#[test]
fn test_scoped() {
    use std::rc::Rc;
    use std::cell::RefCell;
    let x = Rc::new(RefCell::new(10));

    let x1 = x.clone();
    let mut g = Gn::<()>::new(move || {
        *x1.borrow_mut() = 20;
        yield_with(());
        *x1.borrow_mut() = 5;
    });

    g.next();
    assert!(*x.borrow() == 20);

    g.next();
    assert!(*x.borrow() == 5);

    assert!(g.is_done());
}

#[test]
fn test_scoped_1() {
    let mut x = 10;
    {
        let mut g = Gn::<()>::new(|| {
            x = 5;
        });
        g.next();
    }

    assert!(x == 5);
}

#[test]
fn test_inner_ref() {
    use std::mem;
    let mut g = Gn::<()>::new(|| -> &mut u32 {
        // setup something
        let mut x: u32 = 10;

        // the x memory remains on heap even returned!
        // the life time of x is assosiated with the generator
        // however modify this interal value is really unsafe
        // but this is useful pattern for setup and teardown
        // which can be put in the same place
        {
            // mut borrow block
            let y: &mut u32 = unsafe { mem::transmute(&mut x) };
            yield_with(y);
        }
        // this was modified by the invoker
        assert!(x == 5);
        // teardown happened when the generator get dropped
        unsafe { mem::transmute(&mut x) }
    });

    // use the resource setup from generator
    let a = g.next().unwrap();
    assert!(*a == 10);
    *a = 5;
    // a keeps valid until the generator dropped
}

#[test]
fn test_drop() {
    let mut x = 10;
    {
        Gn::<()>::new(|| {
            x = 1;
            yield_with(());
            x = 5;
        });
    }

    assert!(x == 5);
}

#[test]
fn test_ill_drop() {
    let mut x = 10u32;
    {
        Gn::<u32>::new(|| {
            x = 5;
            // here we got None from drop
            // but should no panic
            x = get_yield().unwrap();
        });
    }

    assert!(x == 5);
}

#[test]
fn test_loop_drop() {
    let mut x = 10u32;
    {
        Gn::<()>::new(|| {
            x = 5;
            loop {
                yield_with(());
            }
        });
        // here the generator drop will cancel the loop
    }

    assert!(x == 5);
}

#[test]
fn test_panic_inside() {
    let mut x = 10;
    {
        Gn::<()>::new(|| {
            x = 5;
            panic!("panic inside!");
        });
    }

    assert!(x == 5);
}

#[test]
#[allow(unreachable_code)]
fn test_cancel() {
    let mut g = Gn::<()>::new(|| {
        let mut i = 0;
        loop {
            yield_with(i);
            i += 1;
        }
        i
    });

    loop {
        let i = g.next().unwrap();
        if i > 10 {
            g.cancel();
            break;
        }
    }

    assert!(g.is_done());
}

#[test]
#[should_panic]
fn test_yield_from_functor_context() {
    // this is not run from generator
    yield_::<(), _>(0);
}

#[test]
fn test_yield_with_from_functor_context() {
    // this is not run from generator
    yield_with(0);
}

#[test]
fn test_yield_from_generator_context() {
    let mut g = Gn::<()>::new(|| {
        let mut g1 = Gn::<()>::new(|| {
            yield_with(5);
            10
        });

        let i = g1.send(());
        yield_with(i);
        0
    });

    let n = g.send(());
    assert!(n == 5);

    let n = g.send(());
    assert!(n == 0);
}

#[test]
fn test_yield_from() {
    let mut g = Gn::<()>::new(|| {
        let g1 = Gn::<()>::new(|| {
            yield_with(5);
            10
        });

        yield_from(g1);
        0
    });

    let n = g.send(());
    assert!(n == 5);
    let n = g.send(());
    assert!(n == 10);
    let n = g.send(());
    assert!(n == 0);
    assert!(g.is_done());
}

#[test]
fn test_yield_from_send() {
    let mut g = Gn::<u32>::new(|| {
        let g1 = Gn::<u32>::new(|| {
            let mut i: u32 = yield_(1u32).unwrap();
            i = yield_(i * 2).unwrap();
            i * 2
        });

        yield_from(g1);

        // here we need a unused return to indicate this function's return type
        0u32
    });

    let n = g.send(3);
    assert!(n == 1);
    let n = g.send(4);
    assert!(n == 6);
    let n = g.send(10);
    assert!(n == 8);
    // the last send has no meaning for the return
    let n = g.send(0);
    assert!(n == 0);
    assert!(g.is_done());
}

#[test]
#[should_panic]
fn test_yield_from_send_type_miss_match() {
    let mut g = Gn::<u32>::new(|| {
        let g1 = Gn::<u32>::new(|| {
            let mut i: u32 = yield_(1u32).unwrap();
            i = yield_(i * 2).unwrap();
            i * 2
        });

        yield_from(g1);
        // here the return type should be 0u32
        0
    });

    let n = g.send(3);
    assert!(n == 1);
    let n = g.send(4);
    assert!(n == 6);
    let n = g.send(10);
    assert!(n == 8);
    // the last send has no meaning for the return
    let n = g.send(0);
    assert!(n == 0);
    assert!(g.is_done());
}/*

// windows has it's own check, this test would make the app abort
#[test]
#[should_panic]
fn test_stack_overflow() {
    // here the stack size is not big enough
    // and will panic when get detected in drop
    let clo = || {
        let big_data = [0usize; 0x400];
        println!("this would overflow the stack, {}", big_data[100]);
    };
    Gn::<()>::new_opt(clo, 10);
} */
<commit_msg>fix yield from test<commit_after>extern crate generator;

use generator::*;

#[test]
fn generator_is_done() {
    let mut g = Gn::<()>::new(|| {
        yield_with(());
    });

    g.next();
    assert!(!g.is_done());
    g.next();
    assert!(g.is_done());
}

#[test]
fn test_yield_a() {
    let mut g = Gn::<i32>::new(|| {
        let r: i32 = yield_(10).unwrap();
        r * 2
    });

    // first start the generator
    let i = g.raw_send(None).unwrap();
    assert_eq!(i, 10);
    let i = g.send(3);
    assert_eq!(i, 6);
    assert!(g.is_done());
}

#[test]
fn test_yield_with() {
    let mut g = Gn::new(|| {
        yield_with(10);
        20
    });

    // the para type could be deduced here
    let i = g.send(());
    assert!(i == 10);

    let j = g.next();
    assert!(j.unwrap() == 20);
}

#[test]
#[should_panic]
fn test_yield_with_type_error() {
    let mut g = Gn::<()>::new(|| {
        // yield_with::<i32>(10);
        yield_with(10u32);
        20i32
    });

    g.next();
}

#[test]
#[should_panic]
fn test_get_yield_type_error() {
    let mut g = Gn::<u32>::new(|| {
        get_yield::<i32>();
    });

    g.send(10);
}

#[test]
#[should_panic]
fn test_deep_yield_with_type_error() {
    let mut g = Gn::<()>::new(|| {
        let mut g = Gn::<()>::new(|| {
            yield_with(0);
        });
        g.next();
    });

    g.next();
}

#[test]
fn test_scoped() {
    use std::rc::Rc;
    use std::cell::RefCell;
    let x = Rc::new(RefCell::new(10));

    let x1 = x.clone();
    let mut g = Gn::<()>::new(move || {
        *x1.borrow_mut() = 20;
        yield_with(());
        *x1.borrow_mut() = 5;
    });

    g.next();
    assert!(*x.borrow() == 20);

    g.next();
    assert!(*x.borrow() == 5);

    assert!(g.is_done());
}

#[test]
fn test_scoped_1() {
    let mut x = 10;
    {
        let mut g = Gn::<()>::new(|| {
            x = 5;
        });
        g.next();
    }

    assert!(x == 5);
}

#[test]
fn test_inner_ref() {
    use std::mem;
    let mut g = Gn::<()>::new(|| -> &mut u32 {
        // setup something
        let mut x: u32 = 10;

        // the x memory remains on heap even returned!
        // the life time of x is assosiated with the generator
        // however modify this interal value is really unsafe
        // but this is useful pattern for setup and teardown
        // which can be put in the same place
        {
            // mut borrow block
            let y: &mut u32 = unsafe { mem::transmute(&mut x) };
            yield_with(y);
        }
        // this was modified by the invoker
        assert!(x == 5);
        // teardown happened when the generator get dropped
        unsafe { mem::transmute(&mut x) }
    });

    // use the resource setup from generator
    let a = g.next().unwrap();
    assert!(*a == 10);
    *a = 5;
    // a keeps valid until the generator dropped
}

#[test]
fn test_drop() {
    let mut x = 10;
    {
        Gn::<()>::new(|| {
            x = 1;
            yield_with(());
            x = 5;
        });
    }

    assert!(x == 5);
}

#[test]
fn test_ill_drop() {
    let mut x = 10u32;
    {
        Gn::<u32>::new(|| {
            x = 5;
            // here we got None from drop
            // but should no panic
            x = get_yield().unwrap();
        });
    }

    assert!(x == 5);
}

#[test]
fn test_loop_drop() {
    let mut x = 10u32;
    {
        Gn::<()>::new(|| {
            x = 5;
            loop {
                yield_with(());
            }
        });
        // here the generator drop will cancel the loop
    }

    assert!(x == 5);
}

#[test]
fn test_panic_inside() {
    let mut x = 10;
    {
        Gn::<()>::new(|| {
            x = 5;
            panic!("panic inside!");
        });
    }

    assert!(x == 5);
}

#[test]
#[allow(unreachable_code)]
fn test_cancel() {
    let mut g = Gn::<()>::new(|| {
        let mut i = 0;
        loop {
            yield_with(i);
            i += 1;
        }
        i
    });

    loop {
        let i = g.next().unwrap();
        if i > 10 {
            g.cancel();
            break;
        }
    }

    assert!(g.is_done());
}

#[test]
#[should_panic]
fn test_yield_from_functor_context() {
    // this is not run from generator
    yield_::<(), _>(0);
}

#[test]
fn test_yield_with_from_functor_context() {
    // this is not run from generator
    yield_with(0);
}

#[test]
fn test_yield_from_generator_context() {
    let mut g = Gn::<()>::new(|| {
        let mut g1 = Gn::<()>::new(|| {
            yield_with(5);
            10
        });

        let i = g1.send(());
        yield_with(i);
        0
    });

    let n = g.send(());
    assert!(n == 5);

    let n = g.send(());
    assert!(n == 0);
}

#[test]
fn test_yield_from() {
    let mut g = Gn::<()>::new(|| {
        let g1 = Gn::<()>::new(|| {
            yield_with(5);
            10
        });

        yield_from(g1);
        0
    });

    let n = g.send(());
    assert!(n == 5);
    let n = g.send(());
    assert!(n == 10);
    let n = g.send(());
    assert!(n == 0);
    assert!(g.is_done());
}

#[test]
fn test_yield_from_send() {
    let mut g = Gn::<u32>::new(|| {
        let g1 = Gn::<u32>::new(|| {
            let mut i: u32 = yield_(1u32).unwrap();
            i = yield_(i * 2).unwrap();
            i * 2
        });

        let i = yield_from(g1).unwrap();
        assert_eq!(i, 10);

        // here we need a unused return to indicate this function's return type
        0u32
    });

    // first start the generator
    let n = g.raw_send(None).unwrap();
    assert!(n == 1);

    let n = g.send(3);
    assert!(n == 6);
    let n = g.send(4);
    assert!(n == 8);
    let n = g.send(10);
    assert!(n == 0);
    assert!(g.is_done());
}

#[test]
#[should_panic]
fn test_yield_from_send_type_miss_match() {
    let mut g = Gn::<u32>::new(|| {
        let g1 = Gn::<u32>::new(|| {
            let mut i: u32 = yield_(1u32).unwrap();
            i = yield_(i * 2).unwrap();
            i * 2
        });

        yield_from(g1);
        // here the return type should be 0u32
        0
    });

    let n = g.send(3);
    assert!(n == 1);
    let n = g.send(4);
    assert!(n == 6);
    let n = g.send(10);
    assert!(n == 8);
    // the last send has no meaning for the return
    let n = g.send(0);
    assert!(n == 0);
    assert!(g.is_done());
}/*

// windows has it's own check, this test would make the app abort
#[test]
#[should_panic]
fn test_stack_overflow() {
    // here the stack size is not big enough
    // and will panic when get detected in drop
    let clo = || {
        let big_data = [0usize; 0x400];
        println!("this would overflow the stack, {}", big_data[100]);
    };
    Gn::<()>::new_opt(clo, 10);
} */
<|endoftext|>


<commit_before>extern crate rig;

mod format_test {

    use std::collections::HashMap;
    use rig::format::{format, Placeholder};

    const W: &'static str = "Fabulous Is Rust";

    #[test]
    fn lower_case() {
        assert_eq!(format(W, "lower".into()), "fabulous is rust");
    }

    #[test]
    fn upper_case() {
        assert_eq!(format(W, "upper".into()), "FABULOUS IS RUST");
    }

    #[test]
    fn capitalize() {
        assert_eq!(format(&W.to_lowercase(), "cap".into()), "Fabulous is rust");
    }

    #[test]
    fn decapitalize() {
        assert_eq!(format(W, "decap".into()), "fabulous Is Rust");
    }

    #[test]
    fn start_case() {
        assert_eq!(format(&W.to_lowercase(), "start".into()), W);
    }

    #[test]
    fn word_only() {
        let includes_ctrls = "_!$what'is-this@charac#ters??";
        assert_eq!(format(includes_ctrls, "word".into()),
                   "_whatisthischaracters");
    }

    #[test]
    fn hyphenate() {
        assert_eq!(format(W, "hyphen".into()), "Fabulous-Is-Rust");
    }

    #[test]
    fn upper_camel() {
        assert_eq!(format(W, "Camel".into()), "FabulousIsRust");
    }

    #[test]
    fn lower_camel() {
        assert_eq!(format(W, "camel".into()), "fabulousIsRust");
    }

    #[test]
    fn normalize() {
        assert_eq!(format(W, "norm".into()), "fabulous-is-rust");
    }

    #[test]
    fn snake_case() {
        assert_eq!(format(W, "snake".into()), "Fabulous_Is_Rust");
    }

    #[test]
    fn directory_path() {
        let p = "path.to.my.directory";
        assert_eq!(format(p, "packaged".into()), "path/to/my/directory");
    }

    #[test]
    fn placeholder_giter8() {
        let ph = Placeholder::parse_g8(r#"project_name;format="upper,hyphen""#).unwrap();
        let mut params: HashMap<String, String> = HashMap::new();
        params.insert("project_name".to_owned(), "A simple proj".to_owned());

        assert_eq!(ph.format_with(&params), "A-SIMPLE-PROJ".to_owned());
    }

    #[test]
    fn placeholder_simple() {
        let ph = Placeholder::parse_simple("project_name;norm").unwrap();
        let mut params: HashMap<String, String> = HashMap::new();
        params.insert("project_name".to_owned(),
                      "A si\nmPLe         p\trOj".to_owned());

        assert_eq!(ph.format_with(&params), "a-si-mple-p-roj".to_owned());
    }

    #[test]
    fn placeholder_dirname() {
        let ph = Placeholder::parse_dirname("twitter_id__word_cap").unwrap();
        let mut params: HashMap<String, String> = HashMap::new();
        params.insert("twitter_id".to_owned(), "bar3s%Ye".to_owned());

        assert_eq!(ph.format_with(&params), "Bar3sye".to_owned());
    }
}

mod template_test {

    use std::collections::HashMap;
    use std::str;
    use rig::format::Style;
    use rig::template::{Params, Template};

    #[test]
    fn compile_inline() {
        let mut params: HashMap<String, String> = HashMap::new();
        params.insert("name".to_owned(), "Rust".to_owned());

        let mut out = Vec::new();

        Template::compile_inline(&mut out, Style::Simple, "Hello, $name$!", &params).unwrap();
        assert_eq!(str::from_utf8(&out).unwrap(), "Hello, Rust!");
    }

    #[test]
    fn format_template() {
        let mut params: HashMap<String, String> = HashMap::new();
        params.insert("DOCUMENT_NAME".to_owned(),
                      "RUST PROGRAMMING LANGUAGE".to_owned());

        let mut out = Vec::new();

        Template::compile_inline(&mut out,
                                 Style::Simple,
                                 "It's a $DOCUMENT_NAME;camel$",
                                 &params)
            .unwrap();
        assert_eq!(str::from_utf8(&out).unwrap(),
                   "It's a rustProgrammingLanguage".to_owned());
    }

    #[test]
    fn escape_character() {
        let mut params: HashMap<String, String> = HashMap::new();
        params.insert("DOCUMENT_NAME".to_owned(),
                      "RUST PROGRAMMING LANGUAGE".to_owned());

        let mut out = Vec::new();

        Template::compile_inline(&mut out,
                                 Style::Simple,
                                 "It's a \\$DOCUMENT_NAME;camel$",
                                 &params)
            .unwrap();
        assert_eq!(str::from_utf8(&out).unwrap(),
                   "It's a \\$DOCUMENT_NAME;camel$".to_owned());
    }

    #[test]
    fn giter8_template() {
        let mut params: HashMap<String, String> = HashMap::new();
        params.insert("name".to_owned(),
                      "awesome distributed interface".to_owned());

        let mut out = Vec::new();

        let mut tpl =
            Template::new_g8(r#"trait $name;format="Camel"$[-A] extends js.Dictionary[A]"#);
        tpl.write(&mut out, &params).unwrap();

        assert_eq!(str::from_utf8(&out).unwrap(),
                   "trait AwesomeDistributedInterface[-A] extends js.Dictionary[A]".to_owned());
    }
}

mod repos_test {

    extern crate tempdir;

    use std::ffi;
    use std::path::Path;
    use self::tempdir::TempDir;

    #[test]
    fn path_sep() {

        let td = TempDir::new("sample-run").unwrap();
        let mut p = td.into_path();
        p.push("such/file");

        assert_eq!(format!("{:?}", p.file_name().unwrap()),
                   r#""file""#.to_string());
    }
}
<commit_msg>tests: removed noop 'repo_test'<commit_after>extern crate rig;

mod format_test {

    use std::collections::HashMap;
    use rig::format::{format, Placeholder};

    const W: &'static str = "Fabulous Is Rust";

    #[test]
    fn lower_case() {
        assert_eq!(format(W, "lower".into()), "fabulous is rust");
    }

    #[test]
    fn upper_case() {
        assert_eq!(format(W, "upper".into()), "FABULOUS IS RUST");
    }

    #[test]
    fn capitalize() {
        assert_eq!(format(&W.to_lowercase(), "cap".into()), "Fabulous is rust");
    }

    #[test]
    fn decapitalize() {
        assert_eq!(format(W, "decap".into()), "fabulous Is Rust");
    }

    #[test]
    fn start_case() {
        assert_eq!(format(&W.to_lowercase(), "start".into()), W);
    }

    #[test]
    fn word_only() {
        let includes_ctrls = "_!$what'is-this@charac#ters??";
        assert_eq!(format(includes_ctrls, "word".into()),
                   "_whatisthischaracters");
    }

    #[test]
    fn hyphenate() {
        assert_eq!(format(W, "hyphen".into()), "Fabulous-Is-Rust");
    }

    #[test]
    fn upper_camel() {
        assert_eq!(format(W, "Camel".into()), "FabulousIsRust");
    }

    #[test]
    fn lower_camel() {
        assert_eq!(format(W, "camel".into()), "fabulousIsRust");
    }

    #[test]
    fn normalize() {
        assert_eq!(format(W, "norm".into()), "fabulous-is-rust");
    }

    #[test]
    fn snake_case() {
        assert_eq!(format(W, "snake".into()), "Fabulous_Is_Rust");
    }

    #[test]
    fn directory_path() {
        let p = "path.to.my.directory";
        assert_eq!(format(p, "packaged".into()), "path/to/my/directory");
    }

    #[test]
    fn placeholder_giter8() {
        let ph = Placeholder::parse_g8(r#"project_name;format="upper,hyphen""#).unwrap();
        let mut params: HashMap<String, String> = HashMap::new();
        params.insert("project_name".to_owned(), "A simple proj".to_owned());

        assert_eq!(ph.format_with(&params), "A-SIMPLE-PROJ".to_owned());
    }

    #[test]
    fn placeholder_simple() {
        let ph = Placeholder::parse_simple("project_name;norm").unwrap();
        let mut params: HashMap<String, String> = HashMap::new();
        params.insert("project_name".to_owned(),
                      "A si\nmPLe         p\trOj".to_owned());

        assert_eq!(ph.format_with(&params), "a-si-mple-p-roj".to_owned());
    }

    #[test]
    fn placeholder_dirname() {
        let ph = Placeholder::parse_dirname("twitter_id__word_cap").unwrap();
        let mut params: HashMap<String, String> = HashMap::new();
        params.insert("twitter_id".to_owned(), "bar3s%Ye".to_owned());

        assert_eq!(ph.format_with(&params), "Bar3sye".to_owned());
    }
}

mod template_test {

    use std::collections::HashMap;
    use std::str;
    use rig::format::Style;
    use rig::template::{Params, Template};

    #[test]
    fn compile_inline() {
        let mut params: HashMap<String, String> = HashMap::new();
        params.insert("name".to_owned(), "Rust".to_owned());

        let mut out = Vec::new();

        Template::compile_inline(&mut out, Style::Simple, "Hello, $name$!", &params).unwrap();
        assert_eq!(str::from_utf8(&out).unwrap(), "Hello, Rust!");
    }

    #[test]
    fn format_template() {
        let mut params: HashMap<String, String> = HashMap::new();
        params.insert("DOCUMENT_NAME".to_owned(),
                      "RUST PROGRAMMING LANGUAGE".to_owned());

        let mut out = Vec::new();

        Template::compile_inline(&mut out,
                                 Style::Simple,
                                 "It's a $DOCUMENT_NAME;camel$",
                                 &params)
            .unwrap();
        assert_eq!(str::from_utf8(&out).unwrap(),
                   "It's a rustProgrammingLanguage".to_owned());
    }

    #[test]
    fn escape_character() {
        let mut params: HashMap<String, String> = HashMap::new();
        params.insert("DOCUMENT_NAME".to_owned(),
                      "RUST PROGRAMMING LANGUAGE".to_owned());

        let mut out = Vec::new();

        Template::compile_inline(&mut out,
                                 Style::Simple,
                                 "It's a \\$DOCUMENT_NAME;camel$",
                                 &params)
            .unwrap();
        assert_eq!(str::from_utf8(&out).unwrap(),
                   "It's a \\$DOCUMENT_NAME;camel$".to_owned());
    }

    #[test]
    fn giter8_template() {
        let mut params: HashMap<String, String> = HashMap::new();
        params.insert("name".to_owned(),
                      "awesome distributed interface".to_owned());

        let mut out = Vec::new();

        let mut tpl =
            Template::new_g8(r#"trait $name;format="Camel"$[-A] extends js.Dictionary[A]"#);
        tpl.write(&mut out, &params).unwrap();

        assert_eq!(str::from_utf8(&out).unwrap(),
                   "trait AwesomeDistributedInterface[-A] extends js.Dictionary[A]".to_owned());
    }
}

mod project_test {

    // TODO:
}
<|endoftext|>


<commit_before>
extern crate readext;

use std::io::{Read,Cursor};
use readext::ReadExt;

#[test]
fn test () {
    let bytes = b"hello";
    let mut input = Cursor::new(bytes);
    let s = input.read_into_string();
    assert_eq!(s, "hello");
}
<commit_msg>test(*): make tests actually work<commit_after>extern crate readext;

use std::io::{Cursor};
use readext::ReadExt;

#[test]
fn can_read_into_string () {
    let bytes = b"hello";
    let mut input = Cursor::new(bytes as &[u8]);
    let s = input.read_into_string().unwrap();
    assert_eq!(s, "hello");
}

#[test]
fn can_read_into_vec () {
    let bytes = b"hello";
    let mut input = Cursor::new(bytes as &[u8]);
    let s = input.read_into_vec().unwrap();
    assert_eq!(s.len(), 5);
}
<|endoftext|>


<commit_before>use std::path::PathBuf;
use std::process::Command;
use std::env;
use std::io::stderr;
use std::io::Write;

pub use clap::App;

use clap::{Arg, ArgMatches};
use log;
use log::LogLevelFilter;

use configuration::Configuration;
use error::RuntimeError;
use error::RuntimeErrorKind;
use error::MapErrInto;
use logger::ImagLogger;

use libimagstore::store::Store;

#[derive(Debug)]
pub struct Runtime<'a> {
    rtp: PathBuf,
    configuration: Option<Configuration>,
    cli_matches: ArgMatches<'a>,
    store: Store,
}

impl<'a> Runtime<'a> {

    /**
     * Gets the CLI spec for the program and retreives the config file path (or uses the default on
     * in $HOME/.imag/config, $XDG_CONFIG_DIR/imag/config or from env("$IMAG_CONFIG")
     * and builds the Runtime object with it.
     *
     * The cli_spec object should be initially build with the ::get_default_cli_builder() function.
     *
     */
    pub fn new(cli_spec: App<'a, 'a>) -> Result<Runtime<'a>, RuntimeError> {
        use std::env;

        use libimagstore::hook::position::HookPosition as HP;
        use libimagstore::hook::Hook;
        use libimagstore::error::StoreErrorKind;
        use libimagstorestdhook::debug::DebugHook;
        use libimagerror::trace::trace_error;
        use libimagerror::trace::trace_error_dbg;
        use libimagerror::into::IntoError;

        use configuration::error::ConfigErrorKind;

        let matches = cli_spec.get_matches();

        let is_debugging = matches.is_present("debugging");
        let is_verbose   = matches.is_present("verbosity");

        Runtime::init_logger(is_debugging, is_verbose);

        let rtp : PathBuf = matches.value_of("runtimepath")
            .map_or_else(|| {
                env::var("HOME")
                    .map(PathBuf::from)
                    .map(|mut p| { p.push(".imag"); p})
                    .unwrap_or_else(|_| {
                        panic!("You seem to be $HOME-less. Please get a $HOME before using this software. We are sorry for you and hope you have some accommodation anyways.");
                    })
            }, PathBuf::from);
        let storepath = matches.value_of("storepath")
                                .map_or_else(|| {
                                    let mut spath = rtp.clone();
                                    spath.push("store");
                                    spath
                                }, PathBuf::from);

        let configpath = matches.value_of("config")
                                .map_or_else(|| {
                                    let mut spath = rtp.clone();
                                    spath.push("store");
                                    spath
                                }, PathBuf::from);

        let cfg = match Configuration::new(&configpath) {
            Err(e) => if e.err_type() != ConfigErrorKind::NoConfigFileFound {
                return Err(RuntimeErrorKind::Instantiate.into_error_with_cause(Box::new(e)));
            } else {
                warn!("No config file found.");
                warn!("Continuing without configuration file");
                None
            },

            Ok(cfg) => Some(cfg),
        };

        let store_config = match cfg {
            Some(ref c) => c.store_config().cloned(),
            None        => None,
        };

        if is_debugging {
            write!(stderr(), "Config: {:?}\n", cfg).ok();
            write!(stderr(), "Store-config: {:?}\n", store_config).ok();
        }

        Store::new(storepath, store_config).map(|mut store| {
            // If we are debugging, generate hooks for all positions
            if is_debugging {
                let hooks : Vec<(Box<Hook>, &str, HP)> = vec![
                    (Box::new(DebugHook::new(HP::PreCreate))          , "debug", HP::PreCreate),
                    (Box::new(DebugHook::new(HP::PostCreate))         , "debug", HP::PostCreate),
                    (Box::new(DebugHook::new(HP::PreRetrieve))        , "debug", HP::PreRetrieve),
                    (Box::new(DebugHook::new(HP::PostRetrieve))       , "debug", HP::PostRetrieve),
                    (Box::new(DebugHook::new(HP::PreUpdate))          , "debug", HP::PreUpdate),
                    (Box::new(DebugHook::new(HP::PostUpdate))         , "debug", HP::PostUpdate),
                    (Box::new(DebugHook::new(HP::PreDelete))          , "debug", HP::PreDelete),
                    (Box::new(DebugHook::new(HP::PostDelete))         , "debug", HP::PostDelete),
                ];

                // If hook registration fails, trace the error and warn, but continue.
                for (hook, aspectname, position) in hooks {
                    if let Err(e) = store.register_hook(position, &String::from(aspectname), hook) {
                        if e.err_type() == StoreErrorKind::HookRegisterError {
                            trace_error_dbg(&e);
                            warn!("Registering debug hook with store failed");
                        } else {
                            trace_error(&e);
                        };
                    }
                }
            }

            Runtime {
                cli_matches: matches,
                configuration: cfg,
                rtp: rtp,
                store: store,
            }
        })
        .map_err_into(RuntimeErrorKind::Instantiate)
    }

    /**
     * Get a commandline-interface builder object from `clap`
     *
     * This commandline interface builder object already contains some predefined interface flags:
     *   * -v | --verbose for verbosity
     *   * --debug for debugging
     *   * -c <file> | --config <file> for alternative configuration file
     *   * -r <path> | --rtp <path> for alternative runtimepath
     *   * --store <path> for alternative store path
     * Each has the appropriate help text included.
     *
     * The `appname` shall be "imag-<command>".
     */
    pub fn get_default_cli_builder(appname: &'a str,
                                   version: &'a str,
                                   about: &'a str)
        -> App<'a, 'a>
    {
        App::new(appname)
            .version(version)
            .author("Matthias Beyer <mail@beyermatthias.de>")
            .about(about)
            .arg(Arg::with_name("verbosity")
                .short("v")
                .long("verbose")
                .help("Enables verbosity")
                .required(false)
                .takes_value(false))

            .arg(Arg::with_name("debugging")
                .long("debug")
                .help("Enables debugging output")
                .required(false)
                .takes_value(false))

            .arg(Arg::with_name("config")
                .long("config")
                .help("Path to alternative config file")
                .required(false)
                .takes_value(true))

            .arg(Arg::with_name("runtimepath")
                .long("rtp")
                .help("Alternative runtimepath")
                .required(false)
                .takes_value(true))

            .arg(Arg::with_name("storepath")
                .long("store")
                .help("Alternative storepath. Must be specified as full path, can be outside of the RTP")
                .required(false)
                .takes_value(true))

            .arg(Arg::with_name("editor")
                .long("editor")
                .help("Set editor")
                .required(false)
                .takes_value(true))
    }

    /**
     * Initialize the internal logger
     */
    fn init_logger(is_debugging: bool, is_verbose: bool) {
        use std::env::var as env_var;
        use env_logger;

        if env_var("IMAG_LOG_ENV").is_ok() {
            env_logger::init().unwrap();
        } else {
            let lvl = if is_debugging {
                LogLevelFilter::Debug
            } else if is_verbose {
                LogLevelFilter::Info
            } else {
                LogLevelFilter::Error
            };

            log::set_logger(|max_log_lvl| {
                max_log_lvl.set(lvl);
                debug!("Init logger with {}", lvl);
                Box::new(ImagLogger::new(lvl.to_log_level().unwrap()))
            })
            .map_err(|_| {
                panic!("Could not setup logger");
            })
            .ok();
        }
    }

    /**
     * Get the verbosity flag value
     */
    pub fn is_verbose(&self) -> bool {
        self.cli_matches.is_present("verbosity")
    }

    /**
     * Get the debugging flag value
     */
    pub fn is_debugging(&self) -> bool {
        self.cli_matches.is_present("debugging")
    }

    /**
     * Get the runtimepath
     */
    pub fn rtp(&self) -> &PathBuf {
        &self.rtp
    }

    /**
     * Get the commandline interface matches
     */
    pub fn cli(&self) -> &ArgMatches {
        &self.cli_matches
    }

    /**
     * Get the configuration object
     */
    pub fn config(&self) -> Option<&Configuration> {
        self.configuration.as_ref()
    }

    /**
     * Get the store object
     */
    pub fn store(&self) -> &Store {
        &self.store
    }

    pub fn editor(&self) -> Option<Command> {
        self.cli()
            .value_of("editor")
            .map(String::from)
            .or({
                match self.configuration {
                    Some(ref c) => c.editor().cloned(),
                    _ => None,
                }
            })
            .or(env::var("EDITOR").ok())
            .map(Command::new)
    }
}

<commit_msg>Change default log level to Warn<commit_after>use std::path::PathBuf;
use std::process::Command;
use std::env;
use std::io::stderr;
use std::io::Write;

pub use clap::App;

use clap::{Arg, ArgMatches};
use log;
use log::LogLevelFilter;

use configuration::Configuration;
use error::RuntimeError;
use error::RuntimeErrorKind;
use error::MapErrInto;
use logger::ImagLogger;

use libimagstore::store::Store;

#[derive(Debug)]
pub struct Runtime<'a> {
    rtp: PathBuf,
    configuration: Option<Configuration>,
    cli_matches: ArgMatches<'a>,
    store: Store,
}

impl<'a> Runtime<'a> {

    /**
     * Gets the CLI spec for the program and retreives the config file path (or uses the default on
     * in $HOME/.imag/config, $XDG_CONFIG_DIR/imag/config or from env("$IMAG_CONFIG")
     * and builds the Runtime object with it.
     *
     * The cli_spec object should be initially build with the ::get_default_cli_builder() function.
     *
     */
    pub fn new(cli_spec: App<'a, 'a>) -> Result<Runtime<'a>, RuntimeError> {
        use std::env;

        use libimagstore::hook::position::HookPosition as HP;
        use libimagstore::hook::Hook;
        use libimagstore::error::StoreErrorKind;
        use libimagstorestdhook::debug::DebugHook;
        use libimagerror::trace::trace_error;
        use libimagerror::trace::trace_error_dbg;
        use libimagerror::into::IntoError;

        use configuration::error::ConfigErrorKind;

        let matches = cli_spec.get_matches();

        let is_debugging = matches.is_present("debugging");
        let is_verbose   = matches.is_present("verbosity");

        Runtime::init_logger(is_debugging, is_verbose);

        let rtp : PathBuf = matches.value_of("runtimepath")
            .map_or_else(|| {
                env::var("HOME")
                    .map(PathBuf::from)
                    .map(|mut p| { p.push(".imag"); p})
                    .unwrap_or_else(|_| {
                        panic!("You seem to be $HOME-less. Please get a $HOME before using this software. We are sorry for you and hope you have some accommodation anyways.");
                    })
            }, PathBuf::from);
        let storepath = matches.value_of("storepath")
                                .map_or_else(|| {
                                    let mut spath = rtp.clone();
                                    spath.push("store");
                                    spath
                                }, PathBuf::from);

        let configpath = matches.value_of("config")
                                .map_or_else(|| {
                                    let mut spath = rtp.clone();
                                    spath.push("store");
                                    spath
                                }, PathBuf::from);

        let cfg = match Configuration::new(&configpath) {
            Err(e) => if e.err_type() != ConfigErrorKind::NoConfigFileFound {
                return Err(RuntimeErrorKind::Instantiate.into_error_with_cause(Box::new(e)));
            } else {
                warn!("No config file found.");
                warn!("Continuing without configuration file");
                None
            },

            Ok(cfg) => Some(cfg),
        };

        let store_config = match cfg {
            Some(ref c) => c.store_config().cloned(),
            None        => None,
        };

        if is_debugging {
            write!(stderr(), "Config: {:?}\n", cfg).ok();
            write!(stderr(), "Store-config: {:?}\n", store_config).ok();
        }

        Store::new(storepath, store_config).map(|mut store| {
            // If we are debugging, generate hooks for all positions
            if is_debugging {
                let hooks : Vec<(Box<Hook>, &str, HP)> = vec![
                    (Box::new(DebugHook::new(HP::PreCreate))          , "debug", HP::PreCreate),
                    (Box::new(DebugHook::new(HP::PostCreate))         , "debug", HP::PostCreate),
                    (Box::new(DebugHook::new(HP::PreRetrieve))        , "debug", HP::PreRetrieve),
                    (Box::new(DebugHook::new(HP::PostRetrieve))       , "debug", HP::PostRetrieve),
                    (Box::new(DebugHook::new(HP::PreUpdate))          , "debug", HP::PreUpdate),
                    (Box::new(DebugHook::new(HP::PostUpdate))         , "debug", HP::PostUpdate),
                    (Box::new(DebugHook::new(HP::PreDelete))          , "debug", HP::PreDelete),
                    (Box::new(DebugHook::new(HP::PostDelete))         , "debug", HP::PostDelete),
                ];

                // If hook registration fails, trace the error and warn, but continue.
                for (hook, aspectname, position) in hooks {
                    if let Err(e) = store.register_hook(position, &String::from(aspectname), hook) {
                        if e.err_type() == StoreErrorKind::HookRegisterError {
                            trace_error_dbg(&e);
                            warn!("Registering debug hook with store failed");
                        } else {
                            trace_error(&e);
                        };
                    }
                }
            }

            Runtime {
                cli_matches: matches,
                configuration: cfg,
                rtp: rtp,
                store: store,
            }
        })
        .map_err_into(RuntimeErrorKind::Instantiate)
    }

    /**
     * Get a commandline-interface builder object from `clap`
     *
     * This commandline interface builder object already contains some predefined interface flags:
     *   * -v | --verbose for verbosity
     *   * --debug for debugging
     *   * -c <file> | --config <file> for alternative configuration file
     *   * -r <path> | --rtp <path> for alternative runtimepath
     *   * --store <path> for alternative store path
     * Each has the appropriate help text included.
     *
     * The `appname` shall be "imag-<command>".
     */
    pub fn get_default_cli_builder(appname: &'a str,
                                   version: &'a str,
                                   about: &'a str)
        -> App<'a, 'a>
    {
        App::new(appname)
            .version(version)
            .author("Matthias Beyer <mail@beyermatthias.de>")
            .about(about)
            .arg(Arg::with_name("verbosity")
                .short("v")
                .long("verbose")
                .help("Enables verbosity")
                .required(false)
                .takes_value(false))

            .arg(Arg::with_name("debugging")
                .long("debug")
                .help("Enables debugging output")
                .required(false)
                .takes_value(false))

            .arg(Arg::with_name("config")
                .long("config")
                .help("Path to alternative config file")
                .required(false)
                .takes_value(true))

            .arg(Arg::with_name("runtimepath")
                .long("rtp")
                .help("Alternative runtimepath")
                .required(false)
                .takes_value(true))

            .arg(Arg::with_name("storepath")
                .long("store")
                .help("Alternative storepath. Must be specified as full path, can be outside of the RTP")
                .required(false)
                .takes_value(true))

            .arg(Arg::with_name("editor")
                .long("editor")
                .help("Set editor")
                .required(false)
                .takes_value(true))
    }

    /**
     * Initialize the internal logger
     */
    fn init_logger(is_debugging: bool, is_verbose: bool) {
        use std::env::var as env_var;
        use env_logger;

        if env_var("IMAG_LOG_ENV").is_ok() {
            env_logger::init().unwrap();
        } else {
            let lvl = if is_debugging {
                LogLevelFilter::Debug
            } else if is_verbose {
                LogLevelFilter::Info
            } else {
                LogLevelFilter::Warn
            };

            log::set_logger(|max_log_lvl| {
                max_log_lvl.set(lvl);
                debug!("Init logger with {}", lvl);
                Box::new(ImagLogger::new(lvl.to_log_level().unwrap()))
            })
            .map_err(|_| {
                panic!("Could not setup logger");
            })
            .ok();
        }
    }

    /**
     * Get the verbosity flag value
     */
    pub fn is_verbose(&self) -> bool {
        self.cli_matches.is_present("verbosity")
    }

    /**
     * Get the debugging flag value
     */
    pub fn is_debugging(&self) -> bool {
        self.cli_matches.is_present("debugging")
    }

    /**
     * Get the runtimepath
     */
    pub fn rtp(&self) -> &PathBuf {
        &self.rtp
    }

    /**
     * Get the commandline interface matches
     */
    pub fn cli(&self) -> &ArgMatches {
        &self.cli_matches
    }

    /**
     * Get the configuration object
     */
    pub fn config(&self) -> Option<&Configuration> {
        self.configuration.as_ref()
    }

    /**
     * Get the store object
     */
    pub fn store(&self) -> &Store {
        &self.store
    }

    pub fn editor(&self) -> Option<Command> {
        self.cli()
            .value_of("editor")
            .map(String::from)
            .or({
                match self.configuration {
                    Some(ref c) => c.editor().cloned(),
                    _ => None,
                }
            })
            .or(env::var("EDITOR").ok())
            .map(Command::new)
    }
}

<|endoftext|>