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

fn main() {
    (return)[0u]; //~ ERROR cannot index a value of type `!`
}
<|endoftext|>


<commit_before><commit_msg>genet-sdk: add docs<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for `Ipv4Addr` methods in a const context<commit_after>// run-pass

#![feature(ip)]
#![feature(const_ipv4)]

use std::net::Ipv4Addr;

fn main() {
    const IP_ADDRESS: Ipv4Addr = Ipv4Addr::new(127, 0, 0, 1);
    assert_eq!(IP_ADDRESS, Ipv4Addr::LOCALHOST);

    const OCTETS: [u8; 4] = IP_ADDRESS.octets();
    assert_eq!(OCTETS, [127, 0, 0, 1]);

    const IS_UNSPECIFIED : bool = IP_ADDRESS.is_unspecified();
    assert!(!IS_UNSPECIFIED);

    const IS_LOOPBACK : bool = IP_ADDRESS.is_loopback();
    assert!(IS_LOOPBACK);

    const IS_PRIVATE : bool = IP_ADDRESS.is_private();
    assert!(!IS_PRIVATE);

    const IS_LINK_LOCAL : bool = IP_ADDRESS.is_link_local();
    assert!(!IS_LINK_LOCAL);

    const IS_SHARED : bool = IP_ADDRESS.is_shared();
    assert!(!IS_SHARED);

    const IS_IETF_PROTOCOL_ASSIGNMENT : bool = IP_ADDRESS.is_ietf_protocol_assignment();
    assert!(!IS_IETF_PROTOCOL_ASSIGNMENT);

    const IS_BENCHMARKING : bool = IP_ADDRESS.is_benchmarking();
    assert!(!IS_BENCHMARKING);

    const IS_MULTICAST : bool = IP_ADDRESS.is_multicast();
    assert!(!IS_MULTICAST);

    const IS_DOCUMENTATION : bool = IP_ADDRESS.is_documentation();
    assert!(!IS_DOCUMENTATION);
}
<|endoftext|>


<commit_before><commit_msg>Refactor imag-ids to fit new store iterator interface<commit_after><|endoftext|>


<commit_before><commit_msg>Auto merge of #69744 - ecstatic-morse:fix-enum-discr-effect-test, r=oli-obk<commit_after>// ignore-wasm32-bare compiled with panic=abort by default

// Ensure that there are no drop terminators in `unwrap<T>` (except the one along the cleanup
// path).

fn unwrap<T>(opt: Option<T>) -> T {
    match opt {
        Some(x) => x,
        None => panic!(),
    }
}

fn main() {
    let _ = unwrap(Some(1i32));
}

// END RUST SOURCE
// START rustc.unwrap.SimplifyCfg-elaborate-drops.after.mir
// fn unwrap(_1: std::option::Option<T>) -> T {
//     ...
//     bb0: {
//         ...
//         switchInt(move _2) -> [0isize: bb2, 1isize: bb4, otherwise: bb3];
//     }
//     bb1 (cleanup): {
//         resume;
//     }
//     bb2: {
//         ...
//         const std::rt::begin_panic::<&'static str>(const "explicit panic") -> bb5;
//     }
//     bb3: {
//         unreachable;
//     }
//     bb4: {
//         ...
//         return;
//     }
//     bb5 (cleanup): {
//         drop(_1) -> bb1;
//     }
// }
// END rustc.unwrap.SimplifyCfg-elaborate-drops.after.mir
<|endoftext|>


<commit_before><commit_msg>Add test for #70121<commit_after>// check-pass

#![feature(type_alias_impl_trait)]

pub type Successors<'a> = impl Iterator<Item = &'a ()>;

pub fn f<'a>() -> Successors<'a> {
    None.into_iter()
}

pub trait Tr {
    type Item;
}

impl<'a> Tr for &'a () {
    type Item = Successors<'a>;
}

pub fn kazusa<'a>() -> <&'a () as Tr>::Item {
    None.into_iter()
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>add -r(reverse) option support<commit_after><|endoftext|>


<commit_before><commit_msg>feat(usart): add example for transmission using DMA<commit_after>#![feature(core)]
#![feature(no_std)]
#![no_std]

//! Transmit "Hello, world!" via USART1 (PA8) using the Channel 4 of DMA1.

extern crate core;
extern crate cortex;
extern crate stm32;

use core::prelude::*;

const CLOCK: u32 = 8_000_000;
const BAUD_RATE: u32 = 115_200;

#[no_mangle]
pub fn main() {
    let dma1 = stm32::peripheral::dma1();
    let gpioa = stm32::peripheral::gpioa();
    let nvic = cortex::peripheral::nvic();
    let rcc = stm32::peripheral::rcc();
    let usart1 = stm32::peripheral::usart1();

    // Enable GPIOA and USART1
    rcc.apb2enr.update(|apb2enr| {
        use stm32::rcc::apb2enr::prelude::*;

        apb2enr | IOPAEN | USART1EN
    });

    // Enable DMA1
    rcc.ahbenr.update(|ahbenr| {
        use stm32::rcc::ahbenr::prelude::*;

        ahbenr | DMA1EN
    });

    // Configure PA8 as USART1 TX
    gpioa.crh.update(|crh| {
        use stm32::gpio::crh::prelude::*;

        crh.configure(Pin::_9, Mode::Output(Alternate, PushPull, _2MHz))
    });

    // Enable USART and transmitter
    usart1.cr1.set({
        use stm32::usart::cr1::prelude::*;

        TE | UE
    });

    // Connect the USART1 transmission event to DMA
    usart1.cr3.set({
        use stm32::usart::cr3::prelude::*;

        DMAT
    });

    // Set baud rate
    usart1.brr.set({
        (CLOCK / BAUD_RATE) as u16
    });

    // Configure Channel 4 of DMA1
    dma1.ccr4.set({
        use stm32::dma::ccr::prelude::*;

        TCIE | DIR | MINC | PSIZE::_8 | MSIZE::_8
    });

    // Enqueue message in the DMA channel
    let message = "Hello, world!\n\r";

    dma1.cmar4.set(message.as_ptr() as u32);
    dma1.cndtr4.set(message.len() as u16);
    dma1.cpar4.set(&usart1.dr as *const _ as u32);

    // Enable DMA interrupt
    nvic.iser0.set({
        use cortex::nvic::iser0::prelude::*;

        _14  // DMA1_Channel4
    });

    // Start DMA transmission
    dma1.ccr4.update(|ccr| {
        use stm32::dma::ccr::prelude::*;

        ccr | EN
    });

    // Wait for interrupt
    cortex::asm::wfi();
}

#[no_mangle]
pub fn dma1_channel4() {
    let dma1 = stm32::peripheral::dma1();

    // Clear transmission complete flag
    dma1.ifcr.set({
        use stm32::dma::ifcr::prelude::*;

        CTCIF4
    });
}
<|endoftext|>


<commit_before>import T = inst::T;
import cmp::{eq, ord};

export min_value, max_value;
export min, max;
export add, sub, mul, div, rem;
export lt, le, eq, ne, ge, gt;
export is_positive, is_negative;
export is_nonpositive, is_nonnegative;
export range;
export compl;
export abs;
export parse_buf, from_str, to_str, to_str_bytes, str;
export num, ord, eq, times;

const min_value: T = -1 as T << (inst::bits - 1 as T);
const max_value: T = min_value - 1 as T;

pure fn min(&&x: T, &&y: T) -> T { if x < y { x } else { y } }
pure fn max(&&x: T, &&y: T) -> T { if x > y { x } else { y } }

pure fn add(&&x: T, &&y: T) -> T { x + y }
pure fn sub(&&x: T, &&y: T) -> T { x - y }
pure fn mul(&&x: T, &&y: T) -> T { x * y }
pure fn div(&&x: T, &&y: T) -> T { x / y }
pure fn rem(&&x: T, &&y: T) -> T { x % y }

pure fn lt(&&x: T, &&y: T) -> bool { x < y }
pure fn le(&&x: T, &&y: T) -> bool { x <= y }
pure fn eq(&&x: T, &&y: T) -> bool { x == y }
pure fn ne(&&x: T, &&y: T) -> bool { x != y }
pure fn ge(&&x: T, &&y: T) -> bool { x >= y }
pure fn gt(&&x: T, &&y: T) -> bool { x > y }

pure fn is_positive(x: T) -> bool { x > 0 as T }
pure fn is_negative(x: T) -> bool { x < 0 as T }
pure fn is_nonpositive(x: T) -> bool { x <= 0 as T }
pure fn is_nonnegative(x: T) -> bool { x >= 0 as T }

#[inline(always)]
/// Iterate over the range [`lo`..`hi`)
fn range(lo: T, hi: T, it: fn(T) -> bool) {
    let mut i = lo;
    while i < hi {
        if !it(i) { break }
        i += 1 as T;
    }
}

/// Computes the bitwise complement
pure fn compl(i: T) -> T {
    -1 as T ^ i
}

/// Computes the absolute value
// FIXME: abs should return an unsigned int (#2353)
pure fn abs(i: T) -> T {
    if is_negative(i) { -i } else { i }
}

/**
 * Parse a buffer of bytes
 *
 * # Arguments
 *
 * * buf - A byte buffer
 * * radix - The base of the number
 */
fn parse_buf(buf: ~[u8], radix: uint) -> option<T> {
    if vec::len(buf) == 0u { ret none; }
    let mut i = vec::len(buf) - 1u;
    let mut start = 0u;
    let mut power = 1 as T;

    if buf[0] == ('-' as u8) {
        power = -1 as T;
        start = 1u;
    }
    let mut n = 0 as T;
    loop {
        alt char::to_digit(buf[i] as char, radix) {
          some(d) { n += (d as T) * power; }
          none { ret none; }
        }
        power *= radix as T;
        if i <= start { ret some(n); }
        i -= 1u;
    };
}

/// Parse a string to an int
fn from_str(s: str) -> option<T> { parse_buf(str::bytes(s), 10u) }

/// Convert to a string in a given base
fn to_str(n: T, radix: uint) -> str {
    do to_str_bytes(n, radix) |slice| {
        do vec::unpack_slice(slice) |p, len| {
            unsafe { str::unsafe::from_buf_len(p, len) }
        }
    }
}

fn to_str_bytes<U>(n: T, radix: uint, f: fn(v: &[u8]) -> U) -> U {
    if n < 0 as T {
        uint::to_str_bytes(true, -n as uint, radix, f)
    } else {
        uint::to_str_bytes(false, n as uint, radix, f)
    }
}

/// Convert to a string
fn str(i: T) -> str { ret to_str(i, 10u); }

impl ord of ord for T {
    fn lt(&&other: T) -> bool {
        ret self < other;
    }
}

impl eq of eq for T {
    fn eq(&&other: T) -> bool {
        ret self == other;
    }
}

impl num of num::num for T {
    fn add(&&other: T)    -> T { ret self + other; }
    fn sub(&&other: T)    -> T { ret self - other; }
    fn mul(&&other: T)    -> T { ret self * other; }
    fn div(&&other: T)    -> T { ret self / other; }
    fn modulo(&&other: T) -> T { ret self % other; }
    fn neg()              -> T { ret -self;        }

    fn to_int()         -> int { ret self as int; }
    fn from_int(n: int) -> T   { ret n as T;      }
}

impl times of iter::times for T {
    #[inline(always)]
    #[doc = "A convenience form for basic iteration. Given a variable `x` \
        of any numeric type, the expression `for x.times { /* anything */ }` \
        will execute the given function exactly x times. If we assume that \
        `x` is an int, this is functionally equivalent to \
        `for int::range(0, x) |_i| { /* anything */ }`."]
    fn times(it: fn() -> bool) {
        if self < 0 {
            fail #fmt("The .times method expects a nonnegative number, \
                       but found %?", self);
        }
        let mut i = self;
        while i > 0 {
            if !it() { break }
            i -= 1;
        }
    }
}

// FIXME: Has alignment issues on windows and 32-bit linux (#2609)
#[test]
#[ignore]
fn test_from_str() {
    assert from_str("0") == some(0 as T);
    assert from_str("3") == some(3 as T);
    assert from_str("10") == some(10 as T);
    assert from_str("123456789") == some(123456789 as T);
    assert from_str("00100") == some(100 as T);

    assert from_str("-1") == some(-1 as T);
    assert from_str("-3") == some(-3 as T);
    assert from_str("-10") == some(-10 as T);
    assert from_str("-123456789") == some(-123456789 as T);
    assert from_str("-00100") == some(-100 as T);

    assert from_str(" ") == none;
    assert from_str("x") == none;
}

// FIXME: Has alignment issues on windows and 32-bit linux (#2609)
#[test]
#[ignore]
fn test_parse_buf() {
    import str::bytes;
    assert parse_buf(bytes("123"), 10u) == some(123 as T);
    assert parse_buf(bytes("1001"), 2u) == some(9 as T);
    assert parse_buf(bytes("123"), 8u) == some(83 as T);
    assert parse_buf(bytes("123"), 16u) == some(291 as T);
    assert parse_buf(bytes("ffff"), 16u) == some(65535 as T);
    assert parse_buf(bytes("FFFF"), 16u) == some(65535 as T);
    assert parse_buf(bytes("z"), 36u) == some(35 as T);
    assert parse_buf(bytes("Z"), 36u) == some(35 as T);

    assert parse_buf(bytes("-123"), 10u) == some(-123 as T);
    assert parse_buf(bytes("-1001"), 2u) == some(-9 as T);
    assert parse_buf(bytes("-123"), 8u) == some(-83 as T);
    assert parse_buf(bytes("-123"), 16u) == some(-291 as T);
    assert parse_buf(bytes("-ffff"), 16u) == some(-65535 as T);
    assert parse_buf(bytes("-FFFF"), 16u) == some(-65535 as T);
    assert parse_buf(bytes("-z"), 36u) == some(-35 as T);
    assert parse_buf(bytes("-Z"), 36u) == some(-35 as T);

    assert parse_buf(str::bytes("Z"), 35u) == none;
    assert parse_buf(str::bytes("-9"), 2u) == none;
}

#[test]
fn test_to_str() {
    import str::eq;
    assert (eq(to_str(0 as T, 10u), "0"));
    assert (eq(to_str(1 as T, 10u), "1"));
    assert (eq(to_str(-1 as T, 10u), "-1"));
    assert (eq(to_str(127 as T, 16u), "7f"));
    assert (eq(to_str(100 as T, 10u), "100"));
}

#[test]
fn test_ifaces() {
    fn test<U:num::num>(ten: U) {
        assert (ten.to_int() == 10);

        let two = ten.from_int(2);
        assert (two.to_int() == 2);

        assert (ten.add(two) == ten.from_int(12));
        assert (ten.sub(two) == ten.from_int(8));
        assert (ten.mul(two) == ten.from_int(20));
        assert (ten.div(two) == ten.from_int(5));
        assert (ten.modulo(two) == ten.from_int(0));
        assert (ten.neg() == ten.from_int(-10));
    }

    test(10 as T);
}

#[test]
fn test_times() {
    let ten = 10 as T;
    let mut accum = 0;
    for ten.times { accum += 1; }
    assert (accum == 10);
}

#[test]
#[should_fail]
fn test_times_negative() {
    for (-10).times { log(error, "nope!"); }
}
<commit_msg>Ignore a should_fail test on windows<commit_after>import T = inst::T;
import cmp::{eq, ord};

export min_value, max_value;
export min, max;
export add, sub, mul, div, rem;
export lt, le, eq, ne, ge, gt;
export is_positive, is_negative;
export is_nonpositive, is_nonnegative;
export range;
export compl;
export abs;
export parse_buf, from_str, to_str, to_str_bytes, str;
export num, ord, eq, times;

const min_value: T = -1 as T << (inst::bits - 1 as T);
const max_value: T = min_value - 1 as T;

pure fn min(&&x: T, &&y: T) -> T { if x < y { x } else { y } }
pure fn max(&&x: T, &&y: T) -> T { if x > y { x } else { y } }

pure fn add(&&x: T, &&y: T) -> T { x + y }
pure fn sub(&&x: T, &&y: T) -> T { x - y }
pure fn mul(&&x: T, &&y: T) -> T { x * y }
pure fn div(&&x: T, &&y: T) -> T { x / y }
pure fn rem(&&x: T, &&y: T) -> T { x % y }

pure fn lt(&&x: T, &&y: T) -> bool { x < y }
pure fn le(&&x: T, &&y: T) -> bool { x <= y }
pure fn eq(&&x: T, &&y: T) -> bool { x == y }
pure fn ne(&&x: T, &&y: T) -> bool { x != y }
pure fn ge(&&x: T, &&y: T) -> bool { x >= y }
pure fn gt(&&x: T, &&y: T) -> bool { x > y }

pure fn is_positive(x: T) -> bool { x > 0 as T }
pure fn is_negative(x: T) -> bool { x < 0 as T }
pure fn is_nonpositive(x: T) -> bool { x <= 0 as T }
pure fn is_nonnegative(x: T) -> bool { x >= 0 as T }

#[inline(always)]
/// Iterate over the range [`lo`..`hi`)
fn range(lo: T, hi: T, it: fn(T) -> bool) {
    let mut i = lo;
    while i < hi {
        if !it(i) { break }
        i += 1 as T;
    }
}

/// Computes the bitwise complement
pure fn compl(i: T) -> T {
    -1 as T ^ i
}

/// Computes the absolute value
// FIXME: abs should return an unsigned int (#2353)
pure fn abs(i: T) -> T {
    if is_negative(i) { -i } else { i }
}

/**
 * Parse a buffer of bytes
 *
 * # Arguments
 *
 * * buf - A byte buffer
 * * radix - The base of the number
 */
fn parse_buf(buf: ~[u8], radix: uint) -> option<T> {
    if vec::len(buf) == 0u { ret none; }
    let mut i = vec::len(buf) - 1u;
    let mut start = 0u;
    let mut power = 1 as T;

    if buf[0] == ('-' as u8) {
        power = -1 as T;
        start = 1u;
    }
    let mut n = 0 as T;
    loop {
        alt char::to_digit(buf[i] as char, radix) {
          some(d) { n += (d as T) * power; }
          none { ret none; }
        }
        power *= radix as T;
        if i <= start { ret some(n); }
        i -= 1u;
    };
}

/// Parse a string to an int
fn from_str(s: str) -> option<T> { parse_buf(str::bytes(s), 10u) }

/// Convert to a string in a given base
fn to_str(n: T, radix: uint) -> str {
    do to_str_bytes(n, radix) |slice| {
        do vec::unpack_slice(slice) |p, len| {
            unsafe { str::unsafe::from_buf_len(p, len) }
        }
    }
}

fn to_str_bytes<U>(n: T, radix: uint, f: fn(v: &[u8]) -> U) -> U {
    if n < 0 as T {
        uint::to_str_bytes(true, -n as uint, radix, f)
    } else {
        uint::to_str_bytes(false, n as uint, radix, f)
    }
}

/// Convert to a string
fn str(i: T) -> str { ret to_str(i, 10u); }

impl ord of ord for T {
    fn lt(&&other: T) -> bool {
        ret self < other;
    }
}

impl eq of eq for T {
    fn eq(&&other: T) -> bool {
        ret self == other;
    }
}

impl num of num::num for T {
    fn add(&&other: T)    -> T { ret self + other; }
    fn sub(&&other: T)    -> T { ret self - other; }
    fn mul(&&other: T)    -> T { ret self * other; }
    fn div(&&other: T)    -> T { ret self / other; }
    fn modulo(&&other: T) -> T { ret self % other; }
    fn neg()              -> T { ret -self;        }

    fn to_int()         -> int { ret self as int; }
    fn from_int(n: int) -> T   { ret n as T;      }
}

impl times of iter::times for T {
    #[inline(always)]
    #[doc = "A convenience form for basic iteration. Given a variable `x` \
        of any numeric type, the expression `for x.times { /* anything */ }` \
        will execute the given function exactly x times. If we assume that \
        `x` is an int, this is functionally equivalent to \
        `for int::range(0, x) |_i| { /* anything */ }`."]
    fn times(it: fn() -> bool) {
        if self < 0 {
            fail #fmt("The .times method expects a nonnegative number, \
                       but found %?", self);
        }
        let mut i = self;
        while i > 0 {
            if !it() { break }
            i -= 1;
        }
    }
}

// FIXME: Has alignment issues on windows and 32-bit linux (#2609)
#[test]
#[ignore]
fn test_from_str() {
    assert from_str("0") == some(0 as T);
    assert from_str("3") == some(3 as T);
    assert from_str("10") == some(10 as T);
    assert from_str("123456789") == some(123456789 as T);
    assert from_str("00100") == some(100 as T);

    assert from_str("-1") == some(-1 as T);
    assert from_str("-3") == some(-3 as T);
    assert from_str("-10") == some(-10 as T);
    assert from_str("-123456789") == some(-123456789 as T);
    assert from_str("-00100") == some(-100 as T);

    assert from_str(" ") == none;
    assert from_str("x") == none;
}

// FIXME: Has alignment issues on windows and 32-bit linux (#2609)
#[test]
#[ignore]
fn test_parse_buf() {
    import str::bytes;
    assert parse_buf(bytes("123"), 10u) == some(123 as T);
    assert parse_buf(bytes("1001"), 2u) == some(9 as T);
    assert parse_buf(bytes("123"), 8u) == some(83 as T);
    assert parse_buf(bytes("123"), 16u) == some(291 as T);
    assert parse_buf(bytes("ffff"), 16u) == some(65535 as T);
    assert parse_buf(bytes("FFFF"), 16u) == some(65535 as T);
    assert parse_buf(bytes("z"), 36u) == some(35 as T);
    assert parse_buf(bytes("Z"), 36u) == some(35 as T);

    assert parse_buf(bytes("-123"), 10u) == some(-123 as T);
    assert parse_buf(bytes("-1001"), 2u) == some(-9 as T);
    assert parse_buf(bytes("-123"), 8u) == some(-83 as T);
    assert parse_buf(bytes("-123"), 16u) == some(-291 as T);
    assert parse_buf(bytes("-ffff"), 16u) == some(-65535 as T);
    assert parse_buf(bytes("-FFFF"), 16u) == some(-65535 as T);
    assert parse_buf(bytes("-z"), 36u) == some(-35 as T);
    assert parse_buf(bytes("-Z"), 36u) == some(-35 as T);

    assert parse_buf(str::bytes("Z"), 35u) == none;
    assert parse_buf(str::bytes("-9"), 2u) == none;
}

#[test]
fn test_to_str() {
    import str::eq;
    assert (eq(to_str(0 as T, 10u), "0"));
    assert (eq(to_str(1 as T, 10u), "1"));
    assert (eq(to_str(-1 as T, 10u), "-1"));
    assert (eq(to_str(127 as T, 16u), "7f"));
    assert (eq(to_str(100 as T, 10u), "100"));
}

#[test]
fn test_ifaces() {
    fn test<U:num::num>(ten: U) {
        assert (ten.to_int() == 10);

        let two = ten.from_int(2);
        assert (two.to_int() == 2);

        assert (ten.add(two) == ten.from_int(12));
        assert (ten.sub(two) == ten.from_int(8));
        assert (ten.mul(two) == ten.from_int(20));
        assert (ten.div(two) == ten.from_int(5));
        assert (ten.modulo(two) == ten.from_int(0));
        assert (ten.neg() == ten.from_int(-10));
    }

    test(10 as T);
}

#[test]
fn test_times() {
    let ten = 10 as T;
    let mut accum = 0;
    for ten.times { accum += 1; }
    assert (accum == 10);
}

#[test]
#[should_fail]
#[ignore(cfg(windows))]
fn test_times_negative() {
    for (-10).times { log(error, "nope!"); }
}
<|endoftext|>


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

use ops::*;

use intrinsics::{overflowing_add, overflowing_sub, overflowing_mul};

use intrinsics::{i8_add_with_overflow, u8_add_with_overflow};
use intrinsics::{i16_add_with_overflow, u16_add_with_overflow};
use intrinsics::{i32_add_with_overflow, u32_add_with_overflow};
use intrinsics::{i64_add_with_overflow, u64_add_with_overflow};
use intrinsics::{i8_sub_with_overflow, u8_sub_with_overflow};
use intrinsics::{i16_sub_with_overflow, u16_sub_with_overflow};
use intrinsics::{i32_sub_with_overflow, u32_sub_with_overflow};
use intrinsics::{i64_sub_with_overflow, u64_sub_with_overflow};
use intrinsics::{i8_mul_with_overflow, u8_mul_with_overflow};
use intrinsics::{i16_mul_with_overflow, u16_mul_with_overflow};
use intrinsics::{i32_mul_with_overflow, u32_mul_with_overflow};
use intrinsics::{i64_mul_with_overflow, u64_mul_with_overflow};

pub trait WrappingOps {
    fn wrapping_add(self, rhs: Self) -> Self;
    fn wrapping_sub(self, rhs: Self) -> Self;
    fn wrapping_mul(self, rhs: Self) -> Self;
}

#[unstable(feature = "core", reason = "may be removed, renamed, or relocated")]
pub trait OverflowingOps {
    fn overflowing_add(self, rhs: Self) -> (Self, bool);
    fn overflowing_sub(self, rhs: Self) -> (Self, bool);
    fn overflowing_mul(self, rhs: Self) -> (Self, bool);
}

macro_rules! wrapping_impl {
    ($($t:ty)*) => ($(
        impl WrappingOps for $t {
            #[inline(always)]
            fn wrapping_add(self, rhs: $t) -> $t {
                unsafe {
                    overflowing_add(self, rhs)
                }
            }
            #[inline(always)]
            fn wrapping_sub(self, rhs: $t) -> $t {
                unsafe {
                    overflowing_sub(self, rhs)
                }
            }
            #[inline(always)]
            fn wrapping_mul(self, rhs: $t) -> $t {
                unsafe {
                    overflowing_mul(self, rhs)
                }
            }
        }
    )*)
}

wrapping_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 }

#[unstable(feature = "core", reason = "may be removed, renamed, or relocated")]
#[derive(PartialEq,Eq,PartialOrd,Ord,Clone,Copy)]
pub struct Wrapping<T>(pub T);

impl<T:WrappingOps> Add for Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline(always)]
    fn add(self, other: Wrapping<T>) -> Wrapping<T> {
        Wrapping(self.0.wrapping_add(other.0))
    }
}

impl<T:WrappingOps> Sub for Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline(always)]
    fn sub(self, other: Wrapping<T>) -> Wrapping<T> {
        Wrapping(self.0.wrapping_sub(other.0))
    }
}

impl<T:WrappingOps> Mul for Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline(always)]
    fn mul(self, other: Wrapping<T>) -> Wrapping<T> {
        Wrapping(self.0.wrapping_mul(other.0))
    }
}

impl<T:WrappingOps+Not<Output=T>> Not for Wrapping<T> {
    type Output = Wrapping<T>;

    fn not(self) -> Wrapping<T> {
        Wrapping(!self.0)
    }
}

impl<T:WrappingOps+BitXor<Output=T>> BitXor for Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline(always)]
    fn bitxor(self, other: Wrapping<T>) -> Wrapping<T> {
        Wrapping(self.0 ^ other.0)
    }
}

impl<T:WrappingOps+BitOr<Output=T>> BitOr for Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline(always)]
    fn bitor(self, other: Wrapping<T>) -> Wrapping<T> {
        Wrapping(self.0 | other.0)
    }
}

impl<T:WrappingOps+BitAnd<Output=T>> BitAnd for Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline(always)]
    fn bitand(self, other: Wrapping<T>) -> Wrapping<T> {
        Wrapping(self.0 & other.0)
    }
}

impl<T:WrappingOps+Shl<uint,Output=T>> Shl<uint> for Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline(always)]
    fn shl(self, other: uint) -> Wrapping<T> {
        Wrapping(self.0 << other)
    }
}

impl<T:WrappingOps+Shr<uint,Output=T>> Shr<uint> for Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline(always)]
    fn shr(self, other: uint) -> Wrapping<T> {
        Wrapping(self.0 >> other)
    }
}

macro_rules! overflowing_impl {
    ($($t:ident)*) => ($(
        impl OverflowingOps for $t {
            #[inline(always)]
            fn overflowing_add(self, rhs: $t) -> ($t, bool) {
                unsafe {
                    concat_idents!($t, _add_with_overflow)(self, rhs)
                }
            }
            #[inline(always)]
            fn overflowing_sub(self, rhs: $t) -> ($t, bool) {
                unsafe {
                    concat_idents!($t, _sub_with_overflow)(self, rhs)
                }
            }
            #[inline(always)]
            fn overflowing_mul(self, rhs: $t) -> ($t, bool) {
                unsafe {
                    concat_idents!($t, _mul_with_overflow)(self, rhs)
                }
            }
        }
    )*)
}

overflowing_impl! { u8 u16 u32 u64 i8 i16 i32 i64 }

#[cfg(target_pointer_width = "64")]
impl OverflowingOps for usize {
    #[inline(always)]
    fn overflowing_add(self, rhs: usize) -> (usize, bool) {
        unsafe {
            let res = u64_add_with_overflow(self as u64, rhs as u64);
            (res.0 as usize, res.1)
        }
    }
    #[inline(always)]
    fn overflowing_sub(self, rhs: usize) -> (usize, bool) {
        unsafe {
            let res = u64_sub_with_overflow(self as u64, rhs as u64);
            (res.0 as usize, res.1)
        }
    }
    #[inline(always)]
    fn overflowing_mul(self, rhs: usize) -> (usize, bool) {
        unsafe {
            let res = u64_mul_with_overflow(self as u64, rhs as u64);
            (res.0 as usize, res.1)
        }
    }
}

#[cfg(target_pointer_width = "32")]
impl OverflowingOps for usize {
    #[inline(always)]
    fn overflowing_add(self, rhs: usize) -> (usize, bool) {
        unsafe {
            let res = u32_add_with_overflow(self as u32, rhs as u32);
            (res.0 as usize, res.1)
        }
    }
    #[inline(always)]
    fn overflowing_sub(self, rhs: usize) -> (usize, bool) {
        unsafe {
            let res = u32_sub_with_overflow(self as u32, rhs as u32);
            (res.0 as usize, res.1)
        }
    }
    #[inline(always)]
    fn overflowing_mul(self, rhs: usize) -> (usize, bool) {
        unsafe {
            let res = u32_mul_with_overflow(self as u32, rhs as u32);
            (res.0 as usize, res.1)
        }
    }
}

#[cfg(target_pointer_width = "64")]
impl OverflowingOps for isize {
    #[inline(always)]
    fn overflowing_add(self, rhs: isize) -> (isize, bool) {
        unsafe {
            let res = i64_add_with_overflow(self as i64, rhs as i64);
            (res.0 as isize, res.1)
        }
    }
    #[inline(always)]
    fn overflowing_sub(self, rhs: isize) -> (isize, bool) {
        unsafe {
            let res = i64_sub_with_overflow(self as i64, rhs as i64);
            (res.0 as isize, res.1)
        }
    }
    #[inline(always)]
    fn overflowing_mul(self, rhs: isize) -> (isize, bool) {
        unsafe {
            let res = i64_mul_with_overflow(self as i64, rhs as i64);
            (res.0 as isize, res.1)
        }
    }
}

#[cfg(target_pointer_width = "32")]
impl OverflowingOps for isize {
    #[inline(always)]
    fn overflowing_add(self, rhs: isize) -> (isize, bool) {
        unsafe {
            let res = i32_add_with_overflow(self as i32, rhs as i32);
            (res.0 as isize, res.1)
        }
    }
    #[inline(always)]
    fn overflowing_sub(self, rhs: isize) -> (isize, bool) {
        unsafe {
            let res = i32_sub_with_overflow(self as i32, rhs as i32);
            (res.0 as isize, res.1)
        }
    }
    #[inline(always)]
    fn overflowing_mul(self, rhs: isize) -> (isize, bool) {
        unsafe {
            let res = i32_mul_with_overflow(self as i32, rhs as i32);
            (res.0 as isize, res.1)
        }
    }
}
<commit_msg>rollup merge of #23780: ruud-v-a/wrapping<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(missing_docs)]

use ops::*;

use intrinsics::{overflowing_add, overflowing_sub, overflowing_mul};

use intrinsics::{i8_add_with_overflow, u8_add_with_overflow};
use intrinsics::{i16_add_with_overflow, u16_add_with_overflow};
use intrinsics::{i32_add_with_overflow, u32_add_with_overflow};
use intrinsics::{i64_add_with_overflow, u64_add_with_overflow};
use intrinsics::{i8_sub_with_overflow, u8_sub_with_overflow};
use intrinsics::{i16_sub_with_overflow, u16_sub_with_overflow};
use intrinsics::{i32_sub_with_overflow, u32_sub_with_overflow};
use intrinsics::{i64_sub_with_overflow, u64_sub_with_overflow};
use intrinsics::{i8_mul_with_overflow, u8_mul_with_overflow};
use intrinsics::{i16_mul_with_overflow, u16_mul_with_overflow};
use intrinsics::{i32_mul_with_overflow, u32_mul_with_overflow};
use intrinsics::{i64_mul_with_overflow, u64_mul_with_overflow};

pub trait WrappingOps {
    fn wrapping_add(self, rhs: Self) -> Self;
    fn wrapping_sub(self, rhs: Self) -> Self;
    fn wrapping_mul(self, rhs: Self) -> Self;
}

#[unstable(feature = "core", reason = "may be removed, renamed, or relocated")]
pub trait OverflowingOps {
    fn overflowing_add(self, rhs: Self) -> (Self, bool);
    fn overflowing_sub(self, rhs: Self) -> (Self, bool);
    fn overflowing_mul(self, rhs: Self) -> (Self, bool);
}

macro_rules! wrapping_impl {
    ($($t:ty)*) => ($(
        impl WrappingOps for $t {
            #[inline(always)]
            fn wrapping_add(self, rhs: $t) -> $t {
                unsafe {
                    overflowing_add(self, rhs)
                }
            }
            #[inline(always)]
            fn wrapping_sub(self, rhs: $t) -> $t {
                unsafe {
                    overflowing_sub(self, rhs)
                }
            }
            #[inline(always)]
            fn wrapping_mul(self, rhs: $t) -> $t {
                unsafe {
                    overflowing_mul(self, rhs)
                }
            }
        }
    )*)
}

wrapping_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 }

#[unstable(feature = "core", reason = "may be removed, renamed, or relocated")]
#[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Copy)]
pub struct Wrapping<T>(pub T);

impl<T:WrappingOps> Add for Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline(always)]
    fn add(self, other: Wrapping<T>) -> Wrapping<T> {
        Wrapping(self.0.wrapping_add(other.0))
    }
}

impl<T:WrappingOps> Sub for Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline(always)]
    fn sub(self, other: Wrapping<T>) -> Wrapping<T> {
        Wrapping(self.0.wrapping_sub(other.0))
    }
}

impl<T:WrappingOps> Mul for Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline(always)]
    fn mul(self, other: Wrapping<T>) -> Wrapping<T> {
        Wrapping(self.0.wrapping_mul(other.0))
    }
}

impl<T:WrappingOps+Not<Output=T>> Not for Wrapping<T> {
    type Output = Wrapping<T>;

    fn not(self) -> Wrapping<T> {
        Wrapping(!self.0)
    }
}

impl<T:WrappingOps+BitXor<Output=T>> BitXor for Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline(always)]
    fn bitxor(self, other: Wrapping<T>) -> Wrapping<T> {
        Wrapping(self.0 ^ other.0)
    }
}

impl<T:WrappingOps+BitOr<Output=T>> BitOr for Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline(always)]
    fn bitor(self, other: Wrapping<T>) -> Wrapping<T> {
        Wrapping(self.0 | other.0)
    }
}

impl<T:WrappingOps+BitAnd<Output=T>> BitAnd for Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline(always)]
    fn bitand(self, other: Wrapping<T>) -> Wrapping<T> {
        Wrapping(self.0 & other.0)
    }
}

impl<T:WrappingOps+Shl<uint,Output=T>> Shl<uint> for Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline(always)]
    fn shl(self, other: uint) -> Wrapping<T> {
        Wrapping(self.0 << other)
    }
}

impl<T:WrappingOps+Shr<uint,Output=T>> Shr<uint> for Wrapping<T> {
    type Output = Wrapping<T>;

    #[inline(always)]
    fn shr(self, other: uint) -> Wrapping<T> {
        Wrapping(self.0 >> other)
    }
}

macro_rules! overflowing_impl {
    ($($t:ident)*) => ($(
        impl OverflowingOps for $t {
            #[inline(always)]
            fn overflowing_add(self, rhs: $t) -> ($t, bool) {
                unsafe {
                    concat_idents!($t, _add_with_overflow)(self, rhs)
                }
            }
            #[inline(always)]
            fn overflowing_sub(self, rhs: $t) -> ($t, bool) {
                unsafe {
                    concat_idents!($t, _sub_with_overflow)(self, rhs)
                }
            }
            #[inline(always)]
            fn overflowing_mul(self, rhs: $t) -> ($t, bool) {
                unsafe {
                    concat_idents!($t, _mul_with_overflow)(self, rhs)
                }
            }
        }
    )*)
}

overflowing_impl! { u8 u16 u32 u64 i8 i16 i32 i64 }

#[cfg(target_pointer_width = "64")]
impl OverflowingOps for usize {
    #[inline(always)]
    fn overflowing_add(self, rhs: usize) -> (usize, bool) {
        unsafe {
            let res = u64_add_with_overflow(self as u64, rhs as u64);
            (res.0 as usize, res.1)
        }
    }
    #[inline(always)]
    fn overflowing_sub(self, rhs: usize) -> (usize, bool) {
        unsafe {
            let res = u64_sub_with_overflow(self as u64, rhs as u64);
            (res.0 as usize, res.1)
        }
    }
    #[inline(always)]
    fn overflowing_mul(self, rhs: usize) -> (usize, bool) {
        unsafe {
            let res = u64_mul_with_overflow(self as u64, rhs as u64);
            (res.0 as usize, res.1)
        }
    }
}

#[cfg(target_pointer_width = "32")]
impl OverflowingOps for usize {
    #[inline(always)]
    fn overflowing_add(self, rhs: usize) -> (usize, bool) {
        unsafe {
            let res = u32_add_with_overflow(self as u32, rhs as u32);
            (res.0 as usize, res.1)
        }
    }
    #[inline(always)]
    fn overflowing_sub(self, rhs: usize) -> (usize, bool) {
        unsafe {
            let res = u32_sub_with_overflow(self as u32, rhs as u32);
            (res.0 as usize, res.1)
        }
    }
    #[inline(always)]
    fn overflowing_mul(self, rhs: usize) -> (usize, bool) {
        unsafe {
            let res = u32_mul_with_overflow(self as u32, rhs as u32);
            (res.0 as usize, res.1)
        }
    }
}

#[cfg(target_pointer_width = "64")]
impl OverflowingOps for isize {
    #[inline(always)]
    fn overflowing_add(self, rhs: isize) -> (isize, bool) {
        unsafe {
            let res = i64_add_with_overflow(self as i64, rhs as i64);
            (res.0 as isize, res.1)
        }
    }
    #[inline(always)]
    fn overflowing_sub(self, rhs: isize) -> (isize, bool) {
        unsafe {
            let res = i64_sub_with_overflow(self as i64, rhs as i64);
            (res.0 as isize, res.1)
        }
    }
    #[inline(always)]
    fn overflowing_mul(self, rhs: isize) -> (isize, bool) {
        unsafe {
            let res = i64_mul_with_overflow(self as i64, rhs as i64);
            (res.0 as isize, res.1)
        }
    }
}

#[cfg(target_pointer_width = "32")]
impl OverflowingOps for isize {
    #[inline(always)]
    fn overflowing_add(self, rhs: isize) -> (isize, bool) {
        unsafe {
            let res = i32_add_with_overflow(self as i32, rhs as i32);
            (res.0 as isize, res.1)
        }
    }
    #[inline(always)]
    fn overflowing_sub(self, rhs: isize) -> (isize, bool) {
        unsafe {
            let res = i32_sub_with_overflow(self as i32, rhs as i32);
            (res.0 as isize, res.1)
        }
    }
    #[inline(always)]
    fn overflowing_mul(self, rhs: isize) -> (isize, bool) {
        unsafe {
            let res = i32_mul_with_overflow(self as i32, rhs as i32);
            (res.0 as isize, res.1)
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Make store_raw unsafe<commit_after><|endoftext|>


<commit_before><commit_msg>should now get pink rays in output<commit_after><|endoftext|>


<commit_before><commit_msg>Got the messages module to compile<commit_after><|endoftext|>


<commit_before><commit_msg>Add println to normal; commented by default<commit_after><|endoftext|>


<commit_before>// Copyright 2014 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.

//! BED reading and writing.
//!
//! # Example
//!
//! ```
//! use std::io;
//! use bio::io::bed;
//! let example = b"1\t5\t5000\tname1\t0.5".as_slice();
//! let mut reader = bed::Reader::new(example);
//! let mut writer = bed::Writer::new(vec![]);
//! for record in reader.records() {
//!     let rec = record.ok().expect("Error reading record.");
//!     println!("{}", rec.chrom());
//!     writer.write(rec);
//! }
//! ```

use std::io;
use std::path;
use std::fs;

use csv;

/// A BED reader.
pub struct Reader<R: io::Read> {
    inner: csv::Reader<R>,
}

impl<R: io::Read> Reader<R> {
    pub fn new(reader: R) -> Self {
        Reader { inner: csv::Reader::from_reader(reader).delimiter(b'\t').has_headers(false) }
    }

    pub fn from_file<P: path::AsPath>(path: P) -> io::Result<Reader<fs::File>> {
        fs::File::open(path).map(|f| Reader::new(f))
    }

    pub fn records(&mut self) -> Records<R> {
        Records { inner: self.inner.decode() }
    }
}

pub struct Records<'a, R: 'a +io::Read> {
    inner: csv::DecodedRecords<'a, R, (String, u64, u64, Vec<String>)>
}

impl<'a, R: io::Read> Iterator for Records<'a, R> {
    type Item = csv::Result<Record>;

    fn next(&mut self) -> Option<csv::Result<Record>> {
        self.inner.next().map(|res| match res {
            Ok((chrom, start, end, aux)) => Ok(Record {
                chrom: chrom, start: start, end: end, aux: aux
            }),
            Err(e) => Err(e)
        })
    }
}

/// A BED writer.
pub struct Writer<W: io::Write> {
    inner: csv::Writer<W>,
}

impl<W: io::Write> Writer<W> {
    pub fn new(writer: W) -> Self {
        Writer { inner: csv::Writer::from_writer(writer).delimiter(b'\t').flexible(true) }
    }

    pub fn from_file<P: path::AsPath>(path: P) -> io::Result<Writer<fs::File>> {
        fs::File::create(path).map(|f| Writer::new(f))
    }

    pub fn write(&mut self, record: Record) -> csv::Result<()> {
        if record.aux.len() == 0 {
            self.inner.encode((record.chrom, record.start, record.end))
        }
        else {
            self.inner.encode(record)
        }
    }
}

/// A BED record as defined by BEDtools (http://bedtools.readthedocs.org/en/latest/content/general-usage.html)
#[derive(RustcEncodable)]
pub struct Record {
    chrom: String,
    start: u64,
    end: u64,
    aux: Vec<String>
}

impl Record {
    pub fn new() -> Self {
        Record { chrom: "".to_string(), start: 0, end: 0, aux: vec![] }
    }

    pub fn chrom(&self) -> &str {
        &self.chrom
    }

    /// Start position of feature (0-based).
    pub fn start(&self) -> u64 {
        self.start
    }

    /// End position of feature (0-based, not included).
    pub fn end(&self) -> u64 {
        self.end
    }

    pub fn name(&self) -> Option<&str> {
        self.aux(3)
    }

    pub fn score(&self) -> Option<&str> {
        self.aux(4)
    }

    pub fn strand(&self) -> Option<Strand> {
        match self.aux(5) {
            Some("+") => Some(Strand::Forward),
            Some("-") => Some(Strand::Reverse),
            _         => None
        }
    }

    pub fn aux(&self, i: usize) -> Option<&str> {
        let j = i - 3;
        if j < self.aux.len() {
            Some(&self.aux[j])
        }
        else {
            None
        }
    }

    pub fn set_chrom(&mut self, chrom: &str) {
        self.chrom = chrom.to_string();
    }

    pub fn set_start(&mut self, start: u64) {
        self.start = start;
    }

    pub fn set_end(&mut self, end: u64) {
        self.end = end;
    }

    pub fn set_name(&mut self, name: &str) {
        if self.aux.len() < 1 {
            self.aux.push(name.to_string());
        }
        else {
            self.aux[0] = name.to_string();
        }
    }

    pub fn set_score(&mut self, score: &str) {
        if self.aux.len() < 1 {
            self.aux.push("".to_string());
        }
        if self.aux.len() < 2 {
            self.aux.push(score.to_string());
        }
        else {
            self.aux[1] = score.to_string();
        }
    }

    pub fn push_aux(&mut self, field: &str) {
        self.aux.push(field.to_string());
    }
}

pub enum Strand {
    Forward,
    Reverse,
}

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

    const BED_FILE: &'static [u8] = b"1\t5\t5000\tname1\tup
2\t3\t5005\tname2\tup
";

    #[test]
    fn test_reader() {
        let chroms = ["1", "2"];
        let starts = [5, 3];
        let ends = [5000, 5005];
        let names = ["name1", "name2"];
        let scores = ["up", "up"];

        let mut reader = Reader::new(BED_FILE);
        for (i, r) in reader.records().enumerate() {
            let record = r.ok().expect("Error reading record");
            assert_eq!(record.chrom(), chroms[i]);
            assert_eq!(record.start(), starts[i]);
            assert_eq!(record.end(), ends[i]);
            assert_eq!(record.name().expect("Error reading name"), names[i]);
            assert_eq!(record.score().expect("Error reading score"), scores[i]);
        }
    }

    #[test]
    fn test_writer() {
        let mut reader = Reader::new(BED_FILE);
        let mut writer = Writer::new(vec![]);
        for r in reader.records() {
            writer.write(r.ok().expect("Error reading record")).ok().expect("Error writing record");
        }
        assert_eq!(writer.inner.as_bytes(), BED_FILE);
    }
}
<commit_msg>Minor.<commit_after>// Copyright 2014 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.

//! BED reading and writing.
//!
//! # Example
//!
//! ```
//! use std::io;
//! use bio::io::bed;
//! let example = b"1\t5\t5000\tname1\t0.5".as_slice();
//! let mut reader = bed::Reader::new(example);
//! let mut writer = bed::Writer::new(vec![]);
//! for record in reader.records() {
//!     let rec = record.ok().expect("Error reading record.");
//!     println!("{}", rec.chrom());
//!     writer.write(rec).ok().expect("Error writing record.");
//! }
//! ```

use std::io;
use std::path;
use std::fs;

use csv;

/// A BED reader.
pub struct Reader<R: io::Read> {
    inner: csv::Reader<R>,
}

impl<R: io::Read> Reader<R> {
    pub fn new(reader: R) -> Self {
        Reader { inner: csv::Reader::from_reader(reader).delimiter(b'\t').has_headers(false) }
    }

    pub fn from_file<P: path::AsPath>(path: P) -> io::Result<Reader<fs::File>> {
        fs::File::open(path).map(|f| Reader::new(f))
    }

    pub fn records(&mut self) -> Records<R> {
        Records { inner: self.inner.decode() }
    }
}

pub struct Records<'a, R: 'a +io::Read> {
    inner: csv::DecodedRecords<'a, R, (String, u64, u64, Vec<String>)>
}

impl<'a, R: io::Read> Iterator for Records<'a, R> {
    type Item = csv::Result<Record>;

    fn next(&mut self) -> Option<csv::Result<Record>> {
        self.inner.next().map(|res| match res {
            Ok((chrom, start, end, aux)) => Ok(Record {
                chrom: chrom, start: start, end: end, aux: aux
            }),
            Err(e) => Err(e)
        })
    }
}

/// A BED writer.
pub struct Writer<W: io::Write> {
    inner: csv::Writer<W>,
}

impl<W: io::Write> Writer<W> {
    pub fn new(writer: W) -> Self {
        Writer { inner: csv::Writer::from_writer(writer).delimiter(b'\t').flexible(true) }
    }

    pub fn from_file<P: path::AsPath>(path: P) -> io::Result<Writer<fs::File>> {
        fs::File::create(path).map(|f| Writer::new(f))
    }

    pub fn write(&mut self, record: Record) -> csv::Result<()> {
        if record.aux.len() == 0 {
            self.inner.encode((record.chrom, record.start, record.end))
        }
        else {
            self.inner.encode(record)
        }
    }
}

/// A BED record as defined by BEDtools (http://bedtools.readthedocs.org/en/latest/content/general-usage.html)
#[derive(RustcEncodable)]
pub struct Record {
    chrom: String,
    start: u64,
    end: u64,
    aux: Vec<String>
}

impl Record {
    pub fn new() -> Self {
        Record { chrom: "".to_string(), start: 0, end: 0, aux: vec![] }
    }

    pub fn chrom(&self) -> &str {
        &self.chrom
    }

    /// Start position of feature (0-based).
    pub fn start(&self) -> u64 {
        self.start
    }

    /// End position of feature (0-based, not included).
    pub fn end(&self) -> u64 {
        self.end
    }

    pub fn name(&self) -> Option<&str> {
        self.aux(3)
    }

    pub fn score(&self) -> Option<&str> {
        self.aux(4)
    }

    pub fn strand(&self) -> Option<Strand> {
        match self.aux(5) {
            Some("+") => Some(Strand::Forward),
            Some("-") => Some(Strand::Reverse),
            _         => None
        }
    }

    pub fn aux(&self, i: usize) -> Option<&str> {
        let j = i - 3;
        if j < self.aux.len() {
            Some(&self.aux[j])
        }
        else {
            None
        }
    }

    pub fn set_chrom(&mut self, chrom: &str) {
        self.chrom = chrom.to_string();
    }

    pub fn set_start(&mut self, start: u64) {
        self.start = start;
    }

    pub fn set_end(&mut self, end: u64) {
        self.end = end;
    }

    pub fn set_name(&mut self, name: &str) {
        if self.aux.len() < 1 {
            self.aux.push(name.to_string());
        }
        else {
            self.aux[0] = name.to_string();
        }
    }

    pub fn set_score(&mut self, score: &str) {
        if self.aux.len() < 1 {
            self.aux.push("".to_string());
        }
        if self.aux.len() < 2 {
            self.aux.push(score.to_string());
        }
        else {
            self.aux[1] = score.to_string();
        }
    }

    pub fn push_aux(&mut self, field: &str) {
        self.aux.push(field.to_string());
    }
}

pub enum Strand {
    Forward,
    Reverse,
}

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

    const BED_FILE: &'static [u8] = b"1\t5\t5000\tname1\tup
2\t3\t5005\tname2\tup
";

    #[test]
    fn test_reader() {
        let chroms = ["1", "2"];
        let starts = [5, 3];
        let ends = [5000, 5005];
        let names = ["name1", "name2"];
        let scores = ["up", "up"];

        let mut reader = Reader::new(BED_FILE);
        for (i, r) in reader.records().enumerate() {
            let record = r.ok().expect("Error reading record");
            assert_eq!(record.chrom(), chroms[i]);
            assert_eq!(record.start(), starts[i]);
            assert_eq!(record.end(), ends[i]);
            assert_eq!(record.name().expect("Error reading name"), names[i]);
            assert_eq!(record.score().expect("Error reading score"), scores[i]);
        }
    }

    #[test]
    fn test_writer() {
        let mut reader = Reader::new(BED_FILE);
        let mut writer = Writer::new(vec![]);
        for r in reader.records() {
            writer.write(r.ok().expect("Error reading record")).ok().expect("Error writing record");
        }
        assert_eq!(writer.inner.as_bytes(), BED_FILE);
    }
}
<|endoftext|>


<commit_before><commit_msg>Added Light::State and its Effect, Point and Alert types.<commit_after><|endoftext|>


<commit_before>//! Complete fields in record literals and patterns.
use ide_db::SymbolKind;
use syntax::{ast::Expr, T};

use crate::{
    patterns::ImmediateLocation, CompletionContext, CompletionItem, CompletionItemKind,
    CompletionRelevance, Completions,
};

pub(crate) fn complete_record(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
    let missing_fields = match &ctx.completion_location {
        Some(
            ImmediateLocation::RecordExpr(record_expr)
            | ImmediateLocation::RecordExprUpdate(record_expr),
        ) => {
            let ty = ctx.sema.type_of_expr(&Expr::RecordExpr(record_expr.clone()));
            let default_trait = ctx.famous_defs().core_default_Default();
            let impl_default_trait = default_trait.zip(ty).map_or(false, |(default_trait, ty)| {
                ty.original.impls_trait(ctx.db, default_trait, &[])
            });

            let missing_fields = ctx.sema.record_literal_missing_fields(record_expr);
            if impl_default_trait && !missing_fields.is_empty() && ctx.path_qual().is_none() {
                let completion_text = "..Default::default()";
                let mut item =
                    CompletionItem::new(SymbolKind::Field, ctx.source_range(), completion_text);
                let completion_text =
                    completion_text.strip_prefix(ctx.token.text()).unwrap_or(completion_text);
                item.insert_text(completion_text).set_relevance(CompletionRelevance {
                    exact_postfix_snippet_match: true,
                    ..Default::default()
                });
                item.add_to(acc);
            }
            if ctx.previous_token_is(T![.]) {
                let mut item =
                    CompletionItem::new(CompletionItemKind::Snippet, ctx.source_range(), "..");
                item.insert_text(".");
                item.add_to(acc);
                return None;
            }
            missing_fields
        }
        Some(ImmediateLocation::RecordPat(record_pat)) => {
            ctx.sema.record_pattern_missing_fields(record_pat)
        }
        _ => return None,
    };

    for (field, ty) in missing_fields {
        acc.add_field(ctx, None, field, &ty);
    }

    Some(())
}

pub(crate) fn complete_record_literal(
    acc: &mut Completions,
    ctx: &CompletionContext,
) -> Option<()> {
    if !ctx.expects_expression() {
        return None;
    }

    if let hir::Adt::Struct(strukt) = ctx.expected_type.as_ref()?.as_adt()? {
        let module = if let Some(module) = ctx.module { module } else { strukt.module(ctx.db) };

        let path = module.find_use_path(ctx.db, hir::ModuleDef::from(strukt));

        acc.add_struct_literal(ctx, strukt, path, None);
    }

    Some(())
}

#[cfg(test)]
mod tests {
    use crate::tests::check_edit;

    #[test]
    fn literal_struct_completion_edit() {
        check_edit(
            "FooDesc {…}",
            r#"
struct FooDesc { pub bar: bool }

fn create_foo(foo_desc: &FooDesc) -> () { () }

fn baz() {
    let foo = create_foo(&$0);
}
            "#,
            r#"
struct FooDesc { pub bar: bool }

fn create_foo(foo_desc: &FooDesc) -> () { () }

fn baz() {
    let foo = create_foo(&FooDesc { bar: ${1:()} }$0);
}
            "#,
        )
    }

    #[test]
    fn literal_struct_completion_from_sub_modules() {
        check_edit(
            "Struct {…}",
            r#"
mod submod {
    pub struct Struct {
        pub a: u64,
    }
}

fn f() -> submod::Struct {
    Stru$0
}
            "#,
            r#"
mod submod {
    pub struct Struct {
        pub a: u64,
    }
}

fn f() -> submod::Struct {
    submod::Struct { a: ${1:()} }$0
}
            "#,
        )
    }

    #[test]
    fn literal_struct_complexion_module() {
        check_edit(
            "FooDesc {…}",
            r#"
mod _69latrick {
    pub struct FooDesc { pub six: bool, pub neuf: Vec<String>, pub bar: bool }
    pub fn create_foo(foo_desc: &FooDesc) -> () { () }
}

fn baz() {
    use _69latrick::*;

    let foo = create_foo(&$0);
}
            "#,
            r#"
mod _69latrick {
    pub struct FooDesc { pub six: bool, pub neuf: Vec<String>, pub bar: bool }
    pub fn create_foo(foo_desc: &FooDesc) -> () { () }
}

fn baz() {
    use _69latrick::*;

    let foo = create_foo(&FooDesc { six: ${1:()}, neuf: ${2:()}, bar: ${3:()} }$0);
}
            "#,
        );
    }

    #[test]
    fn default_completion_edit() {
        check_edit(
            "..Default::default()",
            r#"
//- minicore: default
struct Struct { foo: u32, bar: usize }

impl Default for Struct {
    fn default() -> Self {}
}

fn foo() {
    let other = Struct {
        foo: 5,
        .$0
    };
}
"#,
            r#"
struct Struct { foo: u32, bar: usize }

impl Default for Struct {
    fn default() -> Self {}
}

fn foo() {
    let other = Struct {
        foo: 5,
        ..Default::default()
    };
}
"#,
        );
        check_edit(
            "..Default::default()",
            r#"
//- minicore: default
struct Struct { foo: u32, bar: usize }

impl Default for Struct {
    fn default() -> Self {}
}

fn foo() {
    let other = Struct {
        foo: 5,
        $0
    };
}
"#,
            r#"
struct Struct { foo: u32, bar: usize }

impl Default for Struct {
    fn default() -> Self {}
}

fn foo() {
    let other = Struct {
        foo: 5,
        ..Default::default()
    };
}
"#,
        );
        check_edit(
            "..Default::default()",
            r#"
//- minicore: default
struct Struct { foo: u32, bar: usize }

impl Default for Struct {
    fn default() -> Self {}
}

fn foo() {
    let other = Struct {
        foo: 5,
        ..$0
    };
}
"#,
            r#"
struct Struct { foo: u32, bar: usize }

impl Default for Struct {
    fn default() -> Self {}
}

fn foo() {
    let other = Struct {
        foo: 5,
        ..Default::default()
    };
}
"#,
        );
    }
}
<commit_msg>fix: Fix qualfiied record literal completion triggering too eagerly<commit_after>//! Complete fields in record literals and patterns.
use ide_db::SymbolKind;
use syntax::{ast::Expr, T};

use crate::{
    patterns::ImmediateLocation, CompletionContext, CompletionItem, CompletionItemKind,
    CompletionRelevance, Completions,
};

pub(crate) fn complete_record(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
    let missing_fields = match &ctx.completion_location {
        Some(
            ImmediateLocation::RecordExpr(record_expr)
            | ImmediateLocation::RecordExprUpdate(record_expr),
        ) => {
            let ty = ctx.sema.type_of_expr(&Expr::RecordExpr(record_expr.clone()));
            let default_trait = ctx.famous_defs().core_default_Default();
            let impl_default_trait = default_trait.zip(ty).map_or(false, |(default_trait, ty)| {
                ty.original.impls_trait(ctx.db, default_trait, &[])
            });

            let missing_fields = ctx.sema.record_literal_missing_fields(record_expr);
            if impl_default_trait && !missing_fields.is_empty() && ctx.path_qual().is_none() {
                let completion_text = "..Default::default()";
                let mut item =
                    CompletionItem::new(SymbolKind::Field, ctx.source_range(), completion_text);
                let completion_text =
                    completion_text.strip_prefix(ctx.token.text()).unwrap_or(completion_text);
                item.insert_text(completion_text).set_relevance(CompletionRelevance {
                    exact_postfix_snippet_match: true,
                    ..Default::default()
                });
                item.add_to(acc);
            }
            if ctx.previous_token_is(T![.]) {
                let mut item =
                    CompletionItem::new(CompletionItemKind::Snippet, ctx.source_range(), "..");
                item.insert_text(".");
                item.add_to(acc);
                return None;
            }
            missing_fields
        }
        Some(ImmediateLocation::RecordPat(record_pat)) => {
            ctx.sema.record_pattern_missing_fields(record_pat)
        }
        _ => return None,
    };

    for (field, ty) in missing_fields {
        acc.add_field(ctx, None, field, &ty);
    }

    Some(())
}

pub(crate) fn complete_record_literal(
    acc: &mut Completions,
    ctx: &CompletionContext,
) -> Option<()> {
    if !ctx.expects_expression() {
        return None;
    }

    if let hir::Adt::Struct(strukt) = ctx.expected_type.as_ref()?.as_adt()? {
        if ctx.path_qual().is_none() {
            let module = if let Some(module) = ctx.module { module } else { strukt.module(ctx.db) };
            let path = module.find_use_path(ctx.db, hir::ModuleDef::from(strukt));

            acc.add_struct_literal(ctx, strukt, path, None);
        }
    }

    Some(())
}

#[cfg(test)]
mod tests {
    use crate::tests::check_edit;

    #[test]
    fn literal_struct_completion_edit() {
        check_edit(
            "FooDesc {…}",
            r#"
struct FooDesc { pub bar: bool }

fn create_foo(foo_desc: &FooDesc) -> () { () }

fn baz() {
    let foo = create_foo(&$0);
}
            "#,
            r#"
struct FooDesc { pub bar: bool }

fn create_foo(foo_desc: &FooDesc) -> () { () }

fn baz() {
    let foo = create_foo(&FooDesc { bar: ${1:()} }$0);
}
            "#,
        )
    }

    #[test]
    fn literal_struct_completion_from_sub_modules() {
        check_edit(
            "Struct {…}",
            r#"
mod submod {
    pub struct Struct {
        pub a: u64,
    }
}

fn f() -> submod::Struct {
    Stru$0
}
            "#,
            r#"
mod submod {
    pub struct Struct {
        pub a: u64,
    }
}

fn f() -> submod::Struct {
    submod::Struct { a: ${1:()} }$0
}
            "#,
        )
    }

    #[test]
    fn literal_struct_complexion_module() {
        check_edit(
            "FooDesc {…}",
            r#"
mod _69latrick {
    pub struct FooDesc { pub six: bool, pub neuf: Vec<String>, pub bar: bool }
    pub fn create_foo(foo_desc: &FooDesc) -> () { () }
}

fn baz() {
    use _69latrick::*;

    let foo = create_foo(&$0);
}
            "#,
            r#"
mod _69latrick {
    pub struct FooDesc { pub six: bool, pub neuf: Vec<String>, pub bar: bool }
    pub fn create_foo(foo_desc: &FooDesc) -> () { () }
}

fn baz() {
    use _69latrick::*;

    let foo = create_foo(&FooDesc { six: ${1:()}, neuf: ${2:()}, bar: ${3:()} }$0);
}
            "#,
        );
    }

    #[test]
    fn default_completion_edit() {
        check_edit(
            "..Default::default()",
            r#"
//- minicore: default
struct Struct { foo: u32, bar: usize }

impl Default for Struct {
    fn default() -> Self {}
}

fn foo() {
    let other = Struct {
        foo: 5,
        .$0
    };
}
"#,
            r#"
struct Struct { foo: u32, bar: usize }

impl Default for Struct {
    fn default() -> Self {}
}

fn foo() {
    let other = Struct {
        foo: 5,
        ..Default::default()
    };
}
"#,
        );
        check_edit(
            "..Default::default()",
            r#"
//- minicore: default
struct Struct { foo: u32, bar: usize }

impl Default for Struct {
    fn default() -> Self {}
}

fn foo() {
    let other = Struct {
        foo: 5,
        $0
    };
}
"#,
            r#"
struct Struct { foo: u32, bar: usize }

impl Default for Struct {
    fn default() -> Self {}
}

fn foo() {
    let other = Struct {
        foo: 5,
        ..Default::default()
    };
}
"#,
        );
        check_edit(
            "..Default::default()",
            r#"
//- minicore: default
struct Struct { foo: u32, bar: usize }

impl Default for Struct {
    fn default() -> Self {}
}

fn foo() {
    let other = Struct {
        foo: 5,
        ..$0
    };
}
"#,
            r#"
struct Struct { foo: u32, bar: usize }

impl Default for Struct {
    fn default() -> Self {}
}

fn foo() {
    let other = Struct {
        foo: 5,
        ..Default::default()
    };
}
"#,
        );
    }
}
<|endoftext|>


<commit_before><commit_msg>mutable reference in pattern matching<commit_after><|endoftext|>


<commit_before><commit_msg>bittwiddler: Test bitfragment variants<commit_after>use bittwiddler::*;

enum EnumVar1{}
enum EnumVar2{}

#[bitpattern(variant = EnumVar1)]
#[bitpattern(variant = EnumVar2)]
#[derive(Debug, PartialEq, Eq)]
enum MyEnum {
    #[bits(variant = EnumVar1, "00")]
    #[bits(variant = EnumVar2, "11")]
    Choice1,
    #[bits(variant = EnumVar1, "01")]
    #[bits(variant = EnumVar2, "10")]
    Choice2,
    #[bits(variant = EnumVar1, "10")]
    #[bits(variant = EnumVar2, "01")]
    Choice3,
    #[bits(variant = EnumVar1, "11")]
    #[bits(variant = EnumVar2, "00")]
    Choice4,
}

enum FragVar1{}
enum FragVar2{}
enum FragVar3{}

#[bitfragment(variant = FragVar1, dimensions = 1)]
#[bitfragment(variant = FragVar2, dimensions = 1)]
#[bitfragment(variant = FragVar3, dimensions = 1)]
#[derive(Debug, PartialEq, Eq)]
struct MyStruct1 {
    #[pat_bits(frag_variant = FragVar1, pat_variant = EnumVar1, "0" = 1, "1" = 2)]
    #[pat_bits(frag_variant = FragVar2, pat_variant = EnumVar1, "0" = 2, "1" = 3)]
    #[pat_bits(frag_variant = FragVar3, pat_variant = EnumVar2, "0" = 3, "1" = 4)]
    field_enum: MyEnum,
    #[pat_bits(frag_variant = FragVar1, "0" = 0)]
    #[pat_bits(frag_variant = FragVar2, "0" = 1)]
    #[pat_bits(frag_variant = FragVar3, "0" = 2)]
    field_bool: bool,
}

#[test]
fn frag_variants_encode() {
    let mut out = [false; 5];
    let x = MyStruct1 {
        field_enum: MyEnum::Choice2,
        field_bool: false,
    };
    BitFragment::<FragVar1>::encode(&x, &mut out[..], [0], [false]);
    assert_eq!(out, [false, false, true, false, false]);

    let mut out = [false; 5];
    let x = MyStruct1 {
        field_enum: MyEnum::Choice2,
        field_bool: false,
    };
    BitFragment::<FragVar2>::encode(&x, &mut out[..], [0], [false]);
    assert_eq!(out, [false, false, false, true, false]);

    let mut out = [false; 5];
    let x = MyStruct1 {
        field_enum: MyEnum::Choice2,
        field_bool: false,
    };
    BitFragment::<FragVar3>::encode(&x, &mut out[..], [0], [false]);
    assert_eq!(out, [false, false, false, true, false]);
}

#[test]
fn frag_variants_decode() {
    let x = [true, true, false, true, true];
    let out = <MyStruct1 as BitFragment<FragVar1>>::decode(&x[..], [0], [false]).unwrap();
    assert_eq!(out, MyStruct1 {
        field_enum: MyEnum::Choice3,
        field_bool: true,
    });

    let x = [true, true, true, false, true];
    let out = <MyStruct1 as BitFragment<FragVar2>>::decode(&x[..], [0], [false]).unwrap();
    assert_eq!(out, MyStruct1 {
        field_enum: MyEnum::Choice3,
        field_bool: true,
    });

    let x = [true, true, true, true, false];
    let out = <MyStruct1 as BitFragment<FragVar3>>::decode(&x[..], [0], [false]).unwrap();
    assert_eq!(out, MyStruct1 {
        field_enum: MyEnum::Choice2,
        field_bool: true,
    });
}
<|endoftext|>


<commit_before><commit_msg>add CloudWatch Logs integration tests<commit_after>#![cfg(feature = "logs")]

extern crate rusoto;

use rusoto::logs::{CloudWatchLogsClient, DescribeLogGroupsRequest};
use rusoto::{DefaultCredentialsProvider, Region};

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

    let request = DescribeLogGroupsRequest::default();

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


<commit_before><commit_msg>:art: Implement setter methods<commit_after><|endoftext|>


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

// Perlin noise benchmark from https://gist.github.com/1170424

use std::f64;
use std::rand::Rng;
use std::rand;

struct Vec2 {
    x: f32,
    y: f32,
}

#[inline(always)]
fn lerp(a: f32, b: f32, v: f32) -> f32 { a * (1.0 - v) + b * v }

#[inline(always)]
fn smooth(v: f32) -> f32 { v * v * (3.0 - 2.0 * v) }

fn random_gradient<R:Rng>(r: &mut R) -> Vec2 {
    let v = 2.0 * f64::consts::PI * r.gen();
    Vec2 {
        x: v.cos() as f32,
        y: v.sin() as f32,
    }
}

fn gradient(orig: Vec2, grad: Vec2, p: Vec2) -> f32 {
    let sp = Vec2 {x: p.x - orig.x, y: p.y - orig.y};
    grad.x * sp.x + grad.y * sp.y
}

struct Noise2DContext {
    rgradients: [Vec2, ..256],
    permutations: [int, ..256],
}

impl Noise2DContext {
    pub fn new() -> Noise2DContext {
        let mut r = rand::rng();
        let mut rgradients = [ Vec2 { x: 0.0, y: 0.0 }, ..256 ];
        for i in range(0, 256) {
            rgradients[i] = random_gradient(&mut r);
        }
        let mut permutations = [ 0, ..256 ];
        for i in range(0, 256) {
            permutations[i] = i;
        }
        r.shuffle_mut(permutations);

        Noise2DContext {
            rgradients: rgradients,
            permutations: permutations,
        }
    }

    #[inline(always)]
    pub fn get_gradient(&self, x: int, y: int) -> Vec2 {
        let idx = self.permutations[x & 255] + self.permutations[y & 255];
        self.rgradients[idx & 255]
    }

    #[inline]
    pub fn get_gradients(&self,
                         gradients: &mut [Vec2, ..4],
                         origins: &mut [Vec2, ..4],
                         x: f32,
                         y: f32) {
        let x0f = x.floor();
        let y0f = y.floor();
        let x0 = x0f as int;
        let y0 = y0f as int;
        let x1 = x0 + 1;
        let y1 = y0 + 1;

        gradients[0] = self.get_gradient(x0, y0);
        gradients[1] = self.get_gradient(x1, y0);
        gradients[2] = self.get_gradient(x0, y1);
        gradients[3] = self.get_gradient(x1, y1);

        origins[0] = Vec2 {x: x0f + 0.0, y: y0f + 0.0};
        origins[1] = Vec2 {x: x0f + 1.0, y: y0f + 0.0};
        origins[2] = Vec2 {x: x0f + 0.0, y: y0f + 1.0};
        origins[3] = Vec2 {x: x0f + 1.0, y: y0f + 1.0};
    }

    #[inline]
    pub fn get(&self, x: f32, y: f32) -> f32 {
        let p = Vec2 {x: x, y: y};
        let mut gradients = [ Vec2 { x: 0.0, y: 0.0 }, ..4 ];
        let mut origins = [ Vec2 { x: 0.0, y: 0.0 }, ..4 ];
        self.get_gradients(&mut gradients, &mut origins, x, y);
        let v0 = gradient(origins[0], gradients[0], p);
        let v1 = gradient(origins[1], gradients[1], p);
        let v2 = gradient(origins[2], gradients[2], p);
        let v3 = gradient(origins[3], gradients[3], p);
        let fx = smooth(x - origins[0].x);
        let vx0 = lerp(v0, v1, fx);
        let vx1 = lerp(v2, v3, fx);
        let fy = smooth(y - origins[0].y);
        lerp(vx0, vx1, fy)
    }
}

fn main() {
    let symbols = [" ", "░", "▒", "▓", "█", "█"];
    let mut pixels = [0f32, ..256*256];
    let n2d = ~Noise2DContext::new();
    for _ in range(0, 100u) {
        for y in range(0, 256) {
            for x in range(0, 256) {
                let v = n2d.get(
                    x as f32 * 0.1f32,
                    y as f32 * 0.1f32
                ) * 0.5f32 + 0.5f32;
                pixels[y*256+x] = v;
            };
        };
    };

    for y in range(0, 256) {
        for x in range(0, 256) {
            print!("{}", symbols[(pixels[y*256+x] / 0.2f32) as int]);
        }
        println!("");
    }
}
<commit_msg>Clean up the Perlin noise benchmark<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// Multi-language Perlin noise benchmark.
// See https://github.com/nsf/pnoise for timings and alternative implementations.

use std::f32::consts::PI;
use std::rand::{Rng, StdRng};

struct Vec2 {
    x: f32,
    y: f32,
}

fn lerp(a: f32, b: f32, v: f32) -> f32 { a * (1.0 - v) + b * v }

fn smooth(v: f32) -> f32 { v * v * (3.0 - 2.0 * v) }

fn random_gradient<R: Rng>(r: &mut R) -> Vec2 {
    let v = PI * 2.0 * r.gen();
    Vec2 { x: v.cos(), y: v.sin() }
}

fn gradient(orig: Vec2, grad: Vec2, p: Vec2) -> f32 {
    (p.x - orig.x) * grad.x + (p.y - orig.y) * grad.y
}

struct Noise2DContext {
    rgradients: [Vec2, ..256],
    permutations: [i32, ..256],
}

impl Noise2DContext {
    fn new() -> Noise2DContext {
        let mut rng = StdRng::new();

        let mut rgradients = [Vec2 { x: 0.0, y: 0.0 }, ..256];
        for x in rgradients.mut_iter() {
            *x = random_gradient(&mut rng);
        }

        let mut permutations = [0i32, ..256];
        for (i, x) in permutations.mut_iter().enumerate() {
            *x = i as i32;
        }
        rng.shuffle_mut(permutations);

        Noise2DContext { rgradients: rgradients, permutations: permutations }
    }

    fn get_gradient(&self, x: i32, y: i32) -> Vec2 {
        let idx = self.permutations[x & 255] + self.permutations[y & 255];
        self.rgradients[idx & 255]
    }

    fn get_gradients(&self, x: f32, y: f32) -> ([Vec2, ..4], [Vec2, ..4]) {
        let x0f = x.floor();
        let y0f = y.floor();
        let x1f = x0f + 1.0;
        let y1f = y0f + 1.0;

        let x0 = x0f as i32;
        let y0 = y0f as i32;
        let x1 = x0 + 1;
        let y1 = y0 + 1;

        ([self.get_gradient(x0, y0), self.get_gradient(x1, y0),
          self.get_gradient(x0, y1), self.get_gradient(x1, y1)],
         [Vec2 { x: x0f, y: y0f }, Vec2 { x: x1f, y: y0f },
          Vec2 { x: x0f, y: y1f }, Vec2 { x: x1f, y: y1f }])
    }

    fn get(&self, x: f32, y: f32) -> f32 {
        let p = Vec2 {x: x, y: y};
        let (gradients, origins) = self.get_gradients(x, y);

        let v0 = gradient(origins[0], gradients[0], p);
        let v1 = gradient(origins[1], gradients[1], p);
        let v2 = gradient(origins[2], gradients[2], p);
        let v3 = gradient(origins[3], gradients[3], p);

        let fx = smooth(x - origins[0].x);
        let vx0 = lerp(v0, v1, fx);
        let vx1 = lerp(v2, v3, fx);
        let fy = smooth(y - origins[0].y);

        lerp(vx0, vx1, fy)
    }
}

fn main() {
    let symbols = [' ', '░', '▒', '▓', '█', '█'];
    let mut pixels = [0f32, ..256*256];
    let n2d = Noise2DContext::new();

    for _ in range(0, 100) {
        for y in range(0, 256) {
            for x in range(0, 256) {
                let v = n2d.get(x as f32 * 0.1, y as f32 * 0.1);
                pixels[y*256+x] = v * 0.5 + 0.5;
            }
        }
    }

    for y in range(0, 256) {
        for x in range(0, 256) {
            let idx = (pixels[y*256+x] / 0.2) as uint;
            print!("{:c}", symbols[idx]);
        }
        print!("\n");
    }
}
<|endoftext|>


<commit_before><commit_msg>Upgrade to ef352faea84fa16616b773bd9aa5020d7c76bff0 2014-07-18<commit_after><|endoftext|>


<commit_before><commit_msg>Renamed some stuff.<commit_after><|endoftext|>


<commit_before><commit_msg>Refactor libimagnotes to fit new store iterator interface<commit_after><|endoftext|>


<commit_before><commit_msg>Test that bounds checks are elided when slice len is checked up-front<commit_after>// no-system-llvm
// compile-flags: -O
#![crate_type = "lib"]

// CHECK-LABEL: @already_sliced_no_bounds_check
#[no_mangle]
pub fn already_sliced_no_bounds_check(a: &[u8], b: &[u8], c: &mut [u8]) {
    // CHECK: slice_index_len_fail
    // CHECK-NOT: panic_bounds_check
    let _ = (&a[..2048], &b[..2048], &mut c[..2048]);
    for i in 0..1024 {
        c[i] = a[i] ^ b[i];
    }
}

// make sure we're checking for the right thing: there can be a panic if the slice is too small
// CHECK-LABEL: @already_sliced_bounds_check
#[no_mangle]
pub fn already_sliced_bounds_check(a: &[u8], b: &[u8], c: &mut [u8]) {
    // CHECK: slice_index_len_fail
    // CHECK: panic_bounds_check
    let _ = (&a[..1023], &b[..2048], &mut c[..2048]);
    for i in 0..1024 {
        c[i] = a[i] ^ b[i];
    }
}
<|endoftext|>


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

#![feature(core_intrinsics, rustc_attrs)]
#![allow(warnings)]

use std::intrinsics;

#[derive(Copy, Clone)]
struct Foo(i64);
type Bar = &'static Fn();
type Quux = [u8; 100];

#[rustc_no_mir] // FIXME #27840 MIR doesn't provide precise spans for calls.
unsafe fn test_bool_load(p: &mut bool, v: bool) {
    intrinsics::atomic_load(p);
    //~^ ERROR `atomic_load` intrinsic: expected basic integer type, found `bool`
}

#[rustc_no_mir] // FIXME #27840 MIR doesn't provide precise spans for calls.
unsafe fn test_bool_store(p: &mut bool, v: bool) {
    intrinsics::atomic_store(p, v);
    //~^ ERROR `atomic_store` intrinsic: expected basic integer type, found `bool`
}

#[rustc_no_mir] // FIXME #27840 MIR doesn't provide precise spans for calls.
unsafe fn test_bool_xchg(p: &mut bool, v: bool) {
    intrinsics::atomic_xchg(p, v);
    //~^ ERROR `atomic_xchg` intrinsic: expected basic integer type, found `bool`
}

#[rustc_no_mir] // FIXME #27840 MIR doesn't provide precise spans for calls.
unsafe fn test_bool_cxchg(p: &mut bool, v: bool) {
    intrinsics::atomic_cxchg(p, v, v);
    //~^ ERROR `atomic_cxchg` intrinsic: expected basic integer type, found `bool`
}

#[rustc_no_mir] // FIXME #27840 MIR doesn't provide precise spans for calls.
unsafe fn test_Foo_load(p: &mut Foo, v: Foo) {
    intrinsics::atomic_load(p);
    //~^ ERROR `atomic_load` intrinsic: expected basic integer type, found `Foo`
}

#[rustc_no_mir] // FIXME #27840 MIR doesn't provide precise spans for calls.
unsafe fn test_Foo_store(p: &mut Foo, v: Foo) {
    intrinsics::atomic_store(p, v);
    //~^ ERROR `atomic_store` intrinsic: expected basic integer type, found `Foo`
}

#[rustc_no_mir] // FIXME #27840 MIR doesn't provide precise spans for calls.
unsafe fn test_Foo_xchg(p: &mut Foo, v: Foo) {
    intrinsics::atomic_xchg(p, v);
    //~^ ERROR `atomic_xchg` intrinsic: expected basic integer type, found `Foo`
}

#[rustc_no_mir] // FIXME #27840 MIR doesn't provide precise spans for calls.
unsafe fn test_Foo_cxchg(p: &mut Foo, v: Foo) {
    intrinsics::atomic_cxchg(p, v, v);
    //~^ ERROR `atomic_cxchg` intrinsic: expected basic integer type, found `Foo`
}

#[rustc_no_mir] // FIXME #27840 MIR doesn't provide precise spans for calls.
unsafe fn test_Bar_load(p: &mut Bar, v: Bar) {
    intrinsics::atomic_load(p);
    //~^ ERROR expected basic integer type, found `&'static std::ops::Fn() + 'static`
}

#[rustc_no_mir] // FIXME #27840 MIR doesn't provide precise spans for calls.
unsafe fn test_Bar_store(p: &mut Bar, v: Bar) {
    intrinsics::atomic_store(p, v);
    //~^ ERROR expected basic integer type, found `&'static std::ops::Fn() + 'static`
}

#[rustc_no_mir] // FIXME #27840 MIR doesn't provide precise spans for calls.
unsafe fn test_Bar_xchg(p: &mut Bar, v: Bar) {
    intrinsics::atomic_xchg(p, v);
    //~^ ERROR expected basic integer type, found `&'static std::ops::Fn() + 'static`
}

#[rustc_no_mir] // FIXME #27840 MIR doesn't provide precise spans for calls.
unsafe fn test_Bar_cxchg(p: &mut Bar, v: Bar) {
    intrinsics::atomic_cxchg(p, v, v);
    //~^ ERROR expected basic integer type, found `&'static std::ops::Fn() + 'static`
}

#[rustc_no_mir] // FIXME #27840 MIR doesn't provide precise spans for calls.
unsafe fn test_Quux_load(p: &mut Quux, v: Quux) {
    intrinsics::atomic_load(p);
    //~^ ERROR `atomic_load` intrinsic: expected basic integer type, found `[u8; 100]`
}

#[rustc_no_mir] // FIXME #27840 MIR doesn't provide precise spans for calls.
unsafe fn test_Quux_store(p: &mut Quux, v: Quux) {
    intrinsics::atomic_store(p, v);
    //~^ ERROR `atomic_store` intrinsic: expected basic integer type, found `[u8; 100]`
}

#[rustc_no_mir] // FIXME #27840 MIR doesn't provide precise spans for calls.
unsafe fn test_Quux_xchg(p: &mut Quux, v: Quux) {
    intrinsics::atomic_xchg(p, v);
    //~^ ERROR `atomic_xchg` intrinsic: expected basic integer type, found `[u8; 100]`
}

#[rustc_no_mir] // FIXME #27840 MIR doesn't provide precise spans for calls.
unsafe fn test_Quux_cxchg(p: &mut Quux, v: Quux) {
    intrinsics::atomic_cxchg(p, v, v);
    //~^ ERROR `atomic_cxchg` intrinsic: expected basic integer type, found `[u8; 100]`
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Added security level functionality<commit_after><|endoftext|>


<commit_before><commit_msg>Add MTLStructMember<commit_after>use cocoa::base::id;
use cocoa::foundation::NSUInteger;
use MTLDataType;

/// `MTLStructMember` is part of the reflection API that allows Metal framework
/// code to query details about an argument of a Metal shading language
/// function. A `MTLStructMember` object describes the data type of one field
/// in a struct that is passed as a `MTLFunction` argument, which is represented
/// by `MTLArgument`.
///
/// Your app does not create a `MTLStructMember` object directly. A
/// `MTLStructMember` object is either obtained from the members property or the
/// `memberByName:` method of a `MTLStructType` object. You examine the dataType
/// property of the `MTLStructMember` object, which may indicate the struct
/// member is another struct (`MTLDataTypeStruct`), an array
/// (`MTLDataTypeArray`), or some other type. You recursively drill down every
/// struct member until you reach a data type that is neither a struct nor an array.
pub trait MTLStructMember {
	/// The name of the struct member. (read-only)
	unsafe fn name(self) -> id;

	/// The data type of the struct member. (read-only)
	///
	/// #Discussion
	///
	/// For information on possible values, see `MTLDataType`. If the value is
	/// `MTLDataTypeArray`, then the `arrayType` method returns an object that
	/// describes the underlying array. If the value is `MTLDataTypeStruct`,
	/// then the `structType` method returns an object that describes the
	/// underlying struct.
	unsafe fn dataType(self) -> MTLDataType;

	/// The location of this member relative to the start of its struct, in bytes.
	/// (read-only)
	unsafe fn offset(self) -> NSUInteger;

	/// If a struct member holds an array, returns an object that describes the
	/// underlying array.
	unsafe fn arrayType(self) -> id;

	/// If a struct member holds another struct, returns an object that describes
	/// the underlying struct.
	unsafe fn structType(self) -> id;
}

impl MTLStructMember for id {
	unsafe fn name(self) -> id {
		msg_send![self, name]
	}

	unsafe fn dataType(self) -> MTLDataType {
		msg_send![self, dataType]
	}

	unsafe fn offset(self) -> NSUInteger {
		msg_send![self, offset]
	}

	unsafe fn arrayType(self) -> id {
		msg_send![self, arrayType]
	}

	unsafe fn structType(self) -> id {
		msg_send![self, structType]
	}
}
<|endoftext|>


<commit_before><commit_msg>add Heap::peek_mut<commit_after><|endoftext|>