<commit_before>// Copyright 2014 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.

#![feature(plugin, custom_attribute)]
#![plugin(gfx_macros)]

extern crate cgmath;
extern crate gfx;
extern crate gfx_window_glutin;
extern crate glutin;
extern crate time;
extern crate rand;
extern crate genmesh;
extern crate noise;

use std::fmt;
use rand::Rng;
use cgmath::FixedArray;
use cgmath::{Matrix4, Point3, Vector3};
use cgmath::{Transform, AffineMatrix3};
use gfx::traits::*;
use genmesh::{Vertices, Triangulate};
use genmesh::generators::{Plane, SharedVertex, IndexedPolygon};
use time::precise_time_s;

use noise::{Seed, perlin2};

#[vertex_format]
#[derive(Clone, Copy)]
struct Vertex {
    #[name = "a_Pos"]
    pos: [f32; 3],

    #[name = "a_Color"]
    color: [f32; 3],
}

impl fmt::Debug for Vertex {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Pos({}, {}, {})", self.pos[0], self.pos[1], self.pos[2])
    }
}

// The shader_param attribute makes sure the following struct can be used to
// pass parameters to a shader.
#[shader_param]
struct Params<R: gfx::Resources> {
    #[name = "u_Model"]
    model: [[f32; 4]; 4],

    #[name = "u_View"]
    view: [[f32; 4]; 4],

    #[name = "u_Proj"]
    proj: [[f32; 4]; 4],

    _dummy: std::marker::PhantomData<R>,
}

fn calculate_color(height: f32) -> [f32; 3] {
    if height > 8.0 {
        [0.9, 0.9, 0.9] // white
    } else if height > 0.0 {
        [0.7, 0.7, 0.7] // greay
    } else if height > -5.0 {
        [0.2, 0.7, 0.2] // green
    } else {
        [0.2, 0.2, 0.7] // blue
    }
}

pub fn main() {
    let mut canvas = gfx_window_glutin::init(glutin::Window::new().unwrap())
                                       .into_canvas();
    canvas.output.window.set_title("Terrain example");

    let rand_seed = rand::thread_rng().gen();
    let seed = Seed::new(rand_seed);
    let plane = Plane::subdivide(256, 256);
    let vertex_data: Vec<Vertex> = plane.shared_vertex_iter()
        .map(|(x, y)| {
            let h = perlin2(&seed, &[x, y]) * 32.0;
            Vertex {
                pos: [25.0 * x, 25.0 * y, h],
                color: calculate_color(h),
            }
        })
        .collect();

    let index_data: Vec<u32> = plane.indexed_polygon_iter()
        .triangulate()
        .vertices()
        .map(|i| i as u32)
        .collect();

    let slice = canvas.factory
        .create_buffer_index::<u32>(&index_data)
        .to_slice(gfx::PrimitiveType::TriangleList);

    let mesh = canvas.factory.create_mesh(&vertex_data);
    let program = {
        let vs = gfx::ShaderSource {
            glsl_120: Some(include_bytes!("terrain_120.glslv")),
            glsl_150: Some(include_bytes!("terrain_150.glslv")),
            .. gfx::ShaderSource::empty()
        };
        let fs = gfx::ShaderSource {
            glsl_120: Some(include_bytes!("terrain_120.glslf")),
            glsl_150: Some(include_bytes!("terrain_150.glslf")),
            .. gfx::ShaderSource::empty()
        };
        canvas.factory.link_program_source(vs, fs, &canvas.device.get_capabilities())
                      .unwrap()
    };

    let state = gfx::DrawState::new().depth(gfx::state::Comparison::LessEqual, true);

    let data = Params {
        model: Matrix4::identity().into_fixed(),
        view: Matrix4::identity().into_fixed(),
        proj: cgmath::perspective(cgmath::deg(60.0f32),
                                  canvas.get_aspect_ratio(),
                                  0.1, 1000.0
                                  ).into_fixed(),
        _dummy: std::marker::PhantomData,
    };
    let mut context = gfx::batch::Context::new();
    let mut batch = context.make_batch(&program, data, &mesh, slice, &state)
                           .unwrap();

    'main: loop {
        // quit when Esc is pressed.
        for event in canvas.output.window.poll_events() {
            match event {
                glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) => break 'main,
                glutin::Event::Closed => break 'main,
                _ => {},
            }
        }

        let time = precise_time_s() as f32;
        let x = time.sin();
        let y = time.cos();
        let view: AffineMatrix3<f32> = Transform::look_at(
            &Point3::new(x * 32.0, y * 32.0, 16.0),
            &Point3::new(0.0, 0.0, 0.0),
            &Vector3::unit_z(),
        );
        batch.params.view = view.mat.into_fixed();

        canvas.clear(gfx::ClearData {
            color: [0.3, 0.3, 0.3, 1.0],
            depth: 1.0,
            stencil: 0,
        });
        canvas.draw(&(&batch, &context)).unwrap();
        canvas.present();
    }
}
<commit_msg>Fixed the terrain example<commit_after>// Copyright 2014 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 cgmath;
#[macro_use]
extern crate gfx;
extern crate gfx_window_glutin;
extern crate glutin;
extern crate time;
extern crate rand;
extern crate genmesh;
extern crate noise;

use rand::Rng;
use cgmath::FixedArray;
use cgmath::{Matrix4, Point3, Vector3};
use cgmath::{Transform, AffineMatrix3};
use gfx::traits::*;
use genmesh::{Vertices, Triangulate};
use genmesh::generators::{Plane, SharedVertex, IndexedPolygon};
use time::precise_time_s;

use noise::{Seed, perlin2};

gfx_vertex!( Vertex {
    a_Pos@ pos: [f32; 3],
    a_Color@ color: [f32; 3],
});

gfx_parameters!( Params/ParamsLink {
    u_Model@ model: [[f32; 4]; 4],
    u_View@ view: [[f32; 4]; 4],
    u_Proj@ proj: [[f32; 4]; 4],
});

fn calculate_color(height: f32) -> [f32; 3] {
    if height > 8.0 {
        [0.9, 0.9, 0.9] // white
    } else if height > 0.0 {
        [0.7, 0.7, 0.7] // greay
    } else if height > -5.0 {
        [0.2, 0.7, 0.2] // green
    } else {
        [0.2, 0.2, 0.7] // blue
    }
}

pub fn main() {
    let mut canvas = gfx_window_glutin::init(glutin::Window::new().unwrap())
                                       .into_canvas();
    canvas.output.window.set_title("Terrain example");

    let rand_seed = rand::thread_rng().gen();
    let seed = Seed::new(rand_seed);
    let plane = Plane::subdivide(256, 256);
    let vertex_data: Vec<Vertex> = plane.shared_vertex_iter()
        .map(|(x, y)| {
            let h = perlin2(&seed, &[x, y]) * 32.0;
            Vertex {
                pos: [25.0 * x, 25.0 * y, h],
                color: calculate_color(h),
            }
        })
        .collect();

    let index_data: Vec<u32> = plane.indexed_polygon_iter()
        .triangulate()
        .vertices()
        .map(|i| i as u32)
        .collect();

    let slice = canvas.factory
        .create_buffer_index::<u32>(&index_data)
        .to_slice(gfx::PrimitiveType::TriangleList);

    let mesh = canvas.factory.create_mesh(&vertex_data);
    let program = {
        let vs = gfx::ShaderSource {
            glsl_120: Some(include_bytes!("terrain_120.glslv")),
            glsl_150: Some(include_bytes!("terrain_150.glslv")),
            .. gfx::ShaderSource::empty()
        };
        let fs = gfx::ShaderSource {
            glsl_120: Some(include_bytes!("terrain_120.glslf")),
            glsl_150: Some(include_bytes!("terrain_150.glslf")),
            .. gfx::ShaderSource::empty()
        };
        canvas.factory.link_program_source(vs, fs, &canvas.device.get_capabilities())
                      .unwrap()
    };

    let state = gfx::DrawState::new().depth(gfx::state::Comparison::LessEqual, true);

    let data = Params {
        model: Matrix4::identity().into_fixed(),
        view: Matrix4::identity().into_fixed(),
        proj: cgmath::perspective(cgmath::deg(60.0f32),
                                  canvas.get_aspect_ratio(),
                                  0.1, 1000.0
                                  ).into_fixed(),
        _r: std::marker::PhantomData,
    };
    let mut context = gfx::batch::Context::new();
    let mut batch = context.make_batch(&program, data, &mesh, slice, &state)
                           .unwrap();

    'main: loop {
        // quit when Esc is pressed.
        for event in canvas.output.window.poll_events() {
            match event {
                glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) => break 'main,
                glutin::Event::Closed => break 'main,
                _ => {},
            }
        }

        let time = precise_time_s() as f32;
        let x = time.sin();
        let y = time.cos();
        let view: AffineMatrix3<f32> = Transform::look_at(
            &Point3::new(x * 32.0, y * 32.0, 16.0),
            &Point3::new(0.0, 0.0, 0.0),
            &Vector3::unit_z(),
        );
        batch.params.view = view.mat.into_fixed();

        canvas.clear(gfx::ClearData {
            color: [0.3, 0.3, 0.3, 1.0],
            depth: 1.0,
            stencil: 0,
        });
        canvas.draw(&(&batch, &context)).unwrap();
        canvas.present();
    }
}
<|endoftext|>


<commit_before><commit_msg>xenstore structs<commit_after>#[repr(u32)]
enum xsd_sockmsg_type {
    Debug       = 0,
    Directory   = 1,
    Read        = 2,
    GetPerms    = 3,
    Watch       = 4,
    Unwatch     = 5,
    TransactionStart = 6,
    TransactionEnd = 7,
    Introduce   = 8,
    Release     = 9,
    GetDomainPath = 10,
    Write       = 11,
    Mkdir       = 12,
    Rm          = 13,
    SetPerms    = 14,
    WatchEvent  = 15,
    Error       = 16,
    IsDomainIntroduced = 17,
    Resume      = 18,
    SetTarget   = 19,
    Restrict    = 20,
    ResetWatches  = 21,

    Invalid     = 0xffff /* Guaranteed to remain an invalid type */
}

struct xsd_sockmsg {
    _type: xsd_sockmsg_type,
    req_id: u32,
    tx_id: u32,
    len: u32
}
<|endoftext|>


<commit_before><commit_msg>An attempt at a macro to support HTML literals<commit_after>// A test of the macro system. Can we do HTML literals?

// xfail-pretty
// xfail-test

macro_rules! html {
    { $($body:tt)* } => {
        let builder = HTMLBuilder();
        build_html!{builder := $($body)*};
        builder.getDoc()
    }
}

macro_rules! build_html {
    { $builder:expr := </$tag:ident> $($rest:tt)* } => {
        $builder.endTag(stringify!($tag));
        build_html!{ $builder := $($rest)* };
    };

    { $builder:expr := <$tag:ident> $($rest:tt)* } => {
        $builder.beginTag(stringify!($tag));
        build_html!{ $builder := $($rest)* };
    };

    { $builder:expr := . $($rest:tt)* } => {
        $builder.addText(~".");
        build_html!{ $builder := $($rest)* };
    };

    { $builder:expr := $word:ident $($rest:tt)* } => {
        $builder.addText(stringify!($word));
        build_html!{ $builder := $($rest)* };
    };

    { $builder:expr := } => { }
}

fn main() {

    let page = html! {

            <title>This is the title.</title>

This is some text

    };

    // When we can do this, we are successful:
    //
    //let page = tag(~"html", ~[tag(~"head", ~[...])])

}

enum HTMLFragment {
}

struct HTMLBuilder {
    bar: ();
    fn getDoc() -> HTMLFragment { fail }
    fn beginTag(tag: ~str) { }
    fn endTag(tag: ~str) { }
    fn addText(test: ~str) { }
}

fn HTMLBuilder() -> HTMLBuilder {
    HTMLBuilder { bar: () }
}<|endoftext|>


<commit_before><commit_msg>user input and output functionality added<commit_after><|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.

use std::{mem, ptr};
use vk;
use gfx_core::{self as core, draw, pso, shade, target, tex};
use gfx_core::state::RefValues;
use gfx_core::{IndexType, VertexCount};
use native;
use {Resources, Share, SharePointer};

pub struct Buffer {
    inner: vk::CommandBuffer,
    family: u32,
    share: SharePointer,
}

impl Buffer {
    #[doc(hidden)]
    pub fn new(b: vk::CommandBuffer, f: u32, s: SharePointer) -> Buffer {
        Buffer {
            inner: b,
            family: f,
            share: s,
        }
    }
}

impl Drop for Buffer {
    fn drop(&mut self) {
        //TODO
    }
}

impl Buffer {
    pub fn image_barrier(&mut self, image: vk::Image, aspect: vk::ImageAspectFlags,
                         old_layout: vk::ImageLayout, new_layout: vk::ImageLayout) {
        let barrier = vk::ImageMemoryBarrier {
            sType: vk::STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
            pNext: ptr::null(),
            srcAccessMask: if old_layout == vk::IMAGE_LAYOUT_PREINITIALIZED || new_layout == vk::IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL {
                vk::ACCESS_HOST_WRITE_BIT | vk::ACCESS_TRANSFER_WRITE_BIT
            } else {0},
            dstAccessMask: match new_layout {
                vk::IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL | vk::IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL =>
                    vk::ACCESS_TRANSFER_READ_BIT | vk::ACCESS_HOST_WRITE_BIT | vk::ACCESS_TRANSFER_WRITE_BIT,
                vk::IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL => vk::ACCESS_SHADER_READ_BIT,
                _ => 0,
            },
            oldLayout: old_layout,
            newLayout: new_layout,
            srcQueueFamilyIndex: self.family,
            dstQueueFamilyIndex: self.family,
            image: image,
            subresourceRange: vk::ImageSubresourceRange {
                aspectMask: aspect,
                baseMipLevel: 0,
                levelCount: 1,
                baseArrayLayer: 0,
                layerCount: 1,
            },
        };
        let (_dev, vk) = self.share.get_device();
        unsafe {
            vk.CmdPipelineBarrier(self.inner,
                vk::PIPELINE_STAGE_TOP_OF_PIPE_BIT, vk::PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0,
                0, ptr::null(), 0, ptr::null(), 1, &barrier);
        }
    }
}

impl draw::CommandBuffer<Resources> for Buffer {
    fn reset(&mut self) {}
    fn bind_pipeline_state(&mut self, _: native::Pipeline) {}
    fn bind_vertex_buffers(&mut self, _: pso::VertexBufferSet<Resources>) {}
    fn bind_constant_buffers(&mut self, _: &[pso::ConstantBufferParam<Resources>]) {}
    fn bind_global_constant(&mut self, _: shade::Location, _: shade::UniformValue) {}
    fn bind_resource_views(&mut self, _: &[pso::ResourceViewParam<Resources>]) {}
    fn bind_unordered_views(&mut self, _: &[pso::UnorderedViewParam<Resources>]) {}
    fn bind_samplers(&mut self, _: &[pso::SamplerParam<Resources>]) {}
    fn bind_pixel_targets(&mut self, _: pso::PixelTargetSet<Resources>) {}
    fn bind_index(&mut self, _: native::Buffer, _: IndexType) {}
    fn set_scissor(&mut self, _: target::Rect) {}
    fn set_ref_values(&mut self, _: RefValues) {}
    fn update_buffer(&mut self, _: native::Buffer, _: &[u8], _: usize) {}
    fn update_texture(&mut self, _: native::Texture, _: tex::Kind, _: Option<tex::CubeFace>,
                      _: &[u8], _: tex::RawImageInfo) {}
    fn generate_mipmap(&mut self, _: native::TextureView) {}

    fn clear_color(&mut self, tv: native::TextureView, color: draw::ClearColor) {
        let (_, vk) = self.share.get_device();
        let value = match color {
            draw::ClearColor::Float(v) => vk::ClearColorValue::float32(v),
            draw::ClearColor::Int(v)   => vk::ClearColorValue::int32(v),
            draw::ClearColor::Uint(v)  => vk::ClearColorValue::uint32(v),
        };
        unsafe {
            vk.CmdClearColorImage(self.inner, tv.image, tv.layout, &value, 1, &tv.sub_range);
        }
    }

    fn clear_depth_stencil(&mut self, _: native::TextureView, _: Option<target::Depth>,
                           _: Option<target::Stencil>) {}

    fn call_draw(&mut self, _: VertexCount, _: VertexCount, _: draw::InstanceOption) {}
    fn call_draw_indexed(&mut self, _: VertexCount, _: VertexCount,
                         _: VertexCount, _: draw::InstanceOption) {}
}

pub struct GraphicsQueue {
    share: SharePointer,
    family: u32,
    queue: vk::Queue,
    capabilities: core::Capabilities,
}

impl GraphicsQueue {
    #[doc(hidden)]
    pub fn new(share: SharePointer, q: vk::Queue, qf_id: u32) -> GraphicsQueue {
        let caps = core::Capabilities {
            max_vertex_count: 0,
            max_index_count: 0,
            max_texture_size: 0,
            instance_base_supported: false,
            instance_call_supported: false,
            instance_rate_supported: false,
            vertex_base_supported: false,
            srgb_color_supported: false,
            constant_buffer_supported: false,
            unordered_access_view_supported: false,
            separate_blending_slots_supported: false,
        };
        GraphicsQueue {
            share: share,
            family: qf_id,
            queue: q,
            capabilities: caps,
        }
    }
    #[doc(hidden)]
    pub fn get_share(&self) -> &Share {
        &self.share
    }
    #[doc(hidden)]
    pub fn get_queue(&self) -> vk::Queue {
        self.queue
    }
}

impl core::Device for GraphicsQueue {
    type Resources = Resources;
    type CommandBuffer = Buffer;

    fn get_capabilities(&self) -> &core::Capabilities {
        &self.capabilities
    }

    fn pin_submitted_resources(&mut self, _: &core::handle::Manager<Resources>) {}

    fn submit(&mut self, com: &mut Buffer) {
        assert_eq!(self.family, com.family);
        let (_, vk) = self.share.get_device();
        assert_eq!(vk::SUCCESS, unsafe {
            vk.EndCommandBuffer(com.inner)
        });
        let submit_info = vk::SubmitInfo {
            sType: vk::STRUCTURE_TYPE_SUBMIT_INFO,
            commandBufferCount: 1,
            pCommandBuffers: &com.inner,
            .. unsafe { mem::zeroed() }
        };
        assert_eq!(vk::SUCCESS, unsafe {
            vk.QueueSubmit(self.queue, 1, &submit_info, 0)
        });
        let begin_info = vk::CommandBufferBeginInfo {
            sType: vk::STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
            pNext: ptr::null(),
            flags: 0,
            pInheritanceInfo: ptr::null(),
        };
        assert_eq!(vk::SUCCESS, unsafe {
            vk.BeginCommandBuffer(com.inner, &begin_info)
        });
    }

    //note: this should really live elsewhere (Factory?)
    fn cleanup(&mut self) {
        let (dev, mut functions) = self.share.get_device();
        use gfx_core::handle::Producer;
        //self.frame_handles.clear();
        self.share.handles.borrow_mut().clean_with(&mut functions,
            |vk, b| unsafe { //buffer
                vk.DestroyBuffer(dev, b.buffer, ptr::null());
                vk.FreeMemory(dev, b.memory, ptr::null());
            },
            |vk, s| unsafe { //shader
                vk.DestroyShaderModule(dev, *s, ptr::null());
            },
            |_, _p| (), //program
            |vk, p| unsafe { //PSO
                vk.DestroyPipeline(dev, p.pipeline, ptr::null());
                vk.DestroyPipelineLayout(dev, p.pipe_layout, ptr::null());
                vk.DestroyDescriptorSetLayout(dev, p.desc_layout, ptr::null());
                vk.DestroyDescriptorPool(dev, p.desc_pool, ptr::null());
            },
            |vk, t| if t.memory != 0 {unsafe { //texture
                vk.DestroyImage(dev, t.image, ptr::null());
                vk.FreeMemory(dev, t.memory, ptr::null());
            }},
            |vk, v| unsafe { //SRV
                vk.DestroyImageView(dev, v.view, ptr::null());
            },
            |_, _| (), //UAV
            |vk, v| unsafe { //RTV
                vk.DestroyImageView(dev, v.view, ptr::null());
            },
            |_, _v| (), //DSV
            |_, _v| (), //sampler
            |_, _| (), //fence
        );
    }
}
<commit_msg>[vk] depth-stencil clears and view destruction<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.

use std::{mem, ptr};
use vk;
use gfx_core::{self as core, draw, pso, shade, target, tex};
use gfx_core::state::RefValues;
use gfx_core::{IndexType, VertexCount};
use native;
use {Resources, Share, SharePointer};

pub struct Buffer {
    inner: vk::CommandBuffer,
    family: u32,
    share: SharePointer,
}

impl Buffer {
    #[doc(hidden)]
    pub fn new(b: vk::CommandBuffer, f: u32, s: SharePointer) -> Buffer {
        Buffer {
            inner: b,
            family: f,
            share: s,
        }
    }
}

impl Drop for Buffer {
    fn drop(&mut self) {
        //TODO
    }
}

impl Buffer {
    pub fn image_barrier(&mut self, image: vk::Image, aspect: vk::ImageAspectFlags,
                         old_layout: vk::ImageLayout, new_layout: vk::ImageLayout) {
        let barrier = vk::ImageMemoryBarrier {
            sType: vk::STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
            pNext: ptr::null(),
            srcAccessMask: if old_layout == vk::IMAGE_LAYOUT_PREINITIALIZED || new_layout == vk::IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL {
                vk::ACCESS_HOST_WRITE_BIT | vk::ACCESS_TRANSFER_WRITE_BIT
            } else {0},
            dstAccessMask: match new_layout {
                vk::IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL | vk::IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL =>
                    vk::ACCESS_TRANSFER_READ_BIT | vk::ACCESS_HOST_WRITE_BIT | vk::ACCESS_TRANSFER_WRITE_BIT,
                vk::IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL => vk::ACCESS_SHADER_READ_BIT,
                _ => 0,
            },
            oldLayout: old_layout,
            newLayout: new_layout,
            srcQueueFamilyIndex: self.family,
            dstQueueFamilyIndex: self.family,
            image: image,
            subresourceRange: vk::ImageSubresourceRange {
                aspectMask: aspect,
                baseMipLevel: 0,
                levelCount: 1,
                baseArrayLayer: 0,
                layerCount: 1,
            },
        };
        let (_dev, vk) = self.share.get_device();
        unsafe {
            vk.CmdPipelineBarrier(self.inner,
                vk::PIPELINE_STAGE_TOP_OF_PIPE_BIT, vk::PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0,
                0, ptr::null(), 0, ptr::null(), 1, &barrier);
        }
    }
}

impl draw::CommandBuffer<Resources> for Buffer {
    fn reset(&mut self) {}
    fn bind_pipeline_state(&mut self, _: native::Pipeline) {}
    fn bind_vertex_buffers(&mut self, _: pso::VertexBufferSet<Resources>) {}
    fn bind_constant_buffers(&mut self, _: &[pso::ConstantBufferParam<Resources>]) {}
    fn bind_global_constant(&mut self, _: shade::Location, _: shade::UniformValue) {}
    fn bind_resource_views(&mut self, _: &[pso::ResourceViewParam<Resources>]) {}
    fn bind_unordered_views(&mut self, _: &[pso::UnorderedViewParam<Resources>]) {}
    fn bind_samplers(&mut self, _: &[pso::SamplerParam<Resources>]) {}
    fn bind_pixel_targets(&mut self, _: pso::PixelTargetSet<Resources>) {}
    fn bind_index(&mut self, _: native::Buffer, _: IndexType) {}
    fn set_scissor(&mut self, _: target::Rect) {}
    fn set_ref_values(&mut self, _: RefValues) {}
    fn update_buffer(&mut self, _: native::Buffer, _: &[u8], _: usize) {}
    fn update_texture(&mut self, _: native::Texture, _: tex::Kind, _: Option<tex::CubeFace>,
                      _: &[u8], _: tex::RawImageInfo) {}
    fn generate_mipmap(&mut self, _: native::TextureView) {}

    fn clear_color(&mut self, tv: native::TextureView, color: draw::ClearColor) {
        let (_, vk) = self.share.get_device();
        let value = match color {
            draw::ClearColor::Float(v) => vk::ClearColorValue::float32(v),
            draw::ClearColor::Int(v)   => vk::ClearColorValue::int32(v),
            draw::ClearColor::Uint(v)  => vk::ClearColorValue::uint32(v),
        };
        unsafe {
            vk.CmdClearColorImage(self.inner, tv.image, tv.layout, &value, 1, &tv.sub_range);
        }
    }

    fn clear_depth_stencil(&mut self, tv: native::TextureView, depth: Option<target::Depth>,
                           stencil: Option<target::Stencil>) {
        let (_, vk) = self.share.get_device();
        let value = vk::ClearDepthStencilValue {
            depth: depth.unwrap_or(1.0), //TODO
            stencil: stencil.unwrap_or(0) as u32, //TODO
        };
        unsafe {
            vk.CmdClearDepthStencilImage(self.inner, tv.image, tv.layout, &value, 1, &tv.sub_range);
        }
    }

    fn call_draw(&mut self, _: VertexCount, _: VertexCount, _: draw::InstanceOption) {}
    fn call_draw_indexed(&mut self, _: VertexCount, _: VertexCount,
                         _: VertexCount, _: draw::InstanceOption) {}
}

pub struct GraphicsQueue {
    share: SharePointer,
    family: u32,
    queue: vk::Queue,
    capabilities: core::Capabilities,
}

impl GraphicsQueue {
    #[doc(hidden)]
    pub fn new(share: SharePointer, q: vk::Queue, qf_id: u32) -> GraphicsQueue {
        let caps = core::Capabilities {
            max_vertex_count: 0,
            max_index_count: 0,
            max_texture_size: 0,
            instance_base_supported: false,
            instance_call_supported: false,
            instance_rate_supported: false,
            vertex_base_supported: false,
            srgb_color_supported: false,
            constant_buffer_supported: false,
            unordered_access_view_supported: false,
            separate_blending_slots_supported: false,
        };
        GraphicsQueue {
            share: share,
            family: qf_id,
            queue: q,
            capabilities: caps,
        }
    }
    #[doc(hidden)]
    pub fn get_share(&self) -> &Share {
        &self.share
    }
    #[doc(hidden)]
    pub fn get_queue(&self) -> vk::Queue {
        self.queue
    }
}

impl core::Device for GraphicsQueue {
    type Resources = Resources;
    type CommandBuffer = Buffer;

    fn get_capabilities(&self) -> &core::Capabilities {
        &self.capabilities
    }

    fn pin_submitted_resources(&mut self, _: &core::handle::Manager<Resources>) {}

    fn submit(&mut self, com: &mut Buffer) {
        assert_eq!(self.family, com.family);
        let (_, vk) = self.share.get_device();
        assert_eq!(vk::SUCCESS, unsafe {
            vk.EndCommandBuffer(com.inner)
        });
        let submit_info = vk::SubmitInfo {
            sType: vk::STRUCTURE_TYPE_SUBMIT_INFO,
            commandBufferCount: 1,
            pCommandBuffers: &com.inner,
            .. unsafe { mem::zeroed() }
        };
        assert_eq!(vk::SUCCESS, unsafe {
            vk.QueueSubmit(self.queue, 1, &submit_info, 0)
        });
        let begin_info = vk::CommandBufferBeginInfo {
            sType: vk::STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
            pNext: ptr::null(),
            flags: 0,
            pInheritanceInfo: ptr::null(),
        };
        assert_eq!(vk::SUCCESS, unsafe {
            vk.BeginCommandBuffer(com.inner, &begin_info)
        });
    }

    //note: this should really live elsewhere (Factory?)
    fn cleanup(&mut self) {
        let (dev, mut functions) = self.share.get_device();
        use gfx_core::handle::Producer;
        //self.frame_handles.clear();
        self.share.handles.borrow_mut().clean_with(&mut functions,
            |vk, b| unsafe { //buffer
                vk.DestroyBuffer(dev, b.buffer, ptr::null());
                vk.FreeMemory(dev, b.memory, ptr::null());
            },
            |vk, s| unsafe { //shader
                vk.DestroyShaderModule(dev, *s, ptr::null());
            },
            |_, _p| (), //program
            |vk, p| unsafe { //PSO
                vk.DestroyPipeline(dev, p.pipeline, ptr::null());
                vk.DestroyPipelineLayout(dev, p.pipe_layout, ptr::null());
                vk.DestroyDescriptorSetLayout(dev, p.desc_layout, ptr::null());
                vk.DestroyDescriptorPool(dev, p.desc_pool, ptr::null());
            },
            |vk, t| if t.memory != 0 {unsafe { //texture
                vk.DestroyImage(dev, t.image, ptr::null());
                vk.FreeMemory(dev, t.memory, ptr::null());
            }},
            |vk, v| unsafe { //SRV
                vk.DestroyImageView(dev, v.view, ptr::null());
            },
            |_, _| (), //UAV
            |vk, v| unsafe { //RTV
                vk.DestroyImageView(dev, v.view, ptr::null());
            },
            |vk, v| unsafe { //DSV
                vk.DestroyImageView(dev, v.view, ptr::null());
            },
            |_, _v| (), //sampler
            |_, _| (), //fence
        );
    }
}
<|endoftext|>


<commit_before><commit_msg>Add an example for (un-)grabbing the mouse cursor<commit_after>#[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;

extern crate glutin;

use glutin::{Event, ElementState};

mod support;

#[cfg(target_os = "android")]
android_start!(main);

#[cfg(not(feature = "window"))]
fn main() { println!("This example requires glutin to be compiled with the `window` feature"); }

#[cfg(feature = "window")]
fn main() {

    let window = glutin::Window::new().unwrap();
    window.set_title("glutin - Cursor grabbing test");
    unsafe { window.make_current() };

    let context = support::load(&window);
    let mut grabbed = false;

    while !window.is_closed() {
        context.draw_frame((0.0, 1.0, 0.0, 1.0));
        window.swap_buffers();

        for event in window.poll_events() {
            match event {
                Event::KeyboardInput(ElementState::Pressed, _, _) => {
                    if grabbed {
                        grabbed = false;
                        window.ungrab_cursor();
                    }
                    else {
                        grabbed = true;
                        window.grab_cursor().ok().expect("could not grab mouse cursor");
                    }
                },
                _ => (),
            }

        }

    }
}

<|endoftext|>


<commit_before><commit_msg>Implement a generic duplicate module that will be used for checking rule and Rust items duplication. It also generates a map<Ident, Item>.<commit_after>// Copyright 2014 Pierre Talbot (IRCAM)

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

pub use rust::{ExtCtxt,Span};
pub use rust;
pub use identifier::*;
pub use std::collections::HashMap;
pub use monad::partial::Partial;

use middle::semantics::ast::*;
use monad::partial::Partial::*;

pub trait ItemIdent {
  fn ident(&self) -> Ident;
}

pub trait ItemSpan {
  fn span(&self) -> Span;
}

impl ItemIdent for rust::Item {
  fn ident(&self) -> Ident {
    self.ident.clone()
  }
}

impl ItemSpan for rust::Item {
  fn span(&self) -> Span {
    self.span.clone()
  }
}

impl<InnerItem: ItemIdent> ItemIdent for rust::P<InnerItem> {
  fn ident(&self) -> Ident {
    self.deref().ident()
  }
}

impl<InnerItem: ItemSpan> ItemSpan for rust::P<InnerItem> {
  fn span(&self) -> Span {
    self.deref().span()
  }
}

impl ItemIdent for Rule {
  fn ident(&self) -> Ident {
    self.name.node.clone()
  }
}

impl ItemSpan for Rule {
  fn span(&self) -> Span {
    self.name.span.clone()
  }
}

pub struct DuplicateItem<'a, Item>
{
  cx: &'a ExtCtxt<'a>,
  items: HashMap<Ident, Item>,
  has_duplicate: bool,
  what_is_duplicate: String
}

impl<'a, Item: ItemIdent + ItemSpan> DuplicateItem<'a, Item>
{
  pub fn analyse<ItemIter: Iterator<Item>>(cx: &'a ExtCtxt<'a>, iter: ItemIter, item_kind: String) -> Partial<HashMap<Ident, Item>>
  {
    let (min_size, _) = iter.size_hint();
    DuplicateItem {
      cx: cx,
      items: HashMap::with_capacity(min_size),
      has_duplicate: false,
      what_is_duplicate: item_kind
    }.populate(iter)
     .make()
  }

  fn populate<ItemIter: Iterator<Item>>(mut self, iter: ItemIter) -> DuplicateItem<'a, Item>
  {
    let mut iter = iter;
    for item in iter {
      let ident = item.ident();
      if self.items.contains_key(&ident) {
        self.duplicate_items(self.items.get(&ident).unwrap(), item);
        self.has_duplicate = true;
      } else {
        self.items.insert(ident, item);
      }
    }
    self
  }

  fn duplicate_items(&self, pre: &Item, current: Item)
  {
    self.cx.span_err(current.span(), format!(
      "duplicate definition of {} `{}`",
      self.what_is_duplicate, current.ident()).as_slice());
    self.cx.span_note(pre.span(), format!(
      "previous definition of {} `{}` here",
      self.what_is_duplicate, pre.ident()).as_slice());
  }

  fn make(self) -> Partial<HashMap<Ident, Item>>
  {
    if self.has_duplicate {
      Fake(self.items)
    } else {
      Value(self.items)
    }
  }
}<|endoftext|>


<commit_before>// A raw test of vector appending performance.

use std;
import dvec::{dvec, extensions};
import io::writer_util;

fn collect_raw(num: uint) -> [uint] {
    let mut result = [];
    for uint::range(0u, num) { |i|
        //result += [i];
        vec::push(result, i);
        //result = vec::append(result, [i]);
    }
    ret result;
}

fn collect_dvec(num: uint) -> [mut uint] {
    let result = dvec();
    for uint::range(0u, num) { |i|
        result.push(i);
    }
    ret dvec::unwrap(result);
}

fn main(args: [str]) {
    let args = if os::getenv("RUST_BENCH").is_some() {
        ["", "50000000"]
    } else if args.len() <= 1u {
        ["", "100000"]
    } else {
        args
    };
    let max = uint::from_str(args[1]).get();
    let start = std::time::precise_time_s();
    let raw_v = collect_raw(max);
    let mid = std::time::precise_time_s();
    let dvec_v = collect_dvec(max);
    let end = std::time::precise_time_s();

    // check each vector
    assert raw_v.len() == max;
    for raw_v.eachi { |i, v| assert i == v; }
    assert dvec_v.len() == max;
    for dvec_v.eachi { |i, v| assert i == v; }

    let raw = mid - start;
    let dvec = end - mid;

    let maxf = max as float;
    let rawf = raw as float;
    let dvecf = dvec as float;

    io::stdout().write_str(#fmt("Raw     : %? seconds\n", raw));
    io::stdout().write_str(#fmt("        : %f op/sec\n", maxf/rawf));
    io::stdout().write_str(#fmt("\n"));
    io::stdout().write_str(#fmt("Dvec    : %? seconds\n", dvec));
    io::stdout().write_str(#fmt("        : %f op/sec\n", maxf/dvecf));
    io::stdout().write_str(#fmt("\n"));

    if dvec < raw {
        io::stdout().write_str(#fmt("Dvec is %f%% faster than raw\n",
                                    (rawf - dvecf) / rawf * 100.0));
    } else {
        io::stdout().write_str(#fmt("Raw is %f%% faster than dvec\n",
                                    (dvecf - rawf) / dvecf * 100.0));
    }
}
<commit_msg>Remove some commented out code so the pretty printer doesn't get confused.<commit_after>// A raw test of vector appending performance.

use std;
import dvec::{dvec, extensions};
import io::writer_util;

fn collect_raw(num: uint) -> [uint] {
    let mut result = [];
    for uint::range(0u, num) { |i|
        vec::push(result, i);
    }
    ret result;
}

fn collect_dvec(num: uint) -> [mut uint] {
    let result = dvec();
    for uint::range(0u, num) { |i|
        result.push(i);
    }
    ret dvec::unwrap(result);
}

fn main(args: [str]) {
    let args = if os::getenv("RUST_BENCH").is_some() {
        ["", "50000000"]
    } else if args.len() <= 1u {
        ["", "100000"]
    } else {
        args
    };
    let max = uint::from_str(args[1]).get();
    let start = std::time::precise_time_s();
    let raw_v = collect_raw(max);
    let mid = std::time::precise_time_s();
    let dvec_v = collect_dvec(max);
    let end = std::time::precise_time_s();

    // check each vector
    assert raw_v.len() == max;
    for raw_v.eachi { |i, v| assert i == v; }
    assert dvec_v.len() == max;
    for dvec_v.eachi { |i, v| assert i == v; }

    let raw = mid - start;
    let dvec = end - mid;

    let maxf = max as float;
    let rawf = raw as float;
    let dvecf = dvec as float;

    io::stdout().write_str(#fmt("Raw     : %? seconds\n", raw));
    io::stdout().write_str(#fmt("        : %f op/sec\n", maxf/rawf));
    io::stdout().write_str(#fmt("\n"));
    io::stdout().write_str(#fmt("Dvec    : %? seconds\n", dvec));
    io::stdout().write_str(#fmt("        : %f op/sec\n", maxf/dvecf));
    io::stdout().write_str(#fmt("\n"));

    if dvec < raw {
        io::stdout().write_str(#fmt("Dvec is %f%% faster than raw\n",
                                    (rawf - dvecf) / rawf * 100.0));
    } else {
        io::stdout().write_str(#fmt("Raw is %f%% faster than dvec\n",
                                    (dvecf - rawf) / dvecf * 100.0));
    }
}
<|endoftext|>


<commit_before><commit_msg>Add a benchmark for cross-task kernel memory region synchronization<commit_after>// Vectors are allocated in the Rust kernel's memory region, use of
// which requires some amount of synchronization. This test exercises
// that synchronization by spawning a number of tasks and then
// allocating and freeing vectors.

use std;
import std::vec;
import std::uint;
import std::istr;
import std::task;

fn f(n: uint) {
    for each i in uint::range(0u, n) {
        let v: [u8] = [];
        vec::reserve(v, 1000u);
    }
}

fn main(args: [istr]) {
    let n = if vec::len(args) < 2u {
        100u
    } else {
        uint::parse_buf(istr::bytes(args[1]), 10u)
    };
    for each i in uint::range(0u, 100u) {
        task::spawn(bind f(n));
    }
}<|endoftext|>


<commit_before><commit_msg>Fix typo<commit_after><|endoftext|>


<commit_before><commit_msg>Hello World!<commit_after>
fn main() {
  for i in range(0, 5) {
    do spawn {
      println!("Hello {} !", i * 10);
    }
  }
}<|endoftext|>


<commit_before><commit_msg>Rollup merge of #81927 - vandenheuvel:issue_32498, r=Mark-Simulacrum<commit_after>// run-pass
#![allow(dead_code)]

// Making sure that no overflow occurs.

struct L<T> {
    n: Option<T>,
}
type L8<T> = L<L<L<L<L<L<L<L<T>>>>>>>>;
type L64<T> = L8<L8<L8<L8<T>>>>;

fn main() {
    use std::mem::size_of;
    assert_eq!(size_of::<L64<L64<()>>>(), 1);
    assert_eq!(size_of::<L<L64<L64<()>>>>(), 1);
}
<|endoftext|>


<commit_before><commit_msg>example: Add custom_expression implemenation guide<commit_after>extern crate ripin;

use std::env;
use std::marker::PhantomData;
use ripin::{Stack, pop_two_operands, TryFromRef};
use ripin::expression::Expression;
use ripin::evaluate::Evaluate;

// Implementing Expression for a new specific type
// is not a difficult thing to do:

// First you will need something that
// can be understand as an Operand type, like float or integer.
// The type you choose need to implement TryFromRef.
#[derive(Debug, Copy, Clone)]
enum MyOperand {
    Number1,
    Number2,
}

impl<'a> TryFromRef<&'a str> for MyOperand {
    type Err = MyOperandErr<&'a str>;
    fn try_from_ref(s: &&'a str) -> Result<Self, Self::Err> {
        match *s {
            "1" => Ok(MyOperand::Number1),
            "2" => Ok(MyOperand::Number2),
            _ => Err(MyOperandErr::InvalidToken(s))
        }
    }
}

// Secondly an Evaluator type to make evaluation
// of Operands and generate other ones on the stack.
// It needs to implement TryFromRef too.
#[derive(Debug, Copy, Clone)]
enum MyEvaluator<T> {
    Add,
    Sub,
    _Phantom(PhantomData<T>) // make it generic but
                             // don't own the generic T type
}

impl<'a, T> TryFromRef<&'a str> for MyEvaluator<T> {
    type Err = MyOperandErr<&'a str>;
    fn try_from_ref(s: &&'a str) -> Result<Self, Self::Err> {
        match *s {
            "+" => Ok(MyEvaluator::Add),
            "-" => Ok(MyEvaluator::Sub),
            _ => Err(MyOperandErr::InvalidToken(s))
        }
    }
}

// A clear error struct/enum is really important for the parsing part
#[derive(Debug)]
enum MyOperandErr<T> {
    InvalidToken(T),
}

// Be careful both needs to implement the same TryFromRef Trait signature !
// If the Operand type works with TryFromRef<&str>
// then the Evaluator needs the same TryFromRef signature.

// A clear error struct/enum is really important for the evaluation part
#[derive(Debug)]
enum MyEvalErr<T> {
    CannotAddOperands(T, T),
    CannotSubOperands(T, T),
    NotEnoughOperands
}

// The last step is to implement the Evaluate trait on your custom Evaluator.
// Evaluations are done with this trait.
impl Evaluate<MyOperand> for MyEvaluator<MyOperand> {
    type Err = MyEvalErr<MyOperand>;

    fn operands_needed(&self) -> usize {
        match *self {
            MyEvaluator::Add | MyEvaluator::Sub => 2,
            _ => unreachable!(), // _Phantom
        }
    }
    fn operands_generated(&self) -> usize {
        match *self {
            MyEvaluator::Add | MyEvaluator::Sub => 1,
            _ => unreachable!(), // _Phantom
        }
    }

    fn evaluate(self, stack: &mut Stack<MyOperand>) -> Result<(), Self::Err> {
        let (a, b) = pop_two_operands(stack).ok_or(MyEvalErr::NotEnoughOperands)?;
        match self {
            MyEvaluator::Add => {
                match (a, b) {
                    (MyOperand::Number1, MyOperand::Number1) => {
                        Ok(stack.push(MyOperand::Number2))
                    },
                    _ => Err(MyEvalErr::CannotAddOperands(a, b)),
                }
            },
            MyEvaluator::Sub => {
                match (a, b) {
                    (MyOperand::Number2, MyOperand::Number1) => {
                        Ok(stack.push(MyOperand::Number1))
                    },
                    _ => Err(MyEvalErr::CannotSubOperands(a, b)),
                }
            }
            _ => unreachable!() // _Phantom
        }
    }
}

type MyExpression = Expression<MyOperand, MyEvaluator<MyOperand>>;

// Once you implement the TryFromRef trait on your “custom” types,
// make an iterator of it and give it to the Expression struct.
fn main() {
    let expr_str = env::args().nth(1).unwrap_or_else(|| {
        println!("Give me an expression as first argument!");
        "1 1 +".into()
    });

    let tokens = expr_str.split_whitespace();
    match MyExpression::from_iter(tokens) {
        Ok(expr) => println!("Evaluation of {:?}: {:?}", expr_str, expr.evaluate()),
        Err(err) => println!("Parsing results in {:?}", err),
    }
}
<|endoftext|>


<commit_before><commit_msg>add enum implementation<commit_after>use std::env;

enum BinaryTree {
    Child(i32, Box<BinaryTree>, Box<BinaryTree>),
    None(i32),
}

impl BinaryTree {
    pub fn new(item: i32, depth: i32) -> BinaryTree {
        if depth == 0 {
            BinaryTree::None(item)
        } else {
            BinaryTree::Child(item,
              Box::new(BinaryTree::new(2 * item - 1, depth - 1)),
              Box::new(BinaryTree::new(2 * item, depth - 1)))
        }
    }

    pub fn item_check(&self) -> i32 {
        match self {
            &BinaryTree::Child(i, ref l, ref r) => i + l.item_check() - r.item_check(),
            &BinaryTree::None(i) => i,
        }
    }
}

const MIN_DEPTH : i32 = 4;

fn main() {
    let depth = env::args().nth(1).unwrap_or("10".to_string()).parse::<i32>().unwrap();
    println!("stretch tree of depth {}\tcheck {}", depth + 1,
             BinaryTree::new(0, depth + 1).item_check());
    let long_lived = BinaryTree::new(0, depth);
    for (d, i) in (MIN_DEPTH..depth+1).filter(| x | x % 2 == 0).map(| x |
         (x, (1..(1<<(depth-x+MIN_DEPTH))+1).fold(0,| check, j |
      check + BinaryTree::new(j, x).item_check() + BinaryTree::new(-j, x).item_check()))) {
        println!("{}\ttrees of depth {}\tcheck {}", 1<<(depth-d+MIN_DEPTH)+1, d, i);
    }
    println!("long lived tree of depth {}\tcheck {}", depth, long_lived.item_check());
}
<|endoftext|>


<commit_before>use inflector::Inflector;

use botocore::{Service, Shape, Operation};

use self::ec2::Ec2Generator;
use self::json::JsonGenerator;
use self::query::QueryGenerator;
use self::rest_json::RestJsonGenerator;

mod ec2;
mod json;
mod query;
mod rest_json;

pub trait GenerateProtocol {
    fn generate_methods(&self, service: &Service) -> String;

    fn generate_prelude(&self, service: &Service) -> String;

    fn generate_struct_attributes(&self) -> String;

    fn generate_support_types(&self, _name: &str, _shape: &Shape, _service: &Service)
        -> Option<String> {
        None
    }

    fn generate_error_types(&self, _service: &Service) -> Option<String> {
        None
    }

    fn timestamp_type(&self) -> &'static str;
}

pub fn generate_source(service: &Service) -> String {
    match &service.metadata.protocol[..] {
        "json" => generate(service, JsonGenerator),
        "ec2" => generate(service, Ec2Generator),
        "query" => generate(service, QueryGenerator),
        "rest-json" => generate(service, RestJsonGenerator),
        protocol => panic!("Unknown protocol {}", protocol),
    }
}

fn generate<P>(service: &Service, protocol_generator: P) -> String where P: GenerateProtocol {
    format!(
        "{prelude}

        {types}
        {error_types}

        {client}",
        client = generate_client(service, &protocol_generator),
        prelude = &protocol_generator.generate_prelude(service),
        types = generate_types(service, &protocol_generator),
        error_types = protocol_generator.generate_error_types(service).unwrap_or("".to_string()),
    )
}

fn generate_client<P>(service: &Service, protocol_generator: &P) -> String
where P: GenerateProtocol {
    format!(
        "/// A client for the {service_name} API.
        pub struct {type_name}<P> where P: ProvideAwsCredentials {{
            credentials_provider: P,
            region: region::Region,
        }}

        impl<P> {type_name}<P> where P: ProvideAwsCredentials {{
            pub fn new(credentials_provider: P, region: region::Region) -> Self {{
                {type_name} {{
                    credentials_provider: credentials_provider,
                    region: region,
                }}
            }}

            {methods}
        }}
        ",
        methods = protocol_generator.generate_methods(service),
        service_name = match &service.metadata.service_abbreviation {
            &Some(ref service_abbreviation) => service_abbreviation.as_str(),
            &None => {
                match service.metadata.endpoint_prefix {
                    ref x if x == "elastictranscoder" => "Amazon Elastic Transcoder",
                    ref x if x == "cognito-identity" => "Amazon Cognito Identity",
                    _ => panic!("Unable to determine service abbreviation"),
                }
            },
        },
        type_name = service.client_type_name(),
    )
}

fn generate_list(name: &str, shape: &Shape) -> String {
    format!("pub type {} = Vec<{}>;", name, shape.member())
}

fn generate_map(name: &str, shape: &Shape) -> String {
    format!(
        "pub type {} = ::std::collections::HashMap<{}, {}>;",
        name,
        shape.key(),
        shape.value(),
    )
}

fn generate_primitive_type(name: &str, shape_type: &str, for_timestamps: &str) -> String {
    let primitive_type = match shape_type {
        "blob" => "Vec<u8>",
        "boolean" => "bool",
        "double" => "f64",
        "float" => "f32",
        "integer" => "i32",
        "long" => "i64",
        "string" => "String",
        "timestamp" => for_timestamps,
        primitive_type => panic!("Unknown primitive type: {}", primitive_type),
    };

    format!("pub type {} = {};", name, primitive_type)
}

fn generate_types<P>(service: &Service, protocol_generator: &P) -> String
where P: GenerateProtocol {
    service.shapes.iter().filter_map(|(name, shape)| {
        if name == "String" {
            return protocol_generator.generate_support_types(name, shape, &service);
        }

        if shape.exception() && service.typed_errors() {
            return None;
        }

        let mut parts = Vec::with_capacity(3);

        if let Some(ref docs) = shape.documentation {
            parts.push(format!("#[doc=\"{}\"]", docs.replace("\"", "\\\"")));
        }

        match &shape.shape_type[..] {
            "structure" => parts.push(generate_struct(service, name, shape, protocol_generator)),
            "map" => parts.push(generate_map(name, shape)),
            "list" => parts.push(generate_list(name, shape)),
            shape_type => parts.push(generate_primitive_type(name, shape_type, protocol_generator.timestamp_type())),
        }

        if let Some(support_types) = protocol_generator.generate_support_types(name, shape, &service) {
            parts.push(support_types);
        }

        Some(parts.join("\n"))
    }).collect::<Vec<String>>().join("\n")
}

fn generate_struct<P>(
    service: &Service,
    name: &str,
    shape: &Shape,
    protocol_generator: &P,
) -> String where P: GenerateProtocol {
    if shape.members.is_none() || shape.members.as_ref().unwrap().is_empty() {
        format!(
            "{attributes}
            pub struct {name};
            ",
            attributes = protocol_generator.generate_struct_attributes(),
            name = name,
        )
    } else {
        format!(
            "{attributes}
            pub struct {name} {{
                {struct_fields}
            }}
            ",
            attributes = protocol_generator.generate_struct_attributes(),
            name = name,
            struct_fields = generate_struct_fields(service, shape),
        )
    }

}

pub fn generate_field_name(member_name: &str) -> String {
    let name = member_name.to_snake_case();
    if name == "return" || name == "type" {
        name + "_"
    } else {
        name
    }
}

fn generate_struct_fields(service: &Service, shape: &Shape) -> String {
    shape.members.as_ref().unwrap().iter().map(|(member_name, member)| {
        let mut lines = Vec::with_capacity(4);
        let name = generate_field_name(member_name);

        if let Some(ref docs) = member.documentation {
            lines.push(format!("#[doc=\"{}\"]", docs.replace("\"", "\\\"")));
        }

        lines.push("#[allow(unused_attributes)]".to_owned());
        lines.push(format!("#[serde(rename=\"{}\")]", member_name));

        if let Some(shape_type) = service.shape_type_for_member(member) {
            if shape_type == "blob" {
                lines.push(
                    "#[serde(
                        deserialize_with=\"::serialization::SerdeBlob::deserialize_blob\",
                        serialize_with=\"::serialization::SerdeBlob::serialize_blob\",
                        default,
                    )]".to_owned()
                );
            }
        }

        if shape.required(member_name) {
            lines.push(format!("pub {}: {},",  name, member.shape));
        } else if name == "type" {
            lines.push(format!("pub aws_{}: Option<{}>,",  name, member.shape));
        } else {
            lines.push(format!("pub {}: Option<{}>,",  name, member.shape));
        }

        lines.join("\n")
    }).collect::<Vec<String>>().join("\n")
}

impl Operation {
    pub fn error_type_name(&self) -> String {
        format!("{}Error", self.name)
    }
}
<commit_msg>fall back to service full name if abbreviation isn't present in botocore definition<commit_after>use inflector::Inflector;

use botocore::{Service, Shape, Operation};

use self::ec2::Ec2Generator;
use self::json::JsonGenerator;
use self::query::QueryGenerator;
use self::rest_json::RestJsonGenerator;

mod ec2;
mod json;
mod query;
mod rest_json;

pub trait GenerateProtocol {
    fn generate_methods(&self, service: &Service) -> String;

    fn generate_prelude(&self, service: &Service) -> String;

    fn generate_struct_attributes(&self) -> String;

    fn generate_support_types(&self, _name: &str, _shape: &Shape, _service: &Service)
        -> Option<String> {
        None
    }

    fn generate_error_types(&self, _service: &Service) -> Option<String> {
        None
    }

    fn timestamp_type(&self) -> &'static str;
}

pub fn generate_source(service: &Service) -> String {
    match &service.metadata.protocol[..] {
        "json" => generate(service, JsonGenerator),
        "ec2" => generate(service, Ec2Generator),
        "query" => generate(service, QueryGenerator),
        "rest-json" => generate(service, RestJsonGenerator),
        protocol => panic!("Unknown protocol {}", protocol),
    }
}

fn generate<P>(service: &Service, protocol_generator: P) -> String where P: GenerateProtocol {
    format!(
        "{prelude}

        {types}
        {error_types}

        {client}",
        client = generate_client(service, &protocol_generator),
        prelude = &protocol_generator.generate_prelude(service),
        types = generate_types(service, &protocol_generator),
        error_types = protocol_generator.generate_error_types(service).unwrap_or("".to_string()),
    )
}

fn generate_client<P>(service: &Service, protocol_generator: &P) -> String
where P: GenerateProtocol {
    format!(
        "/// A client for the {service_name} API.
        pub struct {type_name}<P> where P: ProvideAwsCredentials {{
            credentials_provider: P,
            region: region::Region,
        }}

        impl<P> {type_name}<P> where P: ProvideAwsCredentials {{
            pub fn new(credentials_provider: P, region: region::Region) -> Self {{
                {type_name} {{
                    credentials_provider: credentials_provider,
                    region: region,
                }}
            }}

            {methods}
        }}
        ",
        methods = protocol_generator.generate_methods(service),
        service_name = match &service.metadata.service_abbreviation {
            &Some(ref service_abbreviation) => service_abbreviation.as_str(),
            &None => service.metadata.service_full_name.as_ref()
        },
        type_name = service.client_type_name(),
    )
}

fn generate_list(name: &str, shape: &Shape) -> String {
    format!("pub type {} = Vec<{}>;", name, shape.member())
}

fn generate_map(name: &str, shape: &Shape) -> String {
    format!(
        "pub type {} = ::std::collections::HashMap<{}, {}>;",
        name,
        shape.key(),
        shape.value(),
    )
}

fn generate_primitive_type(name: &str, shape_type: &str, for_timestamps: &str) -> String {
    let primitive_type = match shape_type {
        "blob" => "Vec<u8>",
        "boolean" => "bool",
        "double" => "f64",
        "float" => "f32",
        "integer" => "i32",
        "long" => "i64",
        "string" => "String",
        "timestamp" => for_timestamps,
        primitive_type => panic!("Unknown primitive type: {}", primitive_type),
    };

    format!("pub type {} = {};", name, primitive_type)
}

fn generate_types<P>(service: &Service, protocol_generator: &P) -> String
where P: GenerateProtocol {
    service.shapes.iter().filter_map(|(name, shape)| {
        if name == "String" {
            return protocol_generator.generate_support_types(name, shape, &service);
        }

        if shape.exception() && service.typed_errors() {
            return None;
        }

        let mut parts = Vec::with_capacity(3);

        if let Some(ref docs) = shape.documentation {
            parts.push(format!("#[doc=\"{}\"]", docs.replace("\"", "\\\"")));
        }

        match &shape.shape_type[..] {
            "structure" => parts.push(generate_struct(service, name, shape, protocol_generator)),
            "map" => parts.push(generate_map(name, shape)),
            "list" => parts.push(generate_list(name, shape)),
            shape_type => parts.push(generate_primitive_type(name, shape_type, protocol_generator.timestamp_type())),
        }

        if let Some(support_types) = protocol_generator.generate_support_types(name, shape, &service) {
            parts.push(support_types);
        }

        Some(parts.join("\n"))
    }).collect::<Vec<String>>().join("\n")
}

fn generate_struct<P>(
    service: &Service,
    name: &str,
    shape: &Shape,
    protocol_generator: &P,
) -> String where P: GenerateProtocol {
    if shape.members.is_none() || shape.members.as_ref().unwrap().is_empty() {
        format!(
            "{attributes}
            pub struct {name};
            ",
            attributes = protocol_generator.generate_struct_attributes(),
            name = name,
        )
    } else {
        format!(
            "{attributes}
            pub struct {name} {{
                {struct_fields}
            }}
            ",
            attributes = protocol_generator.generate_struct_attributes(),
            name = name,
            struct_fields = generate_struct_fields(service, shape),
        )
    }

}

pub fn generate_field_name(member_name: &str) -> String {
    let name = member_name.to_snake_case();
    if name == "return" || name == "type" {
        name + "_"
    } else {
        name
    }
}

fn generate_struct_fields(service: &Service, shape: &Shape) -> String {
    shape.members.as_ref().unwrap().iter().map(|(member_name, member)| {
        let mut lines = Vec::with_capacity(4);
        let name = generate_field_name(member_name);

        if let Some(ref docs) = member.documentation {
            lines.push(format!("#[doc=\"{}\"]", docs.replace("\"", "\\\"")));
        }

        lines.push("#[allow(unused_attributes)]".to_owned());
        lines.push(format!("#[serde(rename=\"{}\")]", member_name));

        if let Some(shape_type) = service.shape_type_for_member(member) {
            if shape_type == "blob" {
                lines.push(
                    "#[serde(
                        deserialize_with=\"::serialization::SerdeBlob::deserialize_blob\",
                        serialize_with=\"::serialization::SerdeBlob::serialize_blob\",
                        default,
                    )]".to_owned()
                );
            }
        }

        if shape.required(member_name) {
            lines.push(format!("pub {}: {},",  name, member.shape));
        } else if name == "type" {
            lines.push(format!("pub aws_{}: Option<{}>,",  name, member.shape));
        } else {
            lines.push(format!("pub {}: Option<{}>,",  name, member.shape));
        }

        lines.join("\n")
    }).collect::<Vec<String>>().join("\n")
}

impl Operation {
    pub fn error_type_name(&self) -> String {
        format!("{}Error", self.name)
    }
}
<|endoftext|>


<commit_before><commit_msg>staircase<commit_after>//https://www.hackerrank.com/challenges/staircase

use std::io;
use std::io::prelude::*;

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

    let count: i32 = stdin.lock().lines() //iterator over lines in stdin
        .next().unwrap().unwrap() //finally it's a string
        .trim().parse().unwrap(); //and then parsing count value...But we don't need it :) lol
    for i in 0..count {
        for _ in 0..count - i - 1 {
            print!(" ");
        }
        for _ in 0..i+1 {
            print!("#");
        }
        println!("");
    }
}<|endoftext|>


<commit_before><commit_msg>Touch up the iOS deploy script<commit_after><|endoftext|>


<commit_before><commit_msg>std::borrow::Cow<commit_after><|endoftext|>


<commit_before><commit_msg> add solution in rust for Easy 0001<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for safe intrinsics<commit_after>#![feature(intrinsics)]
#![feature(no_core)]

#![no_core]
#![crate_name = "foo"]

extern "rust-intrinsic" {
    // @has 'foo/fn.abort.html'
    // @has - '//pre[@class="rust fn"]' 'pub extern "rust-intrinsic" fn abort() -> !'
    pub fn abort() -> !;
    // @has 'foo/fn.unreachable.html'
    // @has - '//pre[@class="rust fn"]' 'pub unsafe extern "rust-intrinsic" fn unreachable() -> !'
    pub fn unreachable() -> !;
}

extern "C" {
    // @has 'foo/fn.needs_drop.html'
    // @has - '//pre[@class="rust fn"]' 'pub unsafe extern "C" fn needs_drop() -> !'
    pub fn needs_drop() -> !;
}
<|endoftext|>


<commit_before><commit_msg>rust queue<commit_after>struct Queue<T> {
    data: Vec<T>
}

impl<T> Queue<T> {
    fn new() -> Queue<T> {
        Queue{data: vec![]}
    }

    fn enqueue(&mut self, e: T) {
        self.data.push(e)
    }

    fn dequeue(&mut self) -> Option<T> {
        if self.data.is_empty() {
            return None;
        }
        Some(self.data.remove(0))
    }

    fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    fn peek(&self) -> Option<&T> {
        if self.data.is_empty() {
            return None;
        }
        let e = &self.data[0];
        Some(e)
    }
}
<|endoftext|>


<commit_before><commit_msg>check-in lazy static replacement<commit_after>//! This module exists because lazy_static causes TSAN to
//! be very unhappy. We rely heavily on TSAN for finding
//! races, so we don't use lazy_static.

use std::sync::atomic::{AtomicBool, AtomicPtr, Ordering::SeqCst};

/// A lazily initialized value
pub struct Lazy<T, F> {
    value: AtomicPtr<T>,
    init_mu: AtomicBool,
    init: F,
}

impl<T, F> Lazy<T, F> {
    /// Create a new Lazy
    pub const fn new(init: F) -> Lazy<T, F>
    where
        F: Sized,
    {
        Lazy {
            value: AtomicPtr::new(std::ptr::null_mut()),
            init_mu: AtomicBool::new(false),
            init,
        }
    }
}

impl<T, F> Drop for Lazy<T, F> {
    fn drop(&mut self) {
        let value_ptr = self.value.load(SeqCst);
        if !value_ptr.is_null() {
            unsafe { drop(Box::from_raw(value_ptr)) }
        }
    }
}

impl<T, F> std::ops::Deref for Lazy<T, F>
where
    F: Fn() -> T,
{
    type Target = T;

    fn deref(&self) -> &T {
        let value_ptr = self.value.load(SeqCst);

        if !value_ptr.is_null() {
            unsafe {
                return &*value_ptr;
            }
        }

        while self.init_mu.compare_and_swap(false, true, SeqCst) != false {}

        let value_ptr = self.value.load(SeqCst);

        // we need to check this again because
        // maybe some other thread completed
        // the initialization already.
        if !value_ptr.is_null() {
            let unlock = self.init_mu.swap(false, SeqCst);
            assert!(unlock);
            unsafe {
                return &*value_ptr;
            }
        }

        let value = (self.init)();

        let value_ptr = Box::into_raw(Box::new(value));

        self.value.store(value_ptr, SeqCst);

        let unlock = self.init_mu.swap(false, SeqCst);
        assert!(unlock);

        unsafe { &*value_ptr }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add entry getter function<commit_after><|endoftext|>


<commit_before><commit_msg>Adapt to new libimagstore::iter::Entries API<commit_after><|endoftext|>


<commit_before><commit_msg>(feat) Added more convenience implementations of Handler.<commit_after><|endoftext|>


<commit_before><commit_msg>Error when .env fails loading for non-parse reasons<commit_after><|endoftext|>


<commit_before>rm use std::mem;
use std::prelude::v1::*;

use {Future, IntoFuture, Poll, Async};

/// Future for the `select_any` combinator, waiting for one of any of a list of
/// futures to succesfully complete. unlike `select_all`, this future ignores all
/// but the last error, if there are any.
///
/// This is created by this `select_any` function.
#[must_use = "futures do nothing unless polled"]
pub struct SelectAny<A> where A: Future {
    inner: Vec<A>,
}

/// Creates a new future which will select the first successful future over a list of futures.
///
/// The returned future will wait for any future within `list` to be ready and Ok. Unlike
/// select_all, this will only return the first successful completion, or the last
/// failure. This is useful in contexts where any success is desired and failures
/// are ignored, unless all the futures fail.
///
/// # Panics
///
/// This function will panic if the iterator specified contains no items.
pub fn select_any<I>(iter: I) -> SelectAny<<I::Item as IntoFuture>::Future>
    where I: IntoIterator,
          I::Item: IntoFuture,
{
    let ret = SelectAny {
        inner: iter.into_iter()
                   .map(|a| a.into_future())
                   .collect(),
    };
    assert!(ret.inner.len() > 0);
    ret
}

impl<A> Future for SelectAny<A> where A: Future {
    type Item = (A::Item, Vec<A>);
    type Error = A::Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        // loop until we've either exhausted all errors, a success was hit, or nothing is ready
        loop {
            let item = self.inner.iter_mut().enumerate().filter_map(|(i, f)| {
                match f.poll() {
                    Ok(Async::NotReady) => None,
                    Ok(Async::Ready(e)) => Some((i, Ok(e))),
                    Err(e) => Some((i, Err(e))),
                }
            }).next();

            match item {
                Some((idx, res)) => {
                    // always remove Ok or Err, if it's not the last Err continue looping
                    drop(self.inner.remove(idx));
                    match res {
                        Ok(e) => {
                            let rest = mem::replace(&mut self.inner, Vec::new());
                            return Ok(Async::Ready((e, rest)))
                        },
                        Err(e) => {
                            if self.inner.is_empty() {
                                return Err(e)
                            }
                        },
                    }
                }
                None => {
                    // based on the filter above, nothing is ready, return
                    return Ok(Async::NotReady)
                },
            }
        }
    }
}
<commit_msg>remove rm typo<commit_after>use std::mem;
use std::prelude::v1::*;

use {Future, IntoFuture, Poll, Async};

/// Future for the `select_any` combinator, waiting for one of any of a list of
/// futures to succesfully complete. unlike `select_all`, this future ignores all
/// but the last error, if there are any.
///
/// This is created by this `select_any` function.
#[must_use = "futures do nothing unless polled"]
pub struct SelectAny<A> where A: Future {
    inner: Vec<A>,
}

/// Creates a new future which will select the first successful future over a list of futures.
///
/// The returned future will wait for any future within `list` to be ready and Ok. Unlike
/// select_all, this will only return the first successful completion, or the last
/// failure. This is useful in contexts where any success is desired and failures
/// are ignored, unless all the futures fail.
///
/// # Panics
///
/// This function will panic if the iterator specified contains no items.
pub fn select_any<I>(iter: I) -> SelectAny<<I::Item as IntoFuture>::Future>
    where I: IntoIterator,
          I::Item: IntoFuture,
{
    let ret = SelectAny {
        inner: iter.into_iter()
                   .map(|a| a.into_future())
                   .collect(),
    };
    assert!(ret.inner.len() > 0);
    ret
}

impl<A> Future for SelectAny<A> where A: Future {
    type Item = (A::Item, Vec<A>);
    type Error = A::Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        // loop until we've either exhausted all errors, a success was hit, or nothing is ready
        loop {
            let item = self.inner.iter_mut().enumerate().filter_map(|(i, f)| {
                match f.poll() {
                    Ok(Async::NotReady) => None,
                    Ok(Async::Ready(e)) => Some((i, Ok(e))),
                    Err(e) => Some((i, Err(e))),
                }
            }).next();

            match item {
                Some((idx, res)) => {
                    // always remove Ok or Err, if it's not the last Err continue looping
                    drop(self.inner.remove(idx));
                    match res {
                        Ok(e) => {
                            let rest = mem::replace(&mut self.inner, Vec::new());
                            return Ok(Async::Ready((e, rest)))
                        },
                        Err(e) => {
                            if self.inner.is_empty() {
                                return Err(e)
                            }
                        },
                    }
                }
                None => {
                    // based on the filter above, nothing is ready, return
                    return Ok(Async::NotReady)
                },
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>add permissions to audio requests<commit_after><|endoftext|>


<commit_before><commit_msg>reorder audio module code<commit_after><|endoftext|>


<commit_before><commit_msg>Add image module.<commit_after>//! Constructs for generating images using the TIS-100.

/// The colors that the TIS-100 can generate.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum Color {
    Black,
    DarkGrey,
    BrightGrey,
    White,
    Red,
}

impl Color {
    /// Get the color for the given integer representation.
    fn from_isize(value: isize) -> Color {
        match value {
            1 => DarkGrey,
            2 => BrightGrey,
            3 => White,
            4 => Red,
            _ => Black,
        }
    }
}

use self::Color::*;

/// The operational modes of the image.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
enum ImageMode {
    Move,
    Paint,
}

use self::ImageMode::*;

/// An image that can receive values from the TIS-100. When in the `Move` mode, the image receives
/// coordinates that tell it where to draw. When in the `Paint` mode, the image will draw values.
/// Sending a negative value at any time will reset the image to `Move` mode.
#[derive(Debug)]
pub struct Image {
    width: usize,
    height: usize,
    data: Vec<Color>,
    mode: ImageMode,
    position: Vec<isize>,
    offset: usize,
}

impl Image {
    /// Construct a new, empty `Image` with the given width and height.
    pub fn new(width: usize, height: usize) -> Image {
        let mut data = Vec::with_capacity(width * height);
        for _ in 0..width * height {
            data.push(Black);
        }

        Image {
            width: width,
            height: height,
            data: data,
            mode: Move,
            position: Vec::new(),
            offset: 0,
        }
    }

    /// Construct a new `Image` with the given width, height, and initial values.
    pub fn with_data(data: &Vec<isize>, width: usize, height: usize) -> Image {
        assert_eq!(data.len(), width * height);

        let data = data.iter().map(|&i| Color::from_isize(i)).collect::<Vec<_>>();

        Image {
            width: width,
            height: height,
            data: data,
            mode: Move,
            position: Vec::new(),
            offset: 0,
        }
    }

    /// Retrieve the image's data.
    pub fn data(&self) -> &Vec<Color> {
        &self.data
    }

    /// Write a value to the image. If the image is in `Move` mode, then the value will be
    /// interpreted as a coordinate. If the image is in `Paint` mode, then the value will be
    /// interpreted as a color unless the value is negative.
    pub fn write(&mut self, value: isize) {
        if value < 0 {
            self.position.clear();
            self.mode = Move;
            self.offset = 0;
            return;
        }

        if self.mode == Move {
            self.position.push(value);

            if self.position.len() == 2 {
                self.mode = Paint;
            }

            return;
        }

        let row_off = self.position[0] as usize * self.width;

        if row_off < self.width * self.height {
            let col = self.position[1] as usize + self.offset;

            if col < self.width {
                self.data[row_off + col] = Color::from_isize(value);
            }
        }

        self.offset += 1;
    }
}

impl PartialEq for Image {
    fn eq(&self, other: &Self) -> bool {
        self.data == other.data
    }
}

impl Eq for Image {}

#[test]
fn test_color_from_isize() {
    assert_eq!(Color::from_isize(0), Black);
    assert_eq!(Color::from_isize(1), DarkGrey);
    assert_eq!(Color::from_isize(2), BrightGrey);
    assert_eq!(Color::from_isize(3), White);
    assert_eq!(Color::from_isize(4), Red);
    assert_eq!(Color::from_isize(5), Black);
}

#[test]
fn test_image_with_data() {
    let expected = vec![DarkGrey, BrightGrey, White, Red];
    let data = vec![1, 2, 3, 4];
    let image = Image::with_data(&data, 2, 2);

    assert_eq!(expected, image.data().clone());
}

#[test]
fn test_image_write() {
    let expected = vec![DarkGrey, BrightGrey, White, Red];
    let mut image = Image::new(2, 2);

    image.write(0);
    image.write(0);
    image.write(1);
    image.write(2);
    image.write(-1);
    image.write(1);
    image.write(0);
    image.write(3);
    image.write(4);
    image.write(-1);

    assert_eq!(expected, image.data().clone());
}
<|endoftext|>


<commit_before>// Copyright 2014 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.

#![allow(non_snake_case)]

register_diagnostics! {
    E0154,
    E0157,
    E0153,
    E0251, // a named type or value has already been imported in this module
    E0252, // a named type or value has already been imported in this module
    E0253, // not directly importable
    E0254, // import conflicts with imported crate in this module
    E0255, // import conflicts with value in this module
    E0256, // import conflicts with type in this module
    E0257, // inherent implementations are only allowed on types defined in the current module
    E0258, // import conflicts with existing submodule
    E0259, // an extern crate has already been imported into this module
    E0260, // name conflicts with an external crate that has been imported into this module
    E0317, // user-defined types or type parameters cannot shadow the primitive types
    E0364, // item is private
    E0365  // item is private
}
<commit_msg>Add error explanation for E0317.<commit_after>// Copyright 2014 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.

#![allow(non_snake_case)]

// Error messages for EXXXX errors.
// Each message should start and end with a new line, and be wrapped to 80 characters.
// In vim you can `:set tw=80` and use `gq` to wrap paragraphs. Use `:set tw=0` to disable.
register_long_diagnostics! {

E0317: r##"
User-defined types or type parameters cannot shadow the primitive types.
This error indicates you tried to define a type, struct or enum with the same
name as an existing primitive type, and is therefore invalid.

See the Types section of the reference for more information about the primitive
types:

http://doc.rust-lang.org/nightly/reference.html#types
"##

}

register_diagnostics! {
    E0154,
    E0157,
    E0153,
    E0251, // a named type or value has already been imported in this module
    E0252, // a named type or value has already been imported in this module
    E0253, // not directly importable
    E0254, // import conflicts with imported crate in this module
    E0255, // import conflicts with value in this module
    E0256, // import conflicts with type in this module
    E0257, // inherent implementations are only allowed on types defined in the current module
    E0258, // import conflicts with existing submodule
    E0259, // an extern crate has already been imported into this module
    E0260, // name conflicts with an external crate that has been imported into this module
    E0364, // item is private
    E0365  // item is private
}
<|endoftext|>


<commit_before><commit_msg>Use 'to_string' in 'raindrops'.<commit_after><|endoftext|>


<commit_before><commit_msg>an empy message<commit_after><|endoftext|>


<commit_before><commit_msg>blank message<commit_after><|endoftext|>


<commit_before><commit_msg>Add a "roundtrip" example which deserializes and serializes a module.<commit_after>extern crate parity_wasm;

use std::env;

fn main() {
    let args = env::args().collect::<Vec<_>>();
    if args.len() != 3 {
        println!("Usage: {} in.wasm out.wasm", args[0]);
        return;
    }

    let module = parity_wasm::deserialize_file(&args[1]).expect("Failed to load module");

    parity_wasm::serialize_to_file(&args[2], module).expect("Failed to write module");
}
<|endoftext|>


<commit_before><commit_msg>video.addToAlbum method<commit_after><|endoftext|>


<commit_before><commit_msg>While with mut countdown<commit_after><|endoftext|>


<commit_before><commit_msg>Add I2C/VL53L0X example<commit_after>#![no_std]

extern crate cortex_m;
extern crate stm32f0x2;
extern crate stm32f0_hal;

use stm32f0x2::{
    GPIOB,
    I2C1,
    RCC,
};
use stm32f0_hal::gpio;

fn main() {
    // This example was developed and tested with the STM32F072B Discovery board
    // and the VL53L0X sattelite board. It assumes that the VL53L0X satellite
    // board is connected to the discovery board in the following way:
    // - GND to GND, VDD to 3V.
    // - XSDN_I to VDD, via a 10kOhm pull-up resistor.
    // - SCL_I to PB6, SDA_I to PB7.

    cortex_m::interrupt::free(|cs| {
        let rcc   = RCC.borrow(cs);
        let gpiob = GPIOB.borrow(cs);
        let i2c   = I2C1.borrow(cs);

        // Set up LEDs that we can later use to signal error or success
        //
        // These LEDs are marked as LD3, LD4, and LD5 on the STM32F0 Discovery
        // board. Please note that the board's documentation that matches those
        // names to PC6, PC8, and PC9 is not correct. It also mixes up the
        // colors of the LEDs. At least that's the case with the board I have in
        // front of me.
        let mut led_init    = gpio::Output::setup(gpio::Pin::PC8); // orange
        let mut led_success = gpio::Output::setup(gpio::Pin::PC9); // green
        let mut led_error   = gpio::Output::setup(gpio::Pin::PC6); // red

        led_init.high();
        led_success.low();
        led_error.low();

        // Enable clock for GPIOB
        //
        // I think this is already included in the GPIO output configuration
        // above, but it's more robust to do it again here explicitely, in case
        // that code changes, or this example switches to another method of
        // signalling success or failure.
        rcc.ahbenr.modify(|_, w| w.iopben().enabled());

        // Enable clock for I2C1
        rcc.apb1enr.modify(|_, w| w.i2c1en().enabled());

        // Reset I2C1 peripheral
        rcc.apb1rstr.modify(|_, w| w.i2c1rst().set_bit());
        rcc.apb1rstr.modify(|_, w| w.i2c1rst().clear_bit());

        // Select alternate I2C functions on pins
        // See data sheet, page 42 and reference manual, section 8.4.9.
        gpiob.afrl.modify(|_, w|
            w
                .afrl6().af1() // I2C1_SCL on PB6
                .afrl7().af1() // I2C1_SDA on PB7
        );

        // Configure the pins
        //
        // I'm basically winging it here. If the need for setting the
        // configuration like this is explained somewhere in the reference
        // manual, I don't know where. The following is based on my own
        // understanding, and bits and pieces I've gathered from around the
        // internet.
        //
        // Fact is, the pins need to be configured (there's no I2C signal
        // otherwise), and the following configuration works.
        gpiob.moder.modify(|_, w|
            w
                .moder6().alternate()
                .moder7().alternate()
        );
        gpiob.ospeedr.modify(|_, w|
            w
                .ospeedr6().low_speed()
                .ospeedr7().low_speed()
        );
        gpiob.otyper.modify(|_, w|
            w
                .ot6().open_drain()
                .ot7().open_drain()
        );

        // Select HSI as the clock source for I2C1
        // This is the default, so unless other code has changed this
        // configuration, the following line is redundant.
        rcc.cfgr3.modify(|_, w| w.i2c1sw().hsi());

        // Make sure the I2C peripheral is disabled
        // The configuration below is not allowed, while I2C is enabled.
        i2c.cr1.modify(|_, w| w.pe().clear_bit());

        // Noise filter configuration would go here, if required. By default, a
        // spec-compliant analog filter is enabled, and I don't see a reason to
        // change that.

        // Configure I2C timings
        // The following values are taken from table 91 on page 650 (section
        // 26.4.10) in the reference manual. This is the right table because the
        // 8 MHz HSI clock has been selected above. Let's choose 100 kHz for the
        // I2C frequency.
        i2c.timingr.modify(|_, w|
            unsafe {
                w
                    .presc().bits(1)
                    .scll().bits(0x13) // required because of master mode
                    .sclh().bits(0xf)  // required because of master mode
                    .sdadel().bits(0x2)
                    .scldel().bits(0x4)
            }
        );

        // Enable I2C peripheral
        i2c.cr1.modify(|_, w| w.pe().set_bit());

        // Configure and start I2C write
        i2c.cr2.write(|w|
            unsafe {
                w
                    // 7-bit addressing mode
                    .add10().clear_bit()
                    // slave address
                    .sadd1().bits(0x52 >> 1)
                    .sadd0().bit(false) // write
                    // write config
                    .rd_wrn().clear_bit() // set transfer direction to write
                    .nbytes().bits(1)     // send 1 byte, the register index
                    .reload().clear_bit() // only send <nbytes> bytes
                    .autoend().set_bit()  // automatically send STOP signal
                    .start().set_bit()    // start signal to start transmission
            }
        );

        // Wait for transmit register to be empty
        while i2c.isr.read().txe().bit_is_clear() {}

        // Send index of reference register
        i2c.txdr.write(|w| w.txdata().bits(0xC0));

        // Wait until transfer is complete
        // Since we set the AUTOEND flag above, the peripheral should
        // automatically generate a stop condition.
        while i2c.isr.read().stopf().bit_is_clear() {}

        // Configure and start I2C read
        i2c.cr2.write(|w|
            unsafe {
                w
                    // 7-bit addressing mode
                    .add10().clear_bit()
                    // slave address
                    .sadd1().bits(0x52 >> 1)
                    .sadd0().bit(true) // read
                    // read config
                    .rd_wrn().set_bit()   // set transfer direction to read
                    .nbytes().bits(1)     // receive 1 byte
                    .reload().clear_bit() // only receive <nbytes> bytes
                    .autoend().set_bit()  // automatically send STOP signal
                    .start().set_bit()    // start signal to start transmission
            }
        );

        // Wait until byte has been received
        while i2c.isr.read().rxne().bit_is_clear() {}

        // Read received byte
        let byte = i2c.rxdr.read().rxdata().bits();

        // Check received data
        // We expect that it's the hardcoded value from the reference register
        // we were reading.
        if byte == 0xEE {
            led_success.high();
        }
        else {
            led_error.high();
        }
    });
}
<|endoftext|>


<commit_before><commit_msg>add Simple Workflow Service integration tests<commit_after>#![cfg(feature = "swf")]

extern crate rusoto;

use rusoto::swf::{SwfClient, ListDomainsInput};
use rusoto::{DefaultCredentialsProvider, Region};

#[test]
fn should_list_domains() {
    let credentials = DefaultCredentialsProvider::new().unwrap();
    let client = SwfClient::new(credentials, Region::UsEast1);

    let mut request = ListDomainsInput::default();
    request.maximum_page_size = Some(10);
    request.registration_status = "REGISTERED".to_string();

    match client.list_domains(&request) {
        Ok(response) => {
            println!("{:#?}", response);
            assert!(true)
        },
        Err(err) => panic!("Expected OK response, got {:#?}", err)
    };
}
<|endoftext|>


<commit_before>use super::*;

impl Editor {
    /// Get pos of next char
    pub fn next_pos(&self) -> (usize, usize) {
        // TODO: Add numerals
        if self.x() == self.text[self.y()].len() {
            if self.y() < self.text.len() - 1 {
                (0, self.y() + 1)
            } else {
                (self.x(), self.y())
            }
        } else {
            (self.x() + 1, self.y())
        }
    }

    /// Get pos of previous char
    pub fn previous_pos(&self) -> (usize, usize) {
        if self.x() == 0 {
            if self.y() > 0 {
                (self.text[self.y()].len(), self.y() - 1)
            } else {
                (self.x(), self.y())
            }
        } else {
            (self.x() - 1, self.y())
        }
    }

    pub fn next(&mut self) {
        let (x, y) = self.next_pos();
        self.cursor_mut().x = x;
        self.cursor_mut().y = y;
    }
    pub fn previous(&mut self) {
        let (x, y) = self.previous_pos();
        self.cursor_mut().x = x;
        self.cursor_mut().y = y;
    }

    /// Get right pos
    pub fn right_pos(&self, n: usize) -> (usize, usize) {
        let x = self.x() + n;

        if x > self.text[self.y()].len() {
            (self.text[self.y()].len(), self.y())
        } else {
            (x, self.y())
        }
    }
    pub fn right(&mut self, n: usize) {
        self.cursor_mut().x = self.right_pos(n).0;
    }

    /// Get left pos
    pub fn left_pos(&self, n: usize) -> (usize, usize) {
        if n <= self.x() {
            (self.x() - n, self.y())
        } else {
            (0, self.y())
        }

    }
    pub fn left(&mut self, n: usize) {
        self.cursor_mut().x = self.left_pos(n).0;
    }

    /// Get up pos
    pub fn up_pos(&self, n: usize) -> (usize, usize) {
        if n <= self.y() {
            (self.cursor().x, self.y() - n)
        } else {
            (self.cursor().x, 0)
        }
    }
    pub fn up(&mut self, n: usize) {
        let (x, y) = self.up_pos(n);
        self.cursor_mut().x = x;
        self.cursor_mut().y = y;
    }

    /// Get down pos
    pub fn down_pos(&self, n: usize) -> (usize, usize) {
        let y = self.y() + n;

        if y >= self.text.len() {
            (self.cursor().x, self.text.len() - 1)
        } else {
            (self.cursor().x, y)
        }
    }

    pub fn down(&mut self, n: usize) {
        let (x, y) = self.down_pos(n);
        self.cursor_mut().x = x;
        self.cursor_mut().y = y;
    }

}
<commit_msg>Fix bug in previous function<commit_after>use super::*;

impl Editor {
    /// Get pos of next char
    pub fn next_pos(&self) -> (usize, usize) {
        // TODO: Add numerals
        if self.x() == self.text[self.y()].len() {
            if self.y() < self.text.len() - 1 {
                (0, self.y() + 1)
            } else {
                (self.x(), self.y())
            }
        } else {
            (self.x() + 1, self.y())
        }
    }

    /// Get pos of previous char
    pub fn previous_pos(&self) -> (usize, usize) {
        if self.x() == 0 {
            if self.y() > 0 {
                (self.text[self.y() - 1].len(), self.y() - 1)
            } else {
                (self.x(), self.y())
            }
        } else {
            (self.x() - 1, self.y())
        }
    }

    pub fn next(&mut self) {
        let (x, y) = self.next_pos();
        self.cursor_mut().x = x;
        self.cursor_mut().y = y;
    }
    pub fn previous(&mut self) {
        let (x, y) = self.previous_pos();
        self.cursor_mut().x = x;
        self.cursor_mut().y = y;
    }

    /// Get right pos
    pub fn right_pos(&self, n: usize) -> (usize, usize) {
        let x = self.x() + n;

        if x > self.text[self.y()].len() {
            (self.text[self.y()].len(), self.y())
        } else {
            (x, self.y())
        }
    }
    pub fn right(&mut self, n: usize) {
        self.cursor_mut().x = self.right_pos(n).0;
    }

    /// Get left pos
    pub fn left_pos(&self, n: usize) -> (usize, usize) {
        if n <= self.x() {
            (self.x() - n, self.y())
        } else {
            (0, self.y())
        }

    }
    pub fn left(&mut self, n: usize) {
        self.cursor_mut().x = self.left_pos(n).0;
    }

    /// Get up pos
    pub fn up_pos(&self, n: usize) -> (usize, usize) {
        if n <= self.y() {
            (self.cursor().x, self.y() - n)
        } else {
            (self.cursor().x, 0)
        }
    }
    pub fn up(&mut self, n: usize) {
        let (x, y) = self.up_pos(n);
        self.cursor_mut().x = x;
        self.cursor_mut().y = y;
    }

    /// Get down pos
    pub fn down_pos(&self, n: usize) -> (usize, usize) {
        let y = self.y() + n;

        if y >= self.text.len() {
            (self.cursor().x, self.text.len() - 1)
        } else {
            (self.cursor().x, y)
        }
    }

    pub fn down(&mut self, n: usize) {
        let (x, y) = self.down_pos(n);
        self.cursor_mut().x = x;
        self.cursor_mut().y = y;
    }

}
<|endoftext|>


<commit_before><commit_msg>Add RawLink<commit_after>use core::ptr;
use core::fmt;
use core::mem;

/// A `RawLink` provides an `Option`-like interface to a raw pointer.
#[allow(raw_pointer_derive)]
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct RawLink<T>(*mut T);

unsafe impl<T> Send for RawLink<T>
where T: 'static
    , T: Send {}

unsafe impl<T> Sync for RawLink<T>
where T: Send
    , T: Sync {}

impl<T> Default for RawLink<T> {
    fn default() -> Self { Self::none() }
}

impl<T> fmt::Display for RawLink<T>
where T: fmt::Display {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.0.is_null() {
            write!(f, "RawLink::none")
        } else {
            unsafe { write!(f, "RawLink::some({})", *self.0) }
        }

    }
}

impl<T> RawLink<T> {

    /// Equivalent of `Option::None` for a `RawLink`
    ///
    /// # Returns
    ///   - A `RawLink<T>` wrapping a null pointer
    #[inline]
    pub fn none() -> RawLink<T> { RawLink(ptr::null_mut()) }

    /// Equivalent of `Option::Some` for a `RawLink`
    ///
    /// # Returns
    ///   - A `RawLink<T>` wrapping a pointer to the specified value
    #[inline]
    pub fn some(thing: &mut T) -> RawLink<T> { RawLink(thing) }

    /// Resolve the `RawLink` to an `Option`
    ///
    /// # Returns
    ///   - `Some<&'a T>` if the `RawLink` is not a null pointer
    ///   - `None` if the `RawLink` is a null pointer
    ///
    /// # Unsafe due to
    ///   - Returning a reference with an arbitrary lifetime
    ///   - Dereferencing a raw pointer
    #[inline]
    pub unsafe fn resolve<'a>(&self) -> Option<&'a T> {
        self.0.as_ref()
    }

    /// Resolve the `RawLink` to an `Option` on a mutable pointer
    ///
    /// # Returns
    ///   - `Some<&'a mut T>` if the `RawLink` is not a null pointer
    ///   - `None` if the `RawLink` is a null pointer
    ///
    /// # Unsafe due to
    ///   - Returning a reference with an arbitrary lifetime
    ///   - Dereferencing a raw pointer
    #[inline]
    pub unsafe fn resolve_mut<'a>(&self) -> Option<&'a mut T> {
        self.0.as_mut()
    }

    /// Returns the `RawLink` and replaces it with `RawLink::none()`.
    #[inline]
    pub fn take(&mut self) -> Self { mem::replace(self, Self::none()) }
}
<|endoftext|>


<commit_before><commit_msg>changed get_opt to get_checked<commit_after><|endoftext|>


<commit_before><commit_msg>impl Display for Action<commit_after><|endoftext|>


<commit_before>// xfail-fast - check-fast doesn't understand aux-build
// aux-build:cci_intrinsic.rs

// xfail-check

use cci_intrinsic;
import cci_intrinsic::atomic_xchng;

fn main() {
    let mut x = 1;
    atomic_xchng(x, 5);
    assert x == 5;
}
<commit_msg>Fix xfail comment<commit_after>// xfail-fast - check-fast doesn't understand aux-build
// aux-build:cci_intrinsic.rs

// xfail-test

use cci_intrinsic;
import cci_intrinsic::atomic_xchng;

fn main() {
    let mut x = 1;
    atomic_xchng(x, 5);
    assert x == 5;
}
<|endoftext|>


<commit_before><commit_msg>Add cargo-fmt binary<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.

// Inspired by Paul Woolcock's cargo-fmt (https://github.com/pwoolcoc/cargo-fmt/)

#![cfg(not(test))]
#![cfg(feature="cargo-fmt")]

extern crate getopts;
extern crate walkdir;
extern crate rustc_serialize;

use std::path::PathBuf;
use std::process::Command;
use std::env;
use std::str;

use getopts::Options;
use walkdir::{WalkDir, DirEntry};
use rustc_serialize::json::Json;

fn main() {
    let mut opts = getopts::Options::new();
    opts.optflag("h", "help", "show this message");

    let matches = match opts.parse(env::args().skip(1)) {
        Ok(m) => m,
        Err(e) => {
            print_usage(&opts, &e.to_string());
            return;
        }
    };

    if matches.opt_present("h") {
        print_usage(&opts, "");
    } else {
        format_crate(&opts);
    }
}

fn print_usage(opts: &Options, reason: &str) {
    let msg = format!("{}\nusage: cargo fmt [options]", reason);
    println!("{}\nThis utility formats all readable .rs files in the src directory of the \
              current crate using rustfmt.",
             opts.usage(&msg));
}

fn format_crate(opts: &Options) {
    let mut root = match locate_root() {
        Ok(r) => r,
        Err(e) => {
            print_usage(opts, &e.to_string());
            return;
        }
    };

    // Currently only files in [root]/src can be formatted
    root.push("src");
    // All unreadable or non .rs files are skipped
    let files: Vec<_> = WalkDir::new(root)
                            .into_iter()
                            .filter(is_rs_file)
                            .filter_map(|f| f.ok())
                            .map(|e| e.path().to_owned())
                            .collect();

    format_files(&files).unwrap_or_else(|e| print_usage(opts, &e.to_string()));
}

fn locate_root() -> Result<PathBuf, std::io::Error> {
    // This seems adequate, as cargo-fmt can only be used systems that have Cargo installed
    let output = try!(Command::new("cargo").arg("locate-project").output());
    if output.status.success() {
        // We assume cargo locate-project is not broken and
        // it will output a valid json document
        let data = &String::from_utf8(output.stdout).unwrap();
        let json = Json::from_str(data).unwrap();
        let root = PathBuf::from(json.find("root").unwrap().as_string().unwrap());

        // root.parent() should never fail if locate-project's output is correct
        Ok(root.parent().unwrap().to_owned())
    } else {
        // This happens when cargo-fmt is not used inside a crate
        Err(std::io::Error::new(std::io::ErrorKind::NotFound,
                                str::from_utf8(&output.stderr).unwrap()))
    }
}

fn is_rs_file(entry: &Result<walkdir::DirEntry, walkdir::Error>) -> bool {
    match *entry {
        Ok(ref file) => {
            match file.path().extension() {
                Some(ext) => ext == "rs",
                None => false,
            }
        }
        Err(_) => false,
    }
}

fn format_files(files: &Vec<PathBuf>) -> Result<(), std::io::Error> {
    let mut command = try!(Command::new("rustfmt")
                               .arg("--write-mode=overwrite")
                               .args(files)
                               .spawn());
    try!(command.wait());

    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #33696 - nham:add-test-21225, r=luqmana<commit_after>// Copyright 2016 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 error message when enum variants are used as types

// issue 21225
enum Ty {
    A,
    B(Ty::A),
    //~^ ERROR: found value `Ty::A` used as a type
}

// issue 19197
enum E {
    A
}

impl E::A {}
//~^ ERROR: found value `E::A` used as a type

fn main() {}
<|endoftext|>