<commit_before>#![feature(phase)]
#![crate_name = "terrain"]

extern crate cgmath;
extern crate gfx;
#[phase(plugin)]
extern crate gfx_macros;
extern crate glfw;
extern crate native;
extern crate time;
extern crate vertex;
extern crate noise;

use cgmath::FixedArray;
use cgmath::{Matrix4, Point3, Vector3};
use cgmath::{Transform, AffineMatrix3};
use gfx::{Device, DeviceHelper};
use glfw::Context;
use vertex::{Vertices, MapToVertices, Triangulate};
use vertex::generators::Plane;
use time::precise_time_s;

use noise::source::Perlin;
use noise::source::Source;

#[vertex_format]
struct Vertex {
    #[name = "a_Pos"]
    pos: [f32, ..3],

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

impl Clone for Vertex {
    fn clone(&self) -> Vertex {
        Vertex { pos: self.pos, color: self.color }
    }
}

// The shader_param attribute makes sure the following struct can be used to
// pass parameters to a shader. Its argument is the name of the type that will
// be generated to represent your the program. Search for link_program below, to
// see how it's used.
#[shader_param(MyProgram)]
struct Params {
    #[name = "u_Model"]
    model: [[f32, ..4], ..4],

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

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

static VERTEX_SRC: gfx::ShaderSource = shaders! {
GLSL_120: b"
    #version 120

    attribute vec3 a_Pos;
    attribute vec3 a_Color;
    varying vec3 v_Color;

    uniform mat4 u_Model;
    uniform mat4 u_View;
    uniform mat4 u_Proj;

    void main() {
        v_Color = a_Color;
        gl_Position = u_Proj * u_View * u_Model * vec4(a_Pos, 1.0);
    }
"
GLSL_150: b"
    #version 150 core

    in vec3 a_Pos;
    in vec3 a_Color;
    out vec3 v_Color;

    uniform mat4 u_Model;
    uniform mat4 u_View;
    uniform mat4 u_Proj;

    void main() {
        v_Color = a_Color;
        gl_Position = u_Proj * u_View * u_Model * vec4(a_Pos, 1.0);
    }
"
};

static FRAGMENT_SRC: gfx::ShaderSource = shaders! {
GLSL_120: b"
    #version 120

    varying vec3 v_Color;
    out vec4 o_Color;

    void main() {
        o_Color = vec4(v_Color, 1.0);
    }
"
GLSL_150: b"
    #version 150 core

    in vec3 v_Color;
    out vec4 o_Color;

    void main() {
        o_Color = vec4(v_Color, 1.0);
    }
"
};

// We need to run on the main thread, so ensure we are using the `native` runtime. This is
// technically not needed, since this is the default, but it's not guaranteed.
#[start]
fn start(argc: int, argv: *const *const u8) -> int {
     native::start(argc, argv, main)
}

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
    }
}

fn main() {
    let glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();

    glfw.window_hint(glfw::ContextVersion(3, 2));
    glfw.window_hint(glfw::OpenglForwardCompat(true));
    glfw.window_hint(glfw::OpenglProfile(glfw::OpenGlCoreProfile));

    let (window, events) = glfw
        .create_window(800, 600, "Terrain example", glfw::Windowed)
        .expect("Failed to create GLFW window.");

    window.make_current();
    glfw.set_error_callback(glfw::FAIL_ON_ERRORS);
    window.set_key_polling(true);

    let (w, h) = window.get_framebuffer_size();
    let frame = gfx::Frame::new(w as u16, h as u16);

    let mut device = gfx::GlDevice::new(|s| glfw.get_proc_address(s));
    let mut renderer = device.create_renderer();

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

    let noise = Perlin::new();

    let vertex_data: Vec<Vertex> = Plane::subdivide(256, 256)
        .vertex(|(x, y)| {
            let h = noise.get(x, y, 0.0) * 32.0;
            Vertex {
                pos: [-25.0 * x, 25.0 * y, h],
                color: calculate_color(h),
            }
        })
        .triangluate()
        .vertices()
        .collect();

    let mesh = device.create_mesh(vertex_data);
    let slice = mesh.get_slice(gfx::TriangleList);

    let prog: MyProgram = device
        .link_program(VERTEX_SRC.clone(), FRAGMENT_SRC.clone())
        .unwrap();

    let aspect = w as f32 / h as f32;
    let mut data = Params {
        model: Matrix4::identity().into_fixed(),
        view: Matrix4::identity().into_fixed(),
        proj: cgmath::perspective(cgmath::deg(60.0f32), aspect,
                                  0.1, 1000.0).into_fixed(),
    };

    let clear_data = gfx::ClearData {
        color: Some([0.3, 0.3, 0.3, 1.0]),
        depth: Some(1.0),
        stencil: None,
    };

    while !window.should_close() {
        glfw.poll_events();
        for (_, event) in glfw::flush_messages(&events) {
            match event {
                glfw::KeyEvent(glfw::KeyEscape, _, glfw::Press, _) =>
                    window.set_should_close(true),
                _ => {},
            }
        }

        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(),
        );
        data.view = view.mat.into_fixed();

        renderer.reset();
        renderer.clear(clear_data, &frame);
        renderer.draw(&mesh, slice, &frame, (&prog, &data), &state).unwrap();
        device.submit(renderer.as_buffer());

        window.swap_buffers();
    }
}
<commit_msg>Update for api-change in upstream of vertex-rs.<commit_after>#![feature(phase)]
#![crate_name = "terrain"]

extern crate cgmath;
extern crate gfx;
#[phase(plugin)]
extern crate gfx_macros;
extern crate glfw;
extern crate native;
extern crate time;
extern crate vertex;
extern crate noise;

use cgmath::FixedArray;
use cgmath::{Matrix4, Point3, Vector3};
use cgmath::{Transform, AffineMatrix3};
use gfx::{Device, DeviceHelper};
use glfw::Context;
use vertex::{Vertices, MapToVertices, Triangulate};
use vertex::generators::Plane;
use time::precise_time_s;

use noise::source::Perlin;
use noise::source::Source;

#[vertex_format]
struct Vertex {
    #[name = "a_Pos"]
    pos: [f32, ..3],

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

impl Clone for Vertex {
    fn clone(&self) -> Vertex {
        Vertex { pos: self.pos, color: self.color }
    }
}

// The shader_param attribute makes sure the following struct can be used to
// pass parameters to a shader. Its argument is the name of the type that will
// be generated to represent your the program. Search for link_program below, to
// see how it's used.
#[shader_param(MyProgram)]
struct Params {
    #[name = "u_Model"]
    model: [[f32, ..4], ..4],

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

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

static VERTEX_SRC: gfx::ShaderSource = shaders! {
GLSL_120: b"
    #version 120

    attribute vec3 a_Pos;
    attribute vec3 a_Color;
    varying vec3 v_Color;

    uniform mat4 u_Model;
    uniform mat4 u_View;
    uniform mat4 u_Proj;

    void main() {
        v_Color = a_Color;
        gl_Position = u_Proj * u_View * u_Model * vec4(a_Pos, 1.0);
    }
"
GLSL_150: b"
    #version 150 core

    in vec3 a_Pos;
    in vec3 a_Color;
    out vec3 v_Color;

    uniform mat4 u_Model;
    uniform mat4 u_View;
    uniform mat4 u_Proj;

    void main() {
        v_Color = a_Color;
        gl_Position = u_Proj * u_View * u_Model * vec4(a_Pos, 1.0);
    }
"
};

static FRAGMENT_SRC: gfx::ShaderSource = shaders! {
GLSL_120: b"
    #version 120

    varying vec3 v_Color;
    out vec4 o_Color;

    void main() {
        o_Color = vec4(v_Color, 1.0);
    }
"
GLSL_150: b"
    #version 150 core

    in vec3 v_Color;
    out vec4 o_Color;

    void main() {
        o_Color = vec4(v_Color, 1.0);
    }
"
};

// We need to run on the main thread, so ensure we are using the `native` runtime. This is
// technically not needed, since this is the default, but it's not guaranteed.
#[start]
fn start(argc: int, argv: *const *const u8) -> int {
     native::start(argc, argv, main)
}

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
    }
}

fn main() {
    let glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();

    glfw.window_hint(glfw::ContextVersion(3, 2));
    glfw.window_hint(glfw::OpenglForwardCompat(true));
    glfw.window_hint(glfw::OpenglProfile(glfw::OpenGlCoreProfile));

    let (window, events) = glfw
        .create_window(800, 600, "Terrain example", glfw::Windowed)
        .expect("Failed to create GLFW window.");

    window.make_current();
    glfw.set_error_callback(glfw::FAIL_ON_ERRORS);
    window.set_key_polling(true);

    let (w, h) = window.get_framebuffer_size();
    let frame = gfx::Frame::new(w as u16, h as u16);

    let mut device = gfx::GlDevice::new(|s| glfw.get_proc_address(s));
    let mut renderer = device.create_renderer();

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

    let noise = Perlin::new();

    let vertex_data: Vec<Vertex> = Plane::subdivide(256, 256)
        .vertex(|(x, y)| {
            let h = noise.get(x, y, 0.0) * 32.0;
            Vertex {
                pos: [-25.0 * x, 25.0 * y, h],
                color: calculate_color(h),
            }
        })
        .triangulate()
        .vertices()
        .collect();

    let mesh = device.create_mesh(vertex_data);
    let slice = mesh.get_slice(gfx::TriangleList);

    let prog: MyProgram = device
        .link_program(VERTEX_SRC.clone(), FRAGMENT_SRC.clone())
        .unwrap();

    let aspect = w as f32 / h as f32;
    let mut data = Params {
        model: Matrix4::identity().into_fixed(),
        view: Matrix4::identity().into_fixed(),
        proj: cgmath::perspective(cgmath::deg(60.0f32), aspect,
                                  0.1, 1000.0).into_fixed(),
    };

    let clear_data = gfx::ClearData {
        color: Some([0.3, 0.3, 0.3, 1.0]),
        depth: Some(1.0),
        stencil: None,
    };

    while !window.should_close() {
        glfw.poll_events();
        for (_, event) in glfw::flush_messages(&events) {
            match event {
                glfw::KeyEvent(glfw::KeyEscape, _, glfw::Press, _) =>
                    window.set_should_close(true),
                _ => {},
            }
        }

        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(),
        );
        data.view = view.mat.into_fixed();

        renderer.reset();
        renderer.clear(clear_data, &frame);
        renderer.draw(&mesh, slice, &frame, (&prog, &data), &state).unwrap();
        device.submit(renderer.as_buffer());

        window.swap_buffers();
    }
}
<|endoftext|>


<commit_before><commit_msg>Reorder Renderer trait methods<commit_after><|endoftext|>


<commit_before>// Copyright 2017 Google Inc. All rights reserved.
//
// 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.

//! RPC types, corresponding to protocol requests, notifications & responses.

use std::path::PathBuf;

use serde::de::{self, Deserialize, Deserializer};
use serde::ser::{self, Serialize, Serializer};
use serde_json::{self, Value};

use xi_rope::rope::RopeDelta;
use super::PluginPid;
use syntax::SyntaxDefinition;
use tabs::{BufferIdentifier, ViewIdentifier};
use config::Table;

//TODO: At the moment (May 08, 2017) this is all very much in flux.
// At some point, it will be stabalized and then perhaps will live in another crate,
// shared with the plugin lib.

// ====================================================================
// core -> plugin RPC method types + responses
// ====================================================================

/// Buffer information sent on plugin init.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PluginBufferInfo {
    /// The buffer's unique identifier.
    pub buffer_id: BufferIdentifier,
    /// The buffer's current views.
    pub views: Vec<ViewIdentifier>,
    pub rev: u64,
    pub buf_size: usize,
    pub nb_lines: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    pub syntax: SyntaxDefinition,
    pub config: Table,
}

//TODO: very likely this should be merged with PluginDescription
//TODO: also this does not belong here.
/// Describes an available plugin to the client.
#[derive(Serialize, Deserialize, Debug)]
pub struct ClientPluginInfo {
    pub name: String,
    pub running: bool,
}

/// A simple update, sent to a plugin.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PluginUpdate {
    pub view_id: ViewIdentifier,
    /// The delta representing changes to the document.
    ///
    /// Note: Is `Some` in the general case; only if the delta involves
    /// inserting more than some maximum number of bytes, will this be `None`,
    /// indicating the plugin should flush cache and fetch manually.
    pub delta: Option<RopeDelta>,
    /// The size of the document after applying this delta.
    pub new_len: usize,
    pub rev: u64,
    pub edit_type: String,
    pub author: String,
}

/// A response to an `update` RPC sent to a plugin.
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
pub enum UpdateResponse {
    /// An edit to the buffer.
    Edit(PluginEdit),
    /// An acknowledgement with no action. A response cannot be Null,
    /// so we send a uint.
    Ack(u64),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmptyStruct {}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "method", content = "params")]
/// RPC requests sent from the host
pub enum HostRequest {
    Update(PluginUpdate),
    CollectTrace(EmptyStruct),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "method", content = "params")]
/// RPC Notifications sent from the host
pub enum HostNotification {
    Ping(EmptyStruct),
    Initialize { plugin_id: PluginPid, buffer_info: Vec<PluginBufferInfo> },
    DidSave { view_id: ViewIdentifier, path: PathBuf },
    ConfigChanged { view_id: ViewIdentifier, changes: Table },
    NewBuffer { buffer_info: Vec<PluginBufferInfo> },
    DidClose { view_id: ViewIdentifier },
    Shutdown(EmptyStruct),
    TracingConfig {enabled: bool},
}

// ====================================================================
// plugin -> core RPC method types
// ====================================================================

/// A simple edit, received from a plugin.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PluginEdit {
    pub rev: u64,
    pub delta: RopeDelta,
    /// the edit priority determines the resolution strategy when merging
    /// concurrent edits. The highest priority edit will be applied last.
    pub priority: u64,
    /// whether the inserted text prefers to be to the right of the cursor.
    pub after_cursor: bool,
    /// the originator of this edit: some identifier (plugin name, 'core', etc)
    pub author: String,
}

#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub struct ScopeSpan {
    pub start: usize,
    pub end: usize,
    pub scope_id: u32,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "method", content = "params")]
/// RPC requests sent from plugins.
pub enum PluginRequest {
    GetData { offset: usize, max_size: usize, rev: u64 },
    LineCount,
    GetSelections,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "method", content = "params")]
/// RPC commands sent from plugins.
pub enum PluginNotification {
    AddScopes { scopes: Vec<Vec<String>> },
    UpdateSpans { start: usize, len: usize, spans: Vec<ScopeSpan>, rev: u64 },
    Edit { edit: PluginEdit },
    Alert { msg: String },
}

/// Common wrapper for plugin-originating RPCs.
pub struct PluginCommand<T> {
    pub view_id: ViewIdentifier,
    pub plugin_id: PluginPid,
    pub cmd: T,
}

impl<T: Serialize> Serialize for PluginCommand<T>
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: Serializer
    {
        let mut v = serde_json::to_value(&self.cmd).map_err(ser::Error::custom)?;
        v["params"]["view_id"] = json!(self.view_id);
        v["params"]["plugin_id"] = json!(self.plugin_id);
        v.serialize(serializer)
    }
}

impl<'de, T: Deserialize<'de>> Deserialize<'de> for PluginCommand<T>
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where D: Deserializer<'de>
    {
        #[derive(Deserialize)]
        struct InnerIds {
            view_id: ViewIdentifier,
            plugin_id: PluginPid,
        }
        #[derive(Deserialize)]
        struct IdsWrapper {
            params: InnerIds,
        }

        let v = Value::deserialize(deserializer)?;
        let helper = IdsWrapper::deserialize(&v).map_err(de::Error::custom)?;
        let InnerIds { view_id, plugin_id } = helper.params;
        let cmd = T::deserialize(v).map_err(de::Error::custom)?;
        Ok(PluginCommand { view_id, plugin_id, cmd })
    }
}

impl PluginBufferInfo {
    pub fn new(buffer_id: BufferIdentifier, views: &[ViewIdentifier],
               rev: u64, buf_size: usize, nb_lines: usize,
               path: Option<PathBuf>, syntax: SyntaxDefinition,
               config: Table) -> Self {
        //TODO: do make any current assertions about paths being valid utf-8? do we want to?
        let path = path.map(|p| p.to_str().unwrap().to_owned());
        let views = views.to_owned();
        PluginBufferInfo { buffer_id, views, rev, buf_size,
        nb_lines, path, syntax, config }
    }
}

impl PluginUpdate {
    pub fn new<D>(view_id: ViewIdentifier, rev: u64, delta: D, new_len: usize,
                  edit_type: String, author: String) -> Self
        where D: Into<Option<RopeDelta>>
    {
        let delta = delta.into();
        PluginUpdate { view_id, delta, new_len, rev, edit_type, author }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json;

    #[test]
    fn test_plugin_update() {
        let json = r#"{
            "view_id": "view-id-42",
            "delta": {"base_len": 6, "els": [{"copy": [0,5]}, {"insert":"rofls"}]},
            "new_len": 404,
            "rev": 5,
            "edit_type": "something",
            "author": "me"
    }"#;

    let val: PluginUpdate = match serde_json::from_str(json) {
        Ok(val) => val,
        Err(err) => panic!("{:?}", err),
    };
    assert!(val.delta.is_some());
    assert!(val.delta.unwrap().as_simple_insert().is_some());
    }

    #[test]
    fn test_deserde_init() {
        let json = r#"
            {"buffer_id": 42,
             "views": ["view-id-4"],
             "rev": 1,
             "buf_size": 20,
             "nb_lines": 5,
             "path": "some_path",
             "syntax": "toml",
             "config": {"some_key": 420}}"#;

        let val: PluginBufferInfo = match serde_json::from_str(json) {
            Ok(val) => val,
            Err(err) => panic!("{:?}", err),
        };
        assert_eq!(val.rev, 1);
        assert_eq!(val.path, Some("some_path".to_owned()));
        assert_eq!(val.syntax, SyntaxDefinition::Toml);
    }

    #[test]
    fn test_de_plugin_rpc() {
        let json = r#"{"method": "alert", "params": {"view_id": "view-id-1", "plugin_id": 42, "msg": "ahhh!"}}"#;
        let de: PluginCommand<PluginNotification> = serde_json::from_str(json).unwrap();
        assert_eq!(de.view_id, "view-id-1".into());
        assert_eq!(de.plugin_id, PluginPid(42));
        match de.cmd {
            PluginNotification::Alert { ref msg } if msg == "ahhh!" => (),
            _ => panic!("{:?}", de.cmd),
        }
    }
}
<commit_msg>Fix incorrect test<commit_after>// Copyright 2017 Google Inc. All rights reserved.
//
// 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.

//! RPC types, corresponding to protocol requests, notifications & responses.

use std::path::PathBuf;

use serde::de::{self, Deserialize, Deserializer};
use serde::ser::{self, Serialize, Serializer};
use serde_json::{self, Value};

use xi_rope::rope::RopeDelta;
use super::PluginPid;
use syntax::SyntaxDefinition;
use tabs::{BufferIdentifier, ViewIdentifier};
use config::Table;

//TODO: At the moment (May 08, 2017) this is all very much in flux.
// At some point, it will be stabalized and then perhaps will live in another crate,
// shared with the plugin lib.

// ====================================================================
// core -> plugin RPC method types + responses
// ====================================================================

/// Buffer information sent on plugin init.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PluginBufferInfo {
    /// The buffer's unique identifier.
    pub buffer_id: BufferIdentifier,
    /// The buffer's current views.
    pub views: Vec<ViewIdentifier>,
    pub rev: u64,
    pub buf_size: usize,
    pub nb_lines: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    pub syntax: SyntaxDefinition,
    pub config: Table,
}

//TODO: very likely this should be merged with PluginDescription
//TODO: also this does not belong here.
/// Describes an available plugin to the client.
#[derive(Serialize, Deserialize, Debug)]
pub struct ClientPluginInfo {
    pub name: String,
    pub running: bool,
}

/// A simple update, sent to a plugin.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PluginUpdate {
    pub view_id: ViewIdentifier,
    /// The delta representing changes to the document.
    ///
    /// Note: Is `Some` in the general case; only if the delta involves
    /// inserting more than some maximum number of bytes, will this be `None`,
    /// indicating the plugin should flush cache and fetch manually.
    pub delta: Option<RopeDelta>,
    /// The size of the document after applying this delta.
    pub new_len: usize,
    pub rev: u64,
    pub edit_type: String,
    pub author: String,
}

/// A response to an `update` RPC sent to a plugin.
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
pub enum UpdateResponse {
    /// An edit to the buffer.
    Edit(PluginEdit),
    /// An acknowledgement with no action. A response cannot be Null,
    /// so we send a uint.
    Ack(u64),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmptyStruct {}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "method", content = "params")]
/// RPC requests sent from the host
pub enum HostRequest {
    Update(PluginUpdate),
    CollectTrace(EmptyStruct),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "method", content = "params")]
/// RPC Notifications sent from the host
pub enum HostNotification {
    Ping(EmptyStruct),
    Initialize { plugin_id: PluginPid, buffer_info: Vec<PluginBufferInfo> },
    DidSave { view_id: ViewIdentifier, path: PathBuf },
    ConfigChanged { view_id: ViewIdentifier, changes: Table },
    NewBuffer { buffer_info: Vec<PluginBufferInfo> },
    DidClose { view_id: ViewIdentifier },
    Shutdown(EmptyStruct),
    TracingConfig {enabled: bool},
}

// ====================================================================
// plugin -> core RPC method types
// ====================================================================

/// A simple edit, received from a plugin.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PluginEdit {
    pub rev: u64,
    pub delta: RopeDelta,
    /// the edit priority determines the resolution strategy when merging
    /// concurrent edits. The highest priority edit will be applied last.
    pub priority: u64,
    /// whether the inserted text prefers to be to the right of the cursor.
    pub after_cursor: bool,
    /// the originator of this edit: some identifier (plugin name, 'core', etc)
    pub author: String,
}

#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub struct ScopeSpan {
    pub start: usize,
    pub end: usize,
    pub scope_id: u32,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "method", content = "params")]
/// RPC requests sent from plugins.
pub enum PluginRequest {
    GetData { offset: usize, max_size: usize, rev: u64 },
    LineCount,
    GetSelections,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "method", content = "params")]
/// RPC commands sent from plugins.
pub enum PluginNotification {
    AddScopes { scopes: Vec<Vec<String>> },
    UpdateSpans { start: usize, len: usize, spans: Vec<ScopeSpan>, rev: u64 },
    Edit { edit: PluginEdit },
    Alert { msg: String },
}

/// Common wrapper for plugin-originating RPCs.
pub struct PluginCommand<T> {
    pub view_id: ViewIdentifier,
    pub plugin_id: PluginPid,
    pub cmd: T,
}

impl<T: Serialize> Serialize for PluginCommand<T>
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: Serializer
    {
        let mut v = serde_json::to_value(&self.cmd).map_err(ser::Error::custom)?;
        v["params"]["view_id"] = json!(self.view_id);
        v["params"]["plugin_id"] = json!(self.plugin_id);
        v.serialize(serializer)
    }
}

impl<'de, T: Deserialize<'de>> Deserialize<'de> for PluginCommand<T>
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where D: Deserializer<'de>
    {
        #[derive(Deserialize)]
        struct InnerIds {
            view_id: ViewIdentifier,
            plugin_id: PluginPid,
        }
        #[derive(Deserialize)]
        struct IdsWrapper {
            params: InnerIds,
        }

        let v = Value::deserialize(deserializer)?;
        let helper = IdsWrapper::deserialize(&v).map_err(de::Error::custom)?;
        let InnerIds { view_id, plugin_id } = helper.params;
        let cmd = T::deserialize(v).map_err(de::Error::custom)?;
        Ok(PluginCommand { view_id, plugin_id, cmd })
    }
}

impl PluginBufferInfo {
    pub fn new(buffer_id: BufferIdentifier, views: &[ViewIdentifier],
               rev: u64, buf_size: usize, nb_lines: usize,
               path: Option<PathBuf>, syntax: SyntaxDefinition,
               config: Table) -> Self {
        //TODO: do make any current assertions about paths being valid utf-8? do we want to?
        let path = path.map(|p| p.to_str().unwrap().to_owned());
        let views = views.to_owned();
        PluginBufferInfo { buffer_id, views, rev, buf_size,
        nb_lines, path, syntax, config }
    }
}

impl PluginUpdate {
    pub fn new<D>(view_id: ViewIdentifier, rev: u64, delta: D, new_len: usize,
                  edit_type: String, author: String) -> Self
        where D: Into<Option<RopeDelta>>
    {
        let delta = delta.into();
        PluginUpdate { view_id, delta, new_len, rev, edit_type, author }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json;

    #[test]
    fn test_plugin_update() {
        let json = r#"{
            "view_id": "view-id-42",
            "delta": {"base_len": 6, "els": [{"copy": [0,5]}, {"insert":"rofls"}, {"copy": [5,6]}]},
            "new_len": 11,
            "rev": 5,
            "edit_type": "something",
            "author": "me"
    }"#;

    let val: PluginUpdate = match serde_json::from_str(json) {
        Ok(val) => val,
        Err(err) => panic!("{:?}", err),
    };
    assert!(val.delta.is_some());
    assert!(val.delta.unwrap().as_simple_insert().is_some());
    }

    #[test]
    fn test_deserde_init() {
        let json = r#"
            {"buffer_id": 42,
             "views": ["view-id-4"],
             "rev": 1,
             "buf_size": 20,
             "nb_lines": 5,
             "path": "some_path",
             "syntax": "toml",
             "config": {"some_key": 420}}"#;

        let val: PluginBufferInfo = match serde_json::from_str(json) {
            Ok(val) => val,
            Err(err) => panic!("{:?}", err),
        };
        assert_eq!(val.rev, 1);
        assert_eq!(val.path, Some("some_path".to_owned()));
        assert_eq!(val.syntax, SyntaxDefinition::Toml);
    }

    #[test]
    fn test_de_plugin_rpc() {
        let json = r#"{"method": "alert", "params": {"view_id": "view-id-1", "plugin_id": 42, "msg": "ahhh!"}}"#;
        let de: PluginCommand<PluginNotification> = serde_json::from_str(json).unwrap();
        assert_eq!(de.view_id, "view-id-1".into());
        assert_eq!(de.plugin_id, PluginPid(42));
        match de.cmd {
            PluginNotification::Alert { ref msg } if msg == "ahhh!" => (),
            _ => panic!("{:?}", de.cmd),
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Parameter modification<commit_after>fn modifies(x: &mut f64) {
    *x = 1.0;
}

fn main() {
    let mut res = 0.0;
    println!("res is {}", res);
    modifies(&mut res);
    println!("res is {}", res);

    //IMPOTANT: THIS DOESN'T WORK
    //Uncomment to see the error warning to better understand
    //let mut_res = modifies(&mut res);
    //println!("res is {}", mut_res);
}
<|endoftext|>


<commit_before>// FIXME: Needs additional cocoa setup on OS X. rust-cocoa should probably just
// be a dependency

#[test]
#[ignore(cfg(target_os = "macos"))]
pub fn test_everything() {

    do task::spawn {
        assert sdl::init(~[sdl::InitVideo, sdl::InitTimer]) == true;
        run_tests(~[
            general::test_was_init,
            general::test_set_error,
            general::test_error,
            general::test_clear_error,
            video::test_set_video_mode,
            // FIXME: Doesn't work when called from a directory that
            // doesn't contain the test image file
            video::test_blit, //Comment out before merge
            test_event::test_poll_event_none,
            // FIXME: This test is interactive
            test_event::test_keyboard, //Comment out before merge

        ]);
        sdl::quit();
    }
}

fn run_tests(tests: &[fn()]) {
    for tests.each |test| {
        (*test)();
    }
}

mod general {
    pub fn test_was_init() {
        assert vec::contains(~[sdl::InitTimer], &sdl::InitTimer);
    }

    pub fn test_set_error() {
        sdl::set_error(~"test");
        assert sdl::get_error() == ~"test";
    }

    pub fn test_error() {
        sdl::clear_error();
        assert str::is_empty(sdl::get_error());
        sdl::error(sdl::ENoMem);
        assert str::is_not_empty(sdl::get_error());
    }

    pub fn test_clear_error() {
        sdl::set_error(~"test");
        sdl::clear_error();
        assert str::is_empty(sdl::get_error());
    }
}

mod test_event {
    pub fn test_poll_event_none() {
        ::event::poll_event(|event| assert event == ::event::NoEvent);
    }

    pub fn test_keyboard() {
        io::println(~"press a key in the window");
        let maybe_surface = ::video::set_video_mode(320, 200, 32,
            ~[::video::SWSurface], ~[::video::DoubleBuf, ::video::Resizable]);

        match maybe_surface {
            result::Ok(_) => {
                let mut keydown = false;
                let mut keyup = false;
                while !keydown || !keyup {
                    ::event::poll_event(|event| {
                        match event {
                          event::KeyUpEvent(_) => keyup = true,
                          event::KeyDownEvent(_) => keydown = true,
                          _ => { }
                        }
                    })
                }
            }
            result::Err(_) => {
                fail;
            }
        }
    }
}

mod video {

    pub fn test_set_video_mode() {
        let maybe_surface = ::video::set_video_mode(320, 200, 32,
            ~[::video::HWSurface], ~[::video::DoubleBuf]);

        assert result::is_ok(&maybe_surface);
    }

    pub fn test_blit() {
        let maybe_screen = ::video::set_video_mode(320, 200, 32,
            ~[::video::SWSurface], ~[::video::DoubleBuf]);

        assert result::is_ok(&maybe_screen);

        match maybe_screen {
            result::Ok(screen) => {
                // FIXME: We need to load this from the crate instead of
                // off the filesystem
                let maybe_image = match ::video::load_bmp(~"rust-logo-128x128-blk.bmp") {
                    result::Ok(raw_image) => {
                        raw_image.display_format()
                    },
                    result::Err(err) => result::Err(err)
                };

                assert result::is_ok(&maybe_image);

                match maybe_image {
                    result::Ok(image) => {
                        for iter::repeat(1u) || {
                            screen.blit_surface(image);
                            screen.flip();
                            ::event::poll_event(|_event| {})
                        };
                    },
                    result::Err(_) => ()
                };
            },
            result::Err(_) => ()
        };
    }
}
<commit_msg>Added notes of tests I need to write<commit_after>// FIXME: Needs additional cocoa setup on OS X. rust-cocoa should probably just
// be a dependency

#[test]
#[ignore(cfg(target_os = "macos"))]
pub fn test_everything() {

    do task::spawn {
        assert sdl::init(~[sdl::InitVideo, sdl::InitTimer]) == true;
        run_tests(~[
            general::test_was_init,
            general::test_set_error,
            general::test_error,
            general::test_clear_error,
            video::test_set_video_mode,
            // FIXME: Doesn't work when called from a directory that
            // doesn't contain the test image file
            video::test_blit, //Comment out before merge
            test_event::test_poll_event_none,
            // FIXME: This test is interactive
            test_event::test_keyboard, //Comment out before merge

        ]);
        sdl::quit();
    }
}

fn run_tests(tests: &[fn()]) {
    for tests.each |test| {
        (*test)();
    }
}

mod general {
    pub fn test_was_init() {
        assert vec::contains(~[sdl::InitTimer], &sdl::InitTimer);
    }

    pub fn test_set_error() {
        sdl::set_error(~"test");
        assert sdl::get_error() == ~"test";
    }

    pub fn test_error() {
        sdl::clear_error();
        assert str::is_empty(sdl::get_error());
        sdl::error(sdl::ENoMem);
        assert str::is_not_empty(sdl::get_error());
    }

    pub fn test_clear_error() {
        sdl::set_error(~"test");
        sdl::clear_error();
        assert str::is_empty(sdl::get_error());
    }
}

mod test_event {
    pub fn test_poll_event_none() {
        ::event::poll_event(|event| assert event == ::event::NoEvent);
    }

    pub fn test_keyboard_event_conversion() {
        //TODO: Implement me!
    }

    pub fn test_keyboard() {
        io::println(~"press a key in the window");
        let maybe_surface = ::video::set_video_mode(320, 200, 32,
            ~[::video::SWSurface], ~[::video::DoubleBuf, ::video::Resizable]);

        match maybe_surface {
            result::Ok(_) => {
                let mut keydown = false;
                let mut keyup = false;
                while !keydown || !keyup {
                    ::event::poll_event(|event| {
                        match event {
                          event::KeyUpEvent(_) => keyup = true,
                          event::KeyDownEvent(event) => keydown = true,
                          _ => { }
                        }
                    })
                }
            }
            result::Err(_) => {
                fail;
            }
        }
    }
}

mod video {

    pub fn test_set_video_mode() {
        let maybe_surface = ::video::set_video_mode(320, 200, 32,
            ~[::video::HWSurface], ~[::video::DoubleBuf]);

        assert result::is_ok(&maybe_surface);
    }

    pub fn test_blit() {
        let maybe_screen = ::video::set_video_mode(320, 200, 32,
            ~[::video::SWSurface], ~[::video::DoubleBuf]);

        assert result::is_ok(&maybe_screen);

        match maybe_screen {
            result::Ok(screen) => {
                // FIXME: We need to load this from the crate instead of
                // off the filesystem
                let maybe_image = match ::video::load_bmp(~"rust-logo-128x128-blk.bmp") {
                    result::Ok(raw_image) => {
                        raw_image.display_format()
                    },
                    result::Err(err) => result::Err(err)
                };

                assert result::is_ok(&maybe_image);

                match maybe_image {
                    result::Ok(image) => {
                        for iter::repeat(1u) || {
                            screen.blit_surface(image);
                            screen.flip();
                            ::event::poll_event(|_event| {})
                        };
                    },
                    result::Err(_) => ()
                };
            },
            result::Err(_) => ()
        };
    }
}
<|endoftext|>


<commit_before><commit_msg>r0.3.0/login: Add device_id to request & response<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for #59972<commit_after>// compile-flags: --edition=2018

#![feature(async_await, await_macro)]

pub enum Uninhabited { }

fn uninhabited_async() -> Uninhabited {
    unreachable!()
}

async fn noop() { }

#[allow(unused)]
async fn contains_never() {
    let error = uninhabited_async();
    await!(noop());
    let error2 = error;
}

#[allow(unused_must_use)]
fn main() {
    contains_never();
}
<|endoftext|>


<commit_before><commit_msg>update<commit_after>//计划用rust实现我大一C语言作业...
fn main(){

    let a = leijia(100);
    let b = add(20,10);
    println!("{} , {}",a,b);
}

fn add(a:i32, b:i32) -> i32{
    a + b
}
//此函数用来返回1+2+3+…+n，若n<=0,函数用来返回0。
fn leijia(mut a:i32) -> i32{
    let mut answer=0;
    while a>0 {
        answer = answer + a;
        a = a - 1;
    }
    answer
}

//此函数用来返回n!,若n<=0,函数用来返回0。
fn jiecheng(mut n:i32) -> i64{
    let mut answer:i64 = 1;
    if n <= 0 {
        return 0i64;
    }else{
        for i in 1..n+1 {
            answer = answer * i;
        }
    }
    answer
}
<|endoftext|>


<commit_before><commit_msg>Initial config<commit_after>use node::serde_json;
use super::super::crypto::PublicKey;

#[derive(Debug, Serialize, Deserialize)]
pub struct Configuration {
    version: u16,
    validators: Vec<PublicKey>,
    consensus: ConsensusCfg,
    network: NetworkCfg
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ConsensusCfg {
    round_timeout: u64,    // 2000
    status_timeout: u64,   // 5000
    peers_timeout: u64,    // 10000
    propose_timeout: u64,  // 500
    txs_block_limit: u16   // 500
}

#[derive(Debug, Serialize, Deserialize)]
pub struct NetworkCfg {
    max_incoming_connections: u16, // 128
    max_outgoing_connections: u16, // 128,
    tcp_keep_alive: Option<u32>,   // None,
    tcp_nodelay: bool,             // false,
    tcp_reconnect_timeout: u64,    // 5000,
    tcp_reconnect_timeout_max: u64 // 600000,
}

trait ConfigurationValidator {
    fn is_valid(&self) -> bool;
}

impl ConfigurationValidator for ConsensusCfg {
    fn is_valid(&self) -> bool {
        self.round_timeout < 10000
    }
}

impl ConfigurationValidator for NetworkCfg {
    fn is_valid(&self) -> bool {
        true
    }
}

impl Configuration {

    #[allow(dead_code)]
    fn serialize(&self) -> String {
        serde_json::to_string(&self).unwrap()
    }

    #[allow(dead_code)]
    fn deserialize(serialized: &str) -> Result<Configuration, &str> {
        let cfg: Configuration = serde_json::from_str(serialized).unwrap();
        if cfg.is_valid() {
            return Ok(cfg);
        }
        Err("not valid")
    }
}

impl ConfigurationValidator for Configuration {
    fn is_valid(&self) -> bool {
        self.consensus.is_valid() && self.network.is_valid()
    }
}

#[cfg(test)]
mod tests {

    use super::super::super::crypto::{gen_keypair};
    use super::{Configuration, ConsensusCfg, NetworkCfg, ConfigurationValidator};

    #[test]
    fn validate_configuration(){
        // Arrange

        let (p1, _) = gen_keypair();
        let (p2, _) = gen_keypair();
        let (p3, _) = gen_keypair();

        let cfg = Configuration {
            version: 1,
            validators: vec![p1, p2, p3],
            consensus: ConsensusCfg {
                round_timeout: 2000,
                status_timeout: 5000,
                peers_timeout: 10000,
                propose_timeout: 500,
                txs_block_limit: 500
            },
            network: NetworkCfg {
                max_incoming_connections: 128,
                max_outgoing_connections: 128,
                tcp_keep_alive: None,
                tcp_nodelay: false,
                tcp_reconnect_timeout: 5000,
                tcp_reconnect_timeout_max: 600000
            }

        };

        // Assert
        assert_eq!(cfg.is_valid(), true);
    }

    #[test]
    fn deserialize_correct_configuration(){
        // Arrange
        let json = "{\"version\":1,\"validators\":[[255,110,239,100,242,107,33,125,149,196,6,71,45,5,143,15,66,144,168,233,171,18,1,81,183,253,49,72,248,226,88,224],[100,2,253,143,161,127,247,209,175,28,191,6,240,0,255,119,238,66,101,154,110,219,187,25,28,34,69,65,223,131,163,227],[185,187,188,22,223,202,133,226,118,76,203,52,17,132,193,213,117,57,36,15,106,67,129,218,175,32,34,235,240,51,83,81]],\"consensus\":{\"round_timeout\":2000,\"status_timeout\":5000,\"peers_timeout\":10000,\"propose_timeout\":500,\"txs_block_limit\":500},\"network\":{\"max_incoming_connections\":128,\"max_outgoing_connections\":128,\"tcp_keep_alive\":null,\"tcp_nodelay\":false,\"tcp_reconnect_timeout\":5000,\"tcp_reconnect_timeout_max\":600000}}";

        // Act
        let cfg = Configuration::deserialize(json);

        // Assert
        assert_eq!(cfg.is_ok(), true);

    }

    #[test]
    fn deserialize_wrong_configuration(){
        // Arrange
        let json = "{\"version\":1,\"validators\":[[255,110,239,100,242,107,33,125,149,196,6,71,45,5,143,15,66,144,168,233,171,18,1,81,183,253,49,72,248,226,88,224],[100,2,253,143,161,127,247,209,175,28,191,6,240,0,255,119,238,66,101,154,110,219,187,25,28,34,69,65,223,131,163,227],[185,187,188,22,223,202,133,226,118,76,203,52,17,132,193,213,117,57,36,15,106,67,129,218,175,32,34,235,240,51,83,81]],\"consensus\":{\"round_timeout\":11000,\"status_timeout\":5000,\"peers_timeout\":10000,\"propose_timeout\":500,\"txs_block_limit\":500},\"network\":{\"max_incoming_connections\":128,\"max_outgoing_connections\":128,\"tcp_keep_alive\":null,\"tcp_nodelay\":false,\"tcp_reconnect_timeout\":5000,\"tcp_reconnect_timeout_max\":600000}}";

        // Act
        let cfg = Configuration::deserialize(json);

        // Assert
        assert_eq!(cfg.is_ok(), false);

    }

}<|endoftext|>


<commit_before>// TODO:
//      - Simplify using instruction iterators
//      - Make movement mode
//      - Record modifiers

mod editor;
pub use self::editor::*;

mod mode;
pub use self::mode::*;

mod movement;
pub use self::movement::*;

mod cursor;
pub use self::cursor::*;

mod insert;
pub use self::insert::*;

mod exec;
pub use self::exec::*;

use redox::*;

pub fn main() {
    let mut window = Window::new((rand() % 400 + 50) as isize,
								 (rand() % 300 + 50) as isize,
								 576,
								 400,
								 &"Sodium");

    let mut editor = Editor::new();

    editor.iter = Some({
        window.clone().filter_map(|x| {
            match x.to_option() {
                EventOption::Key(k) if k.pressed => {

                    Some(k.character)
                }
                _ => None,
            }
        })
    });
    window.set([255, 255, 255, 255]);

}

pub fn redraw() {
    /*
                    // Redraw window
                    window.set([255, 255, 255, 255]);

                    for (y, row) in editor.text.iter().enumerate() {
                        for (x, c) in row.iter().enumerate() {
                            window.char(8 * (y - editor.scroll_y) as isize, 16 * (x - editor.scroll_x) as isize, *c, [128, 128, 128, 255]);
                            if editor.cursor().x == x && editor.cursor().y == y {
                                window.char(8 * (y - editor.scroll_y) as isize, 16 * (x - editor.scroll_x) as isize, '_', [128, 128, 128, 255]);
                            }
                        }
                    }
    */
}
<commit_msg>Fix compile errors<commit_after>// TODO:
//      - Simplify using instruction iterators
//      - Make movement mode
//      - Record modifiers

mod editor;
pub use self::editor::*;

mod mode;
pub use self::mode::*;

mod movement;
pub use self::movement::*;

mod cursor;
pub use self::cursor::*;

mod insert;
pub use self::insert::*;

mod exec;
pub use self::exec::*;

use redox::*;

pub fn main() {
    let mut window = Window::new((rand() % 400 + 50) as isize,
								 (rand() % 300 + 50) as isize,
								 576,
								 400,
								 &"Sodium");

    let mut editor = Editor::new();

    editor.iter = Some({
        window.clone().filter_map(|x| {
            match x.to_option() {
                EventOption::Key(k) if k.pressed => {

                    Some(k.character)
                }
                _ => None,
            }
        })
    });
//    window.set([255, 255, 255, 255]);

}

pub fn redraw() {
    /*
                    // Redraw window
                    window.set([255, 255, 255, 255]);

                    for (y, row) in editor.text.iter().enumerate() {
                        for (x, c) in row.iter().enumerate() {
                            window.char(8 * (y - editor.scroll_y) as isize, 16 * (x - editor.scroll_x) as isize, *c, [128, 128, 128, 255]);
                            if editor.cursor().x == x && editor.cursor().y == y {
                                window.char(8 * (y - editor.scroll_y) as isize, 16 * (x - editor.scroll_x) as isize, '_', [128, 128, 128, 255]);
                            }
                        }
                    }
    */
}
<|endoftext|>


<commit_before><commit_msg>Added tests for Pcg32L<commit_after>extern crate pcg_rand;
extern crate rand;

use rand::{Rng, SeedableRng, thread_rng};
use pcg_rand::Pcg32L;

const NUM_TESTS : usize = 1000;

#[test]
fn pcg32l_unseeded() {
    let mut ra : Pcg32L = Pcg32L::new_unseeded();
    let mut rb : Pcg32L = Pcg32L::new_unseeded();
    assert_eq!(ra.gen_ascii_chars().take(100).collect::<Vec<_>>(),
               rb.gen_ascii_chars().take(100).collect::<Vec<_>>());
}

#[test]
fn pcg32l_seed_match() {
    for _ in 0..NUM_TESTS {
        let s : [u64;4] = thread_rng().gen();
        let mut ra : Pcg32L = SeedableRng::from_seed(s);
        let mut rb : Pcg32L = SeedableRng::from_seed(s);
        assert_eq!(ra.gen_ascii_chars().take(100).collect::<Vec<_>>(),
                   rb.gen_ascii_chars().take(100).collect::<Vec<_>>());
    }
}

#[test]
fn pcg32l_seq_diff() {
    for _ in 0..NUM_TESTS {
        //Test a bad case same seed with just slightly different
        //sequences. Because sequences have to be odd only sequences that are 2 apart
        //are for sure going to be different.
        let mut s : [u64;4] = thread_rng().gen();
        let mut ra : Pcg32L = SeedableRng::from_seed(s);
        s[1] = s[1]+2;
        let mut rb : Pcg32L = SeedableRng::from_seed(s);
        assert!(ra.gen_ascii_chars().take(100).collect::<Vec<_>>() !=
                rb.gen_ascii_chars().take(100).collect::<Vec<_>>());
    }
}

#[test]
fn pcg32l_seed_diff() {
    for _ in 0..NUM_TESTS {
        //Test a bad case same seed with just slightly different
        //seeds
        let mut s : [u64;4] = thread_rng().gen();
        let mut ra : Pcg32L = SeedableRng::from_seed(s);
        s[0] = s[0]+1;
        let mut rb : Pcg32L = SeedableRng::from_seed(s);
        assert!(ra.gen_ascii_chars().take(100).collect::<Vec<_>>() !=
                rb.gen_ascii_chars().take(100).collect::<Vec<_>>());
    }
}
<|endoftext|>


<commit_before><commit_msg>Add shebang tests<commit_after>#[macro_use]
mod macros;

#[test]
fn test_basic() {
    let content = "#!/usr/bin/env rustx\nfn main() {}";
    let file = syn::parse_file(content).unwrap();
    snapshot!(file, @r###"
    File {
        shebang: Some("#!/usr/bin/env rustx"),
        items: [
            Item::Fn {
                vis: Inherited,
                sig: Signature {
                    ident: "main",
                    generics: Generics,
                    output: Default,
                },
                block: Block,
            },
        ],
    }
    "###);
}

#[test]
fn test_comment() {
    let content = "#!//am/i/a/comment\n[allow(dead_code)] fn main() {}";
    let file = syn::parse_file(content).unwrap();
    snapshot!(file, @r###"
    File {
        attrs: [
            Attribute {
                style: Inner,
                path: Path {
                    segments: [
                        PathSegment {
                            ident: "allow",
                            arguments: None,
                        },
                    ],
                },
                tokens: TokenStream(`( dead_code )`),
            },
        ],
        items: [
            Item::Fn {
                vis: Inherited,
                sig: Signature {
                    ident: "main",
                    generics: Generics,
                    output: Default,
                },
                block: Block,
            },
        ],
    }
    "###);
}
<|endoftext|>


<commit_before><commit_msg>Add PowerLevelsEvent.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix tests for new interface<commit_after><|endoftext|>


<commit_before><commit_msg>fust read from file tested<commit_after>fn print_number(x: i32)
{
    println!("x is: {}", x);
}

fn main ()
{
    let x: i32 = 40;

    print_number(x);
}
<|endoftext|>


<commit_before><commit_msg>Add a prelude module<commit_after><|endoftext|>


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

use io::ErrorKind;
use io;
use mem;
use ops::Deref;
use ptr;
use sys::c;
use sys::cvt;

/// An owned container for `HANDLE` object, closing them on Drop.
///
/// All methods are inherited through a `Deref` impl to `RawHandle`
pub struct Handle(RawHandle);

/// A wrapper type for `HANDLE` objects to give them proper Send/Sync inference
/// as well as Rust-y methods.
///
/// This does **not** drop the handle when it goes out of scope, use `Handle`
/// instead for that.
#[derive(Copy, Clone)]
pub struct RawHandle(c::HANDLE);

unsafe impl Send for RawHandle {}
unsafe impl Sync for RawHandle {}

impl Handle {
    pub fn new(handle: c::HANDLE) -> Handle {
        Handle(RawHandle::new(handle))
    }

    pub fn into_raw(self) -> c::HANDLE {
        let ret = self.raw();
        mem::forget(self);
        return ret;
    }
}

impl Deref for Handle {
    type Target = RawHandle;
    fn deref(&self) -> &RawHandle { &self.0 }
}

impl Drop for Handle {
    fn drop(&mut self) {
        unsafe { let _ = c::CloseHandle(self.raw()); }
    }
}

impl RawHandle {
    pub fn new(handle: c::HANDLE) -> RawHandle {
        RawHandle(handle)
    }

    pub fn raw(&self) -> c::HANDLE { self.0 }

    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
        let mut read = 0;
        let res = cvt(unsafe {
            c::ReadFile(self.0, buf.as_ptr() as c::LPVOID,
                           buf.len() as c::DWORD, &mut read,
                           ptr::null_mut())
        });

        match res {
            Ok(_) => Ok(read as usize),

            // The special treatment of BrokenPipe is to deal with Windows
            // pipe semantics, which yields this error when *reading* from
            // a pipe after the other end has closed; we interpret that as
            // EOF on the pipe.
            Err(ref e) if e.kind() == ErrorKind::BrokenPipe => Ok(0),

            Err(e) => Err(e)
        }
    }

    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
        let mut amt = 0;
        try!(cvt(unsafe {
            c::WriteFile(self.0, buf.as_ptr() as c::LPVOID,
                            buf.len() as c::DWORD, &mut amt,
                            ptr::null_mut())
        }));
        Ok(amt as usize)
    }

    pub fn duplicate(&self, access: c::DWORD, inherit: bool,
                     options: c::DWORD) -> io::Result<Handle> {
        let mut ret = 0 as c::HANDLE;
        try!(cvt(unsafe {
            let cur_proc = c::GetCurrentProcess();
            c::DuplicateHandle(cur_proc, self.0, cur_proc, &mut ret,
                            access, inherit as c::BOOL,
                            options)
        }));
        Ok(Handle::new(ret))
    }
}
<commit_msg>Fix reading/writing 4 GiB or larger files on Windows 64-bit<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.

use cmp;
use io::ErrorKind;
use io;
use mem;
use ops::Deref;
use ptr;
use sys::c;
use sys::cvt;
use u32;

/// An owned container for `HANDLE` object, closing them on Drop.
///
/// All methods are inherited through a `Deref` impl to `RawHandle`
pub struct Handle(RawHandle);

/// A wrapper type for `HANDLE` objects to give them proper Send/Sync inference
/// as well as Rust-y methods.
///
/// This does **not** drop the handle when it goes out of scope, use `Handle`
/// instead for that.
#[derive(Copy, Clone)]
pub struct RawHandle(c::HANDLE);

unsafe impl Send for RawHandle {}
unsafe impl Sync for RawHandle {}

impl Handle {
    pub fn new(handle: c::HANDLE) -> Handle {
        Handle(RawHandle::new(handle))
    }

    pub fn into_raw(self) -> c::HANDLE {
        let ret = self.raw();
        mem::forget(self);
        return ret;
    }
}

impl Deref for Handle {
    type Target = RawHandle;
    fn deref(&self) -> &RawHandle { &self.0 }
}

impl Drop for Handle {
    fn drop(&mut self) {
        unsafe { let _ = c::CloseHandle(self.raw()); }
    }
}

impl RawHandle {
    pub fn new(handle: c::HANDLE) -> RawHandle {
        RawHandle(handle)
    }

    pub fn raw(&self) -> c::HANDLE { self.0 }

    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
        let mut read = 0;
        // ReadFile takes a DWORD (u32) for the length so it only supports
        // reading u32::MAX bytes at a time.
        let len = cmp::min(buf.len(), u32::MAX as usize) as c::DWORD;
        let res = cvt(unsafe {
            c::ReadFile(self.0, buf.as_mut_ptr() as c::LPVOID,
                        len, &mut read, ptr::null_mut())
        });

        match res {
            Ok(_) => Ok(read as usize),

            // The special treatment of BrokenPipe is to deal with Windows
            // pipe semantics, which yields this error when *reading* from
            // a pipe after the other end has closed; we interpret that as
            // EOF on the pipe.
            Err(ref e) if e.kind() == ErrorKind::BrokenPipe => Ok(0),

            Err(e) => Err(e)
        }
    }

    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
        let mut amt = 0;
        // WriteFile takes a DWORD (u32) for the length so it only supports
        // writing u32::MAX bytes at a time.
        let len = cmp::min(buf.len(), u32::MAX as usize) as c::DWORD;
        try!(cvt(unsafe {
            c::WriteFile(self.0, buf.as_ptr() as c::LPVOID,
                         len, &mut amt, ptr::null_mut())
        }));
        Ok(amt as usize)
    }

    pub fn duplicate(&self, access: c::DWORD, inherit: bool,
                     options: c::DWORD) -> io::Result<Handle> {
        let mut ret = 0 as c::HANDLE;
        try!(cvt(unsafe {
            let cur_proc = c::GetCurrentProcess();
            c::DuplicateHandle(cur_proc, self.0, cur_proc, &mut ret,
                            access, inherit as c::BOOL,
                            options)
        }));
        Ok(Handle::new(ret))
    }
}
<|endoftext|>


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

use clone::Clone;
use result::{Ok, Err};
use io::net::ip::SocketAddr;
use io::{Reader, Writer, IoResult};
use rt::rtio::{RtioSocket, RtioUdpSocket, IoFactory, LocalIo};

pub struct UdpSocket {
    priv obj: ~RtioUdpSocket
}

impl UdpSocket {
    pub fn bind(addr: SocketAddr) -> IoResult<UdpSocket> {
        LocalIo::maybe_raise(|io| {
            io.udp_bind(addr).map(|s| UdpSocket { obj: s })
        })
    }

    pub fn recvfrom(&mut self, buf: &mut [u8]) -> IoResult<(uint, SocketAddr)> {
        self.obj.recvfrom(buf)
    }

    pub fn sendto(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()> {
        self.obj.sendto(buf, dst)
    }

    pub fn connect(self, other: SocketAddr) -> UdpStream {
        UdpStream { socket: self, connectedTo: other }
    }

    pub fn socket_name(&mut self) -> IoResult<SocketAddr> {
        self.obj.socket_name()
    }
}

impl Clone for UdpSocket {
    /// Creates a new handle to this UDP socket, allowing for simultaneous reads
    /// and writes of the socket.
    ///
    /// The underlying UDP socket will not be closed until all handles to the
    /// socket have been deallocated. Two concurrent reads will not receive the
    /// same data.  Instead, the first read will receive the first packet
    /// received, and the second read will receive the second packet.
    fn clone(&self) -> UdpSocket {
        UdpSocket { obj: self.obj.clone() }
    }
}

pub struct UdpStream {
    priv socket: UdpSocket,
    priv connectedTo: SocketAddr
}

impl UdpStream {
    pub fn as_socket<T>(&mut self, f: |&mut UdpSocket| -> T) -> T {
        f(&mut self.socket)
    }

    pub fn disconnect(self) -> UdpSocket { self.socket }
}

impl Reader for UdpStream {
    fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
        let peer = self.connectedTo;
        self.as_socket(|sock| {
            match sock.recvfrom(buf) {
                Ok((_nread, src)) if src != peer => Ok(0),
                Ok((nread, _src)) => Ok(nread),
                Err(e) => Err(e),
            }
        })
    }
}

impl Writer for UdpStream {
    fn write(&mut self, buf: &[u8]) -> IoResult<()> {
        self.as_socket(|sock| sock.sendto(buf, self.connectedTo))
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use io::net::ip::{SocketAddr};

    // FIXME #11530 this fails on android because tests are run as root
    iotest!(fn bind_error() {
        let addr = SocketAddr { ip: Ipv4Addr(0, 0, 0, 0), port: 1 };
        match UdpSocket::bind(addr) {
            Ok(..) => fail!(),
            Err(e) => assert_eq!(e.kind, PermissionDenied),
        }
    } #[ignore(cfg(windows))] #[ignore(cfg(target_os = "android"))])

    iotest!(fn socket_smoke_test_ip4() {
        let server_ip = next_test_ip4();
        let client_ip = next_test_ip4();
        let (port, chan) = Chan::new();
        let (port2, chan2) = Chan::new();

        spawn(proc() {
            match UdpSocket::bind(client_ip) {
                Ok(ref mut client) => {
                    port.recv();
                    client.sendto([99], server_ip).unwrap()
                }
                Err(..) => fail!()
            }
            chan2.send(());
        });

        match UdpSocket::bind(server_ip) {
            Ok(ref mut server) => {
                chan.send(());
                let mut buf = [0];
                match server.recvfrom(buf) {
                    Ok((nread, src)) => {
                        assert_eq!(nread, 1);
                        assert_eq!(buf[0], 99);
                        assert_eq!(src, client_ip);
                    }
                    Err(..) => fail!()
                }
            }
            Err(..) => fail!()
        }
        port2.recv();
    })

    iotest!(fn socket_smoke_test_ip6() {
        let server_ip = next_test_ip6();
        let client_ip = next_test_ip6();
        let (port, chan) = Chan::<()>::new();

        spawn(proc() {
            match UdpSocket::bind(client_ip) {
                Ok(ref mut client) => {
                    port.recv();
                    client.sendto([99], server_ip).unwrap()
                }
                Err(..) => fail!()
            }
        });

        match UdpSocket::bind(server_ip) {
            Ok(ref mut server) => {
                chan.send(());
                let mut buf = [0];
                match server.recvfrom(buf) {
                    Ok((nread, src)) => {
                        assert_eq!(nread, 1);
                        assert_eq!(buf[0], 99);
                        assert_eq!(src, client_ip);
                    }
                    Err(..) => fail!()
                }
            }
            Err(..) => fail!()
        }
    })

    iotest!(fn stream_smoke_test_ip4() {
        let server_ip = next_test_ip4();
        let client_ip = next_test_ip4();
        let (port, chan) = Chan::new();
        let (port2, chan2) = Chan::new();

        spawn(proc() {
            match UdpSocket::bind(client_ip) {
                Ok(client) => {
                    let client = ~client;
                    let mut stream = client.connect(server_ip);
                    port.recv();
                    stream.write([99]).unwrap();
                }
                Err(..) => fail!()
            }
            chan2.send(());
        });

        match UdpSocket::bind(server_ip) {
            Ok(server) => {
                let server = ~server;
                let mut stream = server.connect(client_ip);
                chan.send(());
                let mut buf = [0];
                match stream.read(buf) {
                    Ok(nread) => {
                        assert_eq!(nread, 1);
                        assert_eq!(buf[0], 99);
                    }
                    Err(..) => fail!()
                }
            }
            Err(..) => fail!()
        }
        port2.recv();
    })

    iotest!(fn stream_smoke_test_ip6() {
        let server_ip = next_test_ip6();
        let client_ip = next_test_ip6();
        let (port, chan) = Chan::new();
        let (port2, chan2) = Chan::new();

        spawn(proc() {
            match UdpSocket::bind(client_ip) {
                Ok(client) => {
                    let client = ~client;
                    let mut stream = client.connect(server_ip);
                    port.recv();
                    stream.write([99]).unwrap();
                }
                Err(..) => fail!()
            }
            chan2.send(());
        });

        match UdpSocket::bind(server_ip) {
            Ok(server) => {
                let server = ~server;
                let mut stream = server.connect(client_ip);
                chan.send(());
                let mut buf = [0];
                match stream.read(buf) {
                    Ok(nread) => {
                        assert_eq!(nread, 1);
                        assert_eq!(buf[0], 99);
                    }
                    Err(..) => fail!()
                }
            }
            Err(..) => fail!()
        }
        port2.recv();
    })

    pub fn socket_name(addr: SocketAddr) {
        let server = UdpSocket::bind(addr);

        assert!(server.is_ok());
        let mut server = server.unwrap();

        // Make sure socket_name gives
        // us the socket we binded to.
        let so_name = server.socket_name();
        assert!(so_name.is_ok());
        assert_eq!(addr, so_name.unwrap());
    }

    iotest!(fn socket_name_ip4() {
        socket_name(next_test_ip4());
    })

    iotest!(fn socket_name_ip6() {
        socket_name(next_test_ip6());
    })

    iotest!(fn udp_clone_smoke() {
        let addr1 = next_test_ip4();
        let addr2 = next_test_ip4();
        let mut sock1 = UdpSocket::bind(addr1).unwrap();
        let sock2 = UdpSocket::bind(addr2).unwrap();

        spawn(proc() {
            let mut sock2 = sock2;
            let mut buf = [0, 0];
            assert_eq!(sock2.recvfrom(buf), Ok((1, addr1)));
            assert_eq!(buf[0], 1);
            sock2.sendto([2], addr1).unwrap();
        });

        let sock3 = sock1.clone();

        let (p1, c1) = Chan::new();
        let (p2, c2) = Chan::new();
        spawn(proc() {
            let mut sock3 = sock3;
            p1.recv();
            sock3.sendto([1], addr2).unwrap();
            c2.send(());
        });
        c1.send(());
        let mut buf = [0, 0];
        assert_eq!(sock1.recvfrom(buf), Ok((1, addr2)));
        p2.recv();
    })

    iotest!(fn udp_clone_two_read() {
        let addr1 = next_test_ip4();
        let addr2 = next_test_ip4();
        let mut sock1 = UdpSocket::bind(addr1).unwrap();
        let sock2 = UdpSocket::bind(addr2).unwrap();
        let (p, c) = SharedChan::new();
        let c2 = c.clone();

        spawn(proc() {
            let mut sock2 = sock2;
            sock2.sendto([1], addr1).unwrap();
            p.recv();
            sock2.sendto([2], addr1).unwrap();
            p.recv();
        });

        let sock3 = sock1.clone();

        let (p, done) = Chan::new();
        spawn(proc() {
            let mut sock3 = sock3;
            let mut buf = [0, 0];
            sock3.recvfrom(buf).unwrap();
            c2.send(());
            done.send(());
        });
        let mut buf = [0, 0];
        sock1.recvfrom(buf).unwrap();
        c.send(());

        p.recv();
    })

    iotest!(fn udp_clone_two_write() {
        let addr1 = next_test_ip4();
        let addr2 = next_test_ip4();
        let mut sock1 = UdpSocket::bind(addr1).unwrap();
        let sock2 = UdpSocket::bind(addr2).unwrap();

        let (p, c) = SharedChan::new();
        let (serv_port, serv_chan) = Chan::new();

        spawn(proc() {
            let mut sock2 = sock2;
            let mut buf = [0, 1];

            p.recv();
            match sock2.recvfrom(buf) {
                Ok(..) => {}
                Err(e) => fail!("failed receive: {}", e),
            }
            serv_chan.send(());
        });

        let sock3 = sock1.clone();

        let (p, done) = Chan::new();
        let c2 = c.clone();
        spawn(proc() {
            let mut sock3 = sock3;
            match sock3.sendto([1], addr2) {
                Ok(..) => { let _ = c2.try_send(()); }
                Err(..) => {}
            }
            done.send(());
        });
        match sock1.sendto([2], addr2) {
            Ok(..) => { let _ = c.try_send(()); }
            Err(..) => {}
        }
        drop(c);

        p.recv();
        serv_port.recv();
    })
}
<commit_msg>io -- introduce local to avoid conflicting borrow<commit_after>// Copyright 2013 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.

use clone::Clone;
use result::{Ok, Err};
use io::net::ip::SocketAddr;
use io::{Reader, Writer, IoResult};
use rt::rtio::{RtioSocket, RtioUdpSocket, IoFactory, LocalIo};

pub struct UdpSocket {
    priv obj: ~RtioUdpSocket
}

impl UdpSocket {
    pub fn bind(addr: SocketAddr) -> IoResult<UdpSocket> {
        LocalIo::maybe_raise(|io| {
            io.udp_bind(addr).map(|s| UdpSocket { obj: s })
        })
    }

    pub fn recvfrom(&mut self, buf: &mut [u8]) -> IoResult<(uint, SocketAddr)> {
        self.obj.recvfrom(buf)
    }

    pub fn sendto(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()> {
        self.obj.sendto(buf, dst)
    }

    pub fn connect(self, other: SocketAddr) -> UdpStream {
        UdpStream { socket: self, connectedTo: other }
    }

    pub fn socket_name(&mut self) -> IoResult<SocketAddr> {
        self.obj.socket_name()
    }
}

impl Clone for UdpSocket {
    /// Creates a new handle to this UDP socket, allowing for simultaneous reads
    /// and writes of the socket.
    ///
    /// The underlying UDP socket will not be closed until all handles to the
    /// socket have been deallocated. Two concurrent reads will not receive the
    /// same data.  Instead, the first read will receive the first packet
    /// received, and the second read will receive the second packet.
    fn clone(&self) -> UdpSocket {
        UdpSocket { obj: self.obj.clone() }
    }
}

pub struct UdpStream {
    priv socket: UdpSocket,
    priv connectedTo: SocketAddr
}

impl UdpStream {
    pub fn as_socket<T>(&mut self, f: |&mut UdpSocket| -> T) -> T {
        f(&mut self.socket)
    }

    pub fn disconnect(self) -> UdpSocket { self.socket }
}

impl Reader for UdpStream {
    fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
        let peer = self.connectedTo;
        self.as_socket(|sock| {
            match sock.recvfrom(buf) {
                Ok((_nread, src)) if src != peer => Ok(0),
                Ok((nread, _src)) => Ok(nread),
                Err(e) => Err(e),
            }
        })
    }
}

impl Writer for UdpStream {
    fn write(&mut self, buf: &[u8]) -> IoResult<()> {
        let connectedTo = self.connectedTo;
        self.as_socket(|sock| sock.sendto(buf, connectedTo))
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use io::net::ip::{SocketAddr};

    // FIXME #11530 this fails on android because tests are run as root
    iotest!(fn bind_error() {
        let addr = SocketAddr { ip: Ipv4Addr(0, 0, 0, 0), port: 1 };
        match UdpSocket::bind(addr) {
            Ok(..) => fail!(),
            Err(e) => assert_eq!(e.kind, PermissionDenied),
        }
    } #[ignore(cfg(windows))] #[ignore(cfg(target_os = "android"))])

    iotest!(fn socket_smoke_test_ip4() {
        let server_ip = next_test_ip4();
        let client_ip = next_test_ip4();
        let (port, chan) = Chan::new();
        let (port2, chan2) = Chan::new();

        spawn(proc() {
            match UdpSocket::bind(client_ip) {
                Ok(ref mut client) => {
                    port.recv();
                    client.sendto([99], server_ip).unwrap()
                }
                Err(..) => fail!()
            }
            chan2.send(());
        });

        match UdpSocket::bind(server_ip) {
            Ok(ref mut server) => {
                chan.send(());
                let mut buf = [0];
                match server.recvfrom(buf) {
                    Ok((nread, src)) => {
                        assert_eq!(nread, 1);
                        assert_eq!(buf[0], 99);
                        assert_eq!(src, client_ip);
                    }
                    Err(..) => fail!()
                }
            }
            Err(..) => fail!()
        }
        port2.recv();
    })

    iotest!(fn socket_smoke_test_ip6() {
        let server_ip = next_test_ip6();
        let client_ip = next_test_ip6();
        let (port, chan) = Chan::<()>::new();

        spawn(proc() {
            match UdpSocket::bind(client_ip) {
                Ok(ref mut client) => {
                    port.recv();
                    client.sendto([99], server_ip).unwrap()
                }
                Err(..) => fail!()
            }
        });

        match UdpSocket::bind(server_ip) {
            Ok(ref mut server) => {
                chan.send(());
                let mut buf = [0];
                match server.recvfrom(buf) {
                    Ok((nread, src)) => {
                        assert_eq!(nread, 1);
                        assert_eq!(buf[0], 99);
                        assert_eq!(src, client_ip);
                    }
                    Err(..) => fail!()
                }
            }
            Err(..) => fail!()
        }
    })

    iotest!(fn stream_smoke_test_ip4() {
        let server_ip = next_test_ip4();
        let client_ip = next_test_ip4();
        let (port, chan) = Chan::new();
        let (port2, chan2) = Chan::new();

        spawn(proc() {
            match UdpSocket::bind(client_ip) {
                Ok(client) => {
                    let client = ~client;
                    let mut stream = client.connect(server_ip);
                    port.recv();
                    stream.write([99]).unwrap();
                }
                Err(..) => fail!()
            }
            chan2.send(());
        });

        match UdpSocket::bind(server_ip) {
            Ok(server) => {
                let server = ~server;
                let mut stream = server.connect(client_ip);
                chan.send(());
                let mut buf = [0];
                match stream.read(buf) {
                    Ok(nread) => {
                        assert_eq!(nread, 1);
                        assert_eq!(buf[0], 99);
                    }
                    Err(..) => fail!()
                }
            }
            Err(..) => fail!()
        }
        port2.recv();
    })

    iotest!(fn stream_smoke_test_ip6() {
        let server_ip = next_test_ip6();
        let client_ip = next_test_ip6();
        let (port, chan) = Chan::new();
        let (port2, chan2) = Chan::new();

        spawn(proc() {
            match UdpSocket::bind(client_ip) {
                Ok(client) => {
                    let client = ~client;
                    let mut stream = client.connect(server_ip);
                    port.recv();
                    stream.write([99]).unwrap();
                }
                Err(..) => fail!()
            }
            chan2.send(());
        });

        match UdpSocket::bind(server_ip) {
            Ok(server) => {
                let server = ~server;
                let mut stream = server.connect(client_ip);
                chan.send(());
                let mut buf = [0];
                match stream.read(buf) {
                    Ok(nread) => {
                        assert_eq!(nread, 1);
                        assert_eq!(buf[0], 99);
                    }
                    Err(..) => fail!()
                }
            }
            Err(..) => fail!()
        }
        port2.recv();
    })

    pub fn socket_name(addr: SocketAddr) {
        let server = UdpSocket::bind(addr);

        assert!(server.is_ok());
        let mut server = server.unwrap();

        // Make sure socket_name gives
        // us the socket we binded to.
        let so_name = server.socket_name();
        assert!(so_name.is_ok());
        assert_eq!(addr, so_name.unwrap());
    }

    iotest!(fn socket_name_ip4() {
        socket_name(next_test_ip4());
    })

    iotest!(fn socket_name_ip6() {
        socket_name(next_test_ip6());
    })

    iotest!(fn udp_clone_smoke() {
        let addr1 = next_test_ip4();
        let addr2 = next_test_ip4();
        let mut sock1 = UdpSocket::bind(addr1).unwrap();
        let sock2 = UdpSocket::bind(addr2).unwrap();

        spawn(proc() {
            let mut sock2 = sock2;
            let mut buf = [0, 0];
            assert_eq!(sock2.recvfrom(buf), Ok((1, addr1)));
            assert_eq!(buf[0], 1);
            sock2.sendto([2], addr1).unwrap();
        });

        let sock3 = sock1.clone();

        let (p1, c1) = Chan::new();
        let (p2, c2) = Chan::new();
        spawn(proc() {
            let mut sock3 = sock3;
            p1.recv();
            sock3.sendto([1], addr2).unwrap();
            c2.send(());
        });
        c1.send(());
        let mut buf = [0, 0];
        assert_eq!(sock1.recvfrom(buf), Ok((1, addr2)));
        p2.recv();
    })

    iotest!(fn udp_clone_two_read() {
        let addr1 = next_test_ip4();
        let addr2 = next_test_ip4();
        let mut sock1 = UdpSocket::bind(addr1).unwrap();
        let sock2 = UdpSocket::bind(addr2).unwrap();
        let (p, c) = SharedChan::new();
        let c2 = c.clone();

        spawn(proc() {
            let mut sock2 = sock2;
            sock2.sendto([1], addr1).unwrap();
            p.recv();
            sock2.sendto([2], addr1).unwrap();
            p.recv();
        });

        let sock3 = sock1.clone();

        let (p, done) = Chan::new();
        spawn(proc() {
            let mut sock3 = sock3;
            let mut buf = [0, 0];
            sock3.recvfrom(buf).unwrap();
            c2.send(());
            done.send(());
        });
        let mut buf = [0, 0];
        sock1.recvfrom(buf).unwrap();
        c.send(());

        p.recv();
    })

    iotest!(fn udp_clone_two_write() {
        let addr1 = next_test_ip4();
        let addr2 = next_test_ip4();
        let mut sock1 = UdpSocket::bind(addr1).unwrap();
        let sock2 = UdpSocket::bind(addr2).unwrap();

        let (p, c) = SharedChan::new();
        let (serv_port, serv_chan) = Chan::new();

        spawn(proc() {
            let mut sock2 = sock2;
            let mut buf = [0, 1];

            p.recv();
            match sock2.recvfrom(buf) {
                Ok(..) => {}
                Err(e) => fail!("failed receive: {}", e),
            }
            serv_chan.send(());
        });

        let sock3 = sock1.clone();

        let (p, done) = Chan::new();
        let c2 = c.clone();
        spawn(proc() {
            let mut sock3 = sock3;
            match sock3.sendto([1], addr2) {
                Ok(..) => { let _ = c2.try_send(()); }
                Err(..) => {}
            }
            done.send(());
        });
        match sock1.sendto([2], addr2) {
            Ok(..) => { let _ = c.try_send(()); }
            Err(..) => {}
        }
        drop(c);

        p.recv();
        serv_port.recv();
    })
}
<|endoftext|>


<commit_before><commit_msg>loop label<commit_after><|endoftext|>


<commit_before><commit_msg>Don't need the type since we use unwrap_or.<commit_after><|endoftext|>


<commit_before><commit_msg>Add simple `[repr(align)]` codegen test.<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.

// compile-flags: -C no-prepopulate-passes
#![crate_type = "lib"]

#![feature(attr_literals)]
#![feature(repr_align)]

#[repr(align(64))]
pub struct Align64(i32);

pub struct Nested64 {
    a: Align64,
    b: i32,
    c: i32,
    d: i8,
}

pub enum Enum64 {
    A(Align64),
    B(i32),
}

// CHECK-LABEL: @align64
#[no_mangle]
pub fn align64(i : i32) -> Align64 {
// CHECK: %a64 = alloca %Align64, align 64
// CHECK: call void @llvm.memcpy.{{.*}}(i8* %{{.*}}, i8* %{{.*}}, i{{[0-9]+}} 64, i32 64, i1 false)
    let a64 = Align64(i);
    a64
}

// CHECK-LABEL: @nested64
#[no_mangle]
pub fn nested64(a: Align64, b: i32, c: i32, d: i8) -> Nested64 {
// CHECK: %n64 = alloca %Nested64, align 64
// CHECK: %a = alloca %Align64, align 64
    let n64 = Nested64 { a, b, c, d };
    n64
}

// CHECK-LABEL: @enum64
#[no_mangle]
pub fn enum64(a: Align64) -> Enum64 {
// CHECK: %e64 = alloca %Enum64, align 64
// CHECK: %a = alloca %Align64, align 64
    let e64 = Enum64::A(a);
    e64
}
<|endoftext|>


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

// ignore-arm
// ignore-wasm
// ignore-emscripten
// ignore-windows
// no-system-llvm
// compile-flags: -C no-prepopulate-passes

#![crate_type = "lib"]

#[no_mangle]
pub fn foo() {
// CHECK: @foo() unnamed_addr #0
// CHECK: attributes #0 = { {{.*}}"probe-stack"="__rust_probestack"{{.*}} }
}
<commit_msg>powerpc: Ignore the stack-probes test<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.

// ignore-arm
// ignore-powerpc
// ignore-wasm
// ignore-emscripten
// ignore-windows
// no-system-llvm
// compile-flags: -C no-prepopulate-passes

#![crate_type = "lib"]

#[no_mangle]
pub fn foo() {
// CHECK: @foo() unnamed_addr #0
// CHECK: attributes #0 = { {{.*}}"probe-stack"="__rust_probestack"{{.*}} }
}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #26460 - nham:test-18809, r=huonw<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.

trait Tup {
    type T0;
    type T1;
}

impl Tup for isize {
    type T0 = f32;
    type T1 = ();
}

fn main() {}
<|endoftext|>


<commit_before>use std::io::{stdin, stdout, Read, Write};
use std::process::Command;

#[no_mangle] pub fn main() {
    loop {
        print!("redox login: ");
        stdout().flush();

        let mut buffer = String::new();
        stdin().read_line(&mut buffer);

        let path = "/apps/shell/main.bin";
        match Command::new(path).spawn() {
            Ok(mut child) => {
                match child.wait() {
                    Ok(status) => {
                        if let Some(code) = status.code() {
                            println!("{}: Child exited with exit code: {}", path, code);
                        } else {
                            println!("{}: No child exit code", path);
                        }
                    },
                    Err(err) => println!("{}: Failed to wait: {}", path, err)
                }
            },
            Err(err) => println!("{}: Failed to execute: {}", path, err)
        }
    }
}
<commit_msg>Something in matching the child wait status is causing issues<commit_after>use std::io::{stdin, stdout, Read, Write};
use std::process::Command;

#[no_mangle] pub fn main() {
    loop {
        print!("redox login: ");
        stdout().flush();

        let mut buffer = String::new();
        stdin().read_line(&mut buffer);

        let path = "/apps/shell/main.bin";
        match Command::new(path).spawn() {
            Ok(mut child) => {
                child.wait();
                /*match  {
                    Ok(status) => {
                        if let Some(code) = status.code() {
                            println!("{}: Child exited with exit code: {}", path, code);
                        } else {
                            println!("{}: No child exit code", path);
                        }
                    },
                    Err(err) => println!("{}: Failed to wait: {}", path, err)
                }*/
            },
            Err(err) => println!("{}: Failed to execute: {}", path, err)
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Fix missing file<commit_after>use system::memory;

pub fn event_cancel() -> bool {
    memory::read(0x803BD3A3)
}

pub fn set_event_cancel(b: bool) {
    memory::write(0x803BD3A3, b);
}<|endoftext|>


<commit_before><commit_msg>Implement plugin run action. Simplify struct initalizers.<commit_after><|endoftext|>


<commit_before><commit_msg>Remove the `render_weird_gradient()`<commit_after><|endoftext|>


<commit_before><commit_msg>Just scan the entire directory, and import anything new.<commit_after><|endoftext|>


<commit_before><commit_msg>add version to example<commit_after><|endoftext|>


<commit_before><commit_msg>Timer example<commit_after>extern crate enigo;
use enigo::{Enigo, KeyboardControllable, Key};
use std::thread;
use std::time::Duration;
use std::time::Instant;

fn main() {
    thread::sleep(Duration::from_secs(2));
    let mut enigo = Enigo::new();

    let now = Instant::now();

    // write text
    enigo.key_sequence("Hello World! ❤");

    let time = now.elapsed();
    println!("{:?}", time);

    // select all
    enigo.key_down(Key::Control);
    enigo.key_click(Key::Layout('a'));
    enigo.key_up(Key::Control);
}
<|endoftext|>


<commit_before><commit_msg>Added test for #41479 from @eddyb.<commit_after>// Copyright 2017 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.

fn split<A, B>(pair: (A, B)) {
    let _a = pair.0;
    let _b = pair.1;
}

fn main() {
    split(((), ((), ())));
}
<|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)]

// 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! {

E0154: r##"
Imports (`use` statements) are not allowed after non-item statements, such as
variable declarations and expression statements.

Wrong example:
```
fn f() {
    // Variable declaration before import
    let x = 0;
    use std::io::Read;
    ...
}
```

The solution is to declare the imports at the top of the block, function, or
file.

Here is the previous example again, with the correct order:
```
fn f() {
    use std::io::Read;
    let x = 0;
    ...
}
```

See the Declaration Statements section of the reference for more information
about what constitutes an Item declaration and what does not:

http://doc.rust-lang.org/reference.html#statements
"##,

E0259: r##"
The name chosen for an external crate conflicts with another external crate that
has been imported into the current module.

Wrong example:
```
extern a;
extern crate_a as a;
```

The solution is to choose a different name that doesn't conflict with any
external crate imported into the current module.

Correct example:
```
extern a;
extern crate_a as other_name;
```
"##,

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/reference.html#types
"##

}

register_diagnostics! {
    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
    E0260, // name conflicts with an external crate that has been imported into this module
    E0364, // item is private
    E0365  // item is private
}
<commit_msg>Add error explanation for E0260.<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! {

E0154: r##"
Imports (`use` statements) are not allowed after non-item statements, such as
variable declarations and expression statements.

Wrong example:
```
fn f() {
    // Variable declaration before import
    let x = 0;
    use std::io::Read;
    ...
}
```

The solution is to declare the imports at the top of the block, function, or
file.

Here is the previous example again, with the correct order:
```
fn f() {
    use std::io::Read;
    let x = 0;
    ...
}
```

See the Declaration Statements section of the reference for more information
about what constitutes an Item declaration and what does not:

http://doc.rust-lang.org/reference.html#statements
"##,

E0259: r##"
The name chosen for an external crate conflicts with another external crate that
has been imported into the current module.

Wrong example:
```
extern a;
extern crate_a as a;
```

The solution is to choose a different name that doesn't conflict with any
external crate imported into the current module.

Correct example:
```
extern a;
extern crate_a as other_name;
```
"##,

E0260: r##"
The name for an item declaration conflicts with an external crate's name.

For instance,
```
extern abc;

struct abc;
```

There are two possible solutions:

Solution #1: Rename the item.

```
extern abc;

struct xyz;
```

Solution #2: Import the crate with a different name.

```
extern abc as xyz;

struct abc;
```

See the Declaration Statements section of the reference for more information
about what constitutes an Item declaration and what does not:

http://doc.rust-lang.org/reference.html#statements
"##,

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/reference.html#types
"##

}

register_diagnostics! {
    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
    E0364, // item is private
    E0365  // item is private
}
<|endoftext|>


<commit_before><commit_msg>casing by coercions<commit_after><|endoftext|>


<commit_before><commit_msg> removed filter for testing<commit_after><|endoftext|>


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