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

// Checks if the "sysv64" calling convention behaves the same as the
// "C" calling convention on platforms where both should be the same

// This file contains versions of the following run-pass tests with
// the calling convention changed to "sysv64"

// cabi-int-widening
// extern-pass-char
// extern-pass-u32
// extern-pass-u64
// extern-pass-double
// extern-pass-empty
// extern-pass-TwoU8s
// extern-pass-TwoU16s
// extern-pass-TwoU32s
// extern-pass-TwoU64s
// extern-return-TwoU8s
// extern-return-TwoU16s
// extern-return-TwoU32s
// extern-return-TwoU64s
// foreign-fn-with-byval
// issue-28676
// struct-return

// ignore-android
// ignore-arm
// ignore-aarch64
// ignore-msvc

// note: msvc is ignored as rust_test_helpers does not have the sysv64 abi on msvc

#![feature(abi_sysv64)]
#[allow(dead_code)]
#[allow(improper_ctypes)]

#[cfg(target_arch = "x86_64")]
mod tests {
    #[repr(C)]
    #[derive(Copy, Clone, PartialEq, Debug)]
    pub struct TwoU8s {
        one: u8, two: u8
    }

    #[repr(C)]
    #[derive(Copy, Clone, PartialEq, Debug)]
    pub struct TwoU16s {
        one: u16, two: u16
    }

    #[repr(C)]
    #[derive(Copy, Clone, PartialEq, Debug)]
    pub struct TwoU32s {
        one: u32, two: u32
    }

    #[repr(C)]
    #[derive(Copy, Clone, PartialEq, Debug)]
    pub struct TwoU64s {
        one: u64, two: u64
    }

    #[repr(C)]
    pub struct ManyInts {
        arg1: i8,
        arg2: i16,
        arg3: i32,
        arg4: i16,
        arg5: i8,
        arg6: TwoU8s,
    }

    #[repr(C)]
    pub struct Empty;

    #[repr(C)]
    #[derive(Copy, Clone)]
    pub struct S {
        x: u64,
        y: u64,
        z: u64,
    }

    #[repr(C)]
    #[derive(Copy, Clone)]
    pub struct Quad { a: u64, b: u64, c: u64, d: u64 }

    #[repr(C)]
    #[derive(Copy, Clone)]
    pub struct Floats { a: f64, b: u8, c: f64 }

    #[link(name = "rust_test_helpers")]
    extern "sysv64" {
        pub fn rust_int8_to_int32(_: i8) -> i32;
        pub fn rust_dbg_extern_identity_u8(v: u8) -> u8;
        pub fn rust_dbg_extern_identity_u32(v: u32) -> u32;
        pub fn rust_dbg_extern_identity_u64(v: u64) -> u64;
        pub fn rust_dbg_extern_identity_double(v: f64) -> f64;
        pub fn rust_dbg_extern_empty_struct(v1: ManyInts, e: Empty, v2: ManyInts);
        pub fn rust_dbg_extern_identity_TwoU8s(v: TwoU8s) -> TwoU8s;
        pub fn rust_dbg_extern_identity_TwoU16s(v: TwoU16s) -> TwoU16s;
        pub fn rust_dbg_extern_identity_TwoU32s(v: TwoU32s) -> TwoU32s;
        pub fn rust_dbg_extern_identity_TwoU64s(v: TwoU64s) -> TwoU64s;
        pub fn rust_dbg_extern_return_TwoU8s() -> TwoU8s;
        pub fn rust_dbg_extern_return_TwoU16s() -> TwoU16s;
        pub fn rust_dbg_extern_return_TwoU32s() -> TwoU32s;
        pub fn rust_dbg_extern_return_TwoU64s() -> TwoU64s;
        pub fn get_x(x: S) -> u64;
        pub fn get_y(x: S) -> u64;
        pub fn get_z(x: S) -> u64;
        pub fn get_c_many_params(_: *const (), _: *const (),
                                 _: *const (), _: *const (), f: Quad) -> u64;
        pub fn rust_dbg_abi_1(q: Quad) -> Quad;
        pub fn rust_dbg_abi_2(f: Floats) -> Floats;
    }

    pub fn cabi_int_widening() {
        let x = unsafe {
            rust_int8_to_int32(-1)
        };

        assert!(x == -1);
    }

    pub fn extern_pass_char() {
        unsafe {
            assert_eq!(22, rust_dbg_extern_identity_u8(22));
        }
    }

    pub fn extern_pass_u32() {
        unsafe {
            assert_eq!(22, rust_dbg_extern_identity_u32(22));
        }
    }

    pub fn extern_pass_u64() {
        unsafe {
            assert_eq!(22, rust_dbg_extern_identity_u64(22));
        }
    }

    pub fn extern_pass_double() {
        unsafe {
            assert_eq!(22.0_f64, rust_dbg_extern_identity_double(22.0_f64));
        }
    }

    pub fn extern_pass_empty() {
        unsafe {
            let x = ManyInts {
                arg1: 2,
                arg2: 3,
                arg3: 4,
                arg4: 5,
                arg5: 6,
                arg6: TwoU8s { one: 7, two: 8, }
            };
            let y = ManyInts {
                arg1: 1,
                arg2: 2,
                arg3: 3,
                arg4: 4,
                arg5: 5,
                arg6: TwoU8s { one: 6, two: 7, }
            };
            let empty = Empty;
            rust_dbg_extern_empty_struct(x, empty, y);
        }
    }

    pub fn extern_pass_twou8s() {
        unsafe {
            let x = TwoU8s {one: 22, two: 23};
            let y = rust_dbg_extern_identity_TwoU8s(x);
            assert_eq!(x, y);
        }
    }

    pub fn extern_pass_twou16s() {
        unsafe {
            let x = TwoU16s {one: 22, two: 23};
            let y = rust_dbg_extern_identity_TwoU16s(x);
            assert_eq!(x, y);
        }
    }

    pub fn extern_pass_twou32s() {
        unsafe {
            let x = TwoU32s {one: 22, two: 23};
            let y = rust_dbg_extern_identity_TwoU32s(x);
            assert_eq!(x, y);
        }
    }

    pub fn extern_pass_twou64s() {
        unsafe {
            let x = TwoU64s {one: 22, two: 23};
            let y = rust_dbg_extern_identity_TwoU64s(x);
            assert_eq!(x, y);
        }
    }

    pub fn extern_return_twou8s() {
        unsafe {
            let y = rust_dbg_extern_return_TwoU8s();
            assert_eq!(y.one, 10);
            assert_eq!(y.two, 20);
        }
    }

    pub fn extern_return_twou16s() {
        unsafe {
            let y = rust_dbg_extern_return_TwoU16s();
            assert_eq!(y.one, 10);
            assert_eq!(y.two, 20);
        }
    }

    pub fn extern_return_twou32s() {
        unsafe {
            let y = rust_dbg_extern_return_TwoU32s();
            assert_eq!(y.one, 10);
            assert_eq!(y.two, 20);
        }
    }

    pub fn extern_return_twou64s() {
        unsafe {
            let y = rust_dbg_extern_return_TwoU64s();
            assert_eq!(y.one, 10);
            assert_eq!(y.two, 20);
        }
    }

    #[inline(never)]
    fn indirect_call(func: unsafe extern "sysv64" fn(s: S) -> u64, s: S) -> u64 {
        unsafe {
            func(s)
        }
    }

    pub fn foreign_fn_with_byval() {
        let s = S { x: 1, y: 2, z: 3 };
        assert_eq!(s.x, indirect_call(get_x, s));
        assert_eq!(s.y, indirect_call(get_y, s));
        assert_eq!(s.z, indirect_call(get_z, s));
    }

    fn test() {
        use std::ptr;
        unsafe {
            let null = ptr::null();
            let q = Quad {
                a: 1,
                b: 2,
                c: 3,
                d: 4
            };
            assert_eq!(get_c_many_params(null, null, null, null, q), q.c);
        }
    }

    pub fn issue_28676() {
        test();
    }

    fn test1() {
        unsafe {
            let q = Quad { a: 0xaaaa_aaaa_aaaa_aaaa,
                     b: 0xbbbb_bbbb_bbbb_bbbb,
                     c: 0xcccc_cccc_cccc_cccc,
                     d: 0xdddd_dddd_dddd_dddd };
            let qq = rust_dbg_abi_1(q);
            println!("a: {:x}", qq.a as usize);
            println!("b: {:x}", qq.b as usize);
            println!("c: {:x}", qq.c as usize);
            println!("d: {:x}", qq.d as usize);
            assert_eq!(qq.a, q.c + 1);
            assert_eq!(qq.b, q.d - 1);
            assert_eq!(qq.c, q.a + 1);
            assert_eq!(qq.d, q.b - 1);
        }
    }

    fn test2() {
        unsafe {
            let f = Floats { a: 1.234567890e-15_f64,
                     b: 0b_1010_1010,
                     c: 1.0987654321e-15_f64 };
            let ff = rust_dbg_abi_2(f);
            println!("a: {}", ff.a as f64);
            println!("b: {}", ff.b as usize);
            println!("c: {}", ff.c as f64);
            assert_eq!(ff.a, f.c + 1.0f64);
            assert_eq!(ff.b, 0xff);
            assert_eq!(ff.c, f.a - 1.0f64);
        }
    }

    pub fn struct_return() {
        test1();
        test2();
    }
}

#[cfg(target_arch = "x86_64")]
fn main() {
    use tests::*;
    cabi_int_widening();
    extern_pass_char();
    extern_pass_u32();
    extern_pass_u64();
    extern_pass_double();
    extern_pass_empty();
    extern_pass_twou8s();
    extern_pass_twou16s();
    extern_pass_twou32s();
    extern_pass_twou64s();
    extern_return_twou8s();
    extern_return_twou16s();
    extern_return_twou32s();
    extern_return_twou64s();
    foreign_fn_with_byval();
    issue_28676();
    struct_return();
}

#[cfg(not(target_arch = "x86_64"))]
fn main() {

}
<commit_msg>the win64 calling convention is also used on x86_64-pc-windows-gnu, so ignore windows entirely instead of just msvc<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.

// Checks if the "sysv64" calling convention behaves the same as the
// "C" calling convention on platforms where both should be the same

// This file contains versions of the following run-pass tests with
// the calling convention changed to "sysv64"

// cabi-int-widening
// extern-pass-char
// extern-pass-u32
// extern-pass-u64
// extern-pass-double
// extern-pass-empty
// extern-pass-TwoU8s
// extern-pass-TwoU16s
// extern-pass-TwoU32s
// extern-pass-TwoU64s
// extern-return-TwoU8s
// extern-return-TwoU16s
// extern-return-TwoU32s
// extern-return-TwoU64s
// foreign-fn-with-byval
// issue-28676
// struct-return

// ignore-android
// ignore-arm
// ignore-aarch64
// ignore-windows

// note: windows is ignored as rust_test_helpers does not have the sysv64 abi on windows

#![feature(abi_sysv64)]
#[allow(dead_code)]
#[allow(improper_ctypes)]

#[cfg(target_arch = "x86_64")]
mod tests {
    #[repr(C)]
    #[derive(Copy, Clone, PartialEq, Debug)]
    pub struct TwoU8s {
        one: u8, two: u8
    }

    #[repr(C)]
    #[derive(Copy, Clone, PartialEq, Debug)]
    pub struct TwoU16s {
        one: u16, two: u16
    }

    #[repr(C)]
    #[derive(Copy, Clone, PartialEq, Debug)]
    pub struct TwoU32s {
        one: u32, two: u32
    }

    #[repr(C)]
    #[derive(Copy, Clone, PartialEq, Debug)]
    pub struct TwoU64s {
        one: u64, two: u64
    }

    #[repr(C)]
    pub struct ManyInts {
        arg1: i8,
        arg2: i16,
        arg3: i32,
        arg4: i16,
        arg5: i8,
        arg6: TwoU8s,
    }

    #[repr(C)]
    pub struct Empty;

    #[repr(C)]
    #[derive(Copy, Clone)]
    pub struct S {
        x: u64,
        y: u64,
        z: u64,
    }

    #[repr(C)]
    #[derive(Copy, Clone)]
    pub struct Quad { a: u64, b: u64, c: u64, d: u64 }

    #[repr(C)]
    #[derive(Copy, Clone)]
    pub struct Floats { a: f64, b: u8, c: f64 }

    #[link(name = "rust_test_helpers")]
    extern "sysv64" {
        pub fn rust_int8_to_int32(_: i8) -> i32;
        pub fn rust_dbg_extern_identity_u8(v: u8) -> u8;
        pub fn rust_dbg_extern_identity_u32(v: u32) -> u32;
        pub fn rust_dbg_extern_identity_u64(v: u64) -> u64;
        pub fn rust_dbg_extern_identity_double(v: f64) -> f64;
        pub fn rust_dbg_extern_empty_struct(v1: ManyInts, e: Empty, v2: ManyInts);
        pub fn rust_dbg_extern_identity_TwoU8s(v: TwoU8s) -> TwoU8s;
        pub fn rust_dbg_extern_identity_TwoU16s(v: TwoU16s) -> TwoU16s;
        pub fn rust_dbg_extern_identity_TwoU32s(v: TwoU32s) -> TwoU32s;
        pub fn rust_dbg_extern_identity_TwoU64s(v: TwoU64s) -> TwoU64s;
        pub fn rust_dbg_extern_return_TwoU8s() -> TwoU8s;
        pub fn rust_dbg_extern_return_TwoU16s() -> TwoU16s;
        pub fn rust_dbg_extern_return_TwoU32s() -> TwoU32s;
        pub fn rust_dbg_extern_return_TwoU64s() -> TwoU64s;
        pub fn get_x(x: S) -> u64;
        pub fn get_y(x: S) -> u64;
        pub fn get_z(x: S) -> u64;
        pub fn get_c_many_params(_: *const (), _: *const (),
                                 _: *const (), _: *const (), f: Quad) -> u64;
        pub fn rust_dbg_abi_1(q: Quad) -> Quad;
        pub fn rust_dbg_abi_2(f: Floats) -> Floats;
    }

    pub fn cabi_int_widening() {
        let x = unsafe {
            rust_int8_to_int32(-1)
        };

        assert!(x == -1);
    }

    pub fn extern_pass_char() {
        unsafe {
            assert_eq!(22, rust_dbg_extern_identity_u8(22));
        }
    }

    pub fn extern_pass_u32() {
        unsafe {
            assert_eq!(22, rust_dbg_extern_identity_u32(22));
        }
    }

    pub fn extern_pass_u64() {
        unsafe {
            assert_eq!(22, rust_dbg_extern_identity_u64(22));
        }
    }

    pub fn extern_pass_double() {
        unsafe {
            assert_eq!(22.0_f64, rust_dbg_extern_identity_double(22.0_f64));
        }
    }

    pub fn extern_pass_empty() {
        unsafe {
            let x = ManyInts {
                arg1: 2,
                arg2: 3,
                arg3: 4,
                arg4: 5,
                arg5: 6,
                arg6: TwoU8s { one: 7, two: 8, }
            };
            let y = ManyInts {
                arg1: 1,
                arg2: 2,
                arg3: 3,
                arg4: 4,
                arg5: 5,
                arg6: TwoU8s { one: 6, two: 7, }
            };
            let empty = Empty;
            rust_dbg_extern_empty_struct(x, empty, y);
        }
    }

    pub fn extern_pass_twou8s() {
        unsafe {
            let x = TwoU8s {one: 22, two: 23};
            let y = rust_dbg_extern_identity_TwoU8s(x);
            assert_eq!(x, y);
        }
    }

    pub fn extern_pass_twou16s() {
        unsafe {
            let x = TwoU16s {one: 22, two: 23};
            let y = rust_dbg_extern_identity_TwoU16s(x);
            assert_eq!(x, y);
        }
    }

    pub fn extern_pass_twou32s() {
        unsafe {
            let x = TwoU32s {one: 22, two: 23};
            let y = rust_dbg_extern_identity_TwoU32s(x);
            assert_eq!(x, y);
        }
    }

    pub fn extern_pass_twou64s() {
        unsafe {
            let x = TwoU64s {one: 22, two: 23};
            let y = rust_dbg_extern_identity_TwoU64s(x);
            assert_eq!(x, y);
        }
    }

    pub fn extern_return_twou8s() {
        unsafe {
            let y = rust_dbg_extern_return_TwoU8s();
            assert_eq!(y.one, 10);
            assert_eq!(y.two, 20);
        }
    }

    pub fn extern_return_twou16s() {
        unsafe {
            let y = rust_dbg_extern_return_TwoU16s();
            assert_eq!(y.one, 10);
            assert_eq!(y.two, 20);
        }
    }

    pub fn extern_return_twou32s() {
        unsafe {
            let y = rust_dbg_extern_return_TwoU32s();
            assert_eq!(y.one, 10);
            assert_eq!(y.two, 20);
        }
    }

    pub fn extern_return_twou64s() {
        unsafe {
            let y = rust_dbg_extern_return_TwoU64s();
            assert_eq!(y.one, 10);
            assert_eq!(y.two, 20);
        }
    }

    #[inline(never)]
    fn indirect_call(func: unsafe extern "sysv64" fn(s: S) -> u64, s: S) -> u64 {
        unsafe {
            func(s)
        }
    }

    pub fn foreign_fn_with_byval() {
        let s = S { x: 1, y: 2, z: 3 };
        assert_eq!(s.x, indirect_call(get_x, s));
        assert_eq!(s.y, indirect_call(get_y, s));
        assert_eq!(s.z, indirect_call(get_z, s));
    }

    fn test() {
        use std::ptr;
        unsafe {
            let null = ptr::null();
            let q = Quad {
                a: 1,
                b: 2,
                c: 3,
                d: 4
            };
            assert_eq!(get_c_many_params(null, null, null, null, q), q.c);
        }
    }

    pub fn issue_28676() {
        test();
    }

    fn test1() {
        unsafe {
            let q = Quad { a: 0xaaaa_aaaa_aaaa_aaaa,
                     b: 0xbbbb_bbbb_bbbb_bbbb,
                     c: 0xcccc_cccc_cccc_cccc,
                     d: 0xdddd_dddd_dddd_dddd };
            let qq = rust_dbg_abi_1(q);
            println!("a: {:x}", qq.a as usize);
            println!("b: {:x}", qq.b as usize);
            println!("c: {:x}", qq.c as usize);
            println!("d: {:x}", qq.d as usize);
            assert_eq!(qq.a, q.c + 1);
            assert_eq!(qq.b, q.d - 1);
            assert_eq!(qq.c, q.a + 1);
            assert_eq!(qq.d, q.b - 1);
        }
    }

    fn test2() {
        unsafe {
            let f = Floats { a: 1.234567890e-15_f64,
                     b: 0b_1010_1010,
                     c: 1.0987654321e-15_f64 };
            let ff = rust_dbg_abi_2(f);
            println!("a: {}", ff.a as f64);
            println!("b: {}", ff.b as usize);
            println!("c: {}", ff.c as f64);
            assert_eq!(ff.a, f.c + 1.0f64);
            assert_eq!(ff.b, 0xff);
            assert_eq!(ff.c, f.a - 1.0f64);
        }
    }

    pub fn struct_return() {
        test1();
        test2();
    }
}

#[cfg(target_arch = "x86_64")]
fn main() {
    use tests::*;
    cabi_int_widening();
    extern_pass_char();
    extern_pass_u32();
    extern_pass_u64();
    extern_pass_double();
    extern_pass_empty();
    extern_pass_twou8s();
    extern_pass_twou16s();
    extern_pass_twou32s();
    extern_pass_twou64s();
    extern_return_twou8s();
    extern_return_twou16s();
    extern_return_twou32s();
    extern_return_twou64s();
    foreign_fn_with_byval();
    issue_28676();
    struct_return();
}

#[cfg(not(target_arch = "x86_64"))]
fn main() {

}
<|endoftext|>


<commit_before><commit_msg>Add cube example<commit_after>#[macro_use]
extern crate glium;
extern crate arcball;
extern crate cgmath;

use glium::Surface;
use glium::index::PrimitiveType;
use glium::glutin::{self, ElementState, Event, VirtualKeyCode, MouseButton, MouseScrollDelta};
use cgmath::{Point3, Vector3, Vector2, Matrix4};
use arcball::ArcballCamera;

#[derive(Copy, Clone)]
struct Vertex {
    pos: [f32; 3],
    color: [f32; 3],
}
implement_vertex!(Vertex, pos, color);

fn main() {
    use glium::DisplayBuild;

    let display = glutin::WindowBuilder::new()
        .with_title("Arcball Camera Cube Example")
        .build_glium()
        .unwrap();

    // Hard-coded cube triangle strip
    let vertex_buffer = glium::VertexBuffer::new(&display,
        &[Vertex { pos: [1.0, 1.0, -1.0], color: [1.0, 0.0, 0.0] },
            Vertex { pos: [-1.0, 1.0, -1.0], color: [1.0, 0.0, 0.0] },
            Vertex { pos: [1.0, 1.0, 1.0], color: [1.0, 0.0, 0.0] },

            Vertex { pos: [-1.0, 1.0, 1.0], color: [0.0, 1.0, 0.0] },
            Vertex { pos: [-1.0, -1.0, 1.0], color: [0.0, 1.0, 0.0] },
            Vertex { pos: [-1.0, 1.0, -1.0], color: [0.0, 1.0, 0.0] },

            Vertex { pos: [-1.0, -1.0, -1.0], color: [0.0, 0.0, 1.0] },
            Vertex { pos: [1.0, 1.0, -1.0], color: [0.0, 0.0, 1.0] },
            Vertex { pos: [1.0, -1.0, -1.0], color: [0.0, 0.0, 1.0] },

            Vertex { pos: [1.0, 1.0, 1.0], color: [1.0, 1.0, 0.0] },
            Vertex { pos: [1.0, -1.0, 1.0], color: [1.0, 1.0, 0.0] },
            Vertex { pos: [-1.0, -1.0, 1.0], color: [1.0, 1.0, 0.0] },

            Vertex { pos: [1.0, -1.0, -1.0], color: [1.0, 0.0, 1.0] },
            Vertex { pos: [-1.0, -1.0, -1.0], color: [1.0, 0.0, 1.0] }
        ]
    ).unwrap();
    let index_buffer = glium::index::NoIndices(PrimitiveType::TriangleStrip);

    let program = program!(&display,
        140 => {
            vertex: "
                #version 140

                uniform mat4 proj_view;

                in vec3 pos;
                in vec3 color;

                out vec3 vcolor;

                void main(void) {
                    gl_Position = proj_view * vec4(pos, 1.0);
                    vcolor = color;
                }
            ",
            fragment: "
                #version 140

                in vec3 vcolor;
                out vec4 color;

                void main(void) {
                    color = vec4(vcolor, 1.0);
                }
            "
        },
    ).unwrap();

    let display_dims = display.get_framebuffer_dimensions();
    let mut persp_proj = cgmath::perspective(cgmath::Deg(65.0), display_dims.0 as f32 / display_dims.1 as f32, 1.0, 200.0);
    let mut arcball_camera = {
        let look_at = Matrix4::<f32>::look_at(Point3::new(0.0, 0.0, 6.0),
                                              Point3::new(0.0, 0.0, 0.0),
                                              Vector3::new(0.0, 1.0, 0.0));
        ArcballCamera::new(&look_at, 0.05, 4.0, [display_dims.0 as f32, display_dims.1 as f32])
    };

    // Track if left/right mouse is down
    let mut mouse_pressed = [false, false];
    let mut prev_mouse = None;
    'outer: loop {
        for e in display.poll_events() {
            match e {
                glutin::Event::Closed => break 'outer,
                Event::KeyboardInput(state, _, code) => {
                    let pressed = state == ElementState::Pressed;
                    match code {
                        Some(VirtualKeyCode::Escape) if pressed => break 'outer,
                        _ => {}
                    }
                },
                Event::MouseMoved(x, y) if prev_mouse.is_none() => {
                    prev_mouse = Some((x, y));
                },
                Event::MouseMoved(x, y) => {
                    let prev = prev_mouse.unwrap();
                    if mouse_pressed[0] {
                        arcball_camera.rotate(Vector2::new(prev.0 as f32, prev.1 as f32), Vector2::new(x as f32, y as f32));
                    } else if mouse_pressed[1] {
                        let mouse_delta = Vector2::new((x - prev.0) as f32, -(y - prev.1) as f32);
                        arcball_camera.pan(mouse_delta, 0.16);
                    }
                    prev_mouse = Some((x, y));
                },
                Event::MouseInput(state, button) => {
                    if button == MouseButton::Left {
                        mouse_pressed[0] = state == ElementState::Pressed;
                    } else if button == MouseButton::Right {
                        mouse_pressed[1] = state == ElementState::Pressed;
                    }
                },
                Event::MouseWheel(delta, _) => {
                    let y = match delta {
                        MouseScrollDelta::LineDelta(_, y) => y,
                        MouseScrollDelta::PixelDelta(_, y) => y,
                    };
                    arcball_camera.zoom(y, 0.16);
                },
                Event::Resized(w, h) => {
                    persp_proj = cgmath::perspective(cgmath::Deg(65.0), w as f32 / h as f32, 1.0, 1000.0);
                    arcball_camera.update_screen(w as f32, h as f32);
                },
                _ => {}
            }
        }
        let proj_view: [[f32; 4]; 4] = (persp_proj * arcball_camera.get_mat4()).into();
        let uniforms = uniform! {
            proj_view: proj_view,
        };
        let draw_params = glium::DrawParameters {
            depth: glium::Depth {
                test: glium::draw_parameters::DepthTest::IfLess,
                write: true,
                .. Default::default()
            },
            .. Default::default()
        };

        let mut target = display.draw();
        target.clear_color(0.1, 0.1, 0.1, 0.0);
        target.clear_depth(1.0);
        target.draw(&vertex_buffer, &index_buffer, &program, &uniforms, &draw_params).unwrap();
        target.finish().unwrap();
    }
}

<|endoftext|>


<commit_before>use ide_db::{base_db::FileId, defs::Definition, search::FileReference};
use syntax::{
    algo::find_node_at_range,
    ast::{self, ArgListOwner},
    AstNode, SourceFile, SyntaxKind, SyntaxNode, TextRange, T,
};

use SyntaxKind::WHITESPACE;

use crate::{
    assist_context::AssistBuilder, utils::next_prev, AssistContext, AssistId, AssistKind, Assists,
};

// Assist: remove_unused_param
//
// Removes unused function parameter.
//
// ```
// fn frobnicate(x: i32$0) {}
//
// fn main() {
//     frobnicate(92);
// }
// ```
// ->
// ```
// fn frobnicate() {}
//
// fn main() {
//     frobnicate();
// }
// ```
pub(crate) fn remove_unused_param(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
    let param: ast::Param = ctx.find_node_at_offset()?;
    let ident_pat = match param.pat()? {
        ast::Pat::IdentPat(it) => it,
        _ => return None,
    };
    let func = param.syntax().ancestors().find_map(ast::Fn::cast)?;

    // check if fn is in impl Trait for ..
    if func
        .syntax()
        .parent() // AssocItemList
        .and_then(|x| x.parent())
        .and_then(ast::Impl::cast)
        .map_or(false, |imp| imp.trait_().is_some())
    {
        cov_mark::hit!(trait_impl);
        return None;
    }

    let param_position = func.param_list()?.params().position(|it| it == param)?;
    let fn_def = {
        let func = ctx.sema.to_def(&func)?;
        Definition::ModuleDef(func.into())
    };

    let param_def = {
        let local = ctx.sema.to_def(&ident_pat)?;
        Definition::Local(local)
    };
    if param_def.usages(&ctx.sema).at_least_one() {
        cov_mark::hit!(keep_used);
        return None;
    }
    acc.add(
        AssistId("remove_unused_param", AssistKind::Refactor),
        "Remove unused parameter",
        param.syntax().text_range(),
        |builder| {
            builder.delete(range_to_remove(param.syntax()));
            for (file_id, references) in fn_def.usages(&ctx.sema).all() {
                process_usages(ctx, builder, file_id, references, param_position);
            }
        },
    )
}

fn process_usages(
    ctx: &AssistContext,
    builder: &mut AssistBuilder,
    file_id: FileId,
    references: Vec<FileReference>,
    arg_to_remove: usize,
) {
    let source_file = ctx.sema.parse(file_id);
    builder.edit_file(file_id);
    for usage in references {
        if let Some(text_range) = process_usage(&source_file, usage, arg_to_remove) {
            builder.delete(text_range);
        }
    }
}

fn process_usage(
    source_file: &SourceFile,
    FileReference { range, .. }: FileReference,
    arg_to_remove: usize,
) -> Option<TextRange> {
    let call_expr: ast::CallExpr = find_node_at_range(source_file.syntax(), range)?;
    let call_expr_range = call_expr.expr()?.syntax().text_range();
    if !call_expr_range.contains_range(range) {
        return None;
    }
    let arg = call_expr.arg_list()?.args().nth(arg_to_remove)?;
    Some(range_to_remove(arg.syntax()))
}

fn range_to_remove(node: &SyntaxNode) -> TextRange {
    let up_to_comma = next_prev().find_map(|dir| {
        node.siblings_with_tokens(dir)
            .filter_map(|it| it.into_token())
            .find(|it| it.kind() == T![,])
            .map(|it| (dir, it))
    });
    if let Some((dir, token)) = up_to_comma {
        if node.next_sibling().is_some() {
            let up_to_space = token
                .siblings_with_tokens(dir)
                .skip(1)
                .take_while(|it| it.kind() == WHITESPACE)
                .last()
                .and_then(|it| it.into_token());
            return node
                .text_range()
                .cover(up_to_space.map_or(token.text_range(), |it| it.text_range()));
        }
        node.text_range().cover(token.text_range())
    } else {
        node.text_range()
    }
}

#[cfg(test)]
mod tests {
    use crate::tests::{check_assist, check_assist_not_applicable};

    use super::*;

    #[test]
    fn remove_unused() {
        check_assist(
            remove_unused_param,
            r#"
fn a() { foo(9, 2) }
fn foo(x: i32, $0y: i32) { x; }
fn b() { foo(9, 2,) }
"#,
            r#"
fn a() { foo(9) }
fn foo(x: i32) { x; }
fn b() { foo(9, ) }
"#,
        );
    }

    #[test]
    fn remove_unused_first_param() {
        check_assist(
            remove_unused_param,
            r#"
fn foo($0x: i32, y: i32) { y; }
fn a() { foo(1, 2) }
fn b() { foo(1, 2,) }
"#,
            r#"
fn foo(y: i32) { y; }
fn a() { foo(2) }
fn b() { foo(2,) }
"#,
        );
    }

    #[test]
    fn remove_unused_single_param() {
        check_assist(
            remove_unused_param,
            r#"
fn foo($0x: i32) { 0; }
fn a() { foo(1) }
fn b() { foo(1, ) }
"#,
            r#"
fn foo() { 0; }
fn a() { foo() }
fn b() { foo( ) }
"#,
        );
    }

    #[test]
    fn remove_unused_surrounded_by_parms() {
        check_assist(
            remove_unused_param,
            r#"
fn foo(x: i32, $0y: i32, z: i32) { x; }
fn a() { foo(1, 2, 3) }
fn b() { foo(1, 2, 3,) }
"#,
            r#"
fn foo(x: i32, z: i32) { x; }
fn a() { foo(1, 3) }
fn b() { foo(1, 3,) }
"#,
        );
    }

    #[test]
    fn remove_unused_qualified_call() {
        check_assist(
            remove_unused_param,
            r#"
mod bar { pub fn foo(x: i32, $0y: i32) { x; } }
fn b() { bar::foo(9, 2) }
"#,
            r#"
mod bar { pub fn foo(x: i32) { x; } }
fn b() { bar::foo(9) }
"#,
        );
    }

    #[test]
    fn remove_unused_turbofished_func() {
        check_assist(
            remove_unused_param,
            r#"
pub fn foo<T>(x: T, $0y: i32) { x; }
fn b() { foo::<i32>(9, 2) }
"#,
            r#"
pub fn foo<T>(x: T) { x; }
fn b() { foo::<i32>(9) }
"#,
        );
    }

    #[test]
    fn remove_unused_generic_unused_param_func() {
        check_assist(
            remove_unused_param,
            r#"
pub fn foo<T>(x: i32, $0y: T) { x; }
fn b() { foo::<i32>(9, 2) }
fn b2() { foo(9, 2) }
"#,
            r#"
pub fn foo<T>(x: i32) { x; }
fn b() { foo::<i32>(9) }
fn b2() { foo(9) }
"#,
        );
    }

    #[test]
    fn keep_used() {
        cov_mark::check!(keep_used);
        check_assist_not_applicable(
            remove_unused_param,
            r#"
fn foo(x: i32, $0y: i32) { y; }
fn main() { foo(9, 2) }
"#,
        );
    }

    #[test]
    fn trait_impl() {
        cov_mark::check!(trait_impl);
        check_assist_not_applicable(
            remove_unused_param,
            r#"
trait Trait {
    fn foo(x: i32);
}
impl Trait for () {
    fn foo($0x: i32) {}
}
"#,
        );
    }

    #[test]
    fn remove_across_files() {
        check_assist(
            remove_unused_param,
            r#"
//- /main.rs
fn foo(x: i32, $0y: i32) { x; }

mod foo;

//- /foo.rs
use super::foo;

fn bar() {
    let _ = foo(1, 2);
}
"#,
            r#"
//- /main.rs
fn foo(x: i32) { x; }

mod foo;

//- /foo.rs
use super::foo;

fn bar() {
    let _ = foo(1);
}
"#,
        )
    }

    #[test]
    fn remove_method_param() {
        // FIXME: This is completely wrong:
        //  * method call expressions are not handled
        //  * assoc function syntax removes the wrong argument.
        check_assist(
            remove_unused_param,
            r#"
struct S;
impl S { fn f(&self, $0_unused: i32) {} }
fn main() {
    S.f(92);
    S.f();
    S.f(92, 92);
    S::f(&S, 92);
}
"#,
            r#"
struct S;
impl S { fn f(&self) {} }
fn main() {
    S.f(92);
    S.f();
    S.f(92, 92);
    S::f(92);
}
"#,
        )
    }
}
<commit_msg>add:  fix: Adding remove_unused_param for method and fixing same for associative func<commit_after>use ide_db::{base_db::FileId, defs::Definition, search::FileReference};
use syntax::{
    algo::find_node_at_range,
    ast::{self, ArgListOwner},
    AstNode, SourceFile, SyntaxKind, SyntaxNode, TextRange, T,
};

use SyntaxKind::WHITESPACE;

use crate::{
    assist_context::AssistBuilder, utils::next_prev, AssistContext, AssistId, AssistKind, Assists,
};

// Assist: remove_unused_param
//
// Removes unused function parameter.
//
// ```
// fn frobnicate(x: i32$0) {}
//
// fn main() {
//     frobnicate(92);
// }
// ```
// ->
// ```
// fn frobnicate() {}
//
// fn main() {
//     frobnicate();
// }
// ```
pub(crate) fn remove_unused_param(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
    let param: ast::Param = ctx.find_node_at_offset()?;
    let ident_pat = match param.pat()? {
        ast::Pat::IdentPat(it) => it,
        _ => return None,
    };
    let func = param.syntax().ancestors().find_map(ast::Fn::cast)?;
    let is_self_present =
        param.syntax().parent()?.children().find_map(ast::SelfParam::cast).is_some();

    // check if fn is in impl Trait for ..
    if func
        .syntax()
        .parent() // AssocItemList
        .and_then(|x| x.parent())
        .and_then(ast::Impl::cast)
        .map_or(false, |imp| imp.trait_().is_some())
    {
        cov_mark::hit!(trait_impl);
        return None;
    }

    let mut param_position = func.param_list()?.params().position(|it| it == param)?;
    // param_list() does not take self param into consideration, hence this additional check is
    // added. There are two cases to handle in this scenario, where functions are
    // associative(functions not associative and not containting contain self, are not allowed), in
    // this case param position is rightly set. If a method call is present which has self param,
    // that needs to be handled and is added below in process_usage function to reduce this increment and
    // not consider self param.
    if is_self_present {
        param_position += 1;
    }
    let fn_def = {
        let func = ctx.sema.to_def(&func)?;
        Definition::ModuleDef(func.into())
    };

    let param_def = {
        let local = ctx.sema.to_def(&ident_pat)?;
        Definition::Local(local)
    };
    if param_def.usages(&ctx.sema).at_least_one() {
        cov_mark::hit!(keep_used);
        return None;
    }
    acc.add(
        AssistId("remove_unused_param", AssistKind::Refactor),
        "Remove unused parameter",
        param.syntax().text_range(),
        |builder| {
            builder.delete(range_to_remove(param.syntax()));
            for (file_id, references) in fn_def.usages(&ctx.sema).all() {
                process_usages(ctx, builder, file_id, references, param_position, is_self_present);
            }
        },
    )
}

fn process_usages(
    ctx: &AssistContext,
    builder: &mut AssistBuilder,
    file_id: FileId,
    references: Vec<FileReference>,
    arg_to_remove: usize,
    is_self_present: bool,
) {
    let source_file = ctx.sema.parse(file_id);
    builder.edit_file(file_id);
    for usage in references {
        if let Some(text_range) = process_usage(&source_file, usage, arg_to_remove, is_self_present)
        {
            builder.delete(text_range);
        }
    }
}

fn process_usage(
    source_file: &SourceFile,
    FileReference { range, .. }: FileReference,
    mut arg_to_remove: usize,
    is_self_present: bool,
) -> Option<TextRange> {
    let call_expr_opt: Option<ast::CallExpr> = find_node_at_range(source_file.syntax(), range);
    if let Some(call_expr) = call_expr_opt {
        let call_expr_range = call_expr.expr()?.syntax().text_range();
        if !call_expr_range.contains_range(range) {
            return None;
        }

        let arg = call_expr.arg_list()?.args().nth(arg_to_remove)?;
        return Some(range_to_remove(arg.syntax()));
    }

    let method_call_expr_opt: Option<ast::MethodCallExpr> =
        find_node_at_range(source_file.syntax(), range);
    if let Some(method_call_expr) = method_call_expr_opt {
        let method_call_expr_range = method_call_expr.name_ref()?.syntax().text_range();
        if !method_call_expr_range.contains_range(range) {
            return None;
        }

        if is_self_present {
            arg_to_remove -= 1;
        }

        let arg = method_call_expr.arg_list()?.args().nth(arg_to_remove)?;
        return Some(range_to_remove(arg.syntax()));
    }

    return None;
}

fn range_to_remove(node: &SyntaxNode) -> TextRange {
    let up_to_comma = next_prev().find_map(|dir| {
        node.siblings_with_tokens(dir)
            .filter_map(|it| it.into_token())
            .find(|it| it.kind() == T![,])
            .map(|it| (dir, it))
    });
    if let Some((dir, token)) = up_to_comma {
        if node.next_sibling().is_some() {
            let up_to_space = token
                .siblings_with_tokens(dir)
                .skip(1)
                .take_while(|it| it.kind() == WHITESPACE)
                .last()
                .and_then(|it| it.into_token());
            return node
                .text_range()
                .cover(up_to_space.map_or(token.text_range(), |it| it.text_range()));
        }
        node.text_range().cover(token.text_range())
    } else {
        node.text_range()
    }
}

#[cfg(test)]
mod tests {
    use crate::tests::{check_assist, check_assist_not_applicable};

    use super::*;

    #[test]
    fn remove_unused() {
        check_assist(
            remove_unused_param,
            r#"
fn a() { foo(9, 2) }
fn foo(x: i32, $0y: i32) { x; }
fn b() { foo(9, 2,) }
"#,
            r#"
fn a() { foo(9) }
fn foo(x: i32) { x; }
fn b() { foo(9, ) }
"#,
        );
    }

    #[test]
    fn remove_unused_first_param() {
        check_assist(
            remove_unused_param,
            r#"
fn foo($0x: i32, y: i32) { y; }
fn a() { foo(1, 2) }
fn b() { foo(1, 2,) }
"#,
            r#"
fn foo(y: i32) { y; }
fn a() { foo(2) }
fn b() { foo(2,) }
"#,
        );
    }

    #[test]
    fn remove_unused_single_param() {
        check_assist(
            remove_unused_param,
            r#"
fn foo($0x: i32) { 0; }
fn a() { foo(1) }
fn b() { foo(1, ) }
"#,
            r#"
fn foo() { 0; }
fn a() { foo() }
fn b() { foo( ) }
"#,
        );
    }

    #[test]
    fn remove_unused_surrounded_by_parms() {
        check_assist(
            remove_unused_param,
            r#"
fn foo(x: i32, $0y: i32, z: i32) { x; }
fn a() { foo(1, 2, 3) }
fn b() { foo(1, 2, 3,) }
"#,
            r#"
fn foo(x: i32, z: i32) { x; }
fn a() { foo(1, 3) }
fn b() { foo(1, 3,) }
"#,
        );
    }

    #[test]
    fn remove_unused_qualified_call() {
        check_assist(
            remove_unused_param,
            r#"
mod bar { pub fn foo(x: i32, $0y: i32) { x; } }
fn b() { bar::foo(9, 2) }
"#,
            r#"
mod bar { pub fn foo(x: i32) { x; } }
fn b() { bar::foo(9) }
"#,
        );
    }

    #[test]
    fn remove_unused_turbofished_func() {
        check_assist(
            remove_unused_param,
            r#"
pub fn foo<T>(x: T, $0y: i32) { x; }
fn b() { foo::<i32>(9, 2) }
"#,
            r#"
pub fn foo<T>(x: T) { x; }
fn b() { foo::<i32>(9) }
"#,
        );
    }

    #[test]
    fn remove_unused_generic_unused_param_func() {
        check_assist(
            remove_unused_param,
            r#"
pub fn foo<T>(x: i32, $0y: T) { x; }
fn b() { foo::<i32>(9, 2) }
fn b2() { foo(9, 2) }
"#,
            r#"
pub fn foo<T>(x: i32) { x; }
fn b() { foo::<i32>(9) }
fn b2() { foo(9) }
"#,
        );
    }

    #[test]
    fn keep_used() {
        cov_mark::check!(keep_used);
        check_assist_not_applicable(
            remove_unused_param,
            r#"
fn foo(x: i32, $0y: i32) { y; }
fn main() { foo(9, 2) }
"#,
        );
    }

    #[test]
    fn trait_impl() {
        cov_mark::check!(trait_impl);
        check_assist_not_applicable(
            remove_unused_param,
            r#"
trait Trait {
    fn foo(x: i32);
}
impl Trait for () {
    fn foo($0x: i32) {}
}
"#,
        );
    }

    #[test]
    fn remove_across_files() {
        check_assist(
            remove_unused_param,
            r#"
//- /main.rs
fn foo(x: i32, $0y: i32) { x; }

mod foo;

//- /foo.rs
use super::foo;

fn bar() {
    let _ = foo(1, 2);
}
"#,
            r#"
//- /main.rs
fn foo(x: i32) { x; }

mod foo;

//- /foo.rs
use super::foo;

fn bar() {
    let _ = foo(1);
}
"#,
        )
    }

    #[test]
    fn test_remove_method_param() {
        check_assist(
            remove_unused_param,
            r#"
struct S;
impl S { fn f(&self, $0_unused: i32) {} }
fn main() {
    S.f(92);
    S.f();
    S.f(93, 92);
    S::f(&S, 92);
}
"#,
            r#"
struct S;
impl S { fn f(&self) {} }
fn main() {
    S.f();
    S.f();
    S.f(92);
    S::f(&S);
}
"#,
        )
    }
}
<|endoftext|>


<commit_before><commit_msg>Import and tidy up macro from Gist<commit_after>/*!
Macro to declare lazily evaluated statics, which allows runtime initialization.

The macro works by defining a custom type with a `Deref` impl, which delegates the dereferencing
to a hidden `static mut` that gets lazily initialized on first access.

# Examples

To load the extension and use it:

```rust,ignore

}
```
*/

#![crate_id = "lazy_static"]
#![crate_type = "dylib"]
#![license = "MIT"]

#![feature(macro_rules)]

#[macro_export]
macro_rules! lazy_static {
    ($(static ref $N:ident : $T:ty = $e:expr;)*) => {
        $(
            #[allow(non_camel_case_types)]
            #[allow(dead_code)]
            struct $N {__unit__: ()}
            static $N: $N = $N {__unit__: ()};
            impl Deref<$T> for $N {
                fn deref<'a>(&'a self) -> &'a $T {
                    use std::sync::{Once, ONCE_INIT};
                    use std::mem::transmute;

                    #[inline(always)]
                    fn require_share<T: Share>(_: &T) { }

                    unsafe {
                        static mut s: *$T = 0 as *$T;
                        static mut ONCE: Once = ONCE_INIT;
                        ONCE.doit(|| {
                            s = transmute::<Box<$T>, *$T>(box() ($e));
                        });
                        let static_ref = &*s;
                        require_share(static_ref);
                        static_ref
                    }
                }
            }

        )*
    }
}

#[cfg(test)]
mod test {
    use std::collections::HashMap;

    lazy_static! {
        static ref NUMBER: uint = times_two(3);
        static ref VEC: [Box<uint>, ..3] = [box 1, box 2, box 3];
        static ref OWNED_STRING: String = "hello".to_string();
        static ref HASHMAP: HashMap<uint, &'static str> = {
            let mut m = HashMap::new();
            m.insert(0u, "abc");
            m.insert(1, "def");
            m.insert(2, "ghi");
            m
        };
        static ref UNUSED: () = ();
    }

    fn times_two(n: uint) -> uint {
        n * 2
    }

    #[test]
    fn test_basic() {
        assert_eq!(OWNED_STRING.as_slice(), "hello");
        assert_eq!(*NUMBER, 6);
        assert!(HASHMAP.find(&1).is_some());
        assert!(HASHMAP.find(&3).is_none());
        assert_eq!(VEC.as_slice(), &[box 1, box 2, box 3]);
    }

    #[test]
    fn test_repeat() {
        assert_eq!(*NUMBER, 6);
        assert_eq!(*NUMBER, 6);
        assert_eq!(*NUMBER, 6);
    }
}
<|endoftext|>


<commit_before><commit_msg>Codeforces 762A<commit_after>use std::collections::LinkedList;

macro_rules! read_line {
    ($v:ident) => {
        let mut temp = String::new();
        std::io::stdin().read_line(&mut temp).unwrap();
        let $v = temp;
    };
    (var, $t:ty, $($v:ident), *) => {
        read_line!(input_line);
        let mut iter = parse_token!($t, input_line);
        $(
            let $v = iter.next().unwrap();
        )*
    };
    (vec, $t:ty, $v:ident) => {
        read_line!(input_line);
        let iter = parse_token!($t, input_line);
        let $v: Vec<$t> = iter.collect();
    };
    ($($v:ident; $t:ty), *) => {
        read_line!(input_line);
        let mut iter = input_line.split_whitespace();
        $(
            let $v: $t = iter.next().unwrap().parse().unwrap();
        )*
    };
}

macro_rules! parse_token {
    ($t:ty, $e:expr) => {
        $e.split_whitespace().map(|x| x.parse::<$t>().unwrap());
    };
}

fn main() {
    read_line!(k;u64, n;u64);
    let mut divisors = LinkedList::new();
    let mut i = (k as f64).sqrt() as u64;
    if i * i == k {
        divisors.push_back(i);
        i -= 1;
    }
    while i >= 1 {
        if k % i == 0 {
            divisors.push_front(i);
            divisors.push_back(k / i);
        }
        i -= 1;
    }
    if n > divisors.len() as u64 {
        println!("-1");
    } else {
        for (idx, divisor) in divisors.iter().enumerate() {
            if idx as u64 == n - 1 {
                println!("{}", divisor);
            }
        }
    }
}<|endoftext|>


<commit_before><commit_msg>Fix: Set isflag when creating a mail in the store<commit_after><|endoftext|>


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

use borrow_check::nll::constraints::OutlivesConstraint;
use borrow_check::nll::type_check::{BorrowCheckContext, Locations};
use rustc::infer::nll_relate::{TypeRelating, TypeRelatingDelegate};
use rustc::infer::{InferCtxt, NLLRegionVariableOrigin};
use rustc::mir::{ConstraintCategory, UserTypeAnnotation};
use rustc::traits::query::Fallible;
use rustc::ty::relate::TypeRelation;
use rustc::ty::subst::UserSubsts;
use rustc::ty::{self, Ty};
use syntax_pos::DUMMY_SP;

/// Adds sufficient constraints to ensure that `a <: b`.
pub(super) fn sub_types<'tcx>(
    infcx: &InferCtxt<'_, '_, 'tcx>,
    a: Ty<'tcx>,
    b: Ty<'tcx>,
    locations: Locations,
    category: ConstraintCategory,
    borrowck_context: Option<&mut BorrowCheckContext<'_, 'tcx>>,
) -> Fallible<()> {
    debug!("sub_types(a={:?}, b={:?}, locations={:?})", a, b, locations);
    TypeRelating::new(
        infcx,
        NllTypeRelatingDelegate::new(infcx, borrowck_context, locations, category),
        ty::Variance::Covariant,
    ).relate(&a, &b)?;
    Ok(())
}

/// Adds sufficient constraints to ensure that `a == b`.
pub(super) fn eq_types<'tcx>(
    infcx: &InferCtxt<'_, '_, 'tcx>,
    a: Ty<'tcx>,
    b: Ty<'tcx>,
    locations: Locations,
    category: ConstraintCategory,
    borrowck_context: Option<&mut BorrowCheckContext<'_, 'tcx>>,
) -> Fallible<()> {
    debug!("eq_types(a={:?}, b={:?}, locations={:?})", a, b, locations);
    TypeRelating::new(
        infcx,
        NllTypeRelatingDelegate::new(infcx, borrowck_context, locations, category),
        ty::Variance::Invariant,
    ).relate(&a, &b)?;
    Ok(())
}

/// Adds sufficient constraints to ensure that `a <: b`, where `b` is
/// a user-given type (which means it may have canonical variables
/// encoding things like `_`).
pub(super) fn relate_type_and_user_type<'tcx>(
    infcx: &InferCtxt<'_, '_, 'tcx>,
    a: Ty<'tcx>,
    v: ty::Variance,
    user_ty: UserTypeAnnotation<'tcx>,
    locations: Locations,
    category: ConstraintCategory,
    borrowck_context: Option<&mut BorrowCheckContext<'_, 'tcx>>,
) -> Fallible<Ty<'tcx>> {
    debug!(
        "relate_type_and_user_type(a={:?}, v={:?}, b={:?}, locations={:?})",
        a, v, user_ty, locations
    );

    let b = match user_ty {
        UserTypeAnnotation::Ty(canonical_ty) => {
            let (ty, _) =
                infcx.instantiate_canonical_with_fresh_inference_vars(DUMMY_SP, &canonical_ty);
            ty
        }
        UserTypeAnnotation::FnDef(def_id, canonical_substs) => {
            let (UserSubsts { substs, user_self_ty }, _) =
                infcx.instantiate_canonical_with_fresh_inference_vars(DUMMY_SP, &canonical_substs);
            assert!(user_self_ty.is_none()); // TODO for now
            infcx.tcx.mk_fn_def(def_id, substs)
        }
        UserTypeAnnotation::AdtDef(adt_def, canonical_substs) => {
            let (UserSubsts { substs, user_self_ty }, _) =
                infcx.instantiate_canonical_with_fresh_inference_vars(DUMMY_SP, &canonical_substs);
            assert!(user_self_ty.is_none()); // TODO for now
            infcx.tcx.mk_adt(adt_def, substs)
        }
    };

    // The `TypeRelating` code assumes that the "canonical variables"
    // appear in the "a" side, so flip `Contravariant` ambient
    // variance to get the right relationship.
    let v1 = ty::Contravariant.xform(v);

    let mut type_relating = TypeRelating::new(
        infcx,
        NllTypeRelatingDelegate::new(infcx, borrowck_context, locations, category),
        v1,
    );
    type_relating.relate(&b, &a)?;

    Ok(b)
}

struct NllTypeRelatingDelegate<'me, 'bccx: 'me, 'gcx: 'tcx, 'tcx: 'bccx> {
    infcx: &'me InferCtxt<'me, 'gcx, 'tcx>,
    borrowck_context: Option<&'me mut BorrowCheckContext<'bccx, 'tcx>>,

    /// Where (and why) is this relation taking place?
    locations: Locations,

    /// What category do we assign the resulting `'a: 'b` relationships?
    category: ConstraintCategory,
}

impl NllTypeRelatingDelegate<'me, 'bccx, 'gcx, 'tcx> {
    fn new(
        infcx: &'me InferCtxt<'me, 'gcx, 'tcx>,
        borrowck_context: Option<&'me mut BorrowCheckContext<'bccx, 'tcx>>,
        locations: Locations,
        category: ConstraintCategory,
    ) -> Self {
        Self {
            infcx,
            borrowck_context,
            locations,
            category,
        }
    }
}

impl TypeRelatingDelegate<'tcx> for NllTypeRelatingDelegate<'_, '_, '_, 'tcx> {
    fn create_next_universe(&mut self) -> ty::UniverseIndex {
        self.infcx.create_next_universe()
    }

    fn next_existential_region_var(&mut self) -> ty::Region<'tcx> {
        let origin = NLLRegionVariableOrigin::Existential;
        self.infcx.next_nll_region_var(origin)
    }

    fn next_placeholder_region(&mut self, placeholder: ty::Placeholder) -> ty::Region<'tcx> {
        let origin = NLLRegionVariableOrigin::Placeholder(placeholder);
        if let Some(borrowck_context) = &mut self.borrowck_context {
            borrowck_context.placeholder_indices.insert(placeholder);
        }
        self.infcx.next_nll_region_var(origin)
    }

    fn generalize_existential(&mut self, universe: ty::UniverseIndex) -> ty::Region<'tcx> {
        self.infcx
            .next_nll_region_var_in_universe(NLLRegionVariableOrigin::Existential, universe)
    }

    fn push_outlives(&mut self, sup: ty::Region<'tcx>, sub: ty::Region<'tcx>) {
        if let Some(borrowck_context) = &mut self.borrowck_context {
            let sub = borrowck_context.universal_regions.to_region_vid(sub);
            let sup = borrowck_context.universal_regions.to_region_vid(sup);
            borrowck_context
                .constraints
                .outlives_constraints
                .push(OutlivesConstraint {
                    sup,
                    sub,
                    locations: self.locations,
                    category: self.category,
                });
        }
    }
}
<commit_msg>pull the common code across user-ty variants up top<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.

use borrow_check::nll::constraints::OutlivesConstraint;
use borrow_check::nll::type_check::{BorrowCheckContext, Locations};
use rustc::infer::nll_relate::{TypeRelating, TypeRelatingDelegate};
use rustc::infer::{InferCtxt, NLLRegionVariableOrigin};
use rustc::mir::{ConstraintCategory, UserTypeAnnotation};
use rustc::traits::query::Fallible;
use rustc::ty::relate::TypeRelation;
use rustc::ty::subst::UserSubsts;
use rustc::ty::{self, Ty};
use syntax_pos::DUMMY_SP;

/// Adds sufficient constraints to ensure that `a <: b`.
pub(super) fn sub_types<'tcx>(
    infcx: &InferCtxt<'_, '_, 'tcx>,
    a: Ty<'tcx>,
    b: Ty<'tcx>,
    locations: Locations,
    category: ConstraintCategory,
    borrowck_context: Option<&mut BorrowCheckContext<'_, 'tcx>>,
) -> Fallible<()> {
    debug!("sub_types(a={:?}, b={:?}, locations={:?})", a, b, locations);
    TypeRelating::new(
        infcx,
        NllTypeRelatingDelegate::new(infcx, borrowck_context, locations, category),
        ty::Variance::Covariant,
    ).relate(&a, &b)?;
    Ok(())
}

/// Adds sufficient constraints to ensure that `a == b`.
pub(super) fn eq_types<'tcx>(
    infcx: &InferCtxt<'_, '_, 'tcx>,
    a: Ty<'tcx>,
    b: Ty<'tcx>,
    locations: Locations,
    category: ConstraintCategory,
    borrowck_context: Option<&mut BorrowCheckContext<'_, 'tcx>>,
) -> Fallible<()> {
    debug!("eq_types(a={:?}, b={:?}, locations={:?})", a, b, locations);
    TypeRelating::new(
        infcx,
        NllTypeRelatingDelegate::new(infcx, borrowck_context, locations, category),
        ty::Variance::Invariant,
    ).relate(&a, &b)?;
    Ok(())
}

/// Adds sufficient constraints to ensure that `a <: b`, where `b` is
/// a user-given type (which means it may have canonical variables
/// encoding things like `_`).
pub(super) fn relate_type_and_user_type<'tcx>(
    infcx: &InferCtxt<'_, '_, 'tcx>,
    a: Ty<'tcx>,
    v: ty::Variance,
    user_ty: UserTypeAnnotation<'tcx>,
    locations: Locations,
    category: ConstraintCategory,
    borrowck_context: Option<&mut BorrowCheckContext<'_, 'tcx>>,
) -> Fallible<Ty<'tcx>> {
    debug!(
        "relate_type_and_user_type(a={:?}, v={:?}, b={:?}, locations={:?})",
        a, v, user_ty, locations
    );

    // The `TypeRelating` code assumes that the "canonical variables"
    // appear in the "a" side, so flip `Contravariant` ambient
    // variance to get the right relationship.
    let v1 = ty::Contravariant.xform(v);

    let mut type_relating = TypeRelating::new(
        infcx,
        NllTypeRelatingDelegate::new(infcx, borrowck_context, locations, category),
        v1,
    );

    match user_ty {
        UserTypeAnnotation::Ty(canonical_ty) => {
            let (ty, _) =
                infcx.instantiate_canonical_with_fresh_inference_vars(DUMMY_SP, &canonical_ty);
            type_relating.relate(&ty, &a)?;
            Ok(ty)
        }
        UserTypeAnnotation::FnDef(def_id, canonical_substs) => {
            let (
                UserSubsts {
                    substs,
                    user_self_ty,
                },
                _,
            ) = infcx.instantiate_canonical_with_fresh_inference_vars(DUMMY_SP, &canonical_substs);
            assert!(user_self_ty.is_none()); // TODO for now
            let ty = infcx.tcx.mk_fn_def(def_id, substs);
            type_relating.relate(&ty, &a)?;
            Ok(ty)
        }
        UserTypeAnnotation::AdtDef(adt_def, canonical_substs) => {
            let (
                UserSubsts {
                    substs,
                    user_self_ty,
                },
                _,
            ) = infcx.instantiate_canonical_with_fresh_inference_vars(DUMMY_SP, &canonical_substs);
            assert!(user_self_ty.is_none()); // TODO for now
            let ty = infcx.tcx.mk_adt(adt_def, substs);
            type_relating.relate(&ty, &a)?;
            Ok(ty)
        }
    }
}

struct NllTypeRelatingDelegate<'me, 'bccx: 'me, 'gcx: 'tcx, 'tcx: 'bccx> {
    infcx: &'me InferCtxt<'me, 'gcx, 'tcx>,
    borrowck_context: Option<&'me mut BorrowCheckContext<'bccx, 'tcx>>,

    /// Where (and why) is this relation taking place?
    locations: Locations,

    /// What category do we assign the resulting `'a: 'b` relationships?
    category: ConstraintCategory,
}

impl NllTypeRelatingDelegate<'me, 'bccx, 'gcx, 'tcx> {
    fn new(
        infcx: &'me InferCtxt<'me, 'gcx, 'tcx>,
        borrowck_context: Option<&'me mut BorrowCheckContext<'bccx, 'tcx>>,
        locations: Locations,
        category: ConstraintCategory,
    ) -> Self {
        Self {
            infcx,
            borrowck_context,
            locations,
            category,
        }
    }
}

impl TypeRelatingDelegate<'tcx> for NllTypeRelatingDelegate<'_, '_, '_, 'tcx> {
    fn create_next_universe(&mut self) -> ty::UniverseIndex {
        self.infcx.create_next_universe()
    }

    fn next_existential_region_var(&mut self) -> ty::Region<'tcx> {
        let origin = NLLRegionVariableOrigin::Existential;
        self.infcx.next_nll_region_var(origin)
    }

    fn next_placeholder_region(&mut self, placeholder: ty::Placeholder) -> ty::Region<'tcx> {
        let origin = NLLRegionVariableOrigin::Placeholder(placeholder);
        if let Some(borrowck_context) = &mut self.borrowck_context {
            borrowck_context.placeholder_indices.insert(placeholder);
        }
        self.infcx.next_nll_region_var(origin)
    }

    fn generalize_existential(&mut self, universe: ty::UniverseIndex) -> ty::Region<'tcx> {
        self.infcx
            .next_nll_region_var_in_universe(NLLRegionVariableOrigin::Existential, universe)
    }

    fn push_outlives(&mut self, sup: ty::Region<'tcx>, sub: ty::Region<'tcx>) {
        if let Some(borrowck_context) = &mut self.borrowck_context {
            let sub = borrowck_context.universal_regions.to_region_vid(sub);
            let sup = borrowck_context.universal_regions.to_region_vid(sup);
            borrowck_context
                .constraints
                .outlives_constraints
                .push(OutlivesConstraint {
                    sup,
                    sub,
                    locations: self.locations,
                    category: self.category,
                });
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>fuchsia: fix regression in fmt::Debug for Events (#699)<commit_after><|endoftext|>


<commit_before><commit_msg>[Auto] bin/core/bookmark: Fix Clippy warnings<commit_after><|endoftext|>


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

extern crate chrono;
extern crate grin_core;
extern crate grin_keychain as keychain;
extern crate grin_util as util;
extern crate grin_wallet as wallet;

use std::sync::{Arc, RwLock};

pub mod common;

use grin_core::core::verifier_cache::{LruVerifierCache, VerifierCache};
use grin_core::core::{Output, OutputFeatures};
use keychain::{ExtKeychain, Keychain};
use wallet::libtx::proof;

fn verifier_cache() -> Arc<RwLock<VerifierCache>> {
	Arc::new(RwLock::new(LruVerifierCache::new()))
}

#[test]
fn test_verifier_cache_rangeproofs() {
	let cache = verifier_cache();

	let keychain = ExtKeychain::from_random_seed().unwrap();
	let key_id = keychain.derive_key_id(1).unwrap();
	let commit = keychain.commit(5, &key_id).unwrap();
	let proof = proof::create(&keychain, 5, &key_id, commit, None).unwrap();

	let out = Output {
		features: OutputFeatures::DEFAULT_OUTPUT,
		commit: commit,
		proof: proof,
	};

	// Check our output is not verified according to the cache.
	{
		let mut cache = cache.write().unwrap();
		let unverified = cache.filter_rangeproof_unverified(&vec![out]);
		assert_eq!(unverified, vec![out]);
	}

	// Add our output to the cache.
	{
		let mut cache = cache.write().unwrap();
		cache.add_rangeproof_verified(vec![out]);
	}

	// Check it shows as verified according to the cache.
	{
		let mut cache = cache.write().unwrap();
		let unverified = cache.filter_rangeproof_unverified(&vec![out]);
		assert_eq!(unverified, vec![]);
	}
}
<|endoftext|>


<commit_before><commit_msg>Add benchmark<commit_after>// cargo bench

#![feature(test)]

extern crate ryu;
extern crate test;

macro_rules! benches {
    ($($name:ident($value:expr),)*) => {
        mod bench_ryu {
            use test::{Bencher, black_box};
            $(
                #[bench]
                fn $name(b: &mut Bencher) {
                    use ryu;

                    let mut buf = ryu::Buffer::new();

                    b.iter(move || {
                        let value = black_box($value);
                        let formatted = buf.format(value);
                        black_box(formatted);
                    });
                }
            )*
        }

        mod bench_std_fmt {
            use test::{Bencher, black_box};
            $(
                #[bench]
                fn $name(b: &mut Bencher) {
                    use std::io::Write;

                    let mut buf = Vec::with_capacity(20);

                    b.iter(|| {
                        buf.clear();
                        let value = black_box($value);
                        write!(&mut buf, "{}", value).unwrap();
                        black_box(buf.as_slice());
                    });
                }
            )*
        }
    }
}

benches!(
    bench_0_f64(0f64),
    bench_short_f64(0.1234f64),
    bench_e_f64(2.718281828459045f64),
    bench_max_f64(::std::f64::MAX),

    bench_0_f32(0f32),
    bench_short_f32(0.1234f32),
    bench_e_f32(2.718281828459045f32),
    bench_max_f32(::std::f32::MAX),
);
<|endoftext|>


<commit_before><commit_msg>Began abstracting quadtree_diffusion<commit_after>
macro_rules! printlnerr(
    ($($arg:tt)*) => { {use std::io::Write;
        let r = writeln!(&mut ::std::io::stderr(), $($arg)*);
        r.expect("failed printing to stderr");
    } }
);

trait TreeContinuumPhysics {
  const DIMENSIONS: usize;
  type Steward: TimeSteward;
  type NodeVarying: QueryResult;
  type BoundaryVarying: QueryResult;
}

use std::cmp::{min, max};
use std::collections::HashSet;

use time_steward::{DeterministicRandomId};
use time_steward::{PersistentTypeId, PersistentlyIdentifiedType, ListedType, DataHandleTrait, DataTimelineCellTrait, Basics as BasicsTrait};
use time_steward::stewards::{simple_full as steward_module};
use steward_module::{TimeSteward, ConstructibleTimeSteward, IncrementalTimeSteward, Event, DataHandle, DataTimelineCell, EventHandle, Accessor, EventAccessor, FutureCleanupAccessor, simple_timeline};
use simple_timeline::{SimpleTimeline, query, set, destroy, just_destroyed};

const DIMENSIONS: usize = 2;

enum Face<Physics: TreeContinuumPhysics> {
  WorldEdge,
  SingleBoundary (BoundaryHandle<Physics>),
  SplitBoundary ([BoundaryHandle<Physics>; 1<<(DIMENSIONS-1)]
}

#[derive (Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
struct NodeData<Physics: TreeContinuumPhysics> {
  width: Distance,
  center: [Distance ; Physics::DIMENSIONS],
  parent: Option <NodeHandle<Physics>>,
  varying: DataTimelineCell <SimpleTimeline <NodeVarying<Physics>, Physics::Steward>>,
}
#[derive (Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
struct NodeVarying<Physics: TreeContinuumPhysics> {
  children: Vec<NodeHandle<Physics>>,
  boundaries: [[Face<Physics>; 2]; DIMENSIONS],
  data: Physics::NodeVarying,
}
type NodeHandle<Physics> = DataHandle <NodeData<Physics>>;
impl PersistentlyIdentifiedType for NodeData<Physics> {
  const ID: PersistentTypeId = PersistentTypeId(Physics::ID ^ 0x0d838bdd804f48d7);
}

#[derive (Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
struct BoundaryData<Physics: TreeContinuumPhysics> {
  length: Distance,
  center: [Distance ; 2],
  nodes: [NodeHandle<Physics>; 2],
  varying: DataTimelineCell <SimpleTimeline <BoundaryVarying<Physics>, Physics::Steward>>,
}
#[derive (Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
struct BoundaryVarying<Physics: TreeContinuumPhysics> {
  data: Physics::BoundaryVarying,
}
type BoundaryHandle<Physics> = DataHandle <BoundaryData<Physics>>;
impl PersistentlyIdentifiedType for BoundaryData<Physics> {
  const ID: PersistentTypeId = PersistentTypeId(Physics::ID ^ 0x4913f629aef09374);
}

macro_rules! get {
  ($accessor: expr, $cell: expr) => {
    query ($accessor, $cell)
  }
}
macro_rules! set {
  ($accessor: expr, $cell: expr, $field: ident, $value: expr) => {
    {
      let mut value = query ($accessor, $cell);
      value.$field = $value;
      set ($accessor, $cell, value);
    }
  }
}
macro_rules! set_with {
  ($accessor: expr, $cell: expr, | $varying: ident | $actions: expr) => {
    {
      let mut $varying = query ($accessor, $cell);
      $actions;
      set ($accessor, $cell, $varying);
    }
  }
}
macro_rules! exists {
  ($accessor: expr, $cell: expr) => {
    $accessor.query ($cell, &GetVarying).is_some()
  }
}

fn audit <A: EventAccessor <Steward = Steward >> (accessor: &A) {
  audit_node (accessor, &accessor.globals().root);
}
fn audit_node <A: EventAccessor <Steward = Steward >> (accessor: &A, node: &NodeHandle) {
  let varying = get!(accessor, &node.varying);
  for dimension in 0..2 {
    for direction in 0..2 {
      for boundary in varying.boundaries [dimension] [direction].iter() {
        assert!(&boundary.nodes[(direction+1)&1] == node);
        audit_boundary (accessor, boundary);
      }
    }
  }
  for child in varying.children.iter() {
    audit_node (accessor, child);
  }
}
fn audit_boundary <A: EventAccessor <Steward = Steward >> (accessor: &A, boundary: &BoundaryHandle) {
  get!(accessor, &boundary.varying);
  for direction in 0..2 {
    assert!(get!(accessor, &boundary.nodes [direction].varying).boundaries.iter().any(|whatever| whatever[(direction+1)&1].iter().any(| other_boundary| other_boundary == boundary)));
  }
}

fn split <A: EventAccessor <Steward = Steward>> (accessor: &A, node: &NodeHandle) {
  let mut varying = get!(accessor, &node.varying);
  //printlnerr!("{:?}", (node.width, node.center, varying.children.len()));
  //if !varying.children.is_empty() {
    //printlnerr!("{:?}", (node.width, node.center, varying.children.len()));
  //}
  assert!(varying.children.is_empty());
  let mut velocities = [[[0;2];2];2];
  let mut old_boundaries = [[[None,None],[None,None]],[[None,None],[None,None]]];
  let mut middle_velocities = [[0;2];2];
  for dimension in 0..2 {
    for direction in 0..2 {
      //let direction_signum = (direction*2)-1;
      let other_direction = (direction + 1) & 1;

      match varying.boundaries [dimension] [direction].len() {
        1 => {
          loop {
            {
              let boundary = &varying.boundaries [dimension] [direction] [0];
              let neighbor = &boundary.nodes [direction];
              if neighbor.width <= node.width {
                break;
              }
              split (accessor, &neighbor);
            }
            varying = get!(accessor, &node.varying);
          }
          let boundary = &varying.boundaries [dimension] [direction] [0];
          assert!(&boundary.nodes[other_direction] == node);
          velocities [dimension] [direction] = [
            get!(accessor, &boundary.varying).transfer_velocity,
            get!(accessor, &boundary.varying).transfer_velocity
          ];
          old_boundaries [dimension] [direction] = [
            Some(boundary.clone()),
            Some(boundary.clone()),
          ];
        },
        2 => {
          let boundaries = &varying.boundaries [dimension] [direction];
          assert!(&boundaries[0].nodes[other_direction] == node);
          assert!(&boundaries[1].nodes[other_direction] == node);
          velocities [dimension] [direction] = [
            get!(accessor, &boundaries [0].varying).transfer_velocity,
            get!(accessor, &boundaries [1].varying).transfer_velocity,
          ];
          old_boundaries [dimension] [direction] = [
            Some(boundaries [0].clone()),
            Some(boundaries [1].clone()),
          ];
        },
        0 => (),
        _ => unreachable!(),
      };
    }
    middle_velocities [dimension] = [
      (velocities [dimension] [0] [0] + velocities [dimension] [1] [0]) / 2,
      (velocities [dimension] [0] [1] + velocities [dimension] [1] [1]) / 2,
    ];
  }

  // TODO: more accurate computation of ideal middle velocities and ink amounts,
  // and conserve ink correctly
  let mut new_children = [[[None,None],[None,None]],[[None,None],[None,None]]];
  for x in 0..2 {
    let x_signum = (x as Distance*2)-1;
    for y in 0..2 {
      let y_signum = (y as Distance*2)-1;
      let center = [
        node.center[0] + (node.width >> 2)*x_signum,
        node.center[1] + (node.width >> 2)*y_signum,
      ];
      let new_child = accessor.new_handle (NodeData {
        width: node.width >> 1,
        center: center,
        parent: Some (node.clone()),
        varying: DataTimelineCell::new (SimpleTimeline::new ()),
      });
      set (accessor, &new_child.varying, NodeVarying {
        last_change: *accessor.now(),
        ink_at_last_change: varying.ink_at_last_change >> 2,
        children: Vec::new(),
        boundaries: [[Vec::new(), Vec::new()], [Vec::new(), Vec::new()]],
        accumulation_rate: 0,
        slope: [0; 2],
      });
      varying.children.push (new_child.clone());
      new_children [0][x][y] = Some(new_child.clone());
      new_children [1][y][x] = Some(new_child.clone());
    }
  }
  for dimension in 0..2 {
    for direction in 0..2 {
      let other_direction = (direction + 1) & 1;
      for which in 0..2 {
        if let Some(boundary) = old_boundaries [dimension] [direction] [which].as_ref() {
          let neighbor = &boundary.nodes [direction];
          assert!(neighbor.width <= node.width);
          set_with!(accessor, &neighbor.varying, | neighbor_varying | {
            for b in neighbor_varying.boundaries [dimension] [other_direction].iter() {
              assert!(&b.nodes[other_direction] == node);
            }
            neighbor_varying.boundaries [dimension] [other_direction].clear();
          });
        }
      }
    }
  }
  let mut new_boundaries = Vec::new();
  for dimension in 0..2 {
    let other_dimension = (dimension + 1) & 1;
    for direction in 0..2 {
      let other_direction = (direction + 1) & 1;
      let direction_signum = (direction as Distance*2)-1;
      for which in 0..2 {
        let which_signum = (which as Distance*2)-1;
        if let Some(boundary) = old_boundaries [dimension] [direction] [which].as_ref() {
          let child = new_children [dimension] [direction] [which].as_ref().unwrap();
          let neighbor = &boundary.nodes [direction];
          let mut center = node.center;
          center [dimension] += (node.width >> 2)*direction_signum;
          center [other_dimension] += (node.width >> 4)*which_signum;
          let new_boundary = accessor.new_handle (BoundaryData {
            length: node.width >> 1,
            center: center,
            nodes: if direction == 0 { [neighbor.clone(), child.clone()] } else { [child.clone(), neighbor.clone()] },
            varying: DataTimelineCell::new (SimpleTimeline::new ()),
          });
          set (accessor, &new_boundary.varying, BoundaryVarying {
            transfer_velocity: velocities [dimension] [direction] [which],
            next_change: None,
          });
          set_with!(accessor, &child.varying, | child_varying | {
            child_varying.boundaries [dimension] [direction].push(new_boundary.clone());
          });
          set_with!(accessor, &neighbor.varying, | neighbor_varying | {
            neighbor_varying.boundaries [dimension] [other_direction].push(new_boundary.clone());
          });
          new_boundaries.push (new_boundary);
        }
      }
    }
  }
  for dimension in 0..2 {
    let other_dimension = (dimension + 1) & 1;
    for which in 0..2 {
      let which_signum = (which as Distance*2)-1;
      let child0 = new_children [dimension] [0] [which].as_ref().unwrap();
      let child1 = new_children [dimension] [1] [which].as_ref().unwrap();
      let mut center = node.center;
      center [other_dimension] += (node.width >> 4)*which_signum;
      let new_boundary = accessor.new_handle (BoundaryData {
        length: node.width >> 1,
        center: center,
        nodes: [child0.clone(), child1.clone()],
        varying: DataTimelineCell::new (SimpleTimeline::new ()),
      });
      set (accessor, &new_boundary.varying, BoundaryVarying {
        transfer_velocity: middle_velocities [dimension] [which],
        next_change: None,
      });
      set_with!(accessor, &child0.varying, | child0_varying | {
        child0_varying.boundaries [dimension] [1].push(new_boundary.clone());
      });
      set_with!(accessor, &child1.varying, | child1_varying | {
        child1_varying.boundaries [dimension] [0].push(new_boundary.clone());
      });
      new_boundaries.push (new_boundary);
    }
  }
  for dimension in 0..2 {
    for direction in 0..2 {
      for which in 0..2 {
        if let Some(boundary) = old_boundaries [dimension] [direction] [which].as_ref() {
          if !just_destroyed (accessor, & boundary.varying) {
            let boundary_varying = query (accessor, &boundary.varying);
            destroy (accessor, &boundary.varying);
          }
        }
      }
    }
  }

  varying.boundaries = [[Vec::new(), Vec::new()], [Vec::new(), Vec::new()]];

  set (accessor, &node.varying, varying);

  for boundary in new_boundaries {
    update_transfer_change_prediction (accessor, &boundary);
  }

}

fn merge <A: EventAccessor <Steward = Steward >> (accessor: &A, node: &NodeHandle) {
  let mut varying = get!(accessor, &node.varying);
  assert!(!varying.children.is_empty());

  varying.last_change =*accessor.now();
  varying.ink_at_last_change = 0;
  let mut prior_boundaries = Vec::new();
  let mut discovered_prior_boundaries = HashSet::new();
  let mut prior_children = HashSet::new();
  let mut neighbors = Vec::new();
  let mut discovered_neighbors = HashSet::new();
  for child in varying.children.iter() {
    update_node(accessor, child);
    let child_varying = get!(accessor, &child.varying);
    assert!(child_varying.children.is_empty());
    assert!(child_varying.last_change == *accessor.now());
    varying.ink_at_last_change += child_varying.ink_at_last_change;
    for (dimension, whatever) in child_varying.boundaries.iter().enumerate() {for (direction, something) in whatever.iter().enumerate() {for other_boundary in something.iter() {
      if discovered_prior_boundaries.insert (other_boundary.clone()) {
        prior_boundaries.push ((dimension, direction, other_boundary.clone()));
      }
    }}}
    prior_children.insert (child.clone()) ;

    destroy (accessor, &child.varying);
  }

  let mut new_boundaries = Vec::new();
  for (dimension, direction, boundary) in prior_boundaries {
    let boundary_varying = get!(accessor, &boundary.varying);
    let neighbor = if !prior_children.contains (&boundary.nodes [1]) {
      Some (boundary.nodes [1].clone())
    } else if !prior_children.contains (&boundary.nodes [0]) {
      Some (boundary.nodes [0].clone())
    } else {None};
    if let Some(neighbor) = neighbor {
      if discovered_neighbors.insert (neighbor.clone()) {
        neighbors.push (neighbor.clone());
        let other_direction = (direction+1)&1;
        set_with!(accessor, &neighbor.varying, | neighbor_varying | {
          for b in neighbor_varying.boundaries [dimension] [other_direction].iter() {
            assert!(prior_children.contains(&b.nodes[other_direction]));
          }
          neighbor_varying.boundaries [dimension] [other_direction].clear();
        });
        let mut center = boundary.center;
        if neighbor.width == node.width {
          center = [
            (node.center[0] + neighbor.center [0]) >> 1,
            (node.center[1] + neighbor.center [1]) >> 1,
          ];
        }
        let nodes = if direction == 1 {[node.clone(), neighbor.clone()]}else{[neighbor.clone(), node.clone()]};
        let new_boundary = accessor.new_handle (BoundaryData {
          length: neighbor.width,
          center: center,
          nodes: nodes.clone(),
          varying: DataTimelineCell::new (SimpleTimeline::new ()),
        });
        set (accessor, &new_boundary.varying, BoundaryVarying {
          transfer_velocity: boundary_varying.transfer_velocity,
          next_change: None,
        });
        set_with!(accessor, &neighbor.varying, | neighbor_varying | {
          neighbor_varying.boundaries [dimension] [other_direction].push(new_boundary.clone());
        });
        varying.boundaries [dimension] [direction].push(new_boundary.clone());
        new_boundaries.push (new_boundary);
      }
    }
    destroy (accessor, &boundary.varying);
  }

  varying.children.clear();
  set (accessor, &node.varying, varying);
  update_inferred_node_properties (accessor, node);

  for boundary in new_boundaries {
    update_transfer_change_prediction (accessor, &boundary);
  }

  if let Some(parent) = node.parent.as_ref() {
    //audit(accessor);
    maybe_merge (accessor, parent);
    //audit(accessor);
  }

  for neighbor in neighbors {
    maybe_merge (accessor, &neighbor);
  }
}
<|endoftext|>


<commit_before><commit_msg>docs: Add basic example (#216)<commit_after>fn main() {
    const CARGO_MANIFEST: &str = r#"
[package]
name = "cargo"
version = "0.57.0"
edition = "2018"
authors = ["Yehuda Katz <wycats@gmail.com>",
           "Carl Lerche <me@carllerche.com>",
           "Alex Crichton <alex@alexcrichton.com>"]
license = "MIT OR Apache-2.0"
homepage = "https://crates.io"
repository = "https://github.com/rust-lang/cargo"
documentation = "https://docs.rs/cargo"
readme = "README.md"
description = """
Cargo, a package manager for Rust.
"""

[lib]
name = "cargo"
path = "src/cargo/lib.rs"

[dependencies]
atty = "0.2"
bytesize = "1.0"
cargo-platform = { path = "crates/cargo-platform", version = "0.1.2" }
cargo-util = { path = "crates/cargo-util", version = "0.1.1" }
crates-io = { path = "crates/crates-io", version = "0.33.0" }
crossbeam-utils = "0.8"
curl = { version = "0.4.38", features = ["http2"] }
curl-sys = "0.4.45"
env_logger = "0.9.0"
pretty_env_logger = { version = "0.4", optional = true }
anyhow = "1.0"
filetime = "0.2.9"
flate2 = { version = "1.0.3", default-features = false, features = ["zlib"] }
git2 = "0.13.16"
git2-curl = "0.14.1"
glob = "0.3.0"
hex = "0.4"
home = "0.5"
humantime = "2.0.0"
ignore = "0.4.7"
lazy_static = "1.2.0"
jobserver = "0.1.24"
lazycell = "1.2.0"
libc = "0.2"
log = "0.4.6"
libgit2-sys = "0.12.18"
memchr = "2.1.3"
num_cpus = "1.0"
opener = "0.5"
percent-encoding = "2.0"
rustfix = "0.6.0"
semver = { version = "1.0.3", features = ["serde"] }
serde = { version = "1.0.123", features = ["derive"] }
serde_ignored = "0.1.0"
serde_json = { version = "1.0.30", features = ["raw_value"] }
shell-escape = "0.1.4"
strip-ansi-escapes = "0.1.0"
tar = { version = "0.4.35", default-features = false }
tempfile = "3.0"
termcolor = "1.1"
toml = "0.5.7"
unicode-xid = "0.2.0"
url = "2.2.2"
walkdir = "2.2"
clap = "2.31.2"
unicode-width = "0.1.5"
openssl = { version = '0.10.11', optional = true }
im-rc = "15.0.0"
itertools = "0.10.0"

# A noop dependency that changes in the Rust repository, it's a bit of a hack.
# See the `src/tools/rustc-workspace-hack/README.md` file in `rust-lang/rust`
# for more information.
rustc-workspace-hack = "1.0.0"

[target.'cfg(windows)'.dependencies]
fwdansi = "1.1.0"

[target.'cfg(windows)'.dependencies.winapi]
version = "0.3"
features = [
  "basetsd",
  "handleapi",
  "jobapi",
  "jobapi2",
  "memoryapi",
  "minwindef",
  "ntdef",
  "ntstatus",
  "processenv",
  "processthreadsapi",
  "psapi",
  "synchapi",
  "winerror",
  "winbase",
  "wincon",
  "winnt",
]

[dev-dependencies]
cargo-test-macro = { path = "crates/cargo-test-macro" }
cargo-test-support = { path = "crates/cargo-test-support" }

[build-dependencies]
flate2 = { version = "1.0.3", default-features = false, features = ["zlib"] }
tar = { version = "0.4.26", default-features = false }

[[bin]]
name = "cargo"
test = false
doc = false

[features]
deny-warnings = []
vendored-openssl = ["openssl/vendored"]
pretty-env-logger = ["pretty_env_logger"]
"#;
    let manifest = CARGO_MANIFEST.parse::<toml_edit::Document>().unwrap();
    println!("{:#?}", manifest);
}
<|endoftext|>


<commit_before><commit_msg>Add an example displaying the current number of CPUs<commit_after>extern crate num_cpus;

fn main() {
    println!("Logical CPUs: {}", num_cpus::get());
    println!("Physical CPUs: {}", num_cpus::get_physical());
}
<|endoftext|>


<commit_before><commit_msg>Added more examples<commit_after><|endoftext|>


<commit_before><commit_msg>impl addr message<commit_after>use std;
extern crate time;
use super::Address;
use ::serialize::{self, Serializable};

#[derive(Debug,Default)]
pub struct AddrMessage {
   pub addrs : Vec<Address>,
}
impl std::fmt::Display for AddrMessage {
   fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
      write!(f, "Addr(len={})", self.addrs.len())
   }
}

impl Serializable for AddrMessage {
   fn get_serialize_size(&self) -> usize {
      self.addrs.get_serialize_size()
   }
   fn serialize(&self, io:&mut std::io::Write) -> serialize::Result {
      self.addrs.serialize(io)
   }
   fn unserialize(&mut self, io:&mut std::io::Read) -> serialize::Result {
      self.addrs.unserialize(io)
   }
}

<|endoftext|>


<commit_before><commit_msg>Fixing daemon<commit_after><|endoftext|>


<commit_before><commit_msg>add test for #14229<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 Foo: Sized {
    fn foo(self) {}
}

trait Bar: Sized {
    fn bar(self) {}
}

struct S;

impl<'l> Foo for &'l S {}

impl<T: Foo> Bar for T {}

fn main() {
    let s = S;
    s.foo();
    (&s).bar();
    s.bar();
}
<|endoftext|>


<commit_before><commit_msg>Add test for #24533<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 std::slice::Iter;
use std::io::{Error, ErrorKind, Result};
use std::vec::*;

fn foo(it: &mut Iter<u8>) -> Result<u8> {
    Ok(*it.next().unwrap())
}

fn bar() -> Result<u8> {
    let data: Vec<u8> = Vec::new();

    if true {
        return Err(Error::new(ErrorKind::NotFound, "msg"));
    }

    let mut it = data.iter();
    foo(&mut it)
}

fn main() {
    bar();
}
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #27140 - dotdash:test-26468, r=luqmana<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.

#![allow(dead_code)]

enum FooMode {
    Check = 0x1001,
}

enum BarMode {
    Check = 0x2001,
}

enum Mode {
    Foo(FooMode),
    Bar(BarMode),
}

#[inline(never)]
fn broken(mode: &Mode) -> u32 {
    for _ in 0..1 {
        if let Mode::Foo(FooMode::Check) = *mode { return 17 }
        if let Mode::Bar(BarMode::Check) = *mode { return 19 }
    }
    return 42;
}

fn main() {
    let mode = Mode::Bar(BarMode::Check);
    assert_eq!(broken(&mode), 19);
}
<|endoftext|>


<commit_before><commit_msg>Added version to handler/mod.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Unhide Archive::from_bytes from docs<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed mistake in previous album<commit_after><|endoftext|>