<commit_before><commit_msg>libproc_macro - Quick tool to dump input/output tokens.<commit_after>
struct Reader<R> {
    inner: R,
}
impl<R: ::std::io::Read> Reader<R> {
    fn getb(&mut self) -> Option<u8> {
        let mut b = [0];
        match self.inner.read(&mut b)
        {
        Ok(1) => Some(b[0]),
        Ok(0) => None,
        Ok(_) => panic!("Bad byte count"),
        Err(e) => panic!("Error reading from stream - {}", e),
        }
    }
    fn get_u128v(&mut self) -> u128 {
        let mut ofs = 0;
        let mut raw_rv = 0u128;
        loop
        {
            let b = self.getb().unwrap();
            raw_rv |= ((b & 0x7F) as u128) << ofs;
            if b < 128 {
                break;
            }
            assert!(ofs < 18*7);  // at most 18 bytes needed for a i128
            ofs += 7;
        }
        raw_rv
    }
    fn get_i128v(&mut self) -> i128 {
        let raw_rv = self.get_u128v();
        // Zig-zag encoding (0 = 0, 1 = -1, 2 = 1, ...)
        if raw_rv & 1 != 0 {
            -( (raw_rv >> 1) as i128 + 1 )
        }
        else {
            (raw_rv >> 1) as i128
        }
    }
    fn get_byte_vec(&mut self) -> Vec<u8> {
        let size = self.get_u128v();
        assert!(size < (1<<30));
        let size = size as usize;
        let mut buf = vec![0u8; size];
        match self.inner.read_exact(&mut buf)
        {
        Ok(_) => {},
        Err(e) => panic!("Error reading from stdin get_byte_vec({}) - {}", size, e),
        }

        buf
    }
    fn get_string(&mut self) -> String {
        let raw = self.get_byte_vec();
        String::from_utf8(raw).expect("Invalid UTF-8 passed from compiler")
    }
    fn get_f64(&mut self) -> f64 {
        let mut buf = [0u8; 8];
        match self.inner.read_exact(&mut buf)
        {
        Ok(_) => {},
        Err(e) => panic!("Error reading from stdin - {}", e),
        }
        unsafe {
            ::std::mem::transmute(buf)
        }
    }
}

/// Receive a token stream from the compiler
pub fn dump_token_stream<R: ::std::io::Read>(reader: R)
{
    let mut s = Reader { inner: reader };
    loop
    {
        let hdr_b = match s.getb()
            {
            Some(b) => b,
            None => break,
            };
        // TODO: leading span
        match hdr_b
        {
        0 => {
            let sym = s.get_string();
            if sym == "" {
                println!("EOF")
            }
            else {
                println!("SYM {}", sym);
            }
            },
        1 => println!("IDENT {}", s.get_string()),
        2 => println!("LIFETIME {}", s.get_string()),
        3 => println!("STRING {:?}", s.get_string()),
        4 => println!("BYTESTRING {:x?}", s.get_byte_vec()),
        5 => println!("CHAR {:?}", ::std::char::from_u32(s.get_i128v() as u32).expect("char lit")),
        6 => println!("UNSIGNED {val:?} ty={ty}", ty=s.getb().expect("getb int ty"), val=s.get_u128v()),
        7 => println!("SIGNED {val:?} ty={ty}", ty=s.getb().expect("getb int ty"), val=s.get_i128v()),
        8 => println!("FLOAT {val:?} ty={ty}", ty=s.getb().expect("getb float ty"), val=s.get_f64()),
        _ => panic!("Unknown tag byte: {:#x}", hdr_b),
        }
    }
}

fn main()
{
    {
        assert_eq!( Reader { inner: ::std::io::stdin().lock() }.getb(), Some(0) );
    }
    dump_token_stream(::std::io::stdin().lock());
}
<|endoftext|>


<commit_before><commit_msg>Day 6 part 1 and 2<commit_after>// advent6.rs
// repetition codes

use std::io;
use std::io::BufRead;
use std::collections::HashMap;

fn main() {
    let stdin = io::stdin();

    let inputs: Vec<String> =
        stdin.lock().lines().map(|l| l.expect("Failed to read line")).collect();
    let messages: Vec<&str> = inputs.iter().map(|x| x.as_str()).collect();

    let corrected = correct_errors(&messages, false);
    println!("Part 1 corrected message: {}", corrected);

    let corrected2 = correct_errors(&messages, true);
    println!("Part 2 corrected message: {}", corrected2);
}

fn correct_errors(messages: &[&str], reverse_sort: bool) -> String {
    if messages.len() == 0 {
        return "".to_string();
    }

    let message_len = messages[0].len();
    let mut histograms = Vec::with_capacity(message_len);
    for _ in 0..message_len {
        histograms.push(HashMap::new());
    }

    for message in messages {
        for (c, mut histogram) in message.chars().zip(histograms.iter_mut()) {
            *histogram.entry(c).or_insert(0) += 1;
        }
    }

    let mut corrected = String::new();
    for histogram in histograms {
        let mut char_counts: Vec<(char, usize)> = histogram.iter().map(|(k, v)| (*k, *v)).collect();
        if reverse_sort {
            // part 2
            char_counts.sort_by(|a, b| a.1.cmp(&b.1));
        } else {
            // part 1
            char_counts.sort_by(|a, b| b.1.cmp(&a.1));
        }

        corrected.push(char_counts[0].0);
    }

    corrected
}

// ///////
// Tests

#[test]
fn test_correct_errors() {
    let v = vec!["eedadn", "drvtee", "eandsr", "raavrd", "atevrs", "tsrnev", "sdttsa", "rasrtv",
                 "nssdts", "ntnada", "svetve", "tesnvt", "vntsnd", "vrdear", "dvrsen", "enarar"];

    assert_eq!("easter", correct_errors(&v, false));
    assert_eq!("advent", correct_errors(&v, true));
}
<|endoftext|>


<commit_before><commit_msg>Attempt at BLKDISCARD ioctl.<commit_after><|endoftext|>


<commit_before><commit_msg>Heap implementation in rust. works but not optimised<commit_after>trait Heap {
    fn build_max_heap(&mut self);
    fn add_element(&mut self, int);
    fn max_heapify(&mut self, index: uint);
    fn heapsort(&mut self) -> ~[int];
}

impl Heap for ~[int] {
    fn build_max_heap(&mut self) {
        let mut index = (self.len() / 2) + 1;
        while index > 0 {
            index = index - 1;
            self.max_heapify(index);
        }
    }
    fn add_element(&mut self, elem: int) {
        self.push(elem);
    }
    fn max_heapify(&mut self, index: uint) {
        let left = (index * 2) + 1;
        let right = (index * 2) + 2;
        let mut largest = index;
        if (left < self.len() && (self[left] > self[largest])) {
            largest = left;
        }
        if (right < self.len() && (self[right] > self[largest])) {
            largest = right;
        }
        if (largest != index) {
            self.swap(index, largest);
            self.max_heapify(largest);
        }
    }
    fn heapsort(&mut self) -> ~[int] {
        self.build_max_heap();
        let mut result = ~[];
        while self.len() > 0 {
            result.push(self.remove(0));
            self.build_max_heap();
        }
        result
    }
}

fn main() {
    let mut a = ~[5,2,6,3,7];
    println(a.to_str());
    let b = a.heapsort();
    println(b.to_str());
}
<|endoftext|>


<commit_before><commit_msg>starting on guibuilder<commit_after>use controls::{Button, Control, Label, Root, Sizer, Slider};
use failure::err_msg;
use failure::Error as FError;
use serde_json::Value;

pub struct gui<'a> {
  pub title: String,
  pub root_control: Option<Box<dyn Control>>,
  sizerstack: Vec<&'a Sizer>,
}

impl gui<'_> {
  fn add_button(&mut self, name: String, label: Option<String>) -> Result<&gui, FError> {
let wat = [1,2,3];
    let newbutton = Box::new(Button {
      control_id: Vec::new(),
      name: String::from(name),
      label: label,
      pressed: false,
    });
    match self.root_control {
      None => {
        self.root_control = Some(newbutton);
        Ok(self)
      }

      Some(_) => match self.sizerstack.last_mut() {
        None => Err(err_msg("no active sizer, can't add Button element!")),
        Some(mut s) => {
          // add new elt to sizer.
          // *s.control_id = wat[..];
          // s.controls.push(newbutton);
          Ok(self)
        }
      },
    }
  }
}

/*
fn deserialize_control(id: Vec<i32>, data: &Value) -> Result<Box<Control>, FError> {
  // what's the type?
  let obj = data
    .as_object()
    .ok_or(err_msg("control is not a valid json object"))?;
  let objtype = get_string(obj, "type")?;

  match objtype {
    "button" => {
      let name = get_string(obj, "name")?;
      let label = match obj.get("label") {
        Some(x) => {
          let s = x.as_string().ok_or(err_msg("'label' is not a string!"))?;
          Some(String::from(s))
        }
        None => None,
      };
      Ok(Box::new(Button {
        control_id: id.clone(),
        name: String::from(name),
        label: label,
        pressed: false,
      }))
    }
    "slider" => {
      let name = get_string(obj, "name")?;
      let label = match obj.get("label") {
        Some(x) => {
          let s = x.as_string().ok_or(err_msg("'label' is not a string!"))?;
          Some(String::from(s))
        }
        None => None,
      };
      Ok(Box::new(Slider {
        control_id: id.clone(),
        name: String::from(name),
        label: label,
        pressed: false,
        location: 0.5,
      }))
    }
    "label" => {
      let name = get_string(obj, "name")?;
      let label = get_string(obj, "label")?;
      Ok(Box::new(Label {
        control_id: id.clone(),
        name: String::from(name),
        label: label.to_string(),
      }))
    }
    "sizer" => {
      let controls = obj
        .get("controls")
        .ok_or(err_msg("'controls' not found"))?
        .as_array()
        .ok_or(err_msg("'controls' is not an array"))?;

      let mut controlv = Vec::new();

      // loop through array, makin controls.
      for (i, v) in controls.into_iter().enumerate() {
        let mut id = id.clone();
        id.push(i as i32);
        let c = try!(deserialize_control(id, v));
        controlv.push(c);
      }

      Ok(Box::new(Sizer {
        control_id: id.clone(),
        controls: controlv,
      }))
    }
    _ => Err(err_msg(format!("objtype '{}' not supported!", objtype))),
  }
}*/
<|endoftext|>


<commit_before><commit_msg>first rust program<commit_after>#[derive(Copy,Clone)]
struct VertexID {
	id: usize,
	is_nil: bool,
}

impl std::fmt::Debug for VertexID {
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
		if self.is_nil {
			write!(f, "nil")
		} else {
			write!(f, "{}", self.id)
		}
	}
}

impl VertexID {
	fn new(id: usize) -> VertexID {
		VertexID{id: id, is_nil: false}
	}

	fn nil() -> VertexID {
		VertexID{id: 0, is_nil: true}
	}
}

type EdgeID = (VertexID, usize);

struct Graph<T> {
	pub vertices: Vec<T>,
	pub edges: Vec<Vec<(VertexID, f64)>>,
}

impl <T> Graph<T> {
	fn new() -> Graph<T> {
		Graph{
			vertices: Vec::new(),
			edges: Vec::new(),
		}
	}

	fn add_vertex(&mut self, v: T) -> VertexID {
		let vid = self.vertices.len();
		self.vertices.push(v);
		self.edges.push(Vec::new());
		VertexID::new(vid)
	}

	fn add_edge(&mut self, vid1: VertexID, vid2: VertexID, weight: f64) -> EdgeID {
		let eid = (vid1, self.edges.len());
		self.edges[vid1.id].push((vid2, weight));
		eid
	}
}

fn dijkstra<T>(graph: &Graph<T>, source: VertexID) -> Vec<(f64, VertexID)> {
	let mut dist_prev = Vec::with_capacity(graph.vertices.len());
	let mut queue = Vec::with_capacity(graph.vertices.len());
	for i in 0..graph.vertices.len() {
		let mut p = (::std::f64::INFINITY, VertexID::nil());
		if i == source.id {
			p = (0.0, VertexID::nil());
		}
		dist_prev.push(p);
		queue.push(VertexID::new(i));
	}

	while !queue.is_empty() {
		let mut minidx = 0;
		let mut mindist = dist_prev[queue[0].id].0;
		for i in 1..queue.len() {
			let vid = queue[i];
			if dist_prev[vid.id].0 < mindist {
				minidx = i;
				mindist = dist_prev[vid.id].0;
			}
		}
		let u = queue.swap_remove(minidx);
		for e in graph.edges[u.id].iter() {
			let alt = dist_prev[u.id].0 + e.1;
			if alt < dist_prev[e.0.id].0 {
				dist_prev[e.0.id] = (alt, u);
			}
		}
	}
	dist_prev
}

fn main() {
	let mut graph = Graph::new();
	let vid1 = graph.add_vertex(1);
	let vid2 = graph.add_vertex(1010);
	graph.add_edge(vid2, vid1, 1.4);
	let dist_prev = dijkstra(&graph, vid1);
	println!("{:?}", dist_prev);
	let dist_prev2 = dijkstra(&graph, vid2);
	println!("{:?}", dist_prev2);
}<|endoftext|>


<commit_before><commit_msg>format change<commit_after><|endoftext|>


<commit_before><commit_msg>Actually allow boxed `Changeset`<commit_after><|endoftext|>


<commit_before><commit_msg>08 - nesting and labels<commit_after>fn main() {
    'outer: loop {
        println!("Entered the outer loop");

        'inner: loop {
            println!("Entered the inner loop");

            // This would break only the inner loop
            //break;

            // This breaks the outer loop
            break 'outer;
        }

        println!("This point will never be reached");
    }

    println!("Exited the outer loop");
}
<|endoftext|>


<commit_before><commit_msg>Fix repeated warning with two calls to to_package_id_specs<commit_after><|endoftext|>


<commit_before><commit_msg>Ensure key ID version contains only valid characters.<commit_after><|endoftext|>


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

// Test case from #39963.

#![feature(nll)]

#[derive(Clone)]
struct Foo(Option<Box<Foo>>, Option<Box<Foo>>);

fn test(f: &mut Foo) {
  match *f {
    Foo(Some(ref mut left), Some(ref mut right)) => match **left {
      Foo(Some(ref mut left), Some(ref mut right)) => panic!(),
      _ => panic!(),
    },
    _ => panic!(),
  }
}

fn main() {
}
<|endoftext|>


<commit_before>#![allow(missing_docs)]
use device as d;
use device::{Device, Resources, Capabilities, SubmitInfo};
use device::draw::{CommandBuffer, Access, Gamma, Target};
use device::shade;
use super::{tex};
use draw_state::target::{Rect, Mirror, Mask, ClearData, Layer, Level};

pub struct DummyDevice {
    capabilities: Capabilities
}
pub struct DummyCommandBuffer {
    buf: Vec<String>
}

#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub enum DummyResources{}

pub type Buffer         = u32;
pub type ArrayBuffer    = u32;
pub type Shader         = u32;
pub type Program        = u32;
pub type FrameBuffer    = u32;
pub type Surface        = u32;
pub type Sampler        = u32;
pub type Texture        = u32;

impl Resources for DummyResources {
    type Buffer         = Buffer;
    type ArrayBuffer    = ArrayBuffer;
    type Shader         = Shader;
    type Program        = Program;
    type FrameBuffer    = FrameBuffer;
    type Surface        = Surface;
    type Texture        = Texture;
    type Sampler        = Sampler;
}

impl CommandBuffer<DummyResources> for DummyCommandBuffer {
    fn new() -> DummyCommandBuffer {
        DummyCommandBuffer {
            buf: Vec::new(),
        }
    }

    fn clear(&mut self) {
        self.buf.clear();
    }

    fn bind_program(&mut self, prog: Program) {
        self.buf.push("bind_program".to_string());
    }

    fn bind_array_buffer(&mut self, vao: ArrayBuffer) {
        self.buf.push("bind_array_buffer".to_string());
    }

    fn bind_attribute(&mut self, slot: d::AttributeSlot, buf: Buffer,
                      format: d::attrib::Format) {
        self.buf.push("bind_attribute".to_string());
    }

    fn bind_index(&mut self, buf: Buffer) {
        self.buf.push("bind_index".to_string());
    }

    fn bind_frame_buffer(&mut self, access: Access, fbo: FrameBuffer,
                         gamma: Gamma) {
        self.buf.push("bind_frame_buffer".to_string());
    }

    fn unbind_target(&mut self, access: Access, tar: Target) {
        self.buf.push("unbind_target".to_string());
    }

    fn bind_target_surface(&mut self, access: Access, tar: Target,
                           suf: Surface) {
        self.buf.push("bind_target_surface".to_string());
    }

    fn bind_target_texture(&mut self, access: Access, tar: Target,
                           tex: Texture, level: Level, layer: Option<Layer>) {
        self.buf.push("bind_target_texture".to_string());
    }

    fn bind_uniform_block(&mut self, prog: Program, slot: d::UniformBufferSlot,
                          index: d::UniformBlockIndex, buf: Buffer) {
        self.buf.push("bind_uniform_block".to_string());
    }

    fn bind_uniform(&mut self, loc: d::shade::Location,
                    value: d::shade::UniformValue) {
        self.buf.push("bind_uniform".to_string());
    }
    fn bind_texture(&mut self, slot: d::TextureSlot, kind: d::tex::Kind,
                    tex: Texture,
                    sampler: Option<(Sampler, d::tex::SamplerInfo)>) {
        self.buf.push("set_draw_color_buffers".to_string());
    }

    fn set_draw_color_buffers(&mut self, num: usize) {
        self.buf.push("set_draw_color_buffers".to_string());
    }

    fn set_primitive(&mut self, prim: d::state::Primitive) {
        self.buf.push("set_primitive".to_string());
    }

    fn set_viewport(&mut self, view: Rect) {
        self.buf.push("set_viewport".to_string());
    }

    fn set_multi_sample(&mut self, ms: Option<d::state::MultiSample>) {
        self.buf.push("set_multi_sample".to_string());
    }

    fn set_scissor(&mut self, rect: Option<Rect>) {
        self.buf.push("set_scissor".to_string());
    }

    fn set_depth_stencil(&mut self, depth: Option<d::state::Depth>,
                         stencil: Option<d::state::Stencil>,
                         cull: d::state::CullFace) {
        self.buf.push("set_depth_stencil".to_string());
    }

    fn set_blend(&mut self, blend: Option<d::state::Blend>) {
        self.buf.push("set_blend".to_string());
    }

    fn set_color_mask(&mut self, mask: d::state::ColorMask) {
        self.buf.push("set_color_mask".to_string());
    }

    fn update_buffer(&mut self, buf: Buffer, data: d::draw::DataPointer,
                        offset_bytes: usize) {
        self.buf.push("update_buffer".to_string());
    }

    fn update_texture(&mut self, kind: d::tex::Kind, tex: Texture,
                      info: d::tex::ImageInfo, data: d::draw::DataPointer) {
        self.buf.push("update_texture".to_string());
    }

    fn call_clear(&mut self, data: ClearData, mask: Mask) {
        self.buf.push("call_clear".to_string());
    }

    fn call_draw(&mut self, ptype: d::PrimitiveType, start: d::VertexCount,
                 count: d::VertexCount, instances: d::draw::InstanceOption) {
        self.buf.push("call_draw".to_string());
    }

    fn call_draw_indexed(&mut self, ptype: d::PrimitiveType,
                         itype: d::IndexType, start: d::VertexCount,
                         count: d::VertexCount, base: d::VertexCount,
                         instances: d::draw::InstanceOption) {
        self.buf.push("call_draw_indexed".to_string());
    }

    fn call_blit(&mut self, s_rect: Rect, d_rect: Rect, mirror: Mirror,
                 mask: Mask) {
        self.buf.push("call_blit".to_string());
    }
}

impl DummyDevice {
    fn new() -> DummyDevice {
        DummyDevice {
            capabilities: Capabilities {
                shader_model: shade::ShaderModel::Unsupported,

                max_vertex_count: 0,
                max_index_count: 0,
                max_draw_buffers: 0,
                max_texture_size: 0,
                max_vertex_attributes: 0,

                buffer_role_change_allowed: false,

                array_buffer_supported: false,
                fragment_output_supported: false,
                immutable_storage_supported: false,
                instance_base_supported: false,
                instance_call_supported: false,
                instance_rate_supported: false,
                render_targets_supported: false,
                sampler_objects_supported: false,
                srgb_color_supported: false,
                uniform_block_supported: false,
                vertex_base_supported: false,
            }
        }
    }
}

impl Device for DummyDevice {
    type Resources = DummyResources;
    type CommandBuffer = DummyCommandBuffer;

    fn get_capabilities<'a>(&'a self) -> &'a Capabilities {
        &self.capabilities
    }
    fn reset_state(&mut self) {}
    fn submit(&mut self, (cb, db, handles): SubmitInfo<Self>) {}
    fn cleanup(&mut self) {}
}
<commit_msg>Added DummyDevice::new(Capabilities)<commit_after>#![allow(missing_docs)]
use device as d;
use device::{Device, Resources, Capabilities, SubmitInfo};
use device::draw::{CommandBuffer, Access, Gamma, Target};
use device::shade;
use super::{tex};
use draw_state::target::{Rect, Mirror, Mask, ClearData, Layer, Level};

pub struct DummyDevice {
    capabilities: Capabilities
}
pub struct DummyCommandBuffer {
    buf: Vec<String>
}

#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub enum DummyResources{}

pub type Buffer         = u32;
pub type ArrayBuffer    = u32;
pub type Shader         = u32;
pub type Program        = u32;
pub type FrameBuffer    = u32;
pub type Surface        = u32;
pub type Sampler        = u32;
pub type Texture        = u32;

impl Resources for DummyResources {
    type Buffer         = Buffer;
    type ArrayBuffer    = ArrayBuffer;
    type Shader         = Shader;
    type Program        = Program;
    type FrameBuffer    = FrameBuffer;
    type Surface        = Surface;
    type Texture        = Texture;
    type Sampler        = Sampler;
}

impl CommandBuffer<DummyResources> for DummyCommandBuffer {
    fn new() -> DummyCommandBuffer {
        DummyCommandBuffer {
            buf: Vec::new(),
        }
    }

    fn clear(&mut self) {
        self.buf.clear();
    }

    fn bind_program(&mut self, prog: Program) {
        self.buf.push("bind_program".to_string());
    }

    fn bind_array_buffer(&mut self, vao: ArrayBuffer) {
        self.buf.push("bind_array_buffer".to_string());
    }

    fn bind_attribute(&mut self, slot: d::AttributeSlot, buf: Buffer,
                      format: d::attrib::Format) {
        self.buf.push("bind_attribute".to_string());
    }

    fn bind_index(&mut self, buf: Buffer) {
        self.buf.push("bind_index".to_string());
    }

    fn bind_frame_buffer(&mut self, access: Access, fbo: FrameBuffer,
                         gamma: Gamma) {
        self.buf.push("bind_frame_buffer".to_string());
    }

    fn unbind_target(&mut self, access: Access, tar: Target) {
        self.buf.push("unbind_target".to_string());
    }

    fn bind_target_surface(&mut self, access: Access, tar: Target,
                           suf: Surface) {
        self.buf.push("bind_target_surface".to_string());
    }

    fn bind_target_texture(&mut self, access: Access, tar: Target,
                           tex: Texture, level: Level, layer: Option<Layer>) {
        self.buf.push("bind_target_texture".to_string());
    }

    fn bind_uniform_block(&mut self, prog: Program, slot: d::UniformBufferSlot,
                          index: d::UniformBlockIndex, buf: Buffer) {
        self.buf.push("bind_uniform_block".to_string());
    }

    fn bind_uniform(&mut self, loc: d::shade::Location,
                    value: d::shade::UniformValue) {
        self.buf.push("bind_uniform".to_string());
    }
    fn bind_texture(&mut self, slot: d::TextureSlot, kind: d::tex::Kind,
                    tex: Texture,
                    sampler: Option<(Sampler, d::tex::SamplerInfo)>) {
        self.buf.push("set_draw_color_buffers".to_string());
    }

    fn set_draw_color_buffers(&mut self, num: usize) {
        self.buf.push("set_draw_color_buffers".to_string());
    }

    fn set_primitive(&mut self, prim: d::state::Primitive) {
        self.buf.push("set_primitive".to_string());
    }

    fn set_viewport(&mut self, view: Rect) {
        self.buf.push("set_viewport".to_string());
    }

    fn set_multi_sample(&mut self, ms: Option<d::state::MultiSample>) {
        self.buf.push("set_multi_sample".to_string());
    }

    fn set_scissor(&mut self, rect: Option<Rect>) {
        self.buf.push("set_scissor".to_string());
    }

    fn set_depth_stencil(&mut self, depth: Option<d::state::Depth>,
                         stencil: Option<d::state::Stencil>,
                         cull: d::state::CullFace) {
        self.buf.push("set_depth_stencil".to_string());
    }

    fn set_blend(&mut self, blend: Option<d::state::Blend>) {
        self.buf.push("set_blend".to_string());
    }

    fn set_color_mask(&mut self, mask: d::state::ColorMask) {
        self.buf.push("set_color_mask".to_string());
    }

    fn update_buffer(&mut self, buf: Buffer, data: d::draw::DataPointer,
                        offset_bytes: usize) {
        self.buf.push("update_buffer".to_string());
    }

    fn update_texture(&mut self, kind: d::tex::Kind, tex: Texture,
                      info: d::tex::ImageInfo, data: d::draw::DataPointer) {
        self.buf.push("update_texture".to_string());
    }

    fn call_clear(&mut self, data: ClearData, mask: Mask) {
        self.buf.push("call_clear".to_string());
    }

    fn call_draw(&mut self, ptype: d::PrimitiveType, start: d::VertexCount,
                 count: d::VertexCount, instances: d::draw::InstanceOption) {
        self.buf.push("call_draw".to_string());
    }

    fn call_draw_indexed(&mut self, ptype: d::PrimitiveType,
                         itype: d::IndexType, start: d::VertexCount,
                         count: d::VertexCount, base: d::VertexCount,
                         instances: d::draw::InstanceOption) {
        self.buf.push("call_draw_indexed".to_string());
    }

    fn call_blit(&mut self, s_rect: Rect, d_rect: Rect, mirror: Mirror,
                 mask: Mask) {
        self.buf.push("call_blit".to_string());
    }
}

impl DummyDevice {
    fn new(capabilities: Capabilities) -> DummyDevice {
        DummyDevice {
            capabilities: capabilities
        }
    }
}

impl Device for DummyDevice {
    type Resources = DummyResources;
    type CommandBuffer = DummyCommandBuffer;

    fn get_capabilities<'a>(&'a self) -> &'a Capabilities {
        &self.capabilities
    }
    fn reset_state(&mut self) {}
    fn submit(&mut self, (cb, db, handles): SubmitInfo<Self>) {}
    fn cleanup(&mut self) {}
}
<|endoftext|>


<commit_before><commit_msg>Added an example `test_event_app`<commit_after>#![feature(globs)]

extern crate piston;
extern crate event;

use piston::*;
use event::{
    AddKeyboard,
    AddLasting,
    AddPress,
    AddPressing,

    Event,

    Map,

    BackEnd,
    Observer,
};

pub struct App<'a> {
    e: Event<'a>,
    back_end: TestBackEnd<'a>,
}

impl<'a> App<'a> {
    pub fn new() -> App {
        App {
            e: Event::new(),
            back_end: TestBackEnd::new(),
        }
    }
}

impl<'a> Game for App<'a> {
    fn load(&mut self, _asset_store: &mut AssetStore) {
        self.e.keyboard().press(keyboard::Up).map(&mut self.back_end, || {
            println!("Oops! You pressed keyboard::Up");
        });

        let e = self.e.keyboard().pressing(keyboard::Up);
        e.map(&mut self.back_end, || {
            println!("Wow! You are pressing keyboard::Up");
        });

        e.lasting(1.0).map(&mut self.back_end, || {
            println!("Wooooooow! You are pressing keybaord::Up at least 1.0 second!!");
        });
    }

    fn update(&mut self, dt: f64, _asset_store: &mut AssetStore) {
        self.back_end.update(dt);
    }

    // re-wrap those events to Event, a good way to do this is in the GameWindow
    // implementions.
    fn key_press(
        &mut self,
        key: keyboard::Key,
        _asset_store: &mut AssetStore
    ) {
        self.back_end.on_event(event::KeyPressed(key));
    }

    fn key_release(
        &mut self,
        key: keyboard::Key,
        _asset_store: &mut AssetStore
    ) {
        self.back_end.on_event(event::KeyReleased(key));
    }

    fn mouse_press(
        &mut self,
        button: mouse::Button,
        _asset_store: &mut AssetStore
    ) {
        self.back_end.on_event(event::MouseButtonPressed(button));
    }

    fn mouse_release(
        &mut self,
        button: mouse::Button,
        _asset_store: &mut AssetStore
    ) {
        self.back_end.on_event(event::MouseButtonReleased(button));
    }
}

struct TestBackEnd<'a> {
    observers: Vec<Box<Observer>>,
}

impl<'a> TestBackEnd<'a> {
    pub fn new() -> TestBackEnd {
        TestBackEnd {
            observers: Vec::<Box<Observer>>::new(),
        }
    }
}

impl<'a> BackEnd for TestBackEnd<'a> {
    fn add_observer(&mut self, ob: Box<Observer>) -> uint {
        self.observers.push(ob);
        self.observers.len() - 1
    }

    fn update(&mut self, dt: f64) {
        for i in range(0, self.observers.len()) {
            let ob = self.observers.get_mut(i);

            ob.update(dt);

            if ob.can_trigger() {
                ob.trigger();
            }
        }
    }

    fn on_event(&mut self, e: event::Event) {
        for ob in self.observers.mut_iter() {
            ob.on_event(e);
        }
    }
}

type GameWindowBackEnd = GameWindowSDL2;

fn main() {
    let mut game_window: GameWindowBackEnd = GameWindow::new(
        GameWindowSettings::new (
            "Piston-Lab".to_owned(),
            [300, 300],
            false,
            true,
            [1.0, 1.0, 1.0, 1.0]
        )
    );

    let mut asset_store = AssetStore::from_folder("assets");
    let mut app = App::new();

    app.run(&mut game_window, &mut asset_store);
}

<|endoftext|>


<commit_before><commit_msg>Add solution to problem 46<commit_after>#[macro_use] extern crate libeuler;
extern crate num;

use libeuler::SieveOfAtkin;
use num::integer::Integer;

/// It was proposed by Christian Goldbach that every odd composite number can be written as the sum
/// of a prime and twice a square.
///
/// 9 = 7 + 2×1^2
/// 15 = 7 + 2×2^2
/// 21 = 3 + 2×3^2
/// 25 = 7 + 2×3^2
/// 27 = 19 + 2×2^2
/// 33 = 31 + 2×1^2
///
/// It turns out that the conjecture was false.
///
/// What is the smallest odd composite that cannot be written as the sum of a prime and twice a
/// square?
fn main() {
    solutions! {
        sol naive {
            let sieve = SieveOfAtkin::new(10_000);
            let odd_composites = (2..10_000)
                .filter(|a| a.is_odd())
                .filter(|&a| !sieve.is_prime(a));

            for c in odd_composites {
                let twice_squares: Vec<u64> = (0..1000)
                    .map(|v| 2*v*v)
                    .take_while(|&v| v < c)
                    .collect();

                let no_primes = twice_squares.iter().all(|sq| {
                    !sieve.is_prime(c - sq)
                });

                if no_primes {
                    return Some(c);
                }
            }

            return None;
        }
    }
}
<|endoftext|>


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

// ignore-emscripten
// min-llvm-version 7.0
// error-pattern: panicked

// Test that the simd_f{min,max} intrinsics produce the correct results.

#![feature(repr_simd, platform_intrinsics)]
#![allow(non_camel_case_types)]

#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
struct f32x4(pub f32, pub f32, pub f32, pub f32);

extern "platform-intrinsic" {
    fn simd_fmin<T>(x: T, y: T) -> T;
    fn simd_fmax<T>(x: T, y: T) -> T;
}

fn main() {
    let x = f32x4(1.0, 2.0, 3.0, 4.0);
    let y = f32x4(2.0, 1.0, 4.0, 3.0);
    let nan = ::std::f32::NAN;
    let n = f32x4(nan, nan, nan, nan);

    unsafe {
        let min0 = simd_fmin(x, y);
        let min1 = simd_fmin(y, x);
        assert_eq!(min0, min1);
        let e = f32x4(1.0, 1.0, 3.0, 3.0);
        assert_eq!(min0, e);
        let minn = simd_fmin(x, n);
        assert_eq!(minn, x);
        let minn = simd_fmin(y, n);
        assert_eq!(minn, y);

        let max0 = simd_fmax(x, y);
        let max1 = simd_fmax(y, x);
        assert_eq!(max0, max1);
        let e = f32x4(2.0, 2.0, 4.0, 4.0);
        assert_eq!(max0, e);
        let maxn = simd_fmax(x, n);
        assert_eq!(maxn, x);
        let maxn = simd_fmax(y, n);
        assert_eq!(maxn, y);
    }
}
<commit_msg>run-pass/simd-intrinsic-float-minmax: Force use of qNaN on Mips<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// ignore-emscripten
// min-llvm-version 7.0
// error-pattern: panicked

// Test that the simd_f{min,max} intrinsics produce the correct results.

#![feature(repr_simd, platform_intrinsics)]
#![allow(non_camel_case_types)]

#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
struct f32x4(pub f32, pub f32, pub f32, pub f32);

extern "platform-intrinsic" {
    fn simd_fmin<T>(x: T, y: T) -> T;
    fn simd_fmax<T>(x: T, y: T) -> T;
}

fn main() {
    let x = f32x4(1.0, 2.0, 3.0, 4.0);
    let y = f32x4(2.0, 1.0, 4.0, 3.0);

    #[cfg(not(any(target_arch = "mips", target_arch = "mips64")))]
    let nan = ::std::f32::NAN;
    // MIPS hardware treats f32::NAN as SNAN. Clear the signaling bit.
    // See https://github.com/rust-lang/rust/issues/52746.
    #[cfg(any(target_arch = "mips", target_arch = "mips64"))]
    let nan = f32::from_bits(::std::f32::NAN.to_bits() - 1);

    let n = f32x4(nan, nan, nan, nan);

    unsafe {
        let min0 = simd_fmin(x, y);
        let min1 = simd_fmin(y, x);
        assert_eq!(min0, min1);
        let e = f32x4(1.0, 1.0, 3.0, 3.0);
        assert_eq!(min0, e);
        let minn = simd_fmin(x, n);
        assert_eq!(minn, x);
        let minn = simd_fmin(y, n);
        assert_eq!(minn, y);

        let max0 = simd_fmax(x, y);
        let max1 = simd_fmax(y, x);
        assert_eq!(max0, max1);
        let e = f32x4(2.0, 2.0, 4.0, 4.0);
        assert_eq!(max0, e);
        let maxn = simd_fmax(x, n);
        assert_eq!(maxn, x);
        let maxn = simd_fmax(y, n);
        assert_eq!(maxn, y);
    }
}
<|endoftext|>


<commit_before><commit_msg>Move actual events and repsoses out of the game timer block results in much smoother input.<commit_after><|endoftext|>


<commit_before><commit_msg>Created encode and decode functions for going from Brainfuck programs to binary strings and back<commit_after><|endoftext|>


<commit_before><commit_msg>Move argument parsing into function<commit_after><|endoftext|>


<commit_before><commit_msg>Refactor to determine potential issues with Arc and Mutex with FFI.<commit_after><|endoftext|>


<commit_before>extern crate piston;
extern crate graphics;
extern crate piston_window;
extern crate time;
extern crate rand;
extern crate ai_behavior;
extern crate cgmath;
extern crate opengl_graphics;

mod app;
mod entity;
mod player;
mod config;
mod person;

use player::Player;
use entity::Entity;

use piston_window::{ PistonWindow, WindowSettings };
use piston::input::*;
use piston::event_loop::*;
use opengl_graphics::*;
use graphics::{ Image, clear, default_draw_state };
use graphics::rectangle::square;
use std::path::Path;
use rand::{Rng, SeedableRng, XorShiftRng};

use cgmath::rad;
use cgmath::{ Vector2, Vector4 };
use cgmath::{ Rotation2, Basis2 };

fn transform_camera_coords(player : &Player, x : u32, y: u32, width : u32, height : u32) -> (f64, f64) {
    return (
        x as f64 - player.get_position().x as f64 + (width as f64 / 2f64) as f64 ,
        y as f64 - player.get_position().y as f64 + (height as f64 / 2f64) as f64
    );
}

fn draw_background(x: u32, y: u32, context: graphics::context::Context, gl_graphics: &mut GlGraphics, textures: &Vec<Texture>, seed: [u32;4], player : &mut Player) {
    let mut rng1: XorShiftRng = SeedableRng::from_seed(seed);
    let txt: &Texture = textures.get(0).unwrap();
    let (width, height) = txt.get_size();
    for i in 0..(x/width) + 1 {
        for j in 0..(y/height) + 1 {
            let (k, l) = transform_camera_coords(player, i, j, x, y);
            let rand = rng1.gen::<u32>() % textures.len() as u32;
            let txt: &Texture = textures.get(rand as usize).unwrap();
            let (width, height) = txt.get_size();
            let image = Image::new().rect(square((i as f64 * width as f64) as f64 + k, (j as f64 * height as f64) as f64 + l, width as f64));
            println!("({}, {}) = ({}, {})", (k * width as f64) as f64, (l * height as f64) as f64, k, l);
            image.draw(txt, default_draw_state(), context.transform, gl_graphics);
        }
    }
}

fn main() {
    let mut rng = rand::thread_rng();
    let seed: [u32;4] = [rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>()];
    let opengl = OpenGL::V3_2;
    let mut window: PistonWindow = WindowSettings::new("GGJ2016", [800, 600])
        .exit_on_esc(true)
        .opengl(opengl)
        .build()
        .unwrap_or_else(|e| { panic!("Failed to build PistonWindow: {}", e) });
    window.set_ups(60);
    let mut gl = GlGraphics::new(opengl);

    let emoji_player = Texture::from_path(Path::new("assets/img/emoji/78.png")).unwrap();
    let mut app = app::App::new(emoji_player);

    let emoji = Texture::from_path(Path::new("assets/img/emoji/77.png")).unwrap();
    app.add_entity(Box::new(person::Person::new(emoji, Vector2::new(50.0, 50.0))));

    // Add player to entities (player instanciated in app)
    //app.add_entity(Box::new(player::Player::new()));

    let mut textures :Vec<Texture>= Vec::new();
    textures.push(Texture::from_path(Path::new("assets/img/ground/placeholder_01.jpg")).unwrap());
    textures.push(Texture::from_path(Path::new("assets/img/ground/placeholder_02.jpg")).unwrap());

    for e in window {
        if let Some(args) = e.press_args() {
            app.key_press(args);
            println!("asda");
        }

        if let Some(args) = e.update_args() {
            app.update(args);
        }

        if let Some(args) = e.render_args() {
            gl.draw(args.viewport(), |c, gl| {
                clear([0.5, 0.2, 0.9, 1.0], gl);
                draw_background(args.width, args.height, c, gl, &textures, seed, app.get_player());

                app.render(c, gl, args);
            });
        }
    }
}
<commit_msg>Removed verbosity.<commit_after>extern crate piston;
extern crate graphics;
extern crate piston_window;
extern crate time;
extern crate rand;
extern crate ai_behavior;
extern crate cgmath;
extern crate opengl_graphics;

mod app;
mod entity;
mod player;
mod config;
mod person;

use player::Player;
use entity::Entity;

use piston_window::{ PistonWindow, WindowSettings };
use piston::input::*;
use piston::event_loop::*;
use opengl_graphics::*;
use graphics::{ Image, clear, default_draw_state };
use graphics::rectangle::square;
use std::path::Path;
use rand::{Rng, SeedableRng, XorShiftRng};

use cgmath::rad;
use cgmath::{ Vector2, Vector4 };
use cgmath::{ Rotation2, Basis2 };

fn transform_camera_coords(player : &Player, x : u32, y: u32, width : u32, height : u32) -> (f64, f64) {
    return (
        x as f64 - player.get_position().x as f64 + (width as f64 / 2f64) as f64 ,
        y as f64 - player.get_position().y as f64 + (height as f64 / 2f64) as f64
    );
}

fn draw_background(x: u32, y: u32, context: graphics::context::Context, gl_graphics: &mut GlGraphics, textures: &Vec<Texture>, seed: [u32;4], player : &mut Player) {
    let mut rng1: XorShiftRng = SeedableRng::from_seed(seed);
    let txt: &Texture = textures.get(0).unwrap();
    let (width, height) = txt.get_size();
    for i in 0..(x/width) + 1 {
        for j in 0..(y/height) + 1 {
            let (k, l) = transform_camera_coords(player, i, j, x, y);
            let rand = rng1.gen::<u32>() % textures.len() as u32;
            let txt: &Texture = textures.get(rand as usize).unwrap();
            let (width, height) = txt.get_size();
            let image = Image::new().rect(square((i as f64 * width as f64) as f64 + k, (j as f64 * height as f64) as f64 + l, width as f64));
            image.draw(txt, default_draw_state(), context.transform, gl_graphics);
        }
    }
}

fn main() {
    let mut rng = rand::thread_rng();
    let seed: [u32;4] = [rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>()];
    let opengl = OpenGL::V3_2;
    let mut window: PistonWindow = WindowSettings::new("GGJ2016", [800, 600])
        .exit_on_esc(true)
        .opengl(opengl)
        .build()
        .unwrap_or_else(|e| { panic!("Failed to build PistonWindow: {}", e) });
    window.set_ups(60);
    let mut gl = GlGraphics::new(opengl);

    let emoji_player = Texture::from_path(Path::new("assets/img/emoji/78.png")).unwrap();
    let mut app = app::App::new(emoji_player);

    let emoji = Texture::from_path(Path::new("assets/img/emoji/77.png")).unwrap();
    app.add_entity(Box::new(person::Person::new(emoji, Vector2::new(50.0, 50.0))));

    // Add player to entities (player instanciated in app)
    //app.add_entity(Box::new(player::Player::new()));

    let mut textures :Vec<Texture>= Vec::new();
    textures.push(Texture::from_path(Path::new("assets/img/ground/placeholder_01.jpg")).unwrap());
    textures.push(Texture::from_path(Path::new("assets/img/ground/placeholder_02.jpg")).unwrap());

    for e in window {
        if let Some(args) = e.press_args() {
            app.key_press(args);
            println!("asda");
        }

        if let Some(args) = e.update_args() {
            app.update(args);
        }

        if let Some(args) = e.render_args() {
            gl.draw(args.viewport(), |c, gl| {
                clear([0.5, 0.2, 0.9, 1.0], gl);
                draw_background(args.width, args.height, c, gl, &textures, seed, app.get_player());

                app.render(c, gl, args);
            });
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>adding make command<commit_after><|endoftext|>


<commit_before>#![feature(deque_extras)]
#![feature(box_syntax)]
#![feature(plugin)]
#![plugin(peg_syntax_ext)]

extern crate glob;

use std::collections::HashMap;
use std::fs::File;
use std::io::{stdout, Read, Write};
use std::env;
use std::process;

use self::directory_stack::DirectoryStack;
use self::input_editor::readln;
use self::peg::{parse, Job};
use self::variables::Variables;
use self::history::History;
use self::flow_control::{FlowControl, is_flow_control_command, Statement};
use self::status::{SUCCESS, NO_SUCH_COMMAND, TERMINATED};

pub mod directory_stack;
pub mod to_num;
pub mod input_editor;
pub mod peg;
pub mod variables;
pub mod history;
pub mod flow_control;
pub mod status;

/// This struct will contain all of the data structures related to this
/// instance of the shell.
pub struct Shell {
    variables: Variables,
    flow_control: FlowControl,
    directory_stack: DirectoryStack,
    history: History,
}

impl Shell {
    /// Panics if DirectoryStack construction fails
    pub fn new() -> Self {
        Shell {
            variables: Variables::new(),
            flow_control: FlowControl::new(),
            directory_stack: DirectoryStack::new().expect(""),
            history: History::new(),
        }
    }

    pub fn print_prompt(&self) {
        self.print_prompt_prefix();
        match self.flow_control.current_statement {
            Statement::For(_, _) => self.print_for_prompt(),
            Statement::Default => self.print_default_prompt(),
        }
        if let Err(message) = stdout().flush() {
            println!("{}: failed to flush prompt to stdout", message);
        }

    }

    // TODO eventually this thing should be gone
    fn print_prompt_prefix(&self) {
        let prompt_prefix = self.flow_control.modes.iter().rev().fold(String::new(), |acc, mode| {
            acc +
            if mode.value {
                "+ "
            } else {
                "- "
            }
        });
        print!("{}", prompt_prefix);
    }

    fn print_for_prompt(&self) {
        print!("for> ");
    }

    fn print_default_prompt(&self) {
        let cwd = env::current_dir().ok().map_or("?".to_string(),
                                                 |ref p| p.to_str().unwrap_or("?").to_string());
        print!("ion:{}# ", cwd);
    }

    fn on_command(&mut self, command_string: &str, commands: &HashMap<&str, Command>) {
        self.history.add(command_string.to_string());

        let mut jobs = parse(command_string);

        // Execute commands
        for job in jobs.drain(..) {
            if self.flow_control.collecting_block {
                // TODO move this logic into "end" command
                if job.command == "end" {
                    self.flow_control.collecting_block = false;
                    let block_jobs: Vec<Job> = self.flow_control
                                                   .current_block
                                                   .jobs
                                                   .drain(..)
                                                   .collect();
                    let mut variable = String::new();
                    let mut values: Vec<String> = vec![];
                    if let Statement::For(ref var, ref vals) = self.flow_control.current_statement {
                        variable = var.clone();
                        values = vals.clone();
                    }
                    for value in values {
                        self.variables.set_var(&variable, &value);
                        for job in block_jobs.iter() {
                            self.run_job(job, commands);
                        }
                    }
                    self.flow_control.current_statement = Statement::Default;
                } else {
                    self.flow_control.current_block.jobs.push(job);
                }
            } else {
                if self.flow_control.skipping() && !is_flow_control_command(&job.command) {
                    continue;
                }
                self.run_job(&job, commands);
            }
        }
    }

    fn run_job(&mut self, job: &Job, commands: &HashMap<&str, Command>) {
        let mut job = self.variables.expand_job(job);
        job.expand_globs();
        let exit_status = if let Some(command) = commands.get(job.command.as_str()) {
            Some((*command.main)(job.args.as_slice(), self))
        } else {
            self.run_external_commmand(&job.args)
        };
        if let Some(code) = exit_status {
            self.variables.set_var("?", &code.to_string());
        }
    }

    /// Returns an exit code if a command was run
    fn run_external_commmand(&mut self, args: &Vec<String>) -> Option<i32> {
        if let Some(path) = args.get(0) {
            let mut command = process::Command::new(path);
            for i in 1..args.len() {
                if let Some(arg) = args.get(i) {
                    command.arg(arg);
                }
            }
            match command.spawn() {
                Ok(mut child) => {
                    match child.wait() {
                        Ok(status) => {
                            if let Some(code) = status.code() {
                                Some(code)
                            } else {
                                println!("{}: child ended by signal", path);
                                Some(TERMINATED)
                            }
                        }
                        Err(err) => {
                            println!("{}: Failed to wait: {}", path, err);
                            Some(100) // TODO what should we return here?
                        }
                    }
                }
                Err(err) => {
                    println!("{}: Failed to execute: {}", path, err);
                    Some(NO_SUCH_COMMAND)
                }
            }
        } else {
            None
        }
    }
}

/// Structure which represents a Terminal's command.
/// This command structure contains a name, and the code which run the
/// functionnality associated to this one, with zero, one or several argument(s).
/// # Example
/// ```
/// let my_command = Command {
///     name: "my_command",
///     help: "Describe what my_command does followed by a newline showing usage",
///     main: box|args: &[String], &mut Shell| -> i32 {
///         println!("Say 'hello' to my command! :-D");
///     }
/// }
/// ```
pub struct Command {
    pub name: &'static str,
    pub help: &'static str,
    pub main: Box<Fn(&[String], &mut Shell) -> i32>,
}

impl Command {
    /// Return the map from command names to commands
    pub fn map() -> HashMap<&'static str, Self> {
        let mut commands: HashMap<&str, Self> = HashMap::new();

        commands.insert("cd",
                        Command {
                            name: "cd",
                            help: "Change the current directory\n    cd <path>",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.directory_stack.cd(args)
                            },
                        });

        commands.insert("dirs",
                        Command {
                            name: "dirs",
                            help: "Display the current directory stack",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.directory_stack.dirs(args)
                            },
                        });

        commands.insert("exit",
                        Command {
                            name: "exit",
                            help: "To exit the curent session",
                            main: box |args: &[String], _: &mut Shell| -> i32 {
                                if let Some(status) = args.get(1) {
                                    if let Ok(status) = status.parse::<i32>() {
                                        process::exit(status);
                                    }
                                }
                                // TODO should use exit status of previously run command, not 0
                                process::exit(0);
                            },
                        });

        commands.insert("let",
                        Command {
                            name: "let",
                            help: "View, set or unset variables",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.variables.let_(args)
                            },
                        });

        commands.insert("read",
                        Command {
                            name: "read",
                            help: "Read some variables\n    read <variable>",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.variables.read(args)
                            },
                        });

        commands.insert("pushd",
                        Command {
                            name: "pushd",
                            help: "Push a directory to the stack",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.directory_stack.pushd(args)
                            },
                        });

        commands.insert("popd",
                        Command {
                            name: "popd",
                            help: "Pop a directory from the stack",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.directory_stack.popd(args)
                            },
                        });

        commands.insert("history",
                        Command {
                            name: "history",
                            help: "Display a log of all commands previously executed",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.history.history(args)
                            },
                        });

        commands.insert("if",
                        Command {
                            name: "if",
                            help: "Conditionally execute code",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.flow_control.if_(args)
                            },
                        });

        commands.insert("else",
                        Command {
                            name: "else",
                            help: "Execute code if a previous condition was false",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.flow_control.else_(args)
                            },
                        });

        commands.insert("end",
                        Command {
                            name: "end",
                            help: "End a code block",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.flow_control.end(args)
                            },
                        });

        commands.insert("for",
                        Command {
                            name: "for",
                            help: "Iterate through a list",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.flow_control.for_(args)
                            },
                        });

        let command_helper: HashMap<&'static str, &'static str> = commands.iter()
                                                                          .map(|(k, v)| {
                                                                              (*k, v.help)
                                                                          })
                                                                          .collect();

        commands.insert("help",
                        Command {
                            name: "help",
                            help: "Display helpful information about a given command, or list \
                                   commands if none specified\n    help <command>",
                            main: box move |args: &[String], _: &mut Shell| -> i32 {
                                if let Some(command) = args.get(1) {
                                    if command_helper.contains_key(command.as_str()) {
                                        match command_helper.get(command.as_str()) {
                                            Some(help) => println!("{}", help),
                                            None => {
                                                println!("Command helper not found [run 'help']...")
                                            }
                                        }
                                    } else {
                                        println!("Command helper not found [run 'help']...");
                                    }
                                } else {
                                    for (command, _help) in command_helper.iter() {
                                        println!("{}", command);
                                    }
                                }
                                SUCCESS
                            },
                        });

        commands
    }
}

fn main() {
    let commands = Command::map();
    let mut shell = Shell::new();

    for arg in env::args().skip(1) {
        let mut command_list = String::new();
        if let Ok(mut file) = File::open(&arg) {
            if let Err(message) = file.read_to_string(&mut command_list) {
                println!("{}: Failed to read {}", message, arg);
            }
        }
        shell.on_command(&command_list, &commands);
        return;
    }

    loop {
        shell.print_prompt();

        if let Some(command) = readln() {
            let command = command.trim();
            if !command.is_empty() {
                shell.on_command(command, &commands);
            }
        } else {
            break;
        }
    }
}
<commit_msg>WIP job control<commit_after>#![feature(deque_extras)]
#![feature(box_syntax)]
#![feature(plugin)]
#![plugin(peg_syntax_ext)]

extern crate glob;

use std::collections::HashMap;
use std::fs::File;
use std::io::{stdout, Read, Write};
use std::env;
use std::process;

use self::directory_stack::DirectoryStack;
use self::input_editor::readln;
use self::peg::{parse, Job};
use self::variables::Variables;
use self::history::History;
use self::flow_control::{FlowControl, is_flow_control_command, Statement};
use self::status::{SUCCESS, NO_SUCH_COMMAND, TERMINATED};

pub mod directory_stack;
pub mod to_num;
pub mod input_editor;
pub mod peg;
pub mod variables;
pub mod history;
pub mod flow_control;
pub mod status;

/// This struct will contain all of the data structures related to this
/// instance of the shell.
pub struct Shell {
    variables: Variables,
    flow_control: FlowControl,
    directory_stack: DirectoryStack,
    history: History,
}

impl Shell {
    /// Panics if DirectoryStack construction fails
    pub fn new() -> Self {
        Shell {
            variables: Variables::new(),
            flow_control: FlowControl::new(),
            directory_stack: DirectoryStack::new().expect(""),
            history: History::new(),
        }
    }

    pub fn print_prompt(&self) {
        self.print_prompt_prefix();
        match self.flow_control.current_statement {
            Statement::For(_, _) => self.print_for_prompt(),
            Statement::Default => self.print_default_prompt(),
        }
        if let Err(message) = stdout().flush() {
            println!("{}: failed to flush prompt to stdout", message);
        }

    }

    // TODO eventually this thing should be gone
    fn print_prompt_prefix(&self) {
        let prompt_prefix = self.flow_control.modes.iter().rev().fold(String::new(), |acc, mode| {
            acc +
            if mode.value {
                "+ "
            } else {
                "- "
            }
        });
        print!("{}", prompt_prefix);
    }

    fn print_for_prompt(&self) {
        print!("for> ");
    }

    fn print_default_prompt(&self) {
        let cwd = env::current_dir().ok().map_or("?".to_string(),
                                                 |ref p| p.to_str().unwrap_or("?").to_string());
        print!("ion:{}# ", cwd);
    }

    fn on_command(&mut self, command_string: &str, commands: &HashMap<&str, Command>) {
        self.history.add(command_string.to_string());

        let mut jobs = parse(command_string);

        // Execute commands
        for job in jobs.drain(..) {
            if self.flow_control.collecting_block {
                // TODO move this logic into "end" command
                if job.command == "end" {
                    self.flow_control.collecting_block = false;
                    let block_jobs: Vec<Job> = self.flow_control
                                                   .current_block
                                                   .jobs
                                                   .drain(..)
                                                   .collect();
                    let mut variable = String::new();
                    let mut values: Vec<String> = vec![];
                    if let Statement::For(ref var, ref vals) = self.flow_control.current_statement {
                        variable = var.clone();
                        values = vals.clone();
                    }
                    for value in values {
                        self.variables.set_var(&variable, &value);
                        for job in block_jobs.iter() {
                            self.run_job(job, commands);
                        }
                    }
                    self.flow_control.current_statement = Statement::Default;
                } else {
                    self.flow_control.current_block.jobs.push(job);
                }
            } else {
                if self.flow_control.skipping() && !is_flow_control_command(&job.command) {
                    continue;
                }
                self.run_job(&job, commands);
            }
        }
    }

    fn run_job(&mut self, job: &Job, commands: &HashMap<&str, Command>) {
        let mut job = self.variables.expand_job(job);
        job.expand_globs();
        let exit_status = if let Some(command) = commands.get(job.command.as_str()) {
            Some((*command.main)(job.args.as_slice(), self))
        } else {
            self.run_external_commmand(&job)
        };
        if let Some(code) = exit_status {
            self.variables.set_var("?", &code.to_string());
        }
    }

    /// Returns an exit code if a command was run
    fn run_external_commmand(&mut self, job: &Job) -> Option<i32> {
        let mut command = process::Command::new(&job.command);
        for i in 1..job.args.len() {
            if let Some(arg) = job.args.get(i) {
                command.arg(arg);
            }
        }
        if job.background {
            command.stdin(process::Stdio::null());
        }
        match command.spawn() {
            Ok(mut child) => {
                if job.background {
                    None
                } else {
                    Some(Shell::wait_and_get_status(&mut child, &job.command))
                }

            }
            Err(err) => {
                println!("{}: Failed to execute: {}", job.command, err);
                Some(NO_SUCH_COMMAND)
            }
        }
    }

    // TODO don't pass in command and do printing outside this function
    fn wait_and_get_status(child: &mut process::Child, command: &str) -> i32 {
        match child.wait() {
            Ok(status) => {
                if let Some(code) = status.code() {
                    code
                } else {
                    println!("{}: child ended by signal", command);
                    TERMINATED
                }
            }
            Err(err) => {
                println!("{}: Failed to wait: {}", command, err);
                100 // TODO what should we return here?
            }
        }
    }

}

/// Structure which represents a Terminal's command.
/// This command structure contains a name, and the code which run the
/// functionnality associated to this one, with zero, one or several argument(s).
/// # Example
/// ```
/// let my_command = Command {
///     name: "my_command",
///     help: "Describe what my_command does followed by a newline showing usage",
///     main: box|args: &[String], &mut Shell| -> i32 {
///         println!("Say 'hello' to my command! :-D");
///     }
/// }
/// ```
pub struct Command {
    pub name: &'static str,
    pub help: &'static str,
    pub main: Box<Fn(&[String], &mut Shell) -> i32>,
}

impl Command {
    /// Return the map from command names to commands
    pub fn map() -> HashMap<&'static str, Self> {
        let mut commands: HashMap<&str, Self> = HashMap::new();

        commands.insert("cd",
                        Command {
                            name: "cd",
                            help: "Change the current directory\n    cd <path>",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.directory_stack.cd(args)
                            },
                        });

        commands.insert("dirs",
                        Command {
                            name: "dirs",
                            help: "Display the current directory stack",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.directory_stack.dirs(args)
                            },
                        });

        commands.insert("exit",
                        Command {
                            name: "exit",
                            help: "To exit the curent session",
                            main: box |args: &[String], _: &mut Shell| -> i32 {
                                if let Some(status) = args.get(1) {
                                    if let Ok(status) = status.parse::<i32>() {
                                        process::exit(status);
                                    }
                                }
                                // TODO should use exit status of previously run command, not 0
                                process::exit(0);
                            },
                        });

        commands.insert("let",
                        Command {
                            name: "let",
                            help: "View, set or unset variables",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.variables.let_(args)
                            },
                        });

        commands.insert("read",
                        Command {
                            name: "read",
                            help: "Read some variables\n    read <variable>",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.variables.read(args)
                            },
                        });

        commands.insert("pushd",
                        Command {
                            name: "pushd",
                            help: "Push a directory to the stack",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.directory_stack.pushd(args)
                            },
                        });

        commands.insert("popd",
                        Command {
                            name: "popd",
                            help: "Pop a directory from the stack",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.directory_stack.popd(args)
                            },
                        });

        commands.insert("history",
                        Command {
                            name: "history",
                            help: "Display a log of all commands previously executed",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.history.history(args)
                            },
                        });

        commands.insert("if",
                        Command {
                            name: "if",
                            help: "Conditionally execute code",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.flow_control.if_(args)
                            },
                        });

        commands.insert("else",
                        Command {
                            name: "else",
                            help: "Execute code if a previous condition was false",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.flow_control.else_(args)
                            },
                        });

        commands.insert("end",
                        Command {
                            name: "end",
                            help: "End a code block",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.flow_control.end(args)
                            },
                        });

        commands.insert("for",
                        Command {
                            name: "for",
                            help: "Iterate through a list",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.flow_control.for_(args)
                            },
                        });

        let command_helper: HashMap<&'static str, &'static str> = commands.iter()
                                                                          .map(|(k, v)| {
                                                                              (*k, v.help)
                                                                          })
                                                                          .collect();

        commands.insert("help",
                        Command {
                            name: "help",
                            help: "Display helpful information about a given command, or list \
                                   commands if none specified\n    help <command>",
                            main: box move |args: &[String], _: &mut Shell| -> i32 {
                                if let Some(command) = args.get(1) {
                                    if command_helper.contains_key(command.as_str()) {
                                        match command_helper.get(command.as_str()) {
                                            Some(help) => println!("{}", help),
                                            None => {
                                                println!("Command helper not found [run 'help']...")
                                            }
                                        }
                                    } else {
                                        println!("Command helper not found [run 'help']...");
                                    }
                                } else {
                                    for (command, _help) in command_helper.iter() {
                                        println!("{}", command);
                                    }
                                }
                                SUCCESS
                            },
                        });

        commands
    }
}

fn main() {
    let commands = Command::map();
    let mut shell = Shell::new();

    for arg in env::args().skip(1) {
        let mut command_list = String::new();
        if let Ok(mut file) = File::open(&arg) {
            if let Err(message) = file.read_to_string(&mut command_list) {
                println!("{}: Failed to read {}", message, arg);
            }
        }
        shell.on_command(&command_list, &commands);
        return;
    }

    loop {
        shell.print_prompt();

        if let Some(command) = readln() {
            let command = command.trim();
            if !command.is_empty() {
                shell.on_command(command, &commands);
            }
        } else {
            break;
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>dynamic can be relative to many units<commit_after><|endoftext|>


<commit_before><commit_msg>tabbed navigation working<commit_after><|endoftext|>


<commit_before><commit_msg>Key in calculate_response did not need to be mutable<commit_after><|endoftext|>


<commit_before><commit_msg>Added a cool looking colored_ridge example<commit_after>extern crate turtle;

use std::f64::consts::E;

use turtle::{Turtle, Color, random};

fn main() {
    let mut turtle = Turtle::new();

    let amplitude = 100.0;
    let width = 800.0;
    let step = 2.0;
    let height_factor = 2.0;

    turtle.set_speed("fastest");
    turtle.pen_up();
    turtle.right(90.0);
    turtle.backward(width / 2.0);
    turtle.pen_down();

    turtle.set_background_color("grey");

    turtle.set_speed("normal");
    for i in 0..(width / step) as i32 {
        let x = i as f64 * step;
        // y = e^(-x^2) translated and scaled by the width and amplitude
        // 200e^(-(1/200(x - 400))^2)
        let y = amplitude * E.powf(-(1.0/(width / 4.0) * (x - width/2.0)).powi(2));

        turtle.set_pen_color(random::<Color>().visible());
        turtle.set_pen_size(y * height_factor);
        turtle.forward(step);
    }
}
<|endoftext|>


<commit_before>// Copyright 2016 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

extern crate winit;
extern crate xcb;
extern crate vk_sys as vk;
extern crate gfx_core;
extern crate gfx_device_vulkan;

use std::{mem, ptr};
use gfx_core::format;

pub fn init_winit(builder: winit::WindowBuilder) -> (winit::Window, gfx_device_vulkan::GraphicsQueue, gfx_device_vulkan::Factory) {
    let (device, factory, _backend) = gfx_device_vulkan::create(&builder.window.title, 1, &[],
        &["VK_KHR_surface", "VK_KHR_xcb_surface"], &["VK_KHR_swapchain"]);
    let win = builder.build().unwrap();
    (win, device, factory)
}

pub type TargetHandle = gfx_core::handle::RenderTargetView<gfx_device_vulkan::Resources, format::Rgba8>;

pub struct SwapTarget {
    _image: vk::Image,
    target: TargetHandle,
    _fence: vk::Fence,
}

pub struct Window {
    connection: xcb::Connection,
    _foreground: u32,
    window: u32,
    swapchain: vk::SwapchainKHR,
    targets: Vec<SwapTarget>,
    queue: gfx_device_vulkan::GraphicsQueue,
}

pub struct Frame<'a> {
    window: &'a mut Window,
    target_id: u32,
}

impl<'a> Frame<'a> {
    pub fn get_target(&self) -> TargetHandle {
        self.window.targets[self.target_id as usize].target.clone()
    }
    pub fn get_queue(&mut self) -> &mut gfx_device_vulkan::GraphicsQueue {
        &mut self.window.queue
    }
}

impl<'a> Drop for Frame<'a> {
    fn drop(&mut self) {
        let mut result = vk::SUCCESS;
        let info = vk::PresentInfoKHR {
            sType: vk::STRUCTURE_TYPE_PRESENT_INFO_KHR,
            pNext: ptr::null(),
            waitSemaphoreCount: 0,
            pWaitSemaphores: ptr::null(),
            swapchainCount: 1,
            pSwapchains: &self.window.swapchain,
            pImageIndices: &self.target_id,
            pResults: &mut result,
        };
        let (_dev, vk) = self.window.queue.get_share().get_device();
        unsafe {
            vk.QueuePresentKHR(self.window.queue.get_queue(), &info);
        }
        assert_eq!(vk::SUCCESS, result);
    }
}

impl Window {
    pub fn wait_draw(&mut self) -> Result<Option<Frame>, ()> {
        let ev = match self.connection.wait_for_event() {
            Some(ev) => ev,
            None => return Err(()),
        };
        //self.connection.flush();
        match ev.response_type() & 0x7F {
            xcb::EXPOSE => Ok(Some(self.start_frame())),
            xcb::KEY_PRESS => Err(()),
            _ => Ok(None)
        }
    }

    pub fn start_frame(&mut self) -> Frame {
        //TODO: handle window resize
        let index = unsafe {
            let (dev, vk) = self.queue.get_share().get_device();
            let mut i = 0;
            assert_eq!(vk::SUCCESS, vk.AcquireNextImageKHR(dev, self.swapchain, 60, 0, 0, &mut i));
            i
        };
        Frame {
            window: self,
            target_id: index,
        }
    }
}

impl Drop for Window {
    fn drop(&mut self) {
        xcb::unmap_window(&self.connection, self.window);
        xcb::destroy_window(&self.connection, self.window);
        self.connection.flush();
    }
}

pub fn init_xcb(title: &str, width: u32, height: u32) -> (Window, gfx_device_vulkan::Factory) {
    let (mut device, mut factory, backend) = gfx_device_vulkan::create(title, 1, &[],
        &["VK_KHR_surface", "VK_KHR_xcb_surface"], &["VK_KHR_swapchain"]);

    let (conn, screen_num) = xcb::Connection::connect(None).unwrap();
    let (window, foreground) = {
        let setup = conn.get_setup();
        let screen = setup.roots().nth(screen_num as usize).unwrap();

        let foreground = conn.generate_id();
        xcb::create_gc(&conn, foreground, screen.root(), &[
                (xcb::GC_FOREGROUND, screen.black_pixel()),
                (xcb::GC_GRAPHICS_EXPOSURES, 0),
        ]);

        let win = conn.generate_id();
        xcb::create_window(&conn,
            xcb::COPY_FROM_PARENT as u8,
            win,
            screen.root(),
            0, 0,
            width as u16, height as u16,
            10,
            xcb::WINDOW_CLASS_INPUT_OUTPUT as u16,
            screen.root_visual(), &[
                (xcb::CW_BACK_PIXEL, screen.black_pixel()),
                (xcb::CW_EVENT_MASK, xcb::EVENT_MASK_KEY_PRESS | xcb::EVENT_MASK_EXPOSURE),
            ]
        );
        (win, foreground)
    };

    xcb::map_window(&conn, window);
    xcb::change_property(&conn, xcb::PROP_MODE_REPLACE as u8, window,
        xcb::ATOM_WM_NAME, xcb::ATOM_STRING, 8, title.as_bytes());
    conn.flush();

    let surface = {
        let (inst, vk) = backend.get_instance();
        let info = vk::XcbSurfaceCreateInfoKHR {
            sType: vk::STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR,
            pNext: ptr::null(),
            flags: 0,
            connection: conn.get_raw_conn() as *const _,
            window: window as *const _, //HACK! TODO: fix the bindings
        };

        unsafe {
            let mut out = mem::zeroed();
            assert_eq!(vk::SUCCESS, vk.CreateXcbSurfaceKHR(inst, &info, ptr::null(), &mut out));
            out
        }
    };

    let (dev, vk) = backend.get_device();
    let mut images: [vk::Image; 2] = [0; 2];
    let mut num = images.len() as u32;

    let swapchain_info = vk::SwapchainCreateInfoKHR {
        sType: vk::STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
        pNext: ptr::null(),
        flags: 0,
        surface: surface,
        minImageCount: num,
        imageFormat: vk::FORMAT_R8G8B8A8_UNORM,
        imageColorSpace: vk::COLORSPACE_SRGB_NONLINEAR_KHR,
        imageExtent: vk::Extent2D { width: width, height: height },
        imageArrayLayers: 1,
        imageUsage: vk::IMAGE_USAGE_COLOR_ATTACHMENT_BIT | vk::IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
        imageSharingMode: vk::SHARING_MODE_EXCLUSIVE,
        queueFamilyIndexCount: 1,
        pQueueFamilyIndices: &0,
        preTransform: vk::SURFACE_TRANSFORM_IDENTITY_BIT_KHR,
        compositeAlpha: vk::COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
        presentMode: vk::PRESENT_MODE_FIFO_RELAXED_KHR,
        clipped: vk::TRUE,
        oldSwapchain: 0,
    };

    let swapchain = unsafe {
        let mut out = mem::zeroed();
        assert_eq!(vk::SUCCESS, vk.CreateSwapchainKHR(dev, &swapchain_info, ptr::null(), &mut out));
        out
    };

    assert_eq!(vk::SUCCESS, unsafe {
        vk.GetSwapchainImagesKHR(dev, swapchain, &mut num, images.as_mut_ptr())
    });

    let mut cbuf = factory.create_command_buffer();

    let format = format::Format(format::SurfaceType::R8_G8_B8_A8, format::ChannelType::Unorm);
    let targets = images[.. num as usize].iter().map(|image| {
        use gfx_core::factory::Typed;
        cbuf.image_barrier(*image, vk::IMAGE_ASPECT_COLOR_BIT, vk::IMAGE_LAYOUT_UNDEFINED, vk::IMAGE_LAYOUT_PRESENT_SRC_KHR);
        let raw_view = factory.view_swapchain_image(*image, format, (width, height)).unwrap();
        SwapTarget {
            _image: *image,
            target: Typed::new(raw_view),
            _fence: factory.create_fence(true),
        }
    }).collect();

    {
        use gfx_core::Device;
        device.submit(&mut cbuf);
    }

    let win = Window {
        connection: conn,
        _foreground: foreground,
        window: window,
        swapchain: swapchain,
        targets: targets,
        queue: device,
    };
    (win, factory)
}
<commit_msg>[vk] validation layers support<commit_after>// Copyright 2016 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

extern crate winit;
extern crate xcb;
extern crate vk_sys as vk;
extern crate gfx_core;
extern crate gfx_device_vulkan;

use std::ffi::CStr;
use std::{mem, ptr};
use std::os::raw;
use gfx_core::format;

pub fn init_winit(builder: winit::WindowBuilder) -> (winit::Window, gfx_device_vulkan::GraphicsQueue, gfx_device_vulkan::Factory) {
    let (device, factory, _backend) = gfx_device_vulkan::create(&builder.window.title, 1, &[],
        &["VK_KHR_surface", "VK_KHR_xcb_surface"], &["VK_KHR_swapchain"]);
    let win = builder.build().unwrap();
    (win, device, factory)
}

pub type TargetHandle = gfx_core::handle::RenderTargetView<gfx_device_vulkan::Resources, format::Rgba8>;

pub struct SwapTarget {
    _image: vk::Image,
    target: TargetHandle,
    _fence: vk::Fence,
}

pub struct Window {
    connection: xcb::Connection,
    _foreground: u32,
    window: u32,
    _debug_callback: Option<vk::DebugReportCallbackEXT>,
    swapchain: vk::SwapchainKHR,
    targets: Vec<SwapTarget>,
    queue: gfx_device_vulkan::GraphicsQueue,
}

pub struct Frame<'a> {
    window: &'a mut Window,
    target_id: u32,
}

impl<'a> Frame<'a> {
    pub fn get_target(&self) -> TargetHandle {
        self.window.targets[self.target_id as usize].target.clone()
    }
    pub fn get_queue(&mut self) -> &mut gfx_device_vulkan::GraphicsQueue {
        &mut self.window.queue
    }
}

impl<'a> Drop for Frame<'a> {
    fn drop(&mut self) {
        let mut result = vk::SUCCESS;
        let info = vk::PresentInfoKHR {
            sType: vk::STRUCTURE_TYPE_PRESENT_INFO_KHR,
            pNext: ptr::null(),
            waitSemaphoreCount: 0,
            pWaitSemaphores: ptr::null(),
            swapchainCount: 1,
            pSwapchains: &self.window.swapchain,
            pImageIndices: &self.target_id,
            pResults: &mut result,
        };
        let (_dev, vk) = self.window.queue.get_share().get_device();
        unsafe {
            vk.QueuePresentKHR(self.window.queue.get_queue(), &info);
        }
        assert_eq!(vk::SUCCESS, result);
    }
}

impl Window {
    pub fn wait_draw(&mut self) -> Result<Option<Frame>, ()> {
        let ev = match self.connection.wait_for_event() {
            Some(ev) => ev,
            None => return Err(()),
        };
        //self.connection.flush();
        match ev.response_type() & 0x7F {
            xcb::EXPOSE => Ok(Some(self.start_frame())),
            xcb::KEY_PRESS => Err(()),
            _ => Ok(None)
        }
    }

    pub fn start_frame(&mut self) -> Frame {
        //TODO: handle window resize
        let index = unsafe {
            let (dev, vk) = self.queue.get_share().get_device();
            let mut i = 0;
            assert_eq!(vk::SUCCESS, vk.AcquireNextImageKHR(dev, self.swapchain, 60, 0, 0, &mut i));
            i
        };
        Frame {
            window: self,
            target_id: index,
        }
    }
}

impl Drop for Window {
    fn drop(&mut self) {
        xcb::unmap_window(&self.connection, self.window);
        xcb::destroy_window(&self.connection, self.window);
        self.connection.flush();
    }
}

const LAYERS: &'static [&'static str] = &[
];
const LAYERS_DEBUG: &'static [&'static str] = &[
    "VK_LAYER_LUNARG_standard_validation",
];
const EXTENSIONS: &'static [&'static str] = &[
    "VK_KHR_surface",
    "VK_KHR_xcb_surface",
];
const EXTENSIONS_DEBUG: &'static [&'static str] = &[
    "VK_KHR_surface",
    "VK_KHR_xcb_surface",
    "VK_EXT_debug_report",
];
const DEV_EXTENSIONS: &'static [&'static str] = &[
    "VK_KHR_swapchain",
];

extern "system" fn callback(flags: vk::DebugReportFlagsEXT,
                            _ob_type: vk::DebugReportObjectTypeEXT, _object: u64, _location: usize,
                            _msg_code: i32, layer_prefix_c: *const raw::c_char,
                            description_c: *const raw::c_char, _user_data: *mut raw::c_void) -> u32
{
    let layer_prefix = unsafe { CStr::from_ptr(layer_prefix_c) }.to_str().unwrap();
    let description  = unsafe { CStr::from_ptr(description_c)  }.to_str().unwrap();
    println!("Vk flags {:x} in layer {}: {}", flags, layer_prefix, description);
    vk::FALSE
}

pub fn init_xcb(title: &str, width: u32, height: u32) -> (Window, gfx_device_vulkan::Factory) {
    let debug = true;
    let (mut device, mut factory, backend) = gfx_device_vulkan::create(title, 1,
        if debug {LAYERS_DEBUG} else {LAYERS},
        if debug {EXTENSIONS_DEBUG} else {EXTENSIONS},
        DEV_EXTENSIONS);

    let debug_callback = if debug {
        let info = vk::DebugReportCallbackCreateInfoEXT {
            sType: vk::STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT,
            pNext: ptr::null(),
            flags: vk::DEBUG_REPORT_INFORMATION_BIT_EXT | vk::DEBUG_REPORT_WARNING_BIT_EXT |
                   vk::DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT | vk::DEBUG_REPORT_ERROR_BIT_EXT |
                   vk::DEBUG_REPORT_DEBUG_BIT_EXT,
            pfnCallback: callback,
            pUserData: ptr::null_mut(),
        };
        let (inst, vk) = backend.get_instance();
        Some(unsafe {
            let mut out = mem::zeroed();
            assert_eq!(vk::SUCCESS, vk.CreateDebugReportCallbackEXT(inst, &info, ptr::null(), &mut out));
            out
        })
    }else {
        None
    };

    let (conn, screen_num) = xcb::Connection::connect(None).unwrap();
    let (window, foreground) = {
        let setup = conn.get_setup();
        let screen = setup.roots().nth(screen_num as usize).unwrap();

        let foreground = conn.generate_id();
        xcb::create_gc(&conn, foreground, screen.root(), &[
                (xcb::GC_FOREGROUND, screen.black_pixel()),
                (xcb::GC_GRAPHICS_EXPOSURES, 0),
        ]);

        let win = conn.generate_id();
        xcb::create_window(&conn,
            xcb::COPY_FROM_PARENT as u8,
            win,
            screen.root(),
            0, 0,
            width as u16, height as u16,
            10,
            xcb::WINDOW_CLASS_INPUT_OUTPUT as u16,
            screen.root_visual(), &[
                (xcb::CW_BACK_PIXEL, screen.black_pixel()),
                (xcb::CW_EVENT_MASK, xcb::EVENT_MASK_KEY_PRESS | xcb::EVENT_MASK_EXPOSURE),
            ]
        );
        (win, foreground)
    };

    xcb::map_window(&conn, window);
    xcb::change_property(&conn, xcb::PROP_MODE_REPLACE as u8, window,
        xcb::ATOM_WM_NAME, xcb::ATOM_STRING, 8, title.as_bytes());
    conn.flush();

    let surface = {
        let (inst, vk) = backend.get_instance();
        let info = vk::XcbSurfaceCreateInfoKHR {
            sType: vk::STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR,
            pNext: ptr::null(),
            flags: 0,
            connection: conn.get_raw_conn() as *const _,
            window: window as *const _, //HACK! TODO: fix the bindings
        };

        unsafe {
            let mut out = mem::zeroed();
            assert_eq!(vk::SUCCESS, vk.CreateXcbSurfaceKHR(inst, &info, ptr::null(), &mut out));
            out
        }
    };

    let (dev, vk) = backend.get_device();
    let mut images: [vk::Image; 2] = [0; 2];
    let mut num = images.len() as u32;

    let swapchain_info = vk::SwapchainCreateInfoKHR {
        sType: vk::STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
        pNext: ptr::null(),
        flags: 0,
        surface: surface,
        minImageCount: num,
        imageFormat: vk::FORMAT_R8G8B8A8_UNORM,
        imageColorSpace: vk::COLORSPACE_SRGB_NONLINEAR_KHR,
        imageExtent: vk::Extent2D { width: width, height: height },
        imageArrayLayers: 1,
        imageUsage: vk::IMAGE_USAGE_COLOR_ATTACHMENT_BIT | vk::IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
        imageSharingMode: vk::SHARING_MODE_EXCLUSIVE,
        queueFamilyIndexCount: 1,
        pQueueFamilyIndices: &0,
        preTransform: vk::SURFACE_TRANSFORM_IDENTITY_BIT_KHR,
        compositeAlpha: vk::COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
        presentMode: vk::PRESENT_MODE_FIFO_RELAXED_KHR,
        clipped: vk::TRUE,
        oldSwapchain: 0,
    };

    let swapchain = unsafe {
        let mut out = mem::zeroed();
        assert_eq!(vk::SUCCESS, vk.CreateSwapchainKHR(dev, &swapchain_info, ptr::null(), &mut out));
        out
    };

    assert_eq!(vk::SUCCESS, unsafe {
        vk.GetSwapchainImagesKHR(dev, swapchain, &mut num, images.as_mut_ptr())
    });

    let mut cbuf = factory.create_command_buffer();

    let format = format::Format(format::SurfaceType::R8_G8_B8_A8, format::ChannelType::Unorm);
    let targets = images[.. num as usize].iter().map(|image| {
        use gfx_core::factory::Typed;
        cbuf.image_barrier(*image, vk::IMAGE_ASPECT_COLOR_BIT, vk::IMAGE_LAYOUT_UNDEFINED, vk::IMAGE_LAYOUT_PRESENT_SRC_KHR);
        let raw_view = factory.view_swapchain_image(*image, format, (width, height)).unwrap();
        SwapTarget {
            _image: *image,
            target: Typed::new(raw_view),
            _fence: factory.create_fence(true),
        }
    }).collect();

    {
        use gfx_core::Device;
        device.submit(&mut cbuf);
    }

    let win = Window {
        connection: conn,
        _foreground: foreground,
        window: window,
        _debug_callback: debug_callback,
        swapchain: swapchain,
        targets: targets,
        queue: device,
    };
    (win, factory)
}
<|endoftext|>


<commit_before><commit_msg>Fix: Also print if output is a data pipe<commit_after><|endoftext|>


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

// run-pass
// revisions: lxl nll

#![cfg_attr(nll, feature(nll))]

struct Foo {
    x: u32
}

impl Foo {
    fn twiddle(&mut self) -> &mut Self { self }
    fn twaddle(&mut self) -> &mut Self { self }
    fn emit(&mut self) {
        self.x += 1;
    }
}

fn main() {
    let mut foo = Foo { x: 0 };
    match 22 {
        22 => &mut foo,
        44 => foo.twiddle(),
        _ => foo.twaddle(),
    }.emit();
}
<|endoftext|>


<commit_before><commit_msg>Id::transmute<commit_after><|endoftext|>


<commit_before><commit_msg>(test) Added test for failing tests.<commit_after>#![feature(phase)]
#[phase(plugin, link)]
extern crate stainless;

describe! failing {
    failing "should fail" {
        fail!("should still pass");
    }
}

<|endoftext|>


<commit_before><commit_msg>chore: enum<commit_after><|endoftext|>


<commit_before><commit_msg>ask and you shall receive<commit_after><|endoftext|>


<commit_before><commit_msg>initial code<commit_after>//! A simple and easy wrapper around `Vec` to implement a FIFO queue. This is
//! no fancy, advanced data type but something simple you can use easily until
//! or unless you need something different.
//!
//! # Example
//!
//! ```
//! use queue::Queue;
//!
//! let mut q = Queue::new();
//!
//! q.queue("hello").unwrap();
//! q.queue("out").unwrap();
//! q.queue("there!").unwrap();
//!
//! while let Some(item) = q.dequeue() {
//!     println!("{}", item);
//! }
//! ```
//!
//! Outputs:
//!
//! ```text
//! hello
//! out
//! there!
//! ```

#[cfg(test)]
mod tests;

/// A first in, first out queue built around `Vec`. An optional capacity can be
/// set (or changed) to ensure the `Queue` never grows past a certain size. If
/// the capacity is not specified (ie set to `None`) then the `Queue` will grow
/// as needed. If you're worried about memory allocation, set a capacity and
/// the necessary memory will be allocated at that time. Otherwise memory could
/// be allocated, deallocated and reallocated as the queue changes size. The
/// only requirement of the type used is that it implements the `Clone` trait.
#[derive(Clone, Debug)]
pub struct Queue<T> {
	vec: Vec<T>,
	cap: Option<usize>,
}

impl<T: Clone> Queue<T> {
	/// Constructs a new `Queue<T>`.
	///
	/// # Example
	///
	/// ```
	/// # use queue::Queue;
	/// let mut q: Queue<String> = Queue::new();
	/// ```
	pub fn new() -> Queue<T> {
		Queue {
			vec: Vec::new(),
			cap: None,
		}
	}

	/// Constructs a new `Queue<T>` with a specified capacity.
	///
	/// # Example
	///
	/// ```
	/// # use queue::Queue;
	/// let mut q: Queue<String> = Queue::with_capacity(20);
	/// ```
	pub fn with_capacity(cap: usize) -> Queue<T> {
		Queue {
			vec: Vec::with_capacity(cap),
			cap: Some(cap),
		}
	}

	/// Add an item to the end of the `Queue`. Returns `Ok(usize)` with the new
	/// length of the `Queue`, or `Err(())` if there is no more room.
	///
	/// # Example
	///
	/// ```
	/// # use queue::Queue;
	/// let mut q = Queue::new();
	/// q.queue("hello").unwrap();
	/// assert_eq!(q.peek(), Some("hello"));
	/// ```
	pub fn queue(&mut self, item: T) -> Result<usize, ()> {
		if let Some(cap) = self.cap {
			if self.vec.len() >= cap {
				Err(())
			} else {
				self.vec.push(item);
				Ok(self.vec.len())
			}
		} else {
			self.vec.push(item);
			Ok(self.vec.len())
		}
	}

	/// Remove the next item from the `Queue`. Returns `Option<T>` so it will
	/// return either `Some(T)` or `None` depending on if there's anything in
	/// the `Queue` to get.
	///
	/// # Example
	///
	/// ```
	/// # use queue::Queue;
	/// let mut q = Queue::new();
	/// q.queue("hello").unwrap();
	/// q.queue("world").unwrap();
	/// assert_eq!(q.dequeue(), Some("hello"));
	/// ```
	pub fn dequeue(&mut self) -> Option<T> {
		if self.vec.len() > 0 {
			Some(self.vec.remove(0))
		} else {
			None
		}
	}

	/// Peek at the next item in the `Queue`, if there's something there.
	///
	/// # Example
	///
	/// ```
	/// # use queue::Queue;
	/// let mut q = Queue::new();
	/// q.queue(12).unwrap();
	/// assert_eq!(q.peek(), Some(12));
	/// ```
	pub fn peek(&self) -> Option<T> {
		if self.vec.len() > 0 {
			Some(self.vec[0].clone())
		} else {
			None
		}
	}

	/// The number of items currently in the `Queue`.
	///
	/// # Example
	///
	/// ```
	/// # use queue::Queue;
	/// let mut q = Queue::with_capacity(8);
	/// q.queue(1).unwrap();
	/// q.queue(2).unwrap();
	/// assert_eq!(q.len(), 2);
	/// ```
	pub fn len(&self) -> usize {
		self.vec.len()
	}

	/// Query the capacity for a `Queue`. If there is no capacity set (the
	/// `Queue` can grow as needed) then `None` will be returned, otherwise
	/// it will be `Some(usize)`.
	///
	/// # Example
	///
	/// ```
	/// # use queue::Queue;
	/// let q: Queue<u8> = Queue::with_capacity(12);
	/// assert_eq!(q.capacity(), Some(12));
	/// ```
	pub fn capacity(&self) -> Option<usize> {
		self.cap
	}

	/// Modify the capacity of a `Queue`. If set to `None`, the `Queue` will
	/// grow automatically, as needed. Otherwise, it will be limited to the
	/// specified number of items. If there are more items in the `Queue` than
	/// the requested capacity, `Err(())` will be returned, otherwise the
	/// operation will succeed and `Ok(())` will be returned. If the capacity
	/// is shrunk, the underlying `Vec` will be shrunk also, which would free
	/// up whatever extra memory was allocated for the `Queue`.
	///
	/// # Example
	///
	/// ```
	/// # use queue::Queue;
	/// let mut q: Queue<u8> = Queue::new();
	/// q.set_capacity(12).unwrap();
	/// q.set_capacity(None).unwrap();
	/// ```
	pub fn set_capacity<C: Into<Option<usize>>>(&mut self, cap: C) -> Result<(), ()> {
		let cap = cap.into();

		if cap == None {
			self.cap = None;
			return Ok(());
		}

		if cap == self.cap {
			return Ok(());
		}

		let cap = cap.unwrap();

		if cap < self.vec.len() {
			return Err(());
		}

		if let Some(scap) = self.cap {
			if cap < scap {
				self.vec.shrink_to_fit();
			}
		}

		let r = cap - self.vec.len();
		self.vec.reserve_exact(r);
		self.cap = Some(cap);

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


<commit_before><commit_msg>Added tests to ensure that rectangle side methods return valid lines<commit_after><|endoftext|>


<commit_before><commit_msg>Simplifying the bitmap header decoding.<commit_after><|endoftext|>


<commit_before><commit_msg>(doc) Deny missing documentation.<commit_after><|endoftext|>


<commit_before><commit_msg>Update function write<commit_after><|endoftext|>


<commit_before><commit_msg>Zero extend rhs of sar imm, not sign extend<commit_after><|endoftext|>