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

#![allow(private_no_mangle_fns)]

use prelude::v1::*;

use any::Any;
use sys_common::libunwind as uw;

struct Exception {
    uwe: uw::_Unwind_Exception,
    cause: Option<Box<Any + Send + 'static>>,
}

pub unsafe fn panic(data: Box<Any + Send + 'static>) -> ! {
    let exception: Box<_> = box Exception {
        uwe: uw::_Unwind_Exception {
            exception_class: rust_exception_class(),
            exception_cleanup: exception_cleanup,
            private: [0; uw::unwinder_private_data_size],
        },
        cause: Some(data),
    };
    let exception_param = Box::into_raw(exception) as *mut uw::_Unwind_Exception;
    let error = uw::_Unwind_RaiseException(exception_param);
    rtabort!("Could not unwind stack, error = {}", error as isize);

    extern fn exception_cleanup(_unwind_code: uw::_Unwind_Reason_Code,
                                exception: *mut uw::_Unwind_Exception) {
        unsafe {
            let _: Box<Exception> = Box::from_raw(exception as *mut Exception);
        }
    }
}

pub fn payload() -> *mut u8 {
    0 as *mut u8
}

pub unsafe fn cleanup(ptr: *mut u8) -> Box<Any + Send + 'static> {
    let my_ep = ptr as *mut Exception;
    let cause = (*my_ep).cause.take();
    uw::_Unwind_DeleteException(ptr as *mut _);
    cause.unwrap()
}

// Rust's exception class identifier.  This is used by personality routines to
// determine whether the exception was thrown by their own runtime.
fn rust_exception_class() -> uw::_Unwind_Exception_Class {
    // M O Z \0  R U S T -- vendor, language
    0x4d4f5a_00_52555354
}

// We could implement our personality routine in pure Rust, however exception
// info decoding is tedious.  More importantly, personality routines have to
// handle various platform quirks, which are not fun to maintain.  For this
// reason, we attempt to reuse personality routine of the C language:
// __gcc_personality_v0.
//
// Since C does not support exception catching, __gcc_personality_v0 simply
// always returns _URC_CONTINUE_UNWIND in search phase, and always returns
// _URC_INSTALL_CONTEXT (i.e. "invoke cleanup code") in cleanup phase.
//
// This is pretty close to Rust's exception handling approach, except that Rust
// does have a single "catch-all" handler at the bottom of each thread's stack.
// So we have two versions of the personality routine:
// - rust_eh_personality, used by all cleanup landing pads, which never catches,
//   so the behavior of __gcc_personality_v0 is perfectly adequate there, and
// - rust_eh_personality_catch, used only by rust_try(), which always catches.
//
// See also: rustc_trans::trans::intrinsic::trans_gnu_try

#[cfg(all(not(target_arch = "arm"),
          not(all(windows, target_arch = "x86_64")),
          not(test)))]
pub mod eabi {
    use sys_common::libunwind as uw;
    use libc::c_int;

    extern {
        fn __gcc_personality_v0(version: c_int,
                                actions: uw::_Unwind_Action,
                                exception_class: uw::_Unwind_Exception_Class,
                                ue_header: *mut uw::_Unwind_Exception,
                                context: *mut uw::_Unwind_Context)
            -> uw::_Unwind_Reason_Code;
    }

    #[lang = "eh_personality"]
    #[no_mangle]
    extern fn rust_eh_personality(
        version: c_int,
        actions: uw::_Unwind_Action,
        exception_class: uw::_Unwind_Exception_Class,
        ue_header: *mut uw::_Unwind_Exception,
        context: *mut uw::_Unwind_Context
    ) -> uw::_Unwind_Reason_Code
    {
        unsafe {
            __gcc_personality_v0(version, actions, exception_class, ue_header,
                                 context)
        }
    }

    #[lang = "eh_personality_catch"]
    #[no_mangle]
    pub extern fn rust_eh_personality_catch(
        version: c_int,
        actions: uw::_Unwind_Action,
        exception_class: uw::_Unwind_Exception_Class,
        ue_header: *mut uw::_Unwind_Exception,
        context: *mut uw::_Unwind_Context
    ) -> uw::_Unwind_Reason_Code
    {

        if (actions as c_int & uw::_UA_SEARCH_PHASE as c_int) != 0 { // search phase
            uw::_URC_HANDLER_FOUND // catch!
        }
        else { // cleanup phase
            unsafe {
                __gcc_personality_v0(version, actions, exception_class, ue_header,
                                     context)
            }
        }
    }
}

// iOS on armv7 is using SjLj exceptions and therefore requires to use
// a specialized personality routine: __gcc_personality_sj0

#[cfg(all(target_os = "ios", target_arch = "arm", not(test)))]
pub mod eabi {
    use sys_common::libunwind as uw;
    use libc::c_int;

    extern {
        fn __gcc_personality_sj0(version: c_int,
                                actions: uw::_Unwind_Action,
                                exception_class: uw::_Unwind_Exception_Class,
                                ue_header: *mut uw::_Unwind_Exception,
                                context: *mut uw::_Unwind_Context)
            -> uw::_Unwind_Reason_Code;
    }

    #[lang = "eh_personality"]
    #[no_mangle]
    pub extern fn rust_eh_personality(
        version: c_int,
        actions: uw::_Unwind_Action,
        exception_class: uw::_Unwind_Exception_Class,
        ue_header: *mut uw::_Unwind_Exception,
        context: *mut uw::_Unwind_Context
    ) -> uw::_Unwind_Reason_Code
    {
        unsafe {
            __gcc_personality_sj0(version, actions, exception_class, ue_header,
                                  context)
        }
    }

    #[lang = "eh_personality_catch"]
    #[no_mangle]
    pub extern fn rust_eh_personality_catch(
        version: c_int,
        actions: uw::_Unwind_Action,
        exception_class: uw::_Unwind_Exception_Class,
        ue_header: *mut uw::_Unwind_Exception,
        context: *mut uw::_Unwind_Context
    ) -> uw::_Unwind_Reason_Code
    {
        if (actions as c_int & uw::_UA_SEARCH_PHASE as c_int) != 0 { // search phase
            uw::_URC_HANDLER_FOUND // catch!
        }
        else { // cleanup phase
            unsafe {
                __gcc_personality_sj0(version, actions, exception_class, ue_header,
                                      context)
            }
        }
    }
}

// ARM EHABI uses a slightly different personality routine signature,
// but otherwise works the same.
#[cfg(all(target_arch = "arm", not(target_os = "ios"), not(test)))]
pub mod eabi {
    use sys_common::libunwind as uw;
    use libc::c_int;

    extern {
        fn __gcc_personality_v0(state: uw::_Unwind_State,
                                ue_header: *mut uw::_Unwind_Exception,
                                context: *mut uw::_Unwind_Context)
            -> uw::_Unwind_Reason_Code;
    }

    #[lang = "eh_personality"]
    #[no_mangle]
    extern fn rust_eh_personality(
        state: uw::_Unwind_State,
        ue_header: *mut uw::_Unwind_Exception,
        context: *mut uw::_Unwind_Context
    ) -> uw::_Unwind_Reason_Code
    {
        unsafe {
            __gcc_personality_v0(state, ue_header, context)
        }
    }

    #[lang = "eh_personality_catch"]
    #[no_mangle]
    pub extern fn rust_eh_personality_catch(
        state: uw::_Unwind_State,
        ue_header: *mut uw::_Unwind_Exception,
        context: *mut uw::_Unwind_Context
    ) -> uw::_Unwind_Reason_Code
    {
        if (state as c_int & uw::_US_ACTION_MASK as c_int)
                           == uw::_US_VIRTUAL_UNWIND_FRAME as c_int { // search phase
            uw::_URC_HANDLER_FOUND // catch!
        }
        else { // cleanup phase
            unsafe {
                __gcc_personality_v0(state, ue_header, context)
            }
        }
    }
}

// See docs in the `unwind` module.
#[cfg(all(target_os="windows", target_arch = "x86", target_env="gnu", not(test)))]
#[lang = "eh_unwind_resume"]
#[unwind]
unsafe extern fn rust_eh_unwind_resume(panic_ctx: *mut u8) -> ! {
    uw::_Unwind_Resume(panic_ctx as *mut uw::_Unwind_Exception);
}

#[cfg(all(target_os="windows", target_arch = "x86", target_env="gnu"))]
pub mod eh_frame_registry {
    // The implementation of stack unwinding is (for now) deferred to libgcc_eh, however Rust
    // crates use these Rust-specific entry points to avoid potential clashes with GCC runtime.
    // See also: rtbegin.rs, `unwind` module.

    #[link(name = "gcc_eh")]
    #[cfg(not(cargobuild))]
    extern {}

    extern {
        fn __register_frame_info(eh_frame_begin: *const u8, object: *mut u8);
        fn __deregister_frame_info(eh_frame_begin: *const u8, object: *mut u8);
    }
    #[cfg(not(test))]
    #[no_mangle]
    #[unstable(feature = "libstd_sys_internals", issue = "0")]
    pub unsafe extern fn rust_eh_register_frames(eh_frame_begin: *const u8,
                                                 object: *mut u8) {
        __register_frame_info(eh_frame_begin, object);
    }
    #[cfg(not(test))]
    #[no_mangle]
    #[unstable(feature = "libstd_sys_internals", issue = "0")]
    pub  unsafe extern fn rust_eh_unregister_frames(eh_frame_begin: *const u8,
                                                   object: *mut u8) {
        __deregister_frame_info(eh_frame_begin, object);
    }
}
<commit_msg>Fix backtraces on ARM EHABI.<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(private_no_mangle_fns)]

use prelude::v1::*;

use any::Any;
use sys_common::libunwind as uw;

struct Exception {
    uwe: uw::_Unwind_Exception,
    cause: Option<Box<Any + Send + 'static>>,
}

pub unsafe fn panic(data: Box<Any + Send + 'static>) -> ! {
    let exception: Box<_> = box Exception {
        uwe: uw::_Unwind_Exception {
            exception_class: rust_exception_class(),
            exception_cleanup: exception_cleanup,
            private: [0; uw::unwinder_private_data_size],
        },
        cause: Some(data),
    };
    let exception_param = Box::into_raw(exception) as *mut uw::_Unwind_Exception;
    let error = uw::_Unwind_RaiseException(exception_param);
    rtabort!("Could not unwind stack, error = {}", error as isize);

    extern fn exception_cleanup(_unwind_code: uw::_Unwind_Reason_Code,
                                exception: *mut uw::_Unwind_Exception) {
        unsafe {
            let _: Box<Exception> = Box::from_raw(exception as *mut Exception);
        }
    }
}

pub fn payload() -> *mut u8 {
    0 as *mut u8
}

pub unsafe fn cleanup(ptr: *mut u8) -> Box<Any + Send + 'static> {
    let my_ep = ptr as *mut Exception;
    let cause = (*my_ep).cause.take();
    uw::_Unwind_DeleteException(ptr as *mut _);
    cause.unwrap()
}

// Rust's exception class identifier.  This is used by personality routines to
// determine whether the exception was thrown by their own runtime.
fn rust_exception_class() -> uw::_Unwind_Exception_Class {
    // M O Z \0  R U S T -- vendor, language
    0x4d4f5a_00_52555354
}

// We could implement our personality routine in pure Rust, however exception
// info decoding is tedious.  More importantly, personality routines have to
// handle various platform quirks, which are not fun to maintain.  For this
// reason, we attempt to reuse personality routine of the C language:
// __gcc_personality_v0.
//
// Since C does not support exception catching, __gcc_personality_v0 simply
// always returns _URC_CONTINUE_UNWIND in search phase, and always returns
// _URC_INSTALL_CONTEXT (i.e. "invoke cleanup code") in cleanup phase.
//
// This is pretty close to Rust's exception handling approach, except that Rust
// does have a single "catch-all" handler at the bottom of each thread's stack.
// So we have two versions of the personality routine:
// - rust_eh_personality, used by all cleanup landing pads, which never catches,
//   so the behavior of __gcc_personality_v0 is perfectly adequate there, and
// - rust_eh_personality_catch, used only by rust_try(), which always catches.
//
// See also: rustc_trans::trans::intrinsic::trans_gnu_try

#[cfg(all(not(target_arch = "arm"),
          not(all(windows, target_arch = "x86_64")),
          not(test)))]
pub mod eabi {
    use sys_common::libunwind as uw;
    use libc::c_int;

    extern {
        fn __gcc_personality_v0(version: c_int,
                                actions: uw::_Unwind_Action,
                                exception_class: uw::_Unwind_Exception_Class,
                                ue_header: *mut uw::_Unwind_Exception,
                                context: *mut uw::_Unwind_Context)
            -> uw::_Unwind_Reason_Code;
    }

    #[lang = "eh_personality"]
    #[no_mangle]
    extern fn rust_eh_personality(
        version: c_int,
        actions: uw::_Unwind_Action,
        exception_class: uw::_Unwind_Exception_Class,
        ue_header: *mut uw::_Unwind_Exception,
        context: *mut uw::_Unwind_Context
    ) -> uw::_Unwind_Reason_Code
    {
        unsafe {
            __gcc_personality_v0(version, actions, exception_class, ue_header,
                                 context)
        }
    }

    #[lang = "eh_personality_catch"]
    #[no_mangle]
    pub extern fn rust_eh_personality_catch(
        version: c_int,
        actions: uw::_Unwind_Action,
        exception_class: uw::_Unwind_Exception_Class,
        ue_header: *mut uw::_Unwind_Exception,
        context: *mut uw::_Unwind_Context
    ) -> uw::_Unwind_Reason_Code
    {

        if (actions as c_int & uw::_UA_SEARCH_PHASE as c_int) != 0 { // search phase
            uw::_URC_HANDLER_FOUND // catch!
        }
        else { // cleanup phase
            unsafe {
                __gcc_personality_v0(version, actions, exception_class, ue_header,
                                     context)
            }
        }
    }
}

// iOS on armv7 is using SjLj exceptions and therefore requires to use
// a specialized personality routine: __gcc_personality_sj0

#[cfg(all(target_os = "ios", target_arch = "arm", not(test)))]
pub mod eabi {
    use sys_common::libunwind as uw;
    use libc::c_int;

    extern {
        fn __gcc_personality_sj0(version: c_int,
                                actions: uw::_Unwind_Action,
                                exception_class: uw::_Unwind_Exception_Class,
                                ue_header: *mut uw::_Unwind_Exception,
                                context: *mut uw::_Unwind_Context)
            -> uw::_Unwind_Reason_Code;
    }

    #[lang = "eh_personality"]
    #[no_mangle]
    pub extern fn rust_eh_personality(
        version: c_int,
        actions: uw::_Unwind_Action,
        exception_class: uw::_Unwind_Exception_Class,
        ue_header: *mut uw::_Unwind_Exception,
        context: *mut uw::_Unwind_Context
    ) -> uw::_Unwind_Reason_Code
    {
        unsafe {
            __gcc_personality_sj0(version, actions, exception_class, ue_header,
                                  context)
        }
    }

    #[lang = "eh_personality_catch"]
    #[no_mangle]
    pub extern fn rust_eh_personality_catch(
        version: c_int,
        actions: uw::_Unwind_Action,
        exception_class: uw::_Unwind_Exception_Class,
        ue_header: *mut uw::_Unwind_Exception,
        context: *mut uw::_Unwind_Context
    ) -> uw::_Unwind_Reason_Code
    {
        if (actions as c_int & uw::_UA_SEARCH_PHASE as c_int) != 0 { // search phase
            uw::_URC_HANDLER_FOUND // catch!
        }
        else { // cleanup phase
            unsafe {
                __gcc_personality_sj0(version, actions, exception_class, ue_header,
                                      context)
            }
        }
    }
}

// ARM EHABI uses a slightly different personality routine signature,
// but otherwise works the same.
#[cfg(all(target_arch = "arm", not(target_os = "ios"), not(test)))]
pub mod eabi {
    use sys_common::libunwind as uw;
    use libc::c_int;

    extern {
        fn __gcc_personality_v0(state: uw::_Unwind_State,
                                ue_header: *mut uw::_Unwind_Exception,
                                context: *mut uw::_Unwind_Context)
            -> uw::_Unwind_Reason_Code;
    }

    #[lang = "eh_personality"]
    #[no_mangle]
    extern fn rust_eh_personality(
        state: uw::_Unwind_State,
        ue_header: *mut uw::_Unwind_Exception,
        context: *mut uw::_Unwind_Context
    ) -> uw::_Unwind_Reason_Code
    {
        unsafe {
            __gcc_personality_v0(state, ue_header, context)
        }
    }

    #[lang = "eh_personality_catch"]
    #[no_mangle]
    pub extern fn rust_eh_personality_catch(
        state: uw::_Unwind_State,
        ue_header: *mut uw::_Unwind_Exception,
        context: *mut uw::_Unwind_Context
    ) -> uw::_Unwind_Reason_Code
    {
        // Backtraces on ARM will call the personality routine with
        // state == _US_VIRTUAL_UNWIND_FRAME | _US_FORCE_UNWIND. In those cases
        // we want to continue unwinding the stack, otherwise all our backtraces
        // would end at __rust_try.
        if (state as c_int & uw::_US_ACTION_MASK as c_int)
                           == uw::_US_VIRTUAL_UNWIND_FRAME as c_int
               && (state as c_int & uw::_US_FORCE_UNWIND as c_int) == 0 { // search phase
            uw::_URC_HANDLER_FOUND // catch!
        }
        else { // cleanup phase
            unsafe {
                __gcc_personality_v0(state, ue_header, context)
            }
        }
    }
}

// See docs in the `unwind` module.
#[cfg(all(target_os="windows", target_arch = "x86", target_env="gnu", not(test)))]
#[lang = "eh_unwind_resume"]
#[unwind]
unsafe extern fn rust_eh_unwind_resume(panic_ctx: *mut u8) -> ! {
    uw::_Unwind_Resume(panic_ctx as *mut uw::_Unwind_Exception);
}

#[cfg(all(target_os="windows", target_arch = "x86", target_env="gnu"))]
pub mod eh_frame_registry {
    // The implementation of stack unwinding is (for now) deferred to libgcc_eh, however Rust
    // crates use these Rust-specific entry points to avoid potential clashes with GCC runtime.
    // See also: rtbegin.rs, `unwind` module.

    #[link(name = "gcc_eh")]
    #[cfg(not(cargobuild))]
    extern {}

    extern {
        fn __register_frame_info(eh_frame_begin: *const u8, object: *mut u8);
        fn __deregister_frame_info(eh_frame_begin: *const u8, object: *mut u8);
    }
    #[cfg(not(test))]
    #[no_mangle]
    #[unstable(feature = "libstd_sys_internals", issue = "0")]
    pub unsafe extern fn rust_eh_register_frames(eh_frame_begin: *const u8,
                                                 object: *mut u8) {
        __register_frame_info(eh_frame_begin, object);
    }
    #[cfg(not(test))]
    #[no_mangle]
    #[unstable(feature = "libstd_sys_internals", issue = "0")]
    pub  unsafe extern fn rust_eh_unregister_frames(eh_frame_begin: *const u8,
                                                   object: *mut u8) {
        __deregister_frame_info(eh_frame_begin, object);
    }
}
<|endoftext|>


<commit_before><commit_msg>practice<commit_after>fn main() {
    println_sum(5, 6);
}

fn println_sum(x: i32, y: i32) {
    println!("sum is: {}", x + y);
}
<|endoftext|>


<commit_before><commit_msg>Day 22 part 1<commit_after>// advent22.rs
// disk space (sliding blocks puzzle)

#[macro_use]
extern crate lazy_static;
extern crate regex;

use std::io;
use std::io::BufRead;
use regex::Regex;

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

    let nodes: Vec<_> = stdin.lock()
        .lines()
        .map(|l| l.expect("Failed to read line"))
        .filter_map(|l| node_from_str(&l))
        .collect();

    let viable = find_viable_pairs(&nodes);
    println!("part 1: {} viable pairs", viable.len());
}

#[derive(PartialEq)]
struct Node {
    x: usize,
    y: usize,
    used: usize,
    avail: usize,
}

fn is_viable_pair((n1, n2): (&Node, &Node)) -> bool {
    n1.used <= n2.avail && n1 != n2 && n1.used != 0
}

fn find_viable_pairs(nodes: &[Node]) -> Vec<(&Node, &Node)> {
    let mut viable = vec![];
    for n1 in nodes {
        viable.extend(nodes.iter().map(|n2| (n1, n2)).filter(|&x| is_viable_pair(x)))
    }
    viable
}

fn node_from_str(s: &str) -> Option<Node> {
    lazy_static! {
        static ref RE_NODE: Regex =
            Regex::new(r"^/dev/grid/node-x([\d]+)-y([\d]+)\s+[\d]+T\s+([\d]+)T\s+([\d]+)").unwrap();
    }

    RE_NODE.captures(s).map(|caps| {
        let x = caps[1].parse().unwrap();
        let y = caps[2].parse().unwrap();
        let used = caps[3].parse().unwrap();
        let avail = caps[4].parse().unwrap();
        Node {
            x: x,
            y: y,
            used: used,
            avail: avail,
        }
    })
}

// //////
// Tests
#[test]
fn test_is_viable_pair() {
    let node_0_10 = Node {
        x: 0,
        y: 0,
        used: 0,
        avail: 10,
    };
    let node_10_10 = Node {
        x: 0,
        y: 1,
        used: 10,
        avail: 10,
    };
    let node_11_10 = Node {
        x: 1,
        y: 0,
        used: 11,
        avail: 10,
    };

    // false because first node empty
    assert!(!is_viable_pair((&node_0_10, &node_10_10)));
    assert!(!is_viable_pair((&node_0_10, &node_11_10)));
    // false because nodes identical
    assert!(!is_viable_pair((&node_10_10, &node_10_10)));
    // false because second node doesn't have enough space
    assert!(!is_viable_pair((&node_11_10, &node_10_10)));
    assert!(!is_viable_pair((&node_11_10, &node_0_10)));

    assert!(is_viable_pair((&node_10_10, &node_11_10)));
    assert!(is_viable_pair((&node_10_10, &node_0_10)));
}

#[test]
fn test_find_viable_pairs() {
    const NODE_0_10: Node = Node {
        x: 0,
        y: 0,
        used: 0,
        avail: 10,
    };
    const NODE_10_10: Node = Node {
        x: 0,
        y: 1,
        used: 10,
        avail: 10,
    };
    const NODE_11_10: Node = Node {
        x: 1,
        y: 0,
        used: 11,
        avail: 10,
    };
    let nodes = vec![NODE_0_10, NODE_10_10, NODE_11_10];

    let viable = find_viable_pairs(&nodes);
    assert_eq!(2, viable.len());
}
<|endoftext|>


<commit_before><commit_msg>Add to the capacity for the first encoded message to account for zeros<commit_after><|endoftext|>


<commit_before><commit_msg>Fix unused variable warnings.<commit_after><|endoftext|>


<commit_before><commit_msg>Drop the send method<commit_after><|endoftext|>


<commit_before><commit_msg>(feat) Added boilerplate attributes.<commit_after><|endoftext|>


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

extern crate glutin;
extern crate gfx;
extern crate gfx_device_gl;
extern crate gfx_device_dx11;
extern crate gfx_window_glutin;
//extern crate gfx_window_glfw;
extern crate gfx_window_dxgi;

pub type ColorFormat = gfx::format::Srgb8;
pub type DepthFormat = gfx::format::DepthStencil;

pub struct Init<R: gfx::Resources> {
    pub color: gfx::handle::RenderTargetView<R, ColorFormat>,
    pub depth: gfx::handle::DepthStencilView<R, DepthFormat>,
}

pub enum Backend {
    OpenGL2,
    Direct3D11,
}

pub struct Config {
    backend: Backend,
    size: (u16, u16),
}

impl Config {
    pub fn new(back: Backend) -> Config {
        Config {
            backend: back,
            size: (800, 520),
        }
    }
}

pub trait Application<R: gfx::Resources> {
    fn new<F: gfx::Factory<R>>(F, Init<R>) -> Self;
    fn render<C: gfx::CommandBuffer<R>>(&mut self, &mut gfx::Encoder<R, C>);

    fn launch(title: &str, config: Config) where
        Self: Sized + Application<gfx_device_gl::Resources> + Application<gfx_device_dx11::Resources>
    {
        use gfx::traits::{Device, FactoryExt};
        match config.backend {
            Backend::OpenGL2 => {
                let builder = glutin::WindowBuilder::new()
                    .with_title(title.to_string())
                    .with_dimensions(config.size.0 as u32, config.size.1 as u32);
                let (window, mut device, mut factory, main_color, main_depth) =
                    gfx_window_glutin::init::<ColorFormat, DepthFormat>(builder);
                let mut encoder = factory.create_encoder();
                let mut app = Self::new(factory, Init {
                    color: main_color,
                    depth: main_depth,
                });
                'main: loop {
                    // quit when Esc is pressed.
                    for event in window.poll_events() {
                        match event {
                            glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) |
                            glutin::Event::Closed => break 'main,
                            _ => {},
                        }
                    }
                    // draw a frame
                    encoder.reset();
                    app.render(&mut encoder);
                    device.submit(encoder.as_buffer());
                    window.swap_buffers().unwrap();
                    device.cleanup();
                }
            },
            Backend::Direct3D11 => {
                //TODO
            },
        }
    }
}

<|endoftext|>


<commit_before><commit_msg>forgot lib.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Make project no_std and reexport core<commit_after>#![no_std]

#[doc(hidden)]
pub extern crate core as _core;
<|endoftext|>


<commit_before><commit_msg>Add basic `BezNode` and `BezQuad`.<commit_after>use std::ops::Index;
use std::convert::Into;

#[derive(Debug, Clone, Copy)]
pub enum BezNode {
    Point {
        x: f32,
        y: f32
    },

    Control {
        x: f32,
        y: f32
    }
}

impl BezNode {
    pub fn x(self) -> f32 {
        <BezNode as Into<(f32, f32)>>::into(self).0
    }

    pub fn y(self) -> f32 {
        <BezNode as Into<(f32, f32)>>::into(self).1
    }
}

impl Into<[f32; 2]> for BezNode {
    fn into(self) -> [f32; 2] {
        use self::BezNode::*;

        match self {
            Point{x, y} |
            Control{x, y} => [x, y]
        }
    }
}

impl Into<(f32, f32)> for BezNode {
    fn into(self) -> (f32, f32) {
        use self::BezNode::*;

        match self {
            Point{x, y} |
            Control{x, y} => (x, y)
        }
    }
}

pub struct BezQuad<I: Index<usize, Output = BezNode>> {
    array: I
}

<|endoftext|>


<commit_before><commit_msg>Calculate max size of a record during the Environ initialization<commit_after><|endoftext|>


<commit_before><commit_msg>Add an example to crate docs.<commit_after><|endoftext|>


<commit_before><commit_msg>`IXAudio2Voice::DestroyVoice()`<commit_after><|endoftext|>


<commit_before><commit_msg>Newer rustfmt.<commit_after><|endoftext|>


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


<commit_before><commit_msg>fixed bug with target_word_size deprecation<commit_after><|endoftext|>


<commit_before><commit_msg>add test cases for core matchers and assertion behaviour<commit_after>#[macro_use]
extern crate galvanic_assert;

use galvanic_assert::*;
use galvanic_assert::matchers::*;

mod assert_panic {
    use super::*;

    #[test]
    fn should_assert_a_panic() {
        assert_that!(panic!("panic"), panics);
    }

    #[test]
    fn should_fail_to_assert_a_panic() {
        let panicked = std::panic::catch_unwind(|| {
            assert_that!(1+1, panics);
        });
        assert!(panicked.is_err());
    }
}

mod invariants {
    use super::*;

    #[test]
    fn assertion_should_succeed() {
        assert_that!(1, assertion_always_succeeds());
    }

    #[test]
    fn assertion_should_fail() {
        assert_that!(
            assert_that!(1, assertion_always_fails()),
            panics
        );
    }
}

mod eq {
    use super::*;

    #[test]
    fn should_match() {
        assert_that!(1, eq(1));
    }

    #[test]
    fn should_fail() {
        assert_that!(
            assert_that!(1, eq(2)), panics
        );
    }
}

mod less_than {
    use super::*;

    #[test]
    fn should_match() {
        assert_that!(1, less_than(2));
        assert_that!(1, lt(2));
    }

    #[test]
    fn should_fail() {
        assert_that!(
            assert_that!(1, less_than(1)),
            panics
        );
        assert_that!(
            assert_that!(1, lt(1)),
            panics
        );
    }
}

mod greater_than {
    use super::*;

    #[test]
    fn should_match() {
        assert_that!(1, greater_than(0));
        assert_that!(1, gt(0));
    }

    #[test]
    fn should_fail() {
        assert_that!(
            assert_that!(1, greater_than(1)),
            panics
        );
        assert_that!(
            assert_that!(1, gt(1)),
            panics
        );
    }
}

mod less_than_or_equal {
    use super::*;

    #[test]
    fn should_match() {
        assert_that!(1, less_than_or_equal(2));
        assert_that!(1, less_than_or_equal(1));
        assert_that!(1, leq(2));
    }

    #[test]
    fn should_fail() {
        assert_that!(
            assert_that!(1, less_than_or_equal(0)),
            panics
        );
        assert_that!(
            assert_that!(1, leq(0)),
            panics
        );
    }
}

mod greater_than_or_equal {
    use super::*;

    #[test]
    fn should_match() {
        assert_that!(1, greater_than_or_equal(0));
        assert_that!(1, greater_than_or_equal(1));
        assert_that!(1, geq(0));
    }

    #[test]
    fn should_fail() {
        assert_that!(
            assert_that!(1, greater_than_or_equal(2)),
            panics
        );
        assert_that!(
            assert_that!(1, geq(2)),
            panics
        );
    }
}
<|endoftext|>


<commit_before><commit_msg>Create table example<commit_after>extern crate cdrs;

use cdrs::client::{CDRS, Query};
use cdrs::authenticators::PasswordAuthenticator;
use cdrs::compression::Compression;

// default credentials
const user: &'static str = "cassandra";
const pass: &'static str = "cassandra";
const addr: &'static str = "127.0.0.1:9042";

fn main() {
    let authenticator = PasswordAuthenticator::new(user, pass);
    let client = CDRS::new(addr, authenticator).unwrap();
    let mut session = client.start(Compression::None).unwrap();

    // NOTE: keyspace "keyspace" should already exist
    let create_table_cql = "CREATE TABLE keyspace.users (
        user_name varchar PRIMARY KEY,
        password varchar,
        gender varchar,
        session_token varchar,
        state varchar,
        birth_year bigint
    );";
    let create_table_query = Query::new(create_table_cql);

    match session.query_with_builder(create_table_query) {
        Ok(ref res) => println!("table created: {:?}", res.get_body()),
        Err(ref err) => println!("Error occured: {:?}", err)
    }
}
<|endoftext|>


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


<commit_before><commit_msg>Refactor: rename example<commit_after><|endoftext|>


<commit_before><commit_msg>Use more idiomatic field names<commit_after><|endoftext|>


<commit_before>#[macro_use] extern crate log;
#[macro_use] extern crate version;
extern crate clap;

extern crate libimagcounter;
extern crate libimagrt;
extern crate libimagutil;

use std::process::exit;
use std::str::FromStr;

use libimagrt::runtime::Runtime;
use libimagcounter::counter::Counter;
use libimagutil::trace::trace_error;
use libimagutil::key_value_split::IntoKeyValue;

mod create;
mod delete;
mod interactive;
mod list;
mod ui;

use ui::build_ui;
use create::create;
use delete::delete;
use interactive::interactive;
use list::list;

enum Action {
    Inc,
    Dec,
    Reset,
    Set,
}

fn main() {
    let name = "imag-counter";
    let version = &version!()[..];
    let about = "Counter tool to count things";
    let ui = build_ui(Runtime::get_default_cli_builder(name, version, about));
    let rt = {
        let rt = Runtime::new(ui);
        if rt.is_ok() {
            rt.unwrap()
        } else {
            println!("Could not set up Runtime");
            println!("{:?}", rt.err().unwrap());
            exit(1);
        }
    };

    debug!("Hello. Logging was just enabled");
    debug!("I already set up the Runtime object and build the commandline interface parser.");
    debug!("Lets get rollin' ...");

    rt.cli()
        .subcommand_name()
        .map_or_else(|| {
                let (action, name) = {
                    if rt.cli().is_present("increment") {
                        (Action::Inc, rt.cli().value_of("increment").unwrap())
                    } else if rt.cli().is_present("decrement") {
                        (Action::Dec, rt.cli().value_of("decrement").unwrap())
                    } else if rt.cli().is_present("reset") {
                        (Action::Reset, rt.cli().value_of("reset").unwrap())
                    } else /* rt.cli().is_present("set") */ {
                        (Action::Set, rt.cli().value_of("set").unwrap())
                    }
                };

                match action {
                    Action::Inc => {
                        Counter::load(String::from(name), rt.store())
                            .map(|mut counter| {
                                match counter.inc() {
                                    Err(e) => { trace_error(&e); exit(1); },
                                    Ok(_) => info!("Ok"),
                                }
                            })
                    },
                    Action::Dec => {
                        Counter::load(String::from(name), rt.store())
                            .map(|mut counter| {
                                match counter.dec() {
                                    Err(e) => { trace_error(&e); exit(1); },
                                    Ok(_) => info!("Ok"),
                                }
                            })
                    },
                    Action::Reset => {
                        Counter::load(String::from(name), rt.store())
                            .map(|mut counter| {
                                match counter.reset() {
                                    Err(e) => { trace_error(&e); exit(1); },
                                    Ok(_) => info!("Ok"),
                                }
                            })
                    },
                    Action::Set => {
                        let kv = String::from(name).into_kv();
                        if kv.is_none() {
                            warn!("Not a key-value pair: '{}'", name);
                            exit(1);
                        }
                        let (key, value) = kv.unwrap().into();
                        let value = FromStr::from_str(&value[..]);
                        if value.is_err() {
                            warn!("Not a integer: '{:?}'", value);
                            exit(1);
                        }
                        let value : i64 = value.unwrap();
                        Counter::load(String::from(key), rt.store())
                            .map(|mut counter| {
                                match counter.set(value) {
                                    Err(e) => { trace_error(&e); exit(1); },
                                    Ok(_) => info!("Ok"),
                                }
                            })
                    },
                }
                .map_err(|e| trace_error(&e))
                .ok();
            },
            |name| {
                debug!("Call: {}", name);
                match name {
                    "create"      => create(&rt),
                    "delete"      => delete(&rt),
                    "interactive" => interactive(&rt),
                    "list"        => list(&rt),
                    _ => {
                        debug!("Unknown command"); // More error handling
                    },
                };
            })
}

<commit_msg>Enable lints<commit_after>#![deny(
    non_camel_case_types,
    non_snake_case,
    path_statements,
    trivial_numeric_casts,
    unstable_features,
    unused_allocation,
    unused_import_braces,
    unused_imports,
    unused_must_use,
    unused_mut,
    unused_qualifications,
    while_true,
)]

#[macro_use] extern crate log;
#[macro_use] extern crate version;
extern crate clap;

extern crate libimagcounter;
extern crate libimagrt;
extern crate libimagutil;

use std::process::exit;
use std::str::FromStr;

use libimagrt::runtime::Runtime;
use libimagcounter::counter::Counter;
use libimagutil::trace::trace_error;
use libimagutil::key_value_split::IntoKeyValue;

mod create;
mod delete;
mod interactive;
mod list;
mod ui;

use ui::build_ui;
use create::create;
use delete::delete;
use interactive::interactive;
use list::list;

enum Action {
    Inc,
    Dec,
    Reset,
    Set,
}

fn main() {
    let name = "imag-counter";
    let version = &version!()[..];
    let about = "Counter tool to count things";
    let ui = build_ui(Runtime::get_default_cli_builder(name, version, about));
    let rt = {
        let rt = Runtime::new(ui);
        if rt.is_ok() {
            rt.unwrap()
        } else {
            println!("Could not set up Runtime");
            println!("{:?}", rt.err().unwrap());
            exit(1);
        }
    };

    debug!("Hello. Logging was just enabled");
    debug!("I already set up the Runtime object and build the commandline interface parser.");
    debug!("Lets get rollin' ...");

    rt.cli()
        .subcommand_name()
        .map_or_else(|| {
                let (action, name) = {
                    if rt.cli().is_present("increment") {
                        (Action::Inc, rt.cli().value_of("increment").unwrap())
                    } else if rt.cli().is_present("decrement") {
                        (Action::Dec, rt.cli().value_of("decrement").unwrap())
                    } else if rt.cli().is_present("reset") {
                        (Action::Reset, rt.cli().value_of("reset").unwrap())
                    } else /* rt.cli().is_present("set") */ {
                        (Action::Set, rt.cli().value_of("set").unwrap())
                    }
                };

                match action {
                    Action::Inc => {
                        Counter::load(String::from(name), rt.store())
                            .map(|mut counter| {
                                match counter.inc() {
                                    Err(e) => { trace_error(&e); exit(1); },
                                    Ok(_) => info!("Ok"),
                                }
                            })
                    },
                    Action::Dec => {
                        Counter::load(String::from(name), rt.store())
                            .map(|mut counter| {
                                match counter.dec() {
                                    Err(e) => { trace_error(&e); exit(1); },
                                    Ok(_) => info!("Ok"),
                                }
                            })
                    },
                    Action::Reset => {
                        Counter::load(String::from(name), rt.store())
                            .map(|mut counter| {
                                match counter.reset() {
                                    Err(e) => { trace_error(&e); exit(1); },
                                    Ok(_) => info!("Ok"),
                                }
                            })
                    },
                    Action::Set => {
                        let kv = String::from(name).into_kv();
                        if kv.is_none() {
                            warn!("Not a key-value pair: '{}'", name);
                            exit(1);
                        }
                        let (key, value) = kv.unwrap().into();
                        let value = FromStr::from_str(&value[..]);
                        if value.is_err() {
                            warn!("Not a integer: '{:?}'", value);
                            exit(1);
                        }
                        let value : i64 = value.unwrap();
                        Counter::load(String::from(key), rt.store())
                            .map(|mut counter| {
                                match counter.set(value) {
                                    Err(e) => { trace_error(&e); exit(1); },
                                    Ok(_) => info!("Ok"),
                                }
                            })
                    },
                }
                .map_err(|e| trace_error(&e))
                .ok();
            },
            |name| {
                debug!("Call: {}", name);
                match name {
                    "create"      => create(&rt),
                    "delete"      => delete(&rt),
                    "interactive" => interactive(&rt),
                    "list"        => list(&rt),
                    _ => {
                        debug!("Unknown command"); // More error handling
                    },
                };
            })
}

<|endoftext|>


<commit_before>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use std::default::Default;
use std::io::stdout;
use std::io::Write;

use toml::Value;

use libimagentrylist::lister::Lister;
use libimagentrylist::result::Result;
use libimagerror::trace::trace_error;
use libimagstore::store::Entry;
use libimagstore::store::FileLockEntry;
use libimagerror::into::IntoError;
use libimagentrylist::error::ListErrorKind as LEK;

use reference::Ref;
use error::MapErrInto;
use error::RefErrorKind as REK;

pub struct RefLister {
    check_dead: bool,
    check_changed: bool,
    check_changed_content: bool,
    check_changed_permiss: bool,
}

impl RefLister {

    pub fn new() -> RefLister {
        RefLister::default()
    }

    pub fn check_dead(mut self, b: bool) -> RefLister {
        self.check_dead = b;
        self
    }

    pub fn check_changed(mut self, b: bool) -> RefLister {
        self.check_changed = b;
        self
    }

    pub fn check_changed_content(mut self, b: bool) -> RefLister {
        self.check_changed_content = b;
        self
    }

    pub fn check_changed_permiss(mut self, b: bool) -> RefLister {
        self.check_changed_permiss = b;
        self
    }

}

impl Default for RefLister {

    fn default() -> RefLister {
        RefLister {
            check_dead: false,
            check_changed: false,
            check_changed_content: false,
            check_changed_permiss: false,
        }
    }
}

fn list_fn(e: &Entry) -> String {
    let stored_hash = match e.get_header().read("ref.content_hash") {
        Ok(Some(Value::String(s))) => s.clone(),
        _                          => String::from("<Error: Could not read stored hash>"),
    };

    let filepath = match e.get_header().read("ref.path") {
        Ok(Some(Value::String(ref s))) => s.clone(),
        _ => String::from("<Error: Could not read file path>"),
    };

    format!("Ref({} -> {})", stored_hash, filepath)
}

impl Lister for RefLister {

    fn list<'b, I: Iterator<Item = FileLockEntry<'b>>>(&self, entries: I) -> Result<()> {

        debug!("Called list()");
        let (r, n) = entries.fold((Ok(()), 0), |(accu, i), entry| {
            debug!("fold({:?}, {:?})", accu, entry);
            let r = accu.and_then(|_| {
                    debug!("Listing Entry: {:?}", entry);
                    lister_fn(entry,
                              self.check_dead,
                              self.check_changed,
                              self.check_changed_content,
                              self.check_changed_permiss)
                        .and_then(|s| {
                            write!(stdout(), "{}\n", s)
                                .map_err(Box::new)
                                .map_err(|e| LEK::FormatError.into_error_with_cause(e))
                        })
                        .map_err_into(REK::RefToDisplayError)
                })
                .map(|_| ());
            (r, i + 1)
        });
        debug!("Iterated over {} entries", n);
        r.map_err(|e| LEK::FormatError.into_error_with_cause(Box::new(e)))
    }

}

fn lister_fn(fle: FileLockEntry,
             do_check_dead: bool,
             do_check_changed: bool,
             do_check_changed_content: bool,
             do_check_changed_permiss: bool) -> Result<String>
{
    Ref::from_filelockentry(fle)
        .map(|r| {
            let is_dead = if do_check_dead {
                if check_dead(&r) { "dead" } else { "alive" }
            } else {
                "not checked"
            };

            let is_changed = if do_check_changed {
                if check_changed(&r) { "changed" } else { "unchanged" }
            } else {
                "not checked"
            };

            let is_changed_content = if do_check_changed_content {
                if check_changed_content(&r) { "changed" } else { "unchanged" }
            } else {
                "not checked"
            };

            let is_changed_permiss = if do_check_changed_permiss {
                if check_changed_permiss(&r) { "changed" } else { "unchanged" }
            } else {
                "not checked"
            };

            format!("{} | {} | {} | {} | {} | {}",
                    is_dead,
                    is_changed,
                    is_changed_content,
                    is_changed_permiss,
                    r.get_path_hash().unwrap_or_else(|| String::from("Cannot get hash")),
                    r.get_location())
        })
        .map_err(|e| LEK::FormatError.into_error_with_cause(Box::new(e)))
}

fn check_dead(r: &Ref) -> bool {
    match r.fs_link_exists() {
        Ok(b)  => b,
        Err(e) => {
            warn!("Could not check whether the ref {} exists on the FS:", r);
            trace_error(&e);

            // We continue here and tell the callee that this reference is dead, what is kind of
            // true actually, as we might not have access to it right now
            true
        },
    }
}

fn check_changed(r: &Ref) -> bool {
    check_changed_content(r) && check_changed_permiss(r)
}

fn check_changed_content(r: &Ref) -> bool {
    let eq = r.get_current_hash()
        .and_then(|hash| r.get_stored_hash().map(|stored| (hash, stored)))
        .map(|(hash, stored)| hash == stored);

    match eq {
        Ok(eq) => eq,
        Err(e) => {
            warn!("Could not check whether the ref {} changed on the FS:", r);
            trace_error(&e);

            // We continue here and tell the callee that this reference is unchanged
            false
        },
    }
}

fn check_changed_permiss(r: &Ref) -> bool {
    warn!("Permission changes tracking not supported yet.");
    false
}

<commit_msg>Remove unused function<commit_after>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use std::default::Default;
use std::io::stdout;
use std::io::Write;

use toml::Value;

use libimagentrylist::lister::Lister;
use libimagentrylist::result::Result;
use libimagerror::trace::trace_error;
use libimagstore::store::Entry;
use libimagstore::store::FileLockEntry;
use libimagerror::into::IntoError;
use libimagentrylist::error::ListErrorKind as LEK;

use reference::Ref;
use error::MapErrInto;
use error::RefErrorKind as REK;

pub struct RefLister {
    check_dead: bool,
    check_changed: bool,
    check_changed_content: bool,
    check_changed_permiss: bool,
}

impl RefLister {

    pub fn new() -> RefLister {
        RefLister::default()
    }

    pub fn check_dead(mut self, b: bool) -> RefLister {
        self.check_dead = b;
        self
    }

    pub fn check_changed(mut self, b: bool) -> RefLister {
        self.check_changed = b;
        self
    }

    pub fn check_changed_content(mut self, b: bool) -> RefLister {
        self.check_changed_content = b;
        self
    }

    pub fn check_changed_permiss(mut self, b: bool) -> RefLister {
        self.check_changed_permiss = b;
        self
    }

}

impl Default for RefLister {

    fn default() -> RefLister {
        RefLister {
            check_dead: false,
            check_changed: false,
            check_changed_content: false,
            check_changed_permiss: false,
        }
    }
}

impl Lister for RefLister {

    fn list<'b, I: Iterator<Item = FileLockEntry<'b>>>(&self, entries: I) -> Result<()> {

        debug!("Called list()");
        let (r, n) = entries.fold((Ok(()), 0), |(accu, i), entry| {
            debug!("fold({:?}, {:?})", accu, entry);
            let r = accu.and_then(|_| {
                    debug!("Listing Entry: {:?}", entry);
                    lister_fn(entry,
                              self.check_dead,
                              self.check_changed,
                              self.check_changed_content,
                              self.check_changed_permiss)
                        .and_then(|s| {
                            write!(stdout(), "{}\n", s)
                                .map_err(Box::new)
                                .map_err(|e| LEK::FormatError.into_error_with_cause(e))
                        })
                        .map_err_into(REK::RefToDisplayError)
                })
                .map(|_| ());
            (r, i + 1)
        });
        debug!("Iterated over {} entries", n);
        r.map_err(|e| LEK::FormatError.into_error_with_cause(Box::new(e)))
    }

}

fn lister_fn(fle: FileLockEntry,
             do_check_dead: bool,
             do_check_changed: bool,
             do_check_changed_content: bool,
             do_check_changed_permiss: bool) -> Result<String>
{
    Ref::from_filelockentry(fle)
        .map(|r| {
            let is_dead = if do_check_dead {
                if check_dead(&r) { "dead" } else { "alive" }
            } else {
                "not checked"
            };

            let is_changed = if do_check_changed {
                if check_changed(&r) { "changed" } else { "unchanged" }
            } else {
                "not checked"
            };

            let is_changed_content = if do_check_changed_content {
                if check_changed_content(&r) { "changed" } else { "unchanged" }
            } else {
                "not checked"
            };

            let is_changed_permiss = if do_check_changed_permiss {
                if check_changed_permiss(&r) { "changed" } else { "unchanged" }
            } else {
                "not checked"
            };

            format!("{} | {} | {} | {} | {} | {}",
                    is_dead,
                    is_changed,
                    is_changed_content,
                    is_changed_permiss,
                    r.get_path_hash().unwrap_or_else(|| String::from("Cannot get hash")),
                    r.get_location())
        })
        .map_err(|e| LEK::FormatError.into_error_with_cause(Box::new(e)))
}

fn check_dead(r: &Ref) -> bool {
    match r.fs_link_exists() {
        Ok(b)  => b,
        Err(e) => {
            warn!("Could not check whether the ref {} exists on the FS:", r);
            trace_error(&e);

            // We continue here and tell the callee that this reference is dead, what is kind of
            // true actually, as we might not have access to it right now
            true
        },
    }
}

fn check_changed(r: &Ref) -> bool {
    check_changed_content(r) && check_changed_permiss(r)
}

fn check_changed_content(r: &Ref) -> bool {
    let eq = r.get_current_hash()
        .and_then(|hash| r.get_stored_hash().map(|stored| (hash, stored)))
        .map(|(hash, stored)| hash == stored);

    match eq {
        Ok(eq) => eq,
        Err(e) => {
            warn!("Could not check whether the ref {} changed on the FS:", r);
            trace_error(&e);

            // We continue here and tell the callee that this reference is unchanged
            false
        },
    }
}

fn check_changed_permiss(r: &Ref) -> bool {
    warn!("Permission changes tracking not supported yet.");
    false
}

<|endoftext|>


<commit_before><commit_msg>Removed mutexes from Danbooru interface by managing ownership more cleanly.<commit_after><|endoftext|>


<commit_before><commit_msg>Problem: no JSONVectorBlock implementation Solution: implement one!<commit_after>use sputnikvm::{Gas, H256, U256, Address};
use sputnikvm::vm::{Machine, VectorMachine};
use sputnikvm::blockchain::Block;

use serde_json::Value;
use std::collections::HashMap;

pub struct JSONVectorBlock {
    codes: HashMap<Address, Vec<u8>>,
    balances: HashMap<Address, U256>,
    storages: HashMap<Address, Vec<U256>>,

    coinbase: Address,
    timestamp: U256,
    number: U256,
    difficulty: U256,
    gas_limit: Gas
}

impl JSONVectorBlock {
    pub fn new(env: &Value) -> Self {
        let current_coinbase = env["currentCoinbase"].as_str().unwrap();
        let current_difficulty = env["currentDifficulty"].as_str().unwrap();
        let current_gas_limit = env["currentGasLimit"].as_str().unwrap();
        let current_number = env["currentNumber"].as_str().unwrap();
        let current_timestamp = env["currentTimestamp"].as_str().unwrap();

        JSONVectorBlock {
            balances: HashMap::new(),
            storages: HashMap::new(),
            codes: HashMap::new(),

            coinbase: Address::from_str(current_coinbase).unwrap(),
            difficulty: U256::from_str(current_difficulty).unwrap(),
            gas_limit: Gas::from_str(current_gas_limit).unwrap(),
            number: U256::from_str(current_number).unwrap(),
            timestamp: U256::from_str(current_timestamp).unwrap(),
        }
    }

    pub fn set_account_code(&mut self, address: Address, code: &[u8]) {
        self.codes.insert(address, code.into());
    }

    pub fn set_balance(&mut self, address: Address, balance: U256) {
        self.balances.insert(address, balance);
    }
}

impl Block for JSONVectorBlock {
    fn account_code(&self, address: Address) -> Option<&[u8]> {
        self.codes.get(&address).map(|s| s.as_ref())
    }

    fn create_account(&mut self, code: &[u8]) -> Option<Address> {
        unimplemented!()
    }

    fn coinbase(&self) -> Address {
        self.coinbase
    }

    fn balance(&self, address: Address) -> Option<U256> {
        self.balances.get(&address).map(|s| *s)
    }

    fn timestamp(&self) -> U256 {
        self.timestamp
    }

    fn number(&self) -> U256 {
        self.number
    }

    fn difficulty(&self) -> U256 {
        self.difficulty
    }

    fn gas_limit(&self) -> Gas {
        self.gas_limit
    }

    fn account_storage(&self, address: Address, index: U256) -> U256 {
        match self.storages.get(&address) {
            None => U256::zero(),
            Some(ref ve) => {
                let index: usize = index.into();

                match ve.get(index) {
                    Some(&v) => v,
                    None => U256::zero()
                }
            }
        }
    }

    fn set_account_storage(&mut self, address: Address, index: U256, val: U256) {
        if self.storages.get(&address).is_none() {
            self.storages.insert(address, Vec::new());
        }

        let v = self.storages.get_mut(&address).unwrap();

        let index: usize = index.into();

        if v.len() <= index {
            v.resize(index + 1, 0.into());
        }

        v[index] = val;
    }

    fn log(&mut self, address: Address, data: &[u8], topics: &[U256]) {
        unimplemented!()
    }

    fn blockhash(&self, n: U256) -> H256 {
        unimplemented!()
    }
}
<|endoftext|>


<commit_before><commit_msg>Add explanation for E0607<commit_after><|endoftext|>


<commit_before><commit_msg>added fitness function and merged it with interpret function<commit_after><|endoftext|>


<commit_before><commit_msg>Default threads increased<commit_after><|endoftext|>


<commit_before><commit_msg>cleanup<commit_after><|endoftext|>


<commit_before><commit_msg>Just use function for metric parsing, no need for struct + impl<commit_after><|endoftext|>


<commit_before><commit_msg>add CloudTrail integration tests<commit_after>#![cfg(feature = "cloudtrail")]

extern crate rusoto;

use rusoto::cloudtrail::{CloudTrailClient, DescribeTrailsRequest};
use rusoto::{DefaultCredentialsProvider, Region};

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

    let request = DescribeTrailsRequest::default();

    match client.describe_trails(&request) {
    	Ok(response) => {
    		println!("{:#?}", response);
    		assert!(true)
    	},
    	Err(err) => panic!("Expected OK response, got {:#?}", err)
    };
}
<|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 build;
use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
use rustc::mir::Mir;
use rustc::mir::transform::{MirPassIndex, MirSuite, MirSource,
                            MIR_CONST, MIR_VALIDATED, MIR_OPTIMIZED};
use rustc::ty::{self, TyCtxt};
use rustc::ty::maps::Providers;
use rustc::ty::steal::Steal;
use rustc::hir;
use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
use rustc::util::nodemap::DefIdSet;
use std::rc::Rc;
use syntax::ast;
use syntax_pos::{DUMMY_SP, Span};
use transform;

pub mod add_validation;
pub mod clean_end_regions;
pub mod simplify_branches;
pub mod simplify;
pub mod erase_regions;
pub mod no_landing_pads;
pub mod type_check;
pub mod borrow_check;
pub mod rustc_peek;
pub mod elaborate_drops;
pub mod add_call_guards;
pub mod promote_consts;
pub mod qualify_consts;
pub mod dump_mir;
pub mod deaggregator;
pub mod instcombine;
pub mod copy_prop;
pub mod inline;
pub mod nll;

pub(crate) fn provide(providers: &mut Providers) {
    self::qualify_consts::provide(providers);
    *providers = Providers {
        mir_keys,
        mir_const,
        mir_validated,
        optimized_mir,
        is_mir_available,
        ..*providers
    };
}

fn is_mir_available<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool {
    tcx.mir_keys(def_id.krate).contains(&def_id)
}

/// Finds the full set of def-ids within the current crate that have
/// MIR associated with them.
fn mir_keys<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, krate: CrateNum)
                      -> Rc<DefIdSet> {
    assert_eq!(krate, LOCAL_CRATE);

    let mut set = DefIdSet();

    // All body-owners have MIR associated with them.
    set.extend(tcx.body_owners());

    // Additionally, tuple struct/variant constructors have MIR, but
    // they don't have a BodyId, so we need to build them separately.
    struct GatherCtors<'a, 'tcx: 'a> {
        tcx: TyCtxt<'a, 'tcx, 'tcx>,
        set: &'a mut DefIdSet,
    }
    impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
        fn visit_variant_data(&mut self,
                              v: &'tcx hir::VariantData,
                              _: ast::Name,
                              _: &'tcx hir::Generics,
                              _: ast::NodeId,
                              _: Span) {
            if let hir::VariantData::Tuple(_, node_id) = *v {
                self.set.insert(self.tcx.hir.local_def_id(node_id));
            }
            intravisit::walk_struct_def(self, v)
        }
        fn nested_visit_map<'b>(&'b mut self) -> NestedVisitorMap<'b, 'tcx> {
            NestedVisitorMap::None
        }
    }
    tcx.hir.krate().visit_all_item_likes(&mut GatherCtors {
        tcx,
        set: &mut set,
    }.as_deep_visitor());

    Rc::new(set)
}

fn mir_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx Steal<Mir<'tcx>> {
    let mut mir = build::mir_build(tcx, def_id);
    let source = MirSource::from_local_def_id(tcx, def_id);
    transform::run_suite(tcx, source, MIR_CONST, &mut mir);
    tcx.alloc_steal_mir(mir)
}

fn mir_validated<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx Steal<Mir<'tcx>> {
    let source = MirSource::from_local_def_id(tcx, def_id);
    if let MirSource::Const(_) = source {
        // Ensure that we compute the `mir_const_qualif` for constants at
        // this point, before we steal the mir-const result. We don't
        // directly need the result or `mir_const_qualif`, so we can just force it.
        ty::queries::mir_const_qualif::force(tcx, DUMMY_SP, def_id);
    }

    let mut mir = tcx.mir_const(def_id).steal();
    transform::run_suite(tcx, source, MIR_VALIDATED, &mut mir);
    tcx.alloc_steal_mir(mir)
}

fn optimized_mir<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx Mir<'tcx> {
    // Borrowck uses `mir_validated`, so we have to force it to
    // execute before we can steal.
    ty::queries::borrowck::force(tcx, DUMMY_SP, def_id);

    let mut mir = tcx.mir_validated(def_id).steal();
    let source = MirSource::from_local_def_id(tcx, def_id);
    transform::run_suite(tcx, source, MIR_OPTIMIZED, &mut mir);
    tcx.alloc_mir(mir)
}

fn run_suite<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                       source: MirSource,
                       suite: MirSuite,
                       mir: &mut Mir<'tcx>)
{
    let passes = tcx.mir_passes.passes(suite);

    for (pass, index) in passes.iter().zip(0..) {
        let pass_num = MirPassIndex(index);

        for hook in tcx.mir_passes.hooks() {
            hook.on_mir_pass(tcx, suite, pass_num, &pass.name(), source, &mir, false);
        }

        pass.run_pass(tcx, source, mir);

        for hook in tcx.mir_passes.hooks() {
            hook.on_mir_pass(tcx, suite, pass_num, &pass.name(), source, &mir, true);
        }
    }
}
<commit_msg>Auto merge of #43902 - michaelwoerister:fix-mir-passes-promoted, r=arielb1<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 build;
use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
use rustc::mir::Mir;
use rustc::mir::transform::{MirPassIndex, MirSuite, MirSource,
                            MIR_CONST, MIR_VALIDATED, MIR_OPTIMIZED};
use rustc::ty::{self, TyCtxt};
use rustc::ty::maps::Providers;
use rustc::ty::steal::Steal;
use rustc::hir;
use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
use rustc::util::nodemap::DefIdSet;
use std::rc::Rc;
use syntax::ast;
use syntax_pos::{DUMMY_SP, Span};
use transform;

pub mod add_validation;
pub mod clean_end_regions;
pub mod simplify_branches;
pub mod simplify;
pub mod erase_regions;
pub mod no_landing_pads;
pub mod type_check;
pub mod borrow_check;
pub mod rustc_peek;
pub mod elaborate_drops;
pub mod add_call_guards;
pub mod promote_consts;
pub mod qualify_consts;
pub mod dump_mir;
pub mod deaggregator;
pub mod instcombine;
pub mod copy_prop;
pub mod inline;
pub mod nll;

pub(crate) fn provide(providers: &mut Providers) {
    self::qualify_consts::provide(providers);
    *providers = Providers {
        mir_keys,
        mir_const,
        mir_validated,
        optimized_mir,
        is_mir_available,
        ..*providers
    };
}

fn is_mir_available<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool {
    tcx.mir_keys(def_id.krate).contains(&def_id)
}

/// Finds the full set of def-ids within the current crate that have
/// MIR associated with them.
fn mir_keys<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, krate: CrateNum)
                      -> Rc<DefIdSet> {
    assert_eq!(krate, LOCAL_CRATE);

    let mut set = DefIdSet();

    // All body-owners have MIR associated with them.
    set.extend(tcx.body_owners());

    // Additionally, tuple struct/variant constructors have MIR, but
    // they don't have a BodyId, so we need to build them separately.
    struct GatherCtors<'a, 'tcx: 'a> {
        tcx: TyCtxt<'a, 'tcx, 'tcx>,
        set: &'a mut DefIdSet,
    }
    impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
        fn visit_variant_data(&mut self,
                              v: &'tcx hir::VariantData,
                              _: ast::Name,
                              _: &'tcx hir::Generics,
                              _: ast::NodeId,
                              _: Span) {
            if let hir::VariantData::Tuple(_, node_id) = *v {
                self.set.insert(self.tcx.hir.local_def_id(node_id));
            }
            intravisit::walk_struct_def(self, v)
        }
        fn nested_visit_map<'b>(&'b mut self) -> NestedVisitorMap<'b, 'tcx> {
            NestedVisitorMap::None
        }
    }
    tcx.hir.krate().visit_all_item_likes(&mut GatherCtors {
        tcx,
        set: &mut set,
    }.as_deep_visitor());

    Rc::new(set)
}

fn mir_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx Steal<Mir<'tcx>> {
    let mut mir = build::mir_build(tcx, def_id);
    let source = MirSource::from_local_def_id(tcx, def_id);
    transform::run_suite(tcx, source, MIR_CONST, &mut mir);
    tcx.alloc_steal_mir(mir)
}

fn mir_validated<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx Steal<Mir<'tcx>> {
    let source = MirSource::from_local_def_id(tcx, def_id);
    if let MirSource::Const(_) = source {
        // Ensure that we compute the `mir_const_qualif` for constants at
        // this point, before we steal the mir-const result. We don't
        // directly need the result or `mir_const_qualif`, so we can just force it.
        ty::queries::mir_const_qualif::force(tcx, DUMMY_SP, def_id);
    }

    let mut mir = tcx.mir_const(def_id).steal();
    transform::run_suite(tcx, source, MIR_VALIDATED, &mut mir);
    tcx.alloc_steal_mir(mir)
}

fn optimized_mir<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx Mir<'tcx> {
    // Borrowck uses `mir_validated`, so we have to force it to
    // execute before we can steal.
    ty::queries::borrowck::force(tcx, DUMMY_SP, def_id);

    let mut mir = tcx.mir_validated(def_id).steal();
    let source = MirSource::from_local_def_id(tcx, def_id);
    transform::run_suite(tcx, source, MIR_OPTIMIZED, &mut mir);
    tcx.alloc_mir(mir)
}

fn run_suite<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                       source: MirSource,
                       suite: MirSuite,
                       mir: &mut Mir<'tcx>)
{
    let passes = tcx.mir_passes.passes(suite);

    for (pass, index) in passes.iter().zip(0..) {
        let pass_num = MirPassIndex(index);

        for hook in tcx.mir_passes.hooks() {
            hook.on_mir_pass(tcx, suite, pass_num, &pass.name(), source, &mir, false);
        }

        pass.run_pass(tcx, source, mir);

        for (index, promoted_mir) in mir.promoted.iter_enumerated_mut() {
            let promoted_source = MirSource::Promoted(source.item_id(), index);
            pass.run_pass(tcx, promoted_source, promoted_mir);

            // Let's make sure we don't miss any nested instances
            assert!(promoted_mir.promoted.is_empty());
        }

        for hook in tcx.mir_passes.hooks() {
            hook.on_mir_pass(tcx, suite, pass_num, &pass.name(), source, &mir, true);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Line access<commit_after><|endoftext|>


<commit_before>//! Defines types for operating with floating point and 8 bit RGB colors

use std::num::Float;
use linalg;

/// Colorf is a floating point RGB color type
#[deriving(Show, Copy, PartialEq)]
pub struct Colorf {
    pub r: f32,
    pub g: f32,
    pub b: f32,
}

impl Colorf {
    /// Create an RGB color
    pub fn new(r: f32, g: f32, b: f32) -> Colorf {
        Colorf { r: r, g: g, b: b }
    }
    /// Create an RGB color using the same value for all channels
    pub fn broadcast(r: f32) -> Colorf {
        Colorf { r: r, g: r, b: r }
    }
    /// Clamp the color values between [0, 1]
    pub fn clamp(&self) -> Colorf {
        Colorf { r: linalg::clamp(self.r, 0.0, 1.0),
                 g: linalg::clamp(self.g, 0.0, 1.0),
                 b: linalg::clamp(self.b, 0.0, 1.0) }
    }
    /// Compute the luminance of the color
    pub fn luminance(&self) -> f32 {
        0.2126 * self.r + 0.7152 * self.g + 0.0722 * self.b
    }
    /// Check if the color is black
    pub fn is_black(&self) -> bool {
        self.r == 0f32 && self.g == 0f32 && self.b == 0f32
    }
    /// Convert the linear RGB color to sRGB
    pub fn to_srgb(&self) -> Colorf {
        let a = 0.055f32;
        let b = 1f32 / 2.4;
        let mut srgb = Colorf::broadcast(0.0);
        for i in range(0u, 3) {
            if self[i] <= 0.0031308 {
                srgb[i] = 12.92 * self[i];
            } else {
                srgb[i] = (1.0 + a) * Float::powf(self[i], b) - a;
            }
        }
        srgb
    }
    /// Return the color with values { e^r, e^g, e^b }
    pub fn exp(&self) -> Colorf {
        Colorf { r: Float::exp(self.r), g: Float::exp(self.g), b: Float::exp(self.b) }
    }
}

impl Add<Colorf, Colorf> for Colorf {
    /// Add two colors together
    fn add(self, rhs: Colorf) -> Colorf {
        Colorf { r: self.r + rhs.r, g: self.g + rhs.g, b: self.b + rhs.b }
    }
}

impl Sub<Colorf, Colorf> for Colorf {
    /// Subtract the two colors
    fn sub(self, rhs: Colorf) -> Colorf {
        Colorf { r: self.r - rhs.r, g: self.g - rhs.g, b: self.b - rhs.b }
    }
}

impl Mul<Colorf, Colorf> for Colorf {
    /// Multiply the two colors
    fn mul(self, rhs: Colorf) -> Colorf {
        Colorf { r: self.r * rhs.r, g: self.g * rhs.g, b: self.b * rhs.b }
    }
}

impl Mul<f32, Colorf> for Colorf {
    /// Scale the color by the float
    fn mul(self, rhs: f32) -> Colorf {
        Colorf { r: self.r * rhs, g: self.g * rhs, b: self.b * rhs }
    }
}

impl Div<Colorf, Colorf> for Colorf {
    /// Divide the channels of one color by another
    fn div(self, rhs: Colorf) -> Colorf {
        Colorf { r: self.r / rhs.r, g: self.g / rhs.g, b: self.b / rhs.b }
    }
}

impl Div<f32, Colorf> for Colorf {
    /// Divide the channels of the color by the float
    fn div(self, rhs: f32) -> Colorf {
        Colorf { r: self.r / rhs, g: self.g / rhs, b: self.b / rhs }
    }
}

impl Neg<Colorf> for Colorf {
    /// Negate the color channels
    fn neg(self) -> Colorf {
        Colorf { r: -self.r, g: -self.g, b: -self.b }
    }
}

impl Index<uint, f32> for Colorf {
    /// Access the channels by index
    ///
    /// - 0 = r
    /// - 1 = g
    /// - 2 = b
    fn index(&self, i: &uint) -> &f32 {
        match *i {
            0 => &self.r,
            1 => &self.g,
            2 => &self.b,
            _ => panic!("Invalid index into color"),
        }
    }
}

impl IndexMut<uint, f32> for Colorf {
    /// Access the channels by index
    ///
    /// - 0 = r
    /// - 1 = g
    /// - 2 = b
    fn index_mut(&mut self, i: &uint) -> &mut f32 {
        match *i {
            0 => &mut self.r,
            1 => &mut self.g,
            2 => &mut self.b,
            _ => panic!("Invalid index into color"),
        }
    }
}

<commit_msg>Add alpha channel to color for storing color weights<commit_after>//! Defines types for operating with floating point and 8 bit RGB colors

use std::num::Float;
use linalg;

/// Colorf is a floating point RGBA color type
/// `a` is typically used to store the weight of a color eg. in the
/// render target for multisampling we need to track the weight to
/// normalize in the end and is always initialized to 0
#[deriving(Show, Copy, Clone, PartialEq)]
pub struct Colorf {
    pub r: f32,
    pub g: f32,
    pub b: f32,
    pub a: f32,
}

impl Colorf {
    /// Create an RGB color
    pub fn new(r: f32, g: f32, b: f32) -> Colorf {
        Colorf { r: r, g: g, b: b, a: 0f32 }
    }
    /// Create an RGB color using the same value for all channels
    pub fn broadcast(r: f32) -> Colorf {
        Colorf { r: r, g: r, b: r, a: 0f32 }
    }
    /// Clamp the color values between [0, 1]
    pub fn clamp(&self) -> Colorf {
        Colorf { r: linalg::clamp(self.r, 0.0, 1.0),
                 g: linalg::clamp(self.g, 0.0, 1.0),
                 b: linalg::clamp(self.b, 0.0, 1.0),
                 a: linalg::clamp(self.a, 0.0, 1.0) }
    }
    /// Compute the luminance of the color
    pub fn luminance(&self) -> f32 {
        0.2126 * self.r + 0.7152 * self.g + 0.0722 * self.b
    }
    /// Check if the color is black
    pub fn is_black(&self) -> bool {
        self.r == 0f32 && self.g == 0f32 && self.b == 0f32
    }
    /// Convert the linear RGB color to sRGB
    pub fn to_srgb(&self) -> Colorf {
        let a = 0.055f32;
        let b = 1f32 / 2.4;
        let mut srgb = Colorf::broadcast(0.0);
        for i in range(0u, 3) {
            if self[i] <= 0.0031308 {
                srgb[i] = 12.92 * self[i];
            } else {
                srgb[i] = (1.0 + a) * Float::powf(self[i], b) - a;
            }
        }
        srgb
    }
    /// Return the color with values { e^r, e^g, e^b }
    pub fn exp(&self) -> Colorf {
        Colorf { r: Float::exp(self.r), g: Float::exp(self.g),
                 b: Float::exp(self.b), a: Float::exp(self.a) }
    }
}

impl Add<Colorf, Colorf> for Colorf {
    /// Add two colors together
    fn add(self, rhs: Colorf) -> Colorf {
        Colorf { r: self.r + rhs.r, g: self.g + rhs.g, b: self.b + rhs.b, a: self.a + rhs.a }
    }
}

impl Sub<Colorf, Colorf> for Colorf {
    /// Subtract the two colors
    fn sub(self, rhs: Colorf) -> Colorf {
        Colorf { r: self.r - rhs.r, g: self.g - rhs.g, b: self.b - rhs.b, a: self.a - rhs.a }
    }
}

impl Mul<Colorf, Colorf> for Colorf {
    /// Multiply the two colors
    fn mul(self, rhs: Colorf) -> Colorf {
        Colorf { r: self.r * rhs.r, g: self.g * rhs.g, b: self.b * rhs.b, a: self.a * rhs.a }
    }
}

impl Mul<f32, Colorf> for Colorf {
    /// Scale the color by the float
    fn mul(self, rhs: f32) -> Colorf {
        Colorf { r: self.r * rhs, g: self.g * rhs, b: self.b * rhs, a: self.a * rhs}
    }
}

impl Div<Colorf, Colorf> for Colorf {
    /// Divide the channels of one color by another
    fn div(self, rhs: Colorf) -> Colorf {
        Colorf { r: self.r / rhs.r, g: self.g / rhs.g, b: self.b / rhs.b, a: self.a / rhs.a }
    }
}

impl Div<f32, Colorf> for Colorf {
    /// Divide the channels of the color by the float
    fn div(self, rhs: f32) -> Colorf {
        Colorf { r: self.r / rhs, g: self.g / rhs, b: self.b / rhs, a: self.a / rhs }
    }
}

impl Neg<Colorf> for Colorf {
    /// Negate the color channels
    fn neg(self) -> Colorf {
        Colorf { r: -self.r, g: -self.g, b: -self.b, a: -self.a }
    }
}

impl Index<uint, f32> for Colorf {
    /// Access the channels by index
    ///
    /// - 0 = r
    /// - 1 = g
    /// - 2 = b
    /// - 3 = a
    fn index(&self, i: &uint) -> &f32 {
        match *i {
            0 => &self.r,
            1 => &self.g,
            2 => &self.b,
            3 => &self.a,
            _ => panic!("Invalid index into color"),
        }
    }
}

impl IndexMut<uint, f32> for Colorf {
    /// Access the channels by index
    ///
    /// - 0 = r
    /// - 1 = g
    /// - 2 = b
    /// - 3 = a
    fn index_mut(&mut self, i: &uint) -> &mut f32 {
        match *i {
            0 => &mut self.r,
            1 => &mut self.g,
            2 => &mut self.b,
            3 => &mut self.a,
            _ => panic!("Invalid index into color"),
        }
    }
}

<|endoftext|>


<commit_before><commit_msg>am bd6acda9: Merge "Fix bugs in grain where values could go out of bounds." into jb-mr1-dev<commit_after><|endoftext|>


<commit_before><commit_msg>Added destructure pointers example<commit_after>fn main() {
    // Assign a reference of type `i32`. The `&` signifies there
    // is a reference being assigned.
    let reference = &4_i32;

    match reference {
        // If `reference`s is pattern matched against `&val`, it results
        // in a comparison like:
        // `&i32`
        // `&val`
        // ^ We see that if the matching `&`s are dropped, then the `i32`
        // should be assigned to `val`.
        &val => {
          println!("Got a value via destructuring: {:?}", val);
        }
    }

    // To avoid the `&`, you dereference before matching.
    match *reference {
        val => println!("Got a value via dereferencing: {:?}", val),
    }

    // What if you don't start with a reference? `reference` was a `&`
    // because the right side was already a reference. This is not
    // a reference because the right side is not one.
    let _not_a_reference = 3;

    // Rust provides `ref` for exacty this purpose. It modifies the
    // assignment so that a reference is created for the element; this
    // reference is assigned.
    let ref _is_a_reference = 3;

    // Accordingly, by defining 2 values without references, references
    // can be retrieved via `ref` and `ref mut`.
    let value = 5;
    let mut mut_value = 6;

    // Use `ref` keyword to create a reference.
    match value {
        ref r => println!("Got a reference to a value: {:?}", r),
    }

    // Use `ref mut` similarly.
    match mut_value {
        ref mut m => {
            // Got a reference. Gotta dereference it before we can
            // add anything to it.
            *m += 10;
            println!("We added 10. `mut_value`: {:?}", m);
        },
    }
}
<|endoftext|>


<commit_before><commit_msg>Rust tutorial 4.1 - Variable Bindings<commit_after>// A complilation of notes and lessons from https://doc.rust-lang.org/book/variable-bindings.html
// Note: this file will not compile as it is right now - there are lots of warnings about unused variables and such

fn main() {
    // This is the 'basic' way to do it. The 'let' keyword is all you need
    let a = 5;

    // The LHS is a pattern and can be assigned to by the RHS of a similar pattern
    // Patterns are a language concept of their own but can be used to do things like this
    let (b, c) = (2, 3);

    // Rust is statically typed, making 'let' similar to 'auto' in C++ - the language figures it out at compile time
    // However, if we want to we can tell the compiler up front "Hey, this is the type we want this to be", in case
    // there's potential ambiguity (32bit vs 64bit int, for example)
    let d : i64 = 7;

    // By default variables ('bindings' in Rust-speak) are immutable. If you uncomment out the line below the program
    // won't compile
    let e = 7;
    // e = 8;
    // We need to specifically tell Rust that a variable is mutable when we create it with the keyword 'mut'
    let mut f = 8;
    f = 9;

    // Rust bindings must be initialized - there is no 'default' like in C++. As such the following line would not compile
    // let d : i32;
    // println!("{}", d);

    // Scope looks to be very similar to C++ - variables are scoped to the {} block they were created in
    // It does not seem like you can create a variable at the global scope ie. outside of a method

    // Rust allows you to overwrite ("shadow") a variable in the same scope by assigning it another value. This is not
    // the same as mutability - what we're doing here is discarding and overwriting the previous binding with a new one
    // As such we can change things like the type and mutability of a binding
    let g : i32 = 7;
    println!("{}", g); // will print 7
    let mut g = "hello world";
    println!("{}", g); // will print hello world
}<|endoftext|>