<commit_before><commit_msg>Auto merge of #27185 - pnkfelix:test-cyclic-collections, r=alexcrichton<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.

// This test exercises cases where cyclic structure is legal,
// including when the cycles go through data-structures such
// as `Vec` or `TypedArena`.
//
// The intent is to cover as many such cases as possible, ensuring
// that if the compiler did not complain circa Rust 1.x (1.2 as of
// this writing), then it will continue to not complain in the future.
//
// Note that while some of the tests are only exercising using the
// given collection as a "backing store" for a set of nodes that hold
// the actual cycle (and thus the cycle does not go through the
// collection itself in such cases), in general we *do* want to make
// sure to have at least one example exercising a cycle that goes
// through the collection, for every collection type that supports
// this.

#![feature(vecmap)]

use std::cell::Cell;
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::collections::HashMap;
use std::collections::LinkedList;
use std::collections::VecDeque;
use std::collections::VecMap;
use std::collections::btree_map::BTreeMap;
use std::collections::btree_set::BTreeSet;
use std::hash::{Hash, Hasher};

const PRINT: bool = false;

pub fn main() {
    let c_orig = ContextData {
        curr_depth: 0,
        max_depth: 3,
        visited: 0,
        max_visits: 1000,
        skipped: 0,
        curr_mark: 0,
        saw_prev_marked: false,
    };

    // Cycle 1: { v[0] -> v[1], v[1] -> v[0] };
    // does not exercise `v` itself
    let v: Vec<S> = vec![Named::new("s0"),
                         Named::new("s1")];
    v[0].next.set(Some(&v[1]));
    v[1].next.set(Some(&v[0]));

    let mut c = c_orig.clone();
    c.curr_mark = 10;
    assert!(!c.saw_prev_marked);
    v[0].for_each_child(&mut c);
    assert!(c.saw_prev_marked);

    if PRINT { println!(""); }

    // Cycle 2: { v[0] -> v, v[1] -> v }
    let v: V = Named::new("v");
    v.contents[0].set(Some(&v));
    v.contents[1].set(Some(&v));

    let mut c = c_orig.clone();
    c.curr_mark = 20;
    assert!(!c.saw_prev_marked);
    v.for_each_child(&mut c);
    assert!(c.saw_prev_marked);

    if PRINT { println!(""); }

    // Cycle 3: { hk0 -> hv0, hv0 -> hk0, hk1 -> hv1, hv1 -> hk1 };
    // does not exercise `h` itself

    let mut h: HashMap<H,H> = HashMap::new();
    h.insert(Named::new("hk0"), Named::new("hv0"));
    h.insert(Named::new("hk1"), Named::new("hv1"));
    for (key, val) in h.iter() {
        val.next.set(Some(key));
        key.next.set(Some(val));
    }

    let mut c = c_orig.clone();
    c.curr_mark = 30;
    for (key, _) in h.iter() {
        c.curr_mark += 1;
        c.saw_prev_marked = false;
        key.for_each_child(&mut c);
        assert!(c.saw_prev_marked);
    }

    if PRINT { println!(""); }

    // Cycle 4: { h -> (hmk0,hmv0,hmk1,hmv1), {hmk0,hmv0,hmk1,hmv1} -> h }

    let mut h: HashMap<HM,HM> = HashMap::new();
    h.insert(Named::new("hmk0"), Named::new("hmv0"));
    h.insert(Named::new("hmk0"), Named::new("hmv0"));
    for (key, val) in h.iter() {
        val.contents.set(Some(&h));
        key.contents.set(Some(&h));
    }

    let mut c = c_orig.clone();
    c.max_depth = 2;
    c.curr_mark = 40;
    for (key, _) in h.iter() {
        c.curr_mark += 1;
        c.saw_prev_marked = false;
        key.for_each_child(&mut c);
        assert!(c.saw_prev_marked);
        // break;
    }

    if PRINT { println!(""); }

    // Cycle 5: { vd[0] -> vd[1], vd[1] -> vd[0] };
    // does not exercise vd itself
    let mut vd: VecDeque<S> = VecDeque::new();
    vd.push_back(Named::new("d0"));
    vd.push_back(Named::new("d1"));
    vd[0].next.set(Some(&vd[1]));
    vd[1].next.set(Some(&vd[0]));

    let mut c = c_orig.clone();
    c.curr_mark = 50;
    assert!(!c.saw_prev_marked);
    vd[0].for_each_child(&mut c);
    assert!(c.saw_prev_marked);

    if PRINT { println!(""); }

    // Cycle 6: { vd -> (vd0, vd1), {vd0, vd1} -> vd }
    let mut vd: VecDeque<VD> = VecDeque::new();
    vd.push_back(Named::new("vd0"));
    vd.push_back(Named::new("vd1"));
    vd[0].contents.set(Some(&vd));
    vd[1].contents.set(Some(&vd));

    let mut c = c_orig.clone();
    c.curr_mark = 60;
    assert!(!c.saw_prev_marked);
    vd[0].for_each_child(&mut c);
    assert!(c.saw_prev_marked);

    if PRINT { println!(""); }

    // Cycle 7: { vm -> (vm0, vm1), {vm0, vm1} -> vm }
    let mut vm: VecMap<VM> = VecMap::new();
    vm.insert(0, Named::new("vm0"));
    vm.insert(1, Named::new("vm1"));
    vm[0].contents.set(Some(&vm));
    vm[1].contents.set(Some(&vm));

    let mut c = c_orig.clone();
    c.curr_mark = 70;
    assert!(!c.saw_prev_marked);
    vm[0].for_each_child(&mut c);
    assert!(c.saw_prev_marked);

    if PRINT { println!(""); }

    // Cycle 8: { ll -> (ll0, ll1), {ll0, ll1} -> ll }
    let mut ll: LinkedList<LL> = LinkedList::new();
    ll.push_back(Named::new("ll0"));
    ll.push_back(Named::new("ll1"));
    for e in &ll {
        e.contents.set(Some(&ll));
    }

    let mut c = c_orig.clone();
    c.curr_mark = 80;
    for e in &ll {
        c.curr_mark += 1;
        c.saw_prev_marked = false;
        e.for_each_child(&mut c);
        assert!(c.saw_prev_marked);
        // break;
    }

    if PRINT { println!(""); }

    // Cycle 9: { bh -> (bh0, bh1), {bh0, bh1} -> bh }
    let mut bh: BinaryHeap<BH> = BinaryHeap::new();
    bh.push(Named::new("bh0"));
    bh.push(Named::new("bh1"));
    for b in bh.iter() {
        b.contents.set(Some(&bh));
    }

    let mut c = c_orig.clone();
    c.curr_mark = 90;
    for b in &bh {
        c.curr_mark += 1;
        c.saw_prev_marked = false;
        b.for_each_child(&mut c);
        assert!(c.saw_prev_marked);
        // break;
    }

    if PRINT { println!(""); }

    // Cycle 10: { btm -> (btk0, btv1), {bt0, bt1} -> btm }
    let mut btm: BTreeMap<BTM, BTM> = BTreeMap::new();
    btm.insert(Named::new("btk0"), Named::new("btv0"));
    btm.insert(Named::new("btk1"), Named::new("btv1"));
    for (k, v) in btm.iter() {
        k.contents.set(Some(&btm));
        v.contents.set(Some(&btm));
    }

    let mut c = c_orig.clone();
    c.curr_mark = 100;
    for (k, _) in &btm {
        c.curr_mark += 1;
        c.saw_prev_marked = false;
        k.for_each_child(&mut c);
        assert!(c.saw_prev_marked);
        // break;
    }

    if PRINT { println!(""); }

    // Cycle 10: { bts -> (bts0, bts1), {bts0, bts1} -> btm }
    let mut bts: BTreeSet<BTS> = BTreeSet::new();
    bts.insert(Named::new("bts0"));
    bts.insert(Named::new("bts1"));
    for v in bts.iter() {
        v.contents.set(Some(&bts));
    }

    let mut c = c_orig.clone();
    c.curr_mark = 100;
    for b in &bts {
        c.curr_mark += 1;
        c.saw_prev_marked = false;
        b.for_each_child(&mut c);
        assert!(c.saw_prev_marked);
        // break;
    }
}

trait Named {
    fn new(&'static str) -> Self;
    fn name(&self) -> &str;
}

trait Marked<M> {
    fn mark(&self) -> M;
    fn set_mark(&self, mark: M);
}

struct S<'a> {
    name: &'static str,
    mark: Cell<u32>,
    next: Cell<Option<&'a S<'a>>>,
}

impl<'a> Named for S<'a> {
    fn new<'b>(name: &'static str) -> S<'b> {
        S { name: name, mark: Cell::new(0), next: Cell::new(None) }
    }
    fn name(&self) -> &str { self.name }
}

impl<'a> Marked<u32> for S<'a> {
    fn mark(&self) -> u32 { self.mark.get() }
    fn set_mark(&self, mark: u32) { self.mark.set(mark); }
}

struct V<'a> {
    name: &'static str,
    mark: Cell<u32>,
    contents: Vec<Cell<Option<&'a V<'a>>>>,
}

impl<'a> Named for V<'a> {
    fn new<'b>(name: &'static str) -> V<'b> {
        V { name: name,
            mark: Cell::new(0),
            contents: vec![Cell::new(None), Cell::new(None)]
        }
    }
    fn name(&self) -> &str { self.name }
}

impl<'a> Marked<u32> for V<'a> {
    fn mark(&self) -> u32 { self.mark.get() }
    fn set_mark(&self, mark: u32) { self.mark.set(mark); }
}

#[derive(Eq)]
struct H<'a> {
    name: &'static str,
    mark: Cell<u32>,
    next: Cell<Option<&'a H<'a>>>,
}

impl<'a> Named for H<'a> {
    fn new<'b>(name: &'static str) -> H<'b> {
        H { name: name, mark: Cell::new(0), next: Cell::new(None) }
    }
    fn name(&self) -> &str { self.name }
}

impl<'a> Marked<u32> for H<'a> {
    fn mark(&self) -> u32 { self.mark.get() }
    fn set_mark(&self, mark: u32) { self.mark.set(mark); }
}

impl<'a> PartialEq for H<'a> {
    fn eq(&self, rhs: &H<'a>) -> bool {
        self.name == rhs.name
    }
}

impl<'a> Hash for H<'a> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.name.hash(state)
    }
}

#[derive(Eq)]
struct HM<'a> {
    name: &'static str,
    mark: Cell<u32>,
    contents: Cell<Option<&'a HashMap<HM<'a>, HM<'a>>>>,
}

impl<'a> Named for HM<'a> {
    fn new<'b>(name: &'static str) -> HM<'b> {
        HM { name: name,
             mark: Cell::new(0),
             contents: Cell::new(None)
        }
    }
    fn name(&self) -> &str { self.name }
}

impl<'a> Marked<u32> for HM<'a> {
    fn mark(&self) -> u32 { self.mark.get() }
    fn set_mark(&self, mark: u32) { self.mark.set(mark); }
}

impl<'a> PartialEq for HM<'a> {
    fn eq(&self, rhs: &HM<'a>) -> bool {
        self.name == rhs.name
    }
}

impl<'a> Hash for HM<'a> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.name.hash(state)
    }
}

struct VD<'a> {
    name: &'static str,
    mark: Cell<u32>,
    contents: Cell<Option<&'a VecDeque<VD<'a>>>>,
}

impl<'a> Named for VD<'a> {
    fn new<'b>(name: &'static str) -> VD<'b> {
        VD { name: name,
             mark: Cell::new(0),
             contents: Cell::new(None)
        }
    }
    fn name(&self) -> &str { self.name }
}

impl<'a> Marked<u32> for VD<'a> {
    fn mark(&self) -> u32 { self.mark.get() }
    fn set_mark(&self, mark: u32) { self.mark.set(mark); }
}

struct VM<'a> {
    name: &'static str,
    mark: Cell<u32>,
    contents: Cell<Option<&'a VecMap<VM<'a>>>>,
}

impl<'a> Named for VM<'a> {
    fn new<'b>(name: &'static str) -> VM<'b> {
        VM { name: name,
             mark: Cell::new(0),
             contents: Cell::new(None)
        }
    }
    fn name(&self) -> &str { self.name }
}

impl<'a> Marked<u32> for VM<'a> {
    fn mark(&self) -> u32 { self.mark.get() }
    fn set_mark(&self, mark: u32) { self.mark.set(mark); }
}

struct LL<'a> {
    name: &'static str,
    mark: Cell<u32>,
    contents: Cell<Option<&'a LinkedList<LL<'a>>>>,
}

impl<'a> Named for LL<'a> {
    fn new<'b>(name: &'static str) -> LL<'b> {
        LL { name: name,
             mark: Cell::new(0),
             contents: Cell::new(None)
        }
    }
    fn name(&self) -> &str { self.name }
}

impl<'a> Marked<u32> for LL<'a> {
    fn mark(&self) -> u32 { self.mark.get() }
    fn set_mark(&self, mark: u32) { self.mark.set(mark); }
}

struct BH<'a> {
    name: &'static str,
    mark: Cell<u32>,
    contents: Cell<Option<&'a BinaryHeap<BH<'a>>>>,
}

impl<'a> Named for BH<'a> {
    fn new<'b>(name: &'static str) -> BH<'b> {
        BH { name: name,
             mark: Cell::new(0),
             contents: Cell::new(None)
        }
    }
    fn name(&self) -> &str { self.name }
}

impl<'a> Marked<u32> for BH<'a> {
    fn mark(&self) -> u32 { self.mark.get() }
    fn set_mark(&self, mark: u32) { self.mark.set(mark); }
}

impl<'a> Eq for BH<'a> { }

impl<'a> PartialEq for BH<'a> {
    fn eq(&self, rhs: &BH<'a>) -> bool {
        self.name == rhs.name
    }
}

impl<'a> PartialOrd for BH<'a> {
    fn partial_cmp(&self, rhs: &BH<'a>) -> Option<Ordering> {
        Some(self.cmp(rhs))
    }
}

impl<'a> Ord for BH<'a> {
    fn cmp(&self, rhs: &BH<'a>) -> Ordering {
        self.name.cmp(rhs.name)
    }
}

struct BTM<'a> {
    name: &'static str,
    mark: Cell<u32>,
    contents: Cell<Option<&'a BTreeMap<BTM<'a>, BTM<'a>>>>,
}

impl<'a> Named for BTM<'a> {
    fn new<'b>(name: &'static str) -> BTM<'b> {
        BTM { name: name,
             mark: Cell::new(0),
             contents: Cell::new(None)
        }
    }
    fn name(&self) -> &str { self.name }
}

impl<'a> Marked<u32> for BTM<'a> {
    fn mark(&self) -> u32 { self.mark.get() }
    fn set_mark(&self, mark: u32) { self.mark.set(mark); }
}

impl<'a> Eq for BTM<'a> { }

impl<'a> PartialEq for BTM<'a> {
    fn eq(&self, rhs: &BTM<'a>) -> bool {
        self.name == rhs.name
    }
}

impl<'a> PartialOrd for BTM<'a> {
    fn partial_cmp(&self, rhs: &BTM<'a>) -> Option<Ordering> {
        Some(self.cmp(rhs))
    }
}

impl<'a> Ord for BTM<'a> {
    fn cmp(&self, rhs: &BTM<'a>) -> Ordering {
        self.name.cmp(rhs.name)
    }
}

struct BTS<'a> {
    name: &'static str,
    mark: Cell<u32>,
    contents: Cell<Option<&'a BTreeSet<BTS<'a>>>>,
}

impl<'a> Named for BTS<'a> {
    fn new<'b>(name: &'static str) -> BTS<'b> {
        BTS { name: name,
             mark: Cell::new(0),
             contents: Cell::new(None)
        }
    }
    fn name(&self) -> &str { self.name }
}

impl<'a> Marked<u32> for BTS<'a> {
    fn mark(&self) -> u32 { self.mark.get() }
    fn set_mark(&self, mark: u32) { self.mark.set(mark); }
}

impl<'a> Eq for BTS<'a> { }

impl<'a> PartialEq for BTS<'a> {
    fn eq(&self, rhs: &BTS<'a>) -> bool {
        self.name == rhs.name
    }
}

impl<'a> PartialOrd for BTS<'a> {
    fn partial_cmp(&self, rhs: &BTS<'a>) -> Option<Ordering> {
        Some(self.cmp(rhs))
    }
}

impl<'a> Ord for BTS<'a> {
    fn cmp(&self, rhs: &BTS<'a>) -> Ordering {
        self.name.cmp(rhs.name)
    }
}

trait Context {
    fn should_act(&self) -> bool;
    fn increase_visited(&mut self);
    fn increase_skipped(&mut self);
    fn increase_depth(&mut self);
    fn decrease_depth(&mut self);
}

trait PrePost<T> {
    fn pre(&mut self, &T);
    fn post(&mut self, &T);
    fn hit_limit(&mut self, &T);
}

trait Children<'a> {
    fn for_each_child<C>(&self, context: &mut C)
        where C: Context + PrePost<Self>, Self: Sized;

    fn descend_into_self<C>(&self, context: &mut C)
        where C: Context + PrePost<Self>, Self: Sized
    {
        context.pre(self);
        if context.should_act() {
            context.increase_visited();
            context.increase_depth();
            self.for_each_child(context);
            context.decrease_depth();
        } else {
            context.hit_limit(self);
            context.increase_skipped();
        }
        context.post(self);
    }

    fn descend<'b, C>(&self, c: &Cell<Option<&'b Self>>, context: &mut C)
        where C: Context + PrePost<Self>, Self: Sized
    {
        if let Some(r) = c.get() {
            r.descend_into_self(context);
        }
    }
}

impl<'a> Children<'a> for S<'a> {
    fn for_each_child<C>(&self, context: &mut C)
        where C: Context + PrePost<S<'a>>
    {
        self.descend(&self.next, context);
    }
}

impl<'a> Children<'a> for V<'a> {
    fn for_each_child<C>(&self, context: &mut C)
        where C: Context + PrePost<V<'a>>
    {
        for r in &self.contents {
            self.descend(r, context);
        }
    }
}

impl<'a> Children<'a> for H<'a> {
    fn for_each_child<C>(&self, context: &mut C)
        where C: Context + PrePost<H<'a>>
    {
        self.descend(&self.next, context);
    }
}

impl<'a> Children<'a> for HM<'a> {
    fn for_each_child<C>(&self, context: &mut C)
        where C: Context + PrePost<HM<'a>>
    {
        if let Some(ref hm) = self.contents.get() {
            for (k, v) in hm.iter() {
                for r in &[k, v] {
                    r.descend_into_self(context);
                }
            }
        }
    }
}

impl<'a> Children<'a> for VD<'a> {
    fn for_each_child<C>(&self, context: &mut C)
        where C: Context + PrePost<VD<'a>>
    {
        if let Some(ref vd) = self.contents.get() {
            for r in vd.iter() {
                r.descend_into_self(context);
            }
        }
    }
}

impl<'a> Children<'a> for VM<'a> {
    fn for_each_child<C>(&self, context: &mut C)
        where C: Context + PrePost<VM<'a>>
    {
        if let Some(ref vd) = self.contents.get() {
            for (_idx, r) in vd.iter() {
                r.descend_into_self(context);
            }
        }
    }
}

impl<'a> Children<'a> for LL<'a> {
    fn for_each_child<C>(&self, context: &mut C)
        where C: Context + PrePost<LL<'a>>
    {
        if let Some(ref ll) = self.contents.get() {
            for r in ll.iter() {
                r.descend_into_self(context);
            }
        }
    }
}

impl<'a> Children<'a> for BH<'a> {
    fn for_each_child<C>(&self, context: &mut C)
        where C: Context + PrePost<BH<'a>>
    {
        if let Some(ref bh) = self.contents.get() {
            for r in bh.iter() {
                r.descend_into_self(context);
            }
        }
    }
}

impl<'a> Children<'a> for BTM<'a> {
    fn for_each_child<C>(&self, context: &mut C)
        where C: Context + PrePost<BTM<'a>>
    {
        if let Some(ref bh) = self.contents.get() {
            for (k, v) in bh.iter() {
                for r in &[k, v] {
                    r.descend_into_self(context);
                }
            }
        }
    }
}

impl<'a> Children<'a> for BTS<'a> {
    fn for_each_child<C>(&self, context: &mut C)
        where C: Context + PrePost<BTS<'a>>
    {
        if let Some(ref bh) = self.contents.get() {
            for r in bh.iter() {
                r.descend_into_self(context);
            }
        }
    }
}

#[derive(Copy, Clone)]
struct ContextData {
    curr_depth: usize,
    max_depth: usize,
    visited: usize,
    max_visits: usize,
    skipped: usize,
    curr_mark: u32,
    saw_prev_marked: bool,
}

impl Context for ContextData {
    fn should_act(&self) -> bool {
        self.curr_depth < self.max_depth && self.visited < self.max_visits
    }
    fn increase_visited(&mut self) { self.visited += 1; }
    fn increase_skipped(&mut self) { self.skipped += 1; }
    fn increase_depth(&mut self) {  self.curr_depth += 1; }
    fn decrease_depth(&mut self) {  self.curr_depth -= 1; }
}

impl<T:Named+Marked<u32>> PrePost<T> for ContextData {
    fn pre(&mut self, t: &T) {
        for _ in 0..self.curr_depth {
            if PRINT { print!(" "); }
        }
        if PRINT { println!("prev {}", t.name()); }
        if t.mark() == self.curr_mark {
            for _ in 0..self.curr_depth {
                if PRINT { print!(" "); }
            }
            if PRINT { println!("(probably previously marked)"); }
            self.saw_prev_marked = true;
        }
        t.set_mark(self.curr_mark);
    }
    fn post(&mut self, t: &T) {
        for _ in 0..self.curr_depth {
            if PRINT { print!(" "); }
        }
        if PRINT { println!("post {}", t.name()); }
    }
    fn hit_limit(&mut self, t: &T) {
        for _ in 0..self.curr_depth {
            if PRINT { print!(" "); }
        }
        if PRINT { println!("LIMIT {}", t.name()); }
    }
}
<|endoftext|>


<commit_before><commit_msg>run_command API update<commit_after><|endoftext|>


<commit_before><commit_msg>Fix directory when using Cargo<commit_after><|endoftext|>


<commit_before><commit_msg>refactored4<commit_after><|endoftext|>


<commit_before><commit_msg>Still trying to decide how this should look<commit_after><|endoftext|>


<commit_before><commit_msg>Update for Vec type for MemReader<commit_after><|endoftext|>


<commit_before><commit_msg>Show we can match cyclic routes.<commit_after><|endoftext|>


<commit_before><commit_msg>Add panic! before allocator init<commit_after><|endoftext|>


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

// This test checks that instantiating an uninhabited type via `mem::{uninitialized,zeroed}` results
// in a runtime panic.

#![feature(never_type)]

use std::{mem, panic};

struct Foo {
    x: u8,
    y: !,
}

enum Bar {}

fn main() {
    unsafe {
        assert_eq!(
            panic::catch_unwind(|| {
                mem::uninitialized::<!>()
            }).err().and_then(|a| a.downcast_ref::<String>().map(|s| {
                s == "Attempted to instantiate uninhabited type ! using mem::uninitialized"
            })),
            Some(true)
        );

        assert_eq!(
            panic::catch_unwind(|| {
                mem::zeroed::<!>()
            }).err().and_then(|a| a.downcast_ref::<String>().map(|s| {
                s == "Attempted to instantiate uninhabited type ! using mem::zeroed"
            })),
            Some(true)
        );

        assert_eq!(
            panic::catch_unwind(|| {
                mem::uninitialized::<Foo>()
            }).err().and_then(|a| a.downcast_ref::<String>().map(|s| {
                s == "Attempted to instantiate uninhabited type Foo using mem::uninitialized"
            })),
            Some(true)
        );

        assert_eq!(
            panic::catch_unwind(|| {
                mem::zeroed::<Foo>()
            }).err().and_then(|a| a.downcast_ref::<String>().map(|s| {
                s == "Attempted to instantiate uninhabited type Foo using mem::zeroed"
            })),
            Some(true)
        );

        assert_eq!(
            panic::catch_unwind(|| {
                mem::uninitialized::<Bar>()
            }).err().and_then(|a| a.downcast_ref::<String>().map(|s| {
                s == "Attempted to instantiate uninhabited type Bar using mem::uninitialized"
            })),
            Some(true)
        );

        assert_eq!(
            panic::catch_unwind(|| {
                mem::zeroed::<Bar>()
            }).err().and_then(|a| a.downcast_ref::<String>().map(|s| {
                s == "Attempted to instantiate uninhabited type Bar using mem::zeroed"
            })),
            Some(true)
        );
    }
}
<commit_msg>allow dead_code<commit_after>// Copyright 2018 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.

// This test checks that instantiating an uninhabited type via `mem::{uninitialized,zeroed}` results
// in a runtime panic.

#![feature(never_type)]

use std::{mem, panic};

#[allow(dead_code)]
struct Foo {
    x: u8,
    y: !,
}

enum Bar {}

fn main() {
    unsafe {
        assert_eq!(
            panic::catch_unwind(|| {
                mem::uninitialized::<!>()
            }).err().and_then(|a| a.downcast_ref::<String>().map(|s| {
                s == "Attempted to instantiate uninhabited type ! using mem::uninitialized"
            })),
            Some(true)
        );

        assert_eq!(
            panic::catch_unwind(|| {
                mem::zeroed::<!>()
            }).err().and_then(|a| a.downcast_ref::<String>().map(|s| {
                s == "Attempted to instantiate uninhabited type ! using mem::zeroed"
            })),
            Some(true)
        );

        assert_eq!(
            panic::catch_unwind(|| {
                mem::uninitialized::<Foo>()
            }).err().and_then(|a| a.downcast_ref::<String>().map(|s| {
                s == "Attempted to instantiate uninhabited type Foo using mem::uninitialized"
            })),
            Some(true)
        );

        assert_eq!(
            panic::catch_unwind(|| {
                mem::zeroed::<Foo>()
            }).err().and_then(|a| a.downcast_ref::<String>().map(|s| {
                s == "Attempted to instantiate uninhabited type Foo using mem::zeroed"
            })),
            Some(true)
        );

        assert_eq!(
            panic::catch_unwind(|| {
                mem::uninitialized::<Bar>()
            }).err().and_then(|a| a.downcast_ref::<String>().map(|s| {
                s == "Attempted to instantiate uninhabited type Bar using mem::uninitialized"
            })),
            Some(true)
        );

        assert_eq!(
            panic::catch_unwind(|| {
                mem::zeroed::<Bar>()
            }).err().and_then(|a| a.downcast_ref::<String>().map(|s| {
                s == "Attempted to instantiate uninhabited type Bar using mem::zeroed"
            })),
            Some(true)
        );
    }
}
<|endoftext|>


<commit_before><commit_msg>17 - visibility<commit_after>mod my {
    // A public struct with public fields
    pub struct WhiteBox<T> {
        pub contents: T,
    }

    // A public struct with private fields
    #[allow(dead_code)]
    pub struct BlackBox<T> {
        contents: T,
    }

    impl<T> BlackBox<T> {
        // A public constructor
        pub fn new(contents: T) -> BlackBox<T> {
            BlackBox {
                contents: contents,
            }
        }
    }
}

fn main() {
    // Public structs with public fields can be constructed as usual
    let white_box = my::WhiteBox { contents: "public information" };

    // and their fields can be normally accessed
    println!("The white box contains: {}", white_box.contents);

    // but public structs with private fields can't be constructed
    // Error! `BlackBox` has private fields
    //let black_box = my::BlackBox { contents: "classified information" };
    // TODO ^ Try uncommenting this line

    // However, structs with private fields can still be created using
    // constructors
    let _black_box = my::BlackBox::new("classified information");

    // The private fields of a struct can't be accessed
    // Error! The `contents` field is private
    //println!("The black box contains: {}", _black_box.contents);
    // TODO ^ Try uncommenting this line
}
<|endoftext|>


<commit_before>extern mod std;

use libc::c_char;
use libc::c_int;
use libc::size_t;
use libc::c_ulong;
use libc::c_void;
use num::from_int;
use ptr::null;
use ptr::addr_of;
use ptr::mut_addr_of;
use ptr::to_mut_unsafe_ptr;
use str::as_c_str;

struct mpz_struct {
  _mp_alloc: c_int,
  _mp_size: c_int,
  _mp_d: *c_void
}

type mpz_srcptr = *const mpz_struct;
type mpz_ptr = *mut mpz_struct;

extern mod gmp {
  fn __gmpz_init(x: mpz_ptr);
  fn __gmpz_init_set(rop: mpz_ptr, op: mpz_srcptr);
  fn __gmpz_init_set_str(rop: mpz_ptr, str: *c_char, base: c_int) -> c_int;
  fn __gmpz_clear(x: mpz_ptr);
  fn __gmpz_set(rop: mpz_ptr, op: mpz_srcptr);
  fn __gmpz_set_str(rop: mpz_ptr, str: *c_char, base: c_int) -> c_int;
  fn __gmpz_get_str(str: *c_char, base: c_int, op: mpz_srcptr) -> *c_char;
  pure fn __gmpz_sizeinbase(op: mpz_srcptr, base: c_int) -> size_t;
  pure fn __gmpz_cmp(op: mpz_srcptr, op2: mpz_srcptr) -> c_int;
  pure fn __gmpz_cmp_ui(op1: mpz_srcptr, op2: c_ulong) -> c_int;
  fn __gmpz_add(rop: mpz_ptr, op1: mpz_srcptr, op2: mpz_srcptr);
  fn __gmpz_sub(rop: mpz_ptr, op1: mpz_srcptr, op2: mpz_srcptr);
  fn __gmpz_mul(rop: mpz_ptr, op1: mpz_srcptr, op2: mpz_srcptr);
  fn __gmpz_neg(rop: mpz_ptr, op: mpz_srcptr);
  fn __gmpz_tdiv_q(r: mpz_ptr, n: mpz_srcptr, d: mpz_srcptr);
  fn __gmpz_mod(r: mpz_ptr, n: mpz_srcptr, d: mpz_srcptr);
}

use gmp::*;

pub struct Mpz {
  priv mpz: mpz_struct,

  drop {
    __gmpz_clear(mut_addr_of(&self.mpz));
  }
}

impl Mpz {
  fn set(&mut self, other: &Mpz) {
    __gmpz_set(mut_addr_of(&self.mpz), addr_of(&other.mpz));
  }

  fn set_str(&mut self, s: &str, base: int) -> bool {
    let mpz = to_mut_unsafe_ptr(&mut self.mpz);
    let r = as_c_str(s, { |s| __gmpz_set_str(mpz, s, base as c_int) });
    r == 0
  }

  pure fn to_str_radix(&self, base: int) -> ~str unsafe {
    let length = self.size_in_base(10) + 2;
    let dst = vec::to_mut(vec::from_elem(length, '0'));
    let pdst = vec::raw::to_ptr(dst);

    str::raw::from_c_str(__gmpz_get_str(pdst as *c_char, base as c_int,
                         addr_of(&self.mpz)))
  }

  pure fn size_in_base(&self, base: int) -> uint {
    __gmpz_sizeinbase(addr_of(&self.mpz), base as c_int) as uint
  }

  // TODO: implement the clone::Clone trait when 0.5 is released
  pure fn clone() -> Mpz unsafe {
    let mpz = mpz_struct { _mp_alloc: 0, _mp_size: 0, _mp_d: null() };
    __gmpz_init_set(mut_addr_of(&mpz), addr_of(&self.mpz));
    Mpz { mpz: mpz }
  }
}

impl Mpz: cmp::Eq {
  pure fn eq(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) == 0
  }
  pure fn ne(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) != 0
  }
}

impl Mpz: cmp::Ord {
  pure fn lt(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) < 0
  }
  pure fn le(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) <= 0
  }
  pure fn gt(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) > 0
  }
  pure fn ge(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) >= 0
  }
}

impl Mpz: num::Num {
  pure fn add(other: &Mpz) -> Mpz unsafe {
    let res = init();
    __gmpz_add(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn sub(other: &Mpz) -> Mpz unsafe {
    let res = init();
    __gmpz_sub(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn mul(other: &Mpz) -> Mpz unsafe {
    let res = init();
    __gmpz_mul(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn div(other: &Mpz) -> Mpz unsafe {
    if __gmpz_cmp_ui(addr_of(&self.mpz), 0) == 0 {
      fail ~"divide by zero";
    }

    let res = init();
    __gmpz_tdiv_q(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn modulo(other: &Mpz) -> Mpz unsafe {
    if __gmpz_cmp_ui(addr_of(&self.mpz), 0) == 0 {
      fail ~"divide by zero";
    }

    let res = init();
    __gmpz_mod(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn neg() -> Mpz unsafe {
    let res = init();
    __gmpz_neg(mut_addr_of(&res.mpz), addr_of(&self.mpz));
    res
  }
  pure fn to_int() -> int {
    fail ~"not implemented";
  }
  static pure fn from_int(other: int) -> Mpz {
    // the gmp functions dealing with longs aren't usable here - long is only
    // guaranteed to be at least 32-bit
    option::unwrap(from_str(other.to_str()))
  }
}

pub pure fn from_str_radix(s: &str, base: int) -> Option<Mpz> unsafe {
  let mpz = mpz_struct { _mp_alloc: 0, _mp_size: 0, _mp_d: null() };
  let mpz_ptr = mut_addr_of(&mpz);
  let r = as_c_str(s, { |s| __gmpz_init_set_str(mpz_ptr, s, base as c_int) });
  if r == 0 {
    Some(Mpz { mpz: mpz })
  } else {
    __gmpz_clear(mpz_ptr);
    None
  }
}

pub pure fn from_str(s: &str) -> Option<Mpz> {
  from_str_radix(s, 10)
}

impl Mpz : from_str::FromStr {
  static fn from_str(s: &str) -> Option<Mpz> {
    from_str(s)
  }
}

impl Mpz : to_str::ToStr {
  pure fn to_str() -> ~str {
    self.to_str_radix(10)
  }
}

pub pure fn init() -> Mpz unsafe {
  let mpz = mpz_struct { _mp_alloc: 0, _mp_size: 0, _mp_d: null() };
  __gmpz_init(mut_addr_of(&mpz));
  Mpz { mpz: mpz }
}

#[cfg(test)]
mod tests {
  #[test]
  fn test_set() {
    let mut x: Mpz = num::from_int(1000);
    let y: Mpz = num::from_int(5000);
    x.set(&y);
    assert(x == y);
  }

  #[test]
  fn size_in_base() {
    let x = option::unwrap(from_str("150000"));
    assert(x.size_in_base(10) == 6);
    assert(x == option::unwrap(from_str_radix("249f0", 16)));
    assert(x.size_in_base(16) == 5);
  }

  #[test]
  fn eq() {
    let x = option::unwrap(from_str("4242142195"));
    let y = option::unwrap(from_str("4242142195"));
    let z = option::unwrap(from_str("4242142196"));

    assert(x == y);
    assert(x != z);
    assert(y != z);
  }

  #[test]
  fn ord() {
    let x = option::unwrap(from_str("40000000000000000000000"));
    let y = option::unwrap(from_str("45000000000000000000000"));
    let z = option::unwrap(from_str("50000000000000000000000"));

    assert(x < y && x < z && y < z);
    assert(x <= x && x <= y && x <= z && y <= z);
    assert(z > y && z > x && y > x);
    assert(z >= z && z >= y && z >= x && y >= x);
  }

  #[test]
  #[should_fail]
  fn div_zero() {
    let x = init();
    x / x;
  }

  #[test]
  #[should_fail]
  fn modulo_zero() {
    let x = init();
    x % x;
  }

  #[test]
  fn test_div_round() {
    let x: Mpz = from_int(2);
    let y: Mpz = from_int(3);
    assert((x / y).to_str() == (2 / 3).to_str());
    assert((x / -y).to_str() == (2 / -3).to_str());
  }

  #[test]
  fn to_str_radix() {
    let x = option::unwrap(from_str("255"));
    assert(x.to_str_radix(16) == ~"ff");
  }

  #[test]
  fn to_str() {
    let x = option::unwrap(from_str("1234567890"));
    assert(x.to_str() == ~"1234567890");
  }

  #[test]
  fn invalid_str() {
    assert(from_str("foobar").is_none());
  }

  #[test]
  fn test_clone() {
    let a = option::unwrap(from_str("100"));
    let b = a.clone();
    assert(b == a);
    assert(a + b == option::unwrap(from_str("200")));
  }

  #[test]
  fn test_from_int() {
    let x: Mpz = from_int(150);
    assert(x.to_str() == ~"150");
    assert(x == option::unwrap(from_str("150")));
  }
}
<commit_msg>add abs method<commit_after>extern mod std;

use libc::c_char;
use libc::c_int;
use libc::size_t;
use libc::c_ulong;
use libc::c_void;
use num::from_int;
use ptr::null;
use ptr::addr_of;
use ptr::mut_addr_of;
use ptr::to_mut_unsafe_ptr;
use str::as_c_str;

struct mpz_struct {
  _mp_alloc: c_int,
  _mp_size: c_int,
  _mp_d: *c_void
}

type mpz_srcptr = *const mpz_struct;
type mpz_ptr = *mut mpz_struct;

extern mod gmp {
  fn __gmpz_init(x: mpz_ptr);
  fn __gmpz_init_set(rop: mpz_ptr, op: mpz_srcptr);
  fn __gmpz_init_set_str(rop: mpz_ptr, str: *c_char, base: c_int) -> c_int;
  fn __gmpz_clear(x: mpz_ptr);
  fn __gmpz_set(rop: mpz_ptr, op: mpz_srcptr);
  fn __gmpz_set_str(rop: mpz_ptr, str: *c_char, base: c_int) -> c_int;
  fn __gmpz_get_str(str: *c_char, base: c_int, op: mpz_srcptr) -> *c_char;
  pure fn __gmpz_sizeinbase(op: mpz_srcptr, base: c_int) -> size_t;
  pure fn __gmpz_cmp(op: mpz_srcptr, op2: mpz_srcptr) -> c_int;
  pure fn __gmpz_cmp_ui(op1: mpz_srcptr, op2: c_ulong) -> c_int;
  fn __gmpz_add(rop: mpz_ptr, op1: mpz_srcptr, op2: mpz_srcptr);
  fn __gmpz_sub(rop: mpz_ptr, op1: mpz_srcptr, op2: mpz_srcptr);
  fn __gmpz_mul(rop: mpz_ptr, op1: mpz_srcptr, op2: mpz_srcptr);
  fn __gmpz_neg(rop: mpz_ptr, op: mpz_srcptr);
  fn __gmpz_abs(rop: mpz_ptr, op: mpz_srcptr);
  fn __gmpz_tdiv_q(r: mpz_ptr, n: mpz_srcptr, d: mpz_srcptr);
  fn __gmpz_mod(r: mpz_ptr, n: mpz_srcptr, d: mpz_srcptr);
}

use gmp::*;

pub struct Mpz {
  priv mpz: mpz_struct,

  drop {
    __gmpz_clear(mut_addr_of(&self.mpz));
  }
}

impl Mpz {
  fn set(&mut self, other: &Mpz) {
    __gmpz_set(mut_addr_of(&self.mpz), addr_of(&other.mpz));
  }

  fn set_str(&mut self, s: &str, base: int) -> bool {
    let mpz = to_mut_unsafe_ptr(&mut self.mpz);
    let r = as_c_str(s, { |s| __gmpz_set_str(mpz, s, base as c_int) });
    r == 0
  }

  pure fn to_str_radix(&self, base: int) -> ~str unsafe {
    let length = self.size_in_base(10) + 2;
    let dst = vec::to_mut(vec::from_elem(length, '0'));
    let pdst = vec::raw::to_ptr(dst);

    str::raw::from_c_str(__gmpz_get_str(pdst as *c_char, base as c_int,
                         addr_of(&self.mpz)))
  }

  pure fn size_in_base(&self, base: int) -> uint {
    __gmpz_sizeinbase(addr_of(&self.mpz), base as c_int) as uint
  }

  // TODO: implement the clone::Clone trait when 0.5 is released
  pure fn clone() -> Mpz unsafe {
    let mpz = mpz_struct { _mp_alloc: 0, _mp_size: 0, _mp_d: null() };
    __gmpz_init_set(mut_addr_of(&mpz), addr_of(&self.mpz));
    Mpz { mpz: mpz }
  }

  pure fn abs() -> Mpz unsafe {
    let res = init();
    __gmpz_abs(mut_addr_of(&res.mpz), addr_of(&self.mpz));
    res
  }
}

impl Mpz: cmp::Eq {
  pure fn eq(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) == 0
  }
  pure fn ne(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) != 0
  }
}

impl Mpz: cmp::Ord {
  pure fn lt(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) < 0
  }
  pure fn le(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) <= 0
  }
  pure fn gt(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) > 0
  }
  pure fn ge(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) >= 0
  }
}

impl Mpz: num::Num {
  pure fn add(other: &Mpz) -> Mpz unsafe {
    let res = init();
    __gmpz_add(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn sub(other: &Mpz) -> Mpz unsafe {
    let res = init();
    __gmpz_sub(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn mul(other: &Mpz) -> Mpz unsafe {
    let res = init();
    __gmpz_mul(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn div(other: &Mpz) -> Mpz unsafe {
    if __gmpz_cmp_ui(addr_of(&self.mpz), 0) == 0 {
      fail ~"divide by zero";
    }

    let res = init();
    __gmpz_tdiv_q(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn modulo(other: &Mpz) -> Mpz unsafe {
    if __gmpz_cmp_ui(addr_of(&self.mpz), 0) == 0 {
      fail ~"divide by zero";
    }

    let res = init();
    __gmpz_mod(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn neg() -> Mpz unsafe {
    let res = init();
    __gmpz_neg(mut_addr_of(&res.mpz), addr_of(&self.mpz));
    res
  }
  pure fn to_int() -> int {
    fail ~"not implemented";
  }
  static pure fn from_int(other: int) -> Mpz {
    // the gmp functions dealing with longs aren't usable here - long is only
    // guaranteed to be at least 32-bit
    option::unwrap(from_str(other.to_str()))
  }
}

pub pure fn from_str_radix(s: &str, base: int) -> Option<Mpz> unsafe {
  let mpz = mpz_struct { _mp_alloc: 0, _mp_size: 0, _mp_d: null() };
  let mpz_ptr = mut_addr_of(&mpz);
  let r = as_c_str(s, { |s| __gmpz_init_set_str(mpz_ptr, s, base as c_int) });
  if r == 0 {
    Some(Mpz { mpz: mpz })
  } else {
    __gmpz_clear(mpz_ptr);
    None
  }
}

pub pure fn from_str(s: &str) -> Option<Mpz> {
  from_str_radix(s, 10)
}

impl Mpz : from_str::FromStr {
  static fn from_str(s: &str) -> Option<Mpz> {
    from_str(s)
  }
}

impl Mpz : to_str::ToStr {
  pure fn to_str() -> ~str {
    self.to_str_radix(10)
  }
}

pub pure fn init() -> Mpz unsafe {
  let mpz = mpz_struct { _mp_alloc: 0, _mp_size: 0, _mp_d: null() };
  __gmpz_init(mut_addr_of(&mpz));
  Mpz { mpz: mpz }
}

#[cfg(test)]
mod tests {
  #[test]
  fn test_set() {
    let mut x: Mpz = num::from_int(1000);
    let y: Mpz = num::from_int(5000);
    x.set(&y);
    assert(x == y);
  }

  #[test]
  fn size_in_base() {
    let x = option::unwrap(from_str("150000"));
    assert(x.size_in_base(10) == 6);
    assert(x == option::unwrap(from_str_radix("249f0", 16)));
    assert(x.size_in_base(16) == 5);
  }

  #[test]
  fn eq() {
    let x = option::unwrap(from_str("4242142195"));
    let y = option::unwrap(from_str("4242142195"));
    let z = option::unwrap(from_str("4242142196"));

    assert(x == y);
    assert(x != z);
    assert(y != z);
  }

  #[test]
  fn ord() {
    let x = option::unwrap(from_str("40000000000000000000000"));
    let y = option::unwrap(from_str("45000000000000000000000"));
    let z = option::unwrap(from_str("50000000000000000000000"));

    assert(x < y && x < z && y < z);
    assert(x <= x && x <= y && x <= z && y <= z);
    assert(z > y && z > x && y > x);
    assert(z >= z && z >= y && z >= x && y >= x);
  }

  #[test]
  #[should_fail]
  fn div_zero() {
    let x = init();
    x / x;
  }

  #[test]
  #[should_fail]
  fn modulo_zero() {
    let x = init();
    x % x;
  }

  #[test]
  fn test_div_round() {
    let x: Mpz = from_int(2);
    let y: Mpz = from_int(3);
    assert((x / y).to_str() == (2 / 3).to_str());
    assert((x / -y).to_str() == (2 / -3).to_str());
  }

  #[test]
  fn to_str_radix() {
    let x = option::unwrap(from_str("255"));
    assert(x.to_str_radix(16) == ~"ff");
  }

  #[test]
  fn to_str() {
    let x = option::unwrap(from_str("1234567890"));
    assert(x.to_str() == ~"1234567890");
  }

  #[test]
  fn invalid_str() {
    assert(from_str("foobar").is_none());
  }

  #[test]
  fn test_clone() {
    let a = option::unwrap(from_str("100"));
    let b = a.clone();
    assert(b == a);
    assert(a + b == option::unwrap(from_str("200")));
  }

  #[test]
  fn test_from_int() {
    let x: Mpz = from_int(150);
    assert(x.to_str() == ~"150");
    assert(x == option::unwrap(from_str("150")));
  }

  #[test]
  fn test_abs() {
    let x: Mpz = from_int(1000);
    let y: Mpz = from_int(-1000);
    assert(x.neg() == y);
    assert(x == y.neg());
    assert(x == y.abs());
    assert(x.abs() == y.abs());
  }
}
<|endoftext|>


<commit_before><commit_msg>rust: hashset<commit_after><|endoftext|>


<commit_before><commit_msg>Add ui test for writing anyhow instead of bail<commit_after>#![deny(unused_must_use)]

use anyhow::anyhow;

fn main() -> anyhow::Result<()> {
    if true {
        // meant to write bail!
        anyhow!("it failed");
    }
    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>added arithmetic/rational<commit_after>// http://rosettacode.org/wiki/Arithmetic/Rational
use std::num;
use std::fmt;

#[cfg(not(test))]
fn main() {
    for p in perfect_numbers(1 << 19).iter() {
        println!("{} is perfect", p);
    }
}

fn perfect_numbers(max: i64) -> Vec<i64> {
    let mut ret=Vec::new();
    for candidate in range(2, max) {
        let mut sum=Frac::secure_new(1, candidate).unwrap();
        let max2=((candidate as f64).sqrt().floor()) as i64;

        for factor in std::iter::range_inclusive(2, max2) {
            if candidate % factor == 0 {
                sum = sum + Frac::new(1, factor) + Frac::new(factor, candidate);
            }
        }
        if sum == Frac::new(1,1) {ret.push(candidate);}
    }
    ret
}

struct Frac {
    num: i64,
    den: i64
}

fn gcd(m: i64, n:i64) -> i64 {
    let mut t: i64;
    let (mut m, mut n)=(num::abs(m), num::abs(n));
    while n>0 { t = n; n = m % n; m = t; }
    m
}

fn lcm(m: i64, n:i64) -> i64 {
    num::abs(m) / gcd(m, n) * num::abs(n)
}

impl Frac {
    // fails on den=0
    fn new(num: i64, den:i64) -> Frac {
        let (n, d) = match (num, den) {
            (0, _)          => (0, 0),
            (n, d) if d<0   => (-n, -d),
            a @ _           => a
        };

        Frac {num: n, den: d}
    }

    // does not fail (returns Err on den=0)
    fn secure_new(num: i64, den:i64) -> Result<Frac, String> {
        if den==0 {
            Err("Error: Division by zero".to_string())
        } else {
            Ok(Frac::new(num, den))
        }
    }

    // fails on den=0, returns frac already in its reduced form
    fn new_reduced(num: i64, den:i64) -> Frac {
        Frac::new(num, den).reduce()
    }

    // reduces the fraction to lowest terms
    fn reduce(mut self) -> Frac {
        match self {
            z @ Frac{num:0, den:0} => z,
            _         => {
                let gcd=gcd(self.num, self.den);
                self.num /= gcd;
                self.den /= gcd;
                self
            }
        }
    }
}

impl fmt::Show for Frac {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match (self.num, self.den) {
            (_,1) | (0,0) => write!(f, "{}", self.num),
            (_,_) => write!(f, "{}/{}", self.num, self.den)
        }
    }
}

impl PartialEq for Frac {
    fn eq(&self, other: &Frac) -> bool {
        let (red_a, red_b) = (self.reduce(), other.reduce());
        red_a.num==red_b.num && red_a.den==red_b.den
    }
}

impl Eq for Frac {}

impl PartialOrd for Frac {
    fn lt(&self, other: &Frac) -> bool {
        (self.num * other.den) < (self.den * other.num)
    }
}

impl Ord for Frac {
    fn cmp(&self, other: &Frac) -> Ordering {
        (self.num * other.den).cmp(&(self.den * other.num))
    }
}

impl Neg<Frac> for Frac {
    fn neg(&self) -> Frac {
        Frac{num:-self.num, den:self.den}
    }
}

impl Add<Frac, Frac> for Frac {
    fn add(&self, other: &Frac) -> Frac {
        let (a, b)=(self.reduce(), other.reduce());
        let m = lcm(a.den, b.den);

        let na = a.num * m / a.den;
        let nb = b.num * m / b.den;
        Frac::new_reduced(na + nb, m)
    }
}

impl Sub<Frac, Frac> for Frac {
    fn sub(&self, other: &Frac) -> Frac {
        self + (-other)
    }
}

impl Mul<Frac, Frac> for Frac {
    fn mul(&self, other: &Frac) -> Frac {
        Frac::new_reduced(self.num * other.num, self.den * other.den)
    }
}

impl Div<Frac, Frac> for Frac {
    fn div(&self, other: &Frac) -> Frac {
        Frac::new_reduced(self.num * other.den, self.den * other.num)
    }
}

impl num::Zero for Frac {
    fn zero() -> Frac {
        Frac::new(0, 1)
    }

    fn is_zero(&self) -> bool {
        self.num == 0 && self.den == 0
    }
}

impl num::One for Frac {
    fn one() -> Frac {
        Frac::new(1, 1)
    }
}

#[test]
fn operators() {
    let (a, b) =  (Frac::new(1, 2), Frac::new(12,15));
    assert_eq!(a+b, Frac::secure_new(13, 10).unwrap());
    assert_eq!(b-a, Frac::new(3, 10));
    assert_eq!(a-b, Frac::new(-3, 10));
    assert_eq!(a*b, Frac::new(2, 5));
    assert_eq!(a/b, Frac::new(5, 8));

    let (a, b) =  (Frac::new(1, 2), Frac::new(1,2));
    assert_eq!(a+b, num::One::one());
    assert_eq!(b-a, num::Zero::zero());
    assert_eq!(a-b, num::Zero::zero());
    assert_eq!(a*b, Frac::new(1, 4));
    assert_eq!(a/b, Frac::new(1, 1));
}

#[test]
fn first_perfect_numbers() {
    assert_eq!(perfect_numbers(8150), vec![6,28,496,8128]);
}<|endoftext|>


<commit_before><commit_msg>Only look for lib name, do nothing if no lib target.<commit_after><|endoftext|>


<commit_before><commit_msg>polished cd functionality, included string matching for & for background tasks.<commit_after><|endoftext|>


<commit_before><commit_msg>Print response.<commit_after><|endoftext|>


<commit_before><commit_msg>initial commit for average_loop_length solution<commit_after>// http://rosettacode.org/wiki/Average_loop_length

//! Accepts two command-line arguments

extern crate rand;

use rand::{thread_rng};
use rand::distributions::{IndependentSample, Range};
use std::collections::{HashMap, HashSet};
use std::env;
use std::process;

fn help() {
    println!("usage: average_loop_length <max N> <trials>");
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let mut max_n: u32 = 20;
    let mut trials: u32 = 1000;

    match args.len() {
        1 => {},
        3 => {
            max_n = args[1].parse::<u32>().unwrap();
            trials = args[2].parse::<u32>().unwrap();
        },
        _ => {
            help();
            process::exit(0);
        }
    }

    println!(" N    average    analytical    (error)");
    println!("===  =========  ============  =========");
    for n in 1..(max_n + 1) {
        let the_analytical = analytical(n);
        let the_empirical = empirical(n, trials);
        println!(" {:>2}     {:3.4}        {:3.4}  ( {:>+1.2}%)",
            n,
            the_empirical,
            the_analytical,
            100f64 * (the_empirical / the_analytical - 1f64)
        );
    }
}

fn factorial(n: u32) -> f64 {
    (1..n+1).fold(1f64, |p, n| p*n as f64)
}

fn analytical(n: u32) -> f64 {
    let sum: f64 = (1..(n+1)).map(|i| {
        factorial(n) /
        (n as f64).powi(i as i32) /
        factorial(n - i)
    }).fold(0f64, |a, v| a+v);
    sum
}

fn make_mapping(n: u32) -> HashMap<u32, u32> {
    let mut mapping: HashMap<u32, u32> = HashMap::new();
    let mut rng = thread_rng();
    let range = Range::new(1u32, n+1);
    for i in 1..n+1 {
        mapping.insert(i as u32, range.ind_sample(&mut rng));
    }
    mapping
}

fn empirical(n: u32, trials: u32) -> f64 {
    let sum: f64 = (0..trials).map(|_t| {
        let a_mapping = make_mapping(n);
        let mut item = 1u32;
        let mut seen = HashSet::new();
        seen.insert(item);

        for step in 1..(n+1) {
            item = *a_mapping.get(&item).unwrap();
            if seen.contains(&item) {
                return step as f64;
            }
            seen.insert(item);
        }
        n as f64
    }).fold(0f64, |a, v| a+v);
    sum / trials as f64
}

#[cfg(test)]
mod tests {
    use super::{factorial, analytical, empirical};

    #[test]
    fn test_factorial() {
        assert_eq!(factorial(10), 3628800f64);
    }

    #[test]
    fn test_analytical() {
        assert!((analytical(10)-3.6602).abs() < 0.0001);
        assert!((analytical(20)-5.2936).abs() < 0.0001);
    }

    #[test]
    fn test_empirical() {
        let emp = empirical(20, 10000);
        let ana = analytical(20);
        assert!((emp / ana - 1f64).abs() < 0.05);
    }
}
<|endoftext|>


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


<commit_before><commit_msg>Record the command that transitions the acquired swapchain image to the start of the primary command buffer, and switch back to using a semaphore<commit_after><|endoftext|>


<commit_before><commit_msg>Wyvern: When reallocating Vulkan vertex and index buffers, only reallocate for the current thread<commit_after><|endoftext|>


<commit_before><commit_msg>Small cleanup for day 3 problem b<commit_after><|endoftext|>


<commit_before><commit_msg>everywhere.rs<commit_after><|endoftext|>


<commit_before>import codemap::span;
import base::ext_ctxt;

fn mk_lit(cx: ext_ctxt, sp: span, lit: ast::lit_) -> @ast::expr {
    let sp_lit = @{node: lit, span: sp};
    ret @{id: cx.next_id(), node: ast::expr_lit(sp_lit), span: sp};
}
fn mk_str(cx: ext_ctxt, sp: span, s: str) -> @ast::expr {
    let lit = ast::lit_str(@s);
    ret mk_lit(cx, sp, lit);
}
fn mk_int(cx: ext_ctxt, sp: span, i: int) -> @ast::expr {
    let lit = ast::lit_int(i as i64, ast::ty_i);
    ret mk_lit(cx, sp, lit);
}
fn mk_uint(cx: ext_ctxt, sp: span, u: uint) -> @ast::expr {
    let lit = ast::lit_uint(u as u64, ast::ty_u);
    ret mk_lit(cx, sp, lit);
}
fn mk_binary(cx: ext_ctxt, sp: span, op: ast::binop,
             lhs: @ast::expr, rhs: @ast::expr)
   -> @ast::expr {
    let binexpr = ast::expr_binary(op, lhs, rhs);
    ret @{id: cx.next_id(), node: binexpr, span: sp};
}
fn mk_unary(cx: ext_ctxt, sp: span, op: ast::unop, e: @ast::expr)
    -> @ast::expr {
    let expr = ast::expr_unary(op, e);
    ret @{id: cx.next_id(), node: expr, span: sp};
}
fn mk_path(cx: ext_ctxt, sp: span, idents: [ast::ident]/~) ->
    @ast::expr {
    let path = @{span: sp, global: false, idents: idents,
                 rp: none, types: []/~};
    let pathexpr = ast::expr_path(path);
    ret @{id: cx.next_id(), node: pathexpr, span: sp};
}
fn mk_access_(cx: ext_ctxt, sp: span, p: @ast::expr, m: ast::ident)
    -> @ast::expr {
    let expr = ast::expr_field(p, m, []/~);
    ret @{id: cx.next_id(), node: expr, span: sp};
}
fn mk_access(cx: ext_ctxt, sp: span, p: [ast::ident]/~, m: ast::ident)
    -> @ast::expr {
    let pathexpr = mk_path(cx, sp, p);
    ret mk_access_(cx, sp, pathexpr, m);
}
fn mk_call_(cx: ext_ctxt, sp: span, fn_expr: @ast::expr,
            args: [@ast::expr]/~) -> @ast::expr {
    let callexpr = ast::expr_call(fn_expr, args, false);
    ret @{id: cx.next_id(), node: callexpr, span: sp};
}
fn mk_call(cx: ext_ctxt, sp: span, fn_path: [ast::ident]/~,
             args: [@ast::expr]/~) -> @ast::expr {
    let pathexpr = mk_path(cx, sp, fn_path);
    ret mk_call_(cx, sp, pathexpr, args);
}
// e = expr, t = type
fn mk_vec_e(cx: ext_ctxt, sp: span, exprs: [@ast::expr]/~) ->
   @ast::expr {
    let vecexpr = ast::expr_vec(exprs, ast::m_imm);
    ret @{id: cx.next_id(), node: vecexpr, span: sp};
}
fn mk_vstore_e(cx: ext_ctxt, sp: span, expr: @ast::expr, vst: ast::vstore) ->
   @ast::expr {
    let vstoreexpr = ast::expr_vstore(expr, vst);
    ret @{id: cx.next_id(), node: vstoreexpr, span: sp};
}
fn mk_uniq_vec_e(cx: ext_ctxt, sp: span, exprs: [@ast::expr]/~) ->
   @ast::expr {
    mk_vstore_e(cx, sp, mk_vec_e(cx, sp, exprs), ast::vstore_uniq)
}

fn mk_rec_e(cx: ext_ctxt, sp: span,
            fields: [{ident: ast::ident, ex: @ast::expr}]/~) ->
    @ast::expr {
    let mut astfields: [ast::field]/~ = []/~;
    for fields.each {|field|
        let ident = field.ident;
        let val = field.ex;
        let astfield =
            {node: {mutbl: ast::m_imm, ident: ident, expr: val}, span: sp};
        astfields += [astfield]/~;
    }
    let recexpr = ast::expr_rec(astfields, option::none::<@ast::expr>);
    ret @{id: cx.next_id(), node: recexpr, span: sp};
}

<commit_msg>Have the syntax extension ast builders reserve the extra node ids required for overloading. Closes #2732.<commit_after>import codemap::span;
import base::ext_ctxt;

fn mk_lit(cx: ext_ctxt, sp: span, lit: ast::lit_) -> @ast::expr {
    let sp_lit = @{node: lit, span: sp};
    ret @{id: cx.next_id(), node: ast::expr_lit(sp_lit), span: sp};
}
fn mk_str(cx: ext_ctxt, sp: span, s: str) -> @ast::expr {
    let lit = ast::lit_str(@s);
    ret mk_lit(cx, sp, lit);
}
fn mk_int(cx: ext_ctxt, sp: span, i: int) -> @ast::expr {
    let lit = ast::lit_int(i as i64, ast::ty_i);
    ret mk_lit(cx, sp, lit);
}
fn mk_uint(cx: ext_ctxt, sp: span, u: uint) -> @ast::expr {
    let lit = ast::lit_uint(u as u64, ast::ty_u);
    ret mk_lit(cx, sp, lit);
}
fn mk_binary(cx: ext_ctxt, sp: span, op: ast::binop,
             lhs: @ast::expr, rhs: @ast::expr)
   -> @ast::expr {
    cx.next_id(); // see ast_util::op_expr_callee_id
    let binexpr = ast::expr_binary(op, lhs, rhs);
    ret @{id: cx.next_id(), node: binexpr, span: sp};
}
fn mk_unary(cx: ext_ctxt, sp: span, op: ast::unop, e: @ast::expr)
    -> @ast::expr {
    cx.next_id(); // see ast_util::op_expr_callee_id
    let expr = ast::expr_unary(op, e);
    ret @{id: cx.next_id(), node: expr, span: sp};
}
fn mk_path(cx: ext_ctxt, sp: span, idents: [ast::ident]/~) ->
    @ast::expr {
    let path = @{span: sp, global: false, idents: idents,
                 rp: none, types: []/~};
    let pathexpr = ast::expr_path(path);
    ret @{id: cx.next_id(), node: pathexpr, span: sp};
}
fn mk_access_(cx: ext_ctxt, sp: span, p: @ast::expr, m: ast::ident)
    -> @ast::expr {
    let expr = ast::expr_field(p, m, []/~);
    ret @{id: cx.next_id(), node: expr, span: sp};
}
fn mk_access(cx: ext_ctxt, sp: span, p: [ast::ident]/~, m: ast::ident)
    -> @ast::expr {
    let pathexpr = mk_path(cx, sp, p);
    ret mk_access_(cx, sp, pathexpr, m);
}
fn mk_call_(cx: ext_ctxt, sp: span, fn_expr: @ast::expr,
            args: [@ast::expr]/~) -> @ast::expr {
    let callexpr = ast::expr_call(fn_expr, args, false);
    ret @{id: cx.next_id(), node: callexpr, span: sp};
}
fn mk_call(cx: ext_ctxt, sp: span, fn_path: [ast::ident]/~,
             args: [@ast::expr]/~) -> @ast::expr {
    let pathexpr = mk_path(cx, sp, fn_path);
    ret mk_call_(cx, sp, pathexpr, args);
}
// e = expr, t = type
fn mk_vec_e(cx: ext_ctxt, sp: span, exprs: [@ast::expr]/~) ->
   @ast::expr {
    let vecexpr = ast::expr_vec(exprs, ast::m_imm);
    ret @{id: cx.next_id(), node: vecexpr, span: sp};
}
fn mk_vstore_e(cx: ext_ctxt, sp: span, expr: @ast::expr, vst: ast::vstore) ->
   @ast::expr {
    let vstoreexpr = ast::expr_vstore(expr, vst);
    ret @{id: cx.next_id(), node: vstoreexpr, span: sp};
}
fn mk_uniq_vec_e(cx: ext_ctxt, sp: span, exprs: [@ast::expr]/~) ->
   @ast::expr {
    mk_vstore_e(cx, sp, mk_vec_e(cx, sp, exprs), ast::vstore_uniq)
}

fn mk_rec_e(cx: ext_ctxt, sp: span,
            fields: [{ident: ast::ident, ex: @ast::expr}]/~) ->
    @ast::expr {
    let mut astfields: [ast::field]/~ = []/~;
    for fields.each {|field|
        let ident = field.ident;
        let val = field.ex;
        let astfield =
            {node: {mutbl: ast::m_imm, ident: ident, expr: val}, span: sp};
        astfields += [astfield]/~;
    }
    let recexpr = ast::expr_rec(astfields, option::none::<@ast::expr>);
    ret @{id: cx.next_id(), node: recexpr, span: sp};
}

<|endoftext|>


<commit_before><commit_msg>Add problem #37<commit_after>extern mod euler;
use euler::prime::{ Prime };

fn is_r2l(n: uint, ps: &Prime) -> bool {
    let mut itr = n / 10;
    while itr > 0 {
        if !ps.is_prime(itr) {
            return false;
        }
        itr /= 10;
    }
    return true;
}

fn main() {
    let ps = Prime();
    let mut l2r_mat = ~[ ~[ 2, 3, 5, 7 ] ];
    let mut order = 10;

    loop {
        let mut result = ~[];
        for l2r_mat[l2r_mat.len() - 1].each |p| {
            for [ 1, 3, 5, 7, 9 ].each |d| {
                let n = order * (*d) + (*p);
                if ps.is_prime(n) { result += [n]; }
            }
        }
        if result.is_empty() { break; }
        l2r_mat.push(result);
        order *= 10;
    }

    let l2r = vec::concat(l2r_mat);
    let mut sum = 0;
    for l2r.each |n| {
        if *n < 10 { loop; }
        if is_r2l(*n, &ps) {
            io::println(fmt!("%u", *n));
            sum += *n;
        }
    }

    io::println(fmt!("answer: %u", sum));
}<|endoftext|>


<commit_before><commit_msg>Add problem #50<commit_after>extern mod euler;
use euler::prime::{ Prime };

fn get_longer(p: uint, min_len: uint, ps: &Prime) -> Option<uint> {
    fn get_prime(n: int, ps: &Prime)-> uint {
        if n < 0 { 0 } else { ps.get_at(n as uint) }
    }

    let max_avg = if min_len == 0 { p } else { p / min_len };

    let mut start_idx = 0;
    let mut end_idx   = 0;
    let mut start     = ps.get_at(0);
    let mut sum       = ps.get_at(0);
    loop {
        let len = (end_idx - start_idx + 1) as uint;
        if sum / len > max_avg { return None; }
        if sum == p {
            if len <= min_len {
                return None;
            } else {
                return Some(len);
            }
        }

        if sum < p {
            end_idx += 1;
            sum += get_prime(end_idx, ps);
            loop;
        }

        if sum > p {
            sum -= start;
            start_idx += 1;
            start = get_prime(start_idx, ps);
            loop;
        }
    }
}

fn main() {
    let limit = 1000000;
    let ps = Prime();

    let mut len = 0;
    let mut num = 0;
    for ps.each |p| {
        if p > limit { break; }
        match get_longer(p, len, &ps) {
            Some(l) => {
                io::println(fmt!("%u => %u", p, l));
                len = l;
                num = p;
            }
            None => {}
        }
    }
    io::println(fmt!("%u: %u", num, len));
    io::println(fmt!("answer: %u", num));
}
<|endoftext|>


<commit_before><commit_msg>Add Repository struct<commit_after>use object_id::ObjectId;
use tag::Tag;
use branch::Branch;
use reference::Reference;
use pack_index::PackIndex;

pub struct Repository {
    pub path: String,
    pub wc_path: String,
    pub tags: Vec<Tag>,
    pub branches: Vec<Branch>,
    pub references: Vec<Reference>,
    pub pack_indexes: Vec<PackIndex>,
}<|endoftext|>


<commit_before><commit_msg>Add regression 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(rustc_attrs)]

#[rustc_error]
fn main() { //~ ERROR compilation successful
    macro_rules! m { ($s:stmt;) => { $s } }
    m!(vec![].push(0););
}
<|endoftext|>


<commit_before><commit_msg>add some tests with constants that better be valid<commit_after>// compile-pass

// Some constants that *are* valid
#![feature(const_transmute)]

use std::mem;
use std::ptr::NonNull;
use std::num::{NonZeroU8, NonZeroUsize};

const NON_NULL_PTR1: NonNull<u8> = unsafe { mem::transmute(1usize) };
const NON_NULL_PTR2: NonNull<u8> = unsafe { mem::transmute(&0) };

const NON_NULL_U8: NonZeroU8 = unsafe { mem::transmute(1u8) };
const NON_NULL_USIZE: NonZeroUsize = unsafe { mem::transmute(1usize) };

const UNIT: () = ();

fn main() {}
<|endoftext|>


<commit_before><commit_msg>add integration test<commit_after>extern crate stratis_shared as shared;
extern crate stratis;

use stratis::{Server,Client};
use shared::opcode;
use shared::events::Event;

use std::thread;
use std::time::Duration;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::Receiver;

fn assert_opcode (rx: &Receiver<Event>, op: u8) -> Event {
    match rx.try_recv() {
        Ok(ev) => {
            assert_eq!(ev.0,op);
            return ev
        },
        _ => { panic!("no events received"); }
    }
}

fn assert_client () -> (Arc<Mutex<Client>>,Receiver<Event>) {
    let host = "127.0.0.1:65432";
    let _handle = thread::spawn(move || {
        let mut _server = Server::new(host);
    });
    let (mut client, rx) = Client::default();
    client.connect(host);
    client.register();

    let client = Arc::new(Mutex::new(client));
    Client::login(&client);

    assert!(client.lock().unwrap().stream.is_some());

    (client,rx)
}

#[test]
fn client () {
    let (_client, rx) = assert_client();

    thread::sleep(Duration::from_millis(100));

    // we recv player twice
    // once for our own login
    // and again for each player that's connected
    assert_opcode(&rx,opcode::PLAYER);
    assert_opcode(&rx,opcode::PLAYER);

    thread::sleep(Duration::from_millis(100));
}
<|endoftext|>


<commit_before><commit_msg>Expunge --olddriver option: The argument was still present after the previous commit to replace it with an automated detection<commit_after><|endoftext|>


<commit_before><commit_msg>test(config_cli): multi-occurrence cli args with paths<commit_after><|endoftext|>


<commit_before><commit_msg>ICH: Add test case for let-expressions.<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.

// This test case tests the incremental compilation hash (ICH) implementation
// for let expressions.

// The general pattern followed here is: Change one thing between rev1 and rev2
// and make sure that the hash has changed, then change nothing between rev2 and
// rev3 and make sure that the hash has not changed.

// must-compile-successfully
// revisions: cfail1 cfail2 cfail3
// compile-flags: -Z query-dep-graph

#![allow(warnings)]
#![feature(rustc_attrs)]
#![crate_type="rlib"]

// Change Name -----------------------------------------------------------------
#[cfg(cfail1)]
pub fn change_name() {
    let _x = 2u64;
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn change_name() {
    let _y = 2u64;
}

// Add Type --------------------------------------------------------------------
#[cfg(cfail1)]
pub fn add_type() {
    let _x = 2u32;
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn add_type() {
    let _x: u32 = 2u32;
}

// Change Type -----------------------------------------------------------------
#[cfg(cfail1)]
pub fn change_type() {
    let _x: u64 = 2;
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn change_type() {
    let _x: u8 = 2;
}

// Change Mutability of Reference Type -----------------------------------------
#[cfg(cfail1)]
pub fn change_mutability_of_reference_type() {
    let _x: &u64;
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn change_mutability_of_reference_type() {
    let _x: &mut u64;
}

// Change Mutability of Slot ---------------------------------------------------
#[cfg(cfail1)]
pub fn change_mutability_of_slot() {
    let mut _x: u64 = 0;
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn change_mutability_of_slot() {
    let _x: u64 = 0;
}

// Change Simple Binding to Pattern --------------------------------------------
#[cfg(cfail1)]
pub fn change_simple_binding_to_pattern() {
    let _x = (0u8, 'x');
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn change_simple_binding_to_pattern() {
    let (_a, _b) = (0u8, 'x');
}

// Change Name in Pattern ------------------------------------------------------
#[cfg(cfail1)]
pub fn change_name_in_pattern() {
    let (_a, _b) = (1u8, 'y');
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn change_name_in_pattern() {
    let (_a, _c) = (1u8, 'y');
}

// Add `ref` in Pattern --------------------------------------------------------
#[cfg(cfail1)]
pub fn add_ref_in_pattern() {
    let (_a, _b) = (1u8, 'y');
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn add_ref_in_pattern() {
    let (ref _a, _b) = (1u8, 'y');
}

// Add `&` in Pattern ----------------------------------------------------------
#[cfg(cfail1)]
pub fn add_amp_in_pattern() {
    let (_a, _b) = (&1u8, 'y');
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn add_amp_in_pattern() {
    let (&_a, _b) = (&1u8, 'y');
}

// Change Mutability of Binding in Pattern -------------------------------------
#[cfg(cfail1)]
pub fn change_mutability_of_binding_in_pattern() {
    let (_a, _b) = (99u8, 'q');
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn change_mutability_of_binding_in_pattern() {
    let (mut _a, _b) = (99u8, 'q');
}

// Add Initializer -------------------------------------------------------------
#[cfg(cfail1)]
pub fn add_initializer() {
    let _x: i16;
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn add_initializer() {
    let _x: i16 = 3i16;
}

// Change Initializer ----------------------------------------------------------
#[cfg(cfail1)]
pub fn change_initializer() {
    let _x = 4u16;
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn change_initializer() {
    let _x = 5u16;
}
<|endoftext|>


<commit_before><commit_msg>terrain generation back online<commit_after><|endoftext|>


<commit_before>// High-level bindings to Cairo.

import cairo::{CAIRO_STATUS_SUCCESS, cairo_format_t, cairo_status_t, cairo_surface_t, cairo_t};
import cairo::bindgen::{cairo_create, cairo_fill, cairo_image_surface_create};
import cairo::bindgen::{cairo_image_surface_get_data, cairo_image_surface_get_format};
import cairo::bindgen::{cairo_image_surface_get_height, cairo_image_surface_get_stride};
import cairo::bindgen::{cairo_image_surface_get_width, cairo_rectangle, cairo_set_line_width};
import cairo::bindgen::{cairo_set_source_rgb, cairo_stroke, cairo_surface_destroy};
import cairo::bindgen::{cairo_surface_write_to_png_stream};
import io::{mem_buffer, writer};
import ptr::addr_of;
import result::{err, ok, result};
import unsafe::reinterpret_cast;
import vec::unsafe::{form_slice, from_buf};

// FIXME: We should have a hierarchy of surfaces, but this needs to wait on case classes.
class ImageSurface {
    let cairo_surface: *cairo_surface_t;

    new(format: cairo_format_t, width: c_int, height: c_int) {
        self.cairo_surface = cairo_image_surface_create(format, width, height);
        if self.cairo_surface.is_null() {
            fail ~"couldn't create Cairo image surface";
        };
    }

    fn width()  -> c_int    { cairo_image_surface_get_width(self.cairo_surface)  }
    fn height() -> c_int    { cairo_image_surface_get_height(self.cairo_surface) }
    fn stride() -> c_int    { cairo_image_surface_get_stride(self.cairo_surface) }
    fn format() -> c_int    { cairo_image_surface_get_format(self.cairo_surface) }

    fn data() -> ~[u8] unsafe {
        let buffer = cairo_image_surface_get_data(self.cairo_surface);
        return from_buf(buffer, (self.stride() * self.height()) as uint);
    }

    drop {
        cairo_surface_destroy(self.cairo_surface);
    }
}

impl ImageSurface {
    fn write_to_png_stream(buffer: &io::mem_buffer) -> result<(),cairo_status_t> unsafe {
        extern fn write_fn(closure: *c_void, data: *c_uchar, len: c_uint)
                        -> cairo_status_t unsafe {
            let writer: *mem_buffer = reinterpret_cast(closure);
            do form_slice(data, len as uint) |bytes| {
                (*writer).write(bytes);
            }
            return CAIRO_STATUS_SUCCESS;
        }

        let buffer_ptr = reinterpret_cast(buffer);
        let status = cairo_surface_write_to_png_stream(self.cairo_surface, write_fn, buffer_ptr);
        if status != CAIRO_STATUS_SUCCESS {
            return err(status);
        }

        return ok(());
    }
}

class Context {
    let cairo_context: *cairo_t;

    new(&&surface: ImageSurface) {
        self.cairo_context = cairo_create(surface.cairo_surface);
    }

    fn set_line_width(width: c_double) {
        cairo_set_line_width(self.cairo_context, width);
    }

    fn set_source_rgb(r: c_double, g: c_double, b: c_double) {
        cairo_set_source_rgb(self.cairo_context, r, g, b);
    }

    fn rectangle(x: c_double, y: c_double, width: c_double, height: c_double) {
        cairo_rectangle(self.cairo_context, x, y, width, height);
    }

    fn stroke() {
        cairo_stroke(self.cairo_context);
    }

    fn fill() {
        cairo_fill(self.cairo_context);
    }
}

<commit_msg>Add a few more functions to the high-level Cairo API<commit_after>// High-level bindings to Cairo.

import cairo::{CAIRO_STATUS_SUCCESS, cairo_format_t, cairo_status_t, cairo_surface_t, cairo_t};
import cairo::bindgen::{cairo_create, cairo_fill, cairo_image_surface_create};
import cairo::bindgen::{cairo_image_surface_get_data, cairo_image_surface_get_format};
import cairo::bindgen::{cairo_image_surface_get_height, cairo_image_surface_get_stride};
import cairo::bindgen::{cairo_image_surface_get_width, cairo_rectangle, cairo_set_line_width};
import cairo::bindgen::{cairo_set_source_rgb, cairo_stroke, cairo_surface_destroy};
import cairo::bindgen::{cairo_surface_reference, cairo_surface_write_to_png_stream};
import io::{mem_buffer, writer};
import ptr::addr_of;
import result::{err, ok, result};
import unsafe::reinterpret_cast;
import vec::unsafe::{form_slice, from_buf};

// FIXME: We should have a hierarchy of surfaces, but this needs to wait on case classes.
class ImageSurface {
    let cairo_surface: *cairo_surface_t;

    fn width()  -> c_int    { cairo_image_surface_get_width(self.cairo_surface)  }
    fn height() -> c_int    { cairo_image_surface_get_height(self.cairo_surface) }
    fn stride() -> c_int    { cairo_image_surface_get_stride(self.cairo_surface) }
    fn format() -> c_int    { cairo_image_surface_get_format(self.cairo_surface) }

    // FIXME: This should not copy!
    pure fn data() -> ~[u8] unsafe {
        let buffer = cairo_image_surface_get_data(self.cairo_surface);
        return from_buf(buffer, (self.stride() * self.height()) as uint);
    }

    drop {
        cairo_surface_destroy(self.cairo_surface);
    }
}

// Should be private.
fn image_surface_from_cairo_surface(cairo_surface: *cairo_surface_t) -> ImageSurface {
    assert !cairo_surface.is_null();
    ImageSurface { cairo_surface: cairo_surface }
}

fn ImageSurface(format: cairo_format_t, width: c_int, height: c_int) -> ImageSurface {
    let cairo_surface = cairo_image_surface_create(format, width, height);
    if cairo_surface.is_null() {
        fail ~"couldn't create Cairo image surface";
    }
    return image_surface_from_cairo_surface(move cairo_surface);
}

impl ImageSurface {
    fn write_to_png_stream(buffer: &io::mem_buffer) -> result<(),cairo_status_t> unsafe {
        extern fn write_fn(closure: *c_void, data: *c_uchar, len: c_uint)
                        -> cairo_status_t unsafe {
            let writer: *mem_buffer = reinterpret_cast(closure);
            do form_slice(data, len as uint) |bytes| {
                (*writer).write(bytes);
            }
            return CAIRO_STATUS_SUCCESS;
        }

        let buffer_ptr = reinterpret_cast(buffer);
        let status = cairo_surface_write_to_png_stream(self.cairo_surface, write_fn, buffer_ptr);
        if status != CAIRO_STATUS_SUCCESS {
            return err(status);
        }

        return ok(());
    }

    fn clone() -> ImageSurface {
        cairo_surface_reference(self.cairo_surface);
        return image_surface_from_cairo_surface(self.cairo_surface);
    }
}

class Context {
    let cairo_context: *cairo_t;

    new(&&surface: ImageSurface) {
        self.cairo_context = cairo_create(surface.cairo_surface);
    }

    fn set_line_width(width: c_double) {
        cairo_set_line_width(self.cairo_context, width);
    }

    fn set_source_rgb(r: c_double, g: c_double, b: c_double) {
        cairo_set_source_rgb(self.cairo_context, r, g, b);
    }

    fn rectangle(x: c_double, y: c_double, width: c_double, height: c_double) {
        cairo_rectangle(self.cairo_context, x, y, width, height);
    }

    fn stroke() {
        cairo_stroke(self.cairo_context);
    }

    fn fill() {
        cairo_fill(self.cairo_context);
    }
}

<|endoftext|>


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

// Make sure the destructor is run for unit-like structs.

use std::task;

struct Foo;

impl Drop for Foo {
    fn finalize(&self) {
        fail!("This failure should happen.");
    }
}

fn main() {
    let x = do task::try {
        let _b = Foo;
    };
    assert_eq!(x, Err(()));
}
<commit_msg>Mark run-pass/unit-like-struct-drop-run.rs as xfast-fail.<commit_after>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// Make sure the destructor is run for unit-like structs.
// xfail-fast

use std::task;

struct Foo;

impl Drop for Foo {
    fn finalize(&self) {
        fail!("This failure should happen.");
    }
}

fn main() {
    let x = do task::try {
        let _b = Foo;
    };
    assert_eq!(x, Err(()));
}
<|endoftext|>


<commit_before><commit_msg>Update/add some test expressions<commit_after><|endoftext|>


<commit_before><commit_msg>Auto merge of #10002 - TaKO8Ki:fix-clippy-warnings, r=ehuss<commit_after><|endoftext|>


<commit_before>use std::mem;

use runtime::{Message, Sel};

pub struct Encoding<T>(pub &'static str);

pub trait Encode {
	fn code() -> Encoding<Self>;
}

impl Encode for i8 {
	fn code() -> Encoding<i8> { Encoding("c") }
}

impl Encode for i16 {
	fn code() -> Encoding<i16> { Encoding("s") }
}

impl Encode for i32 {
	fn code() -> Encoding<i32> { Encoding("i") }
}

impl Encode for i64 {
	fn code() -> Encoding<i64> { Encoding("q") }
}

impl Encode for int {
	fn code() -> Encoding<int> {
		match mem::size_of::<int>() {
			1 => Encoding("c"),
			2 => Encoding("s"),
			4 => Encoding("i"),
			8 => Encoding("q"),
			_ => Encoding("?"),
		}
	}
}

impl Encode for u8 {
	fn code() -> Encoding<u8> { Encoding("C") }
}

impl Encode for u16 {
	fn code() -> Encoding<u16> { Encoding("S") }
}

impl Encode for u32 {
	fn code() -> Encoding<u32> { Encoding("I") }
}

impl Encode for u64 {
	fn code() -> Encoding<u64> { Encoding("Q") }
}

impl Encode for uint {
	fn code() -> Encoding<uint> {
		match mem::size_of::<uint>() {
			1 => Encoding("C"),
			2 => Encoding("S"),
			4 => Encoding("I"),
			8 => Encoding("Q"),
			_ => Encoding("?"),
		}
	}
}

impl Encode for f32 {
	fn code() -> Encoding<f32> { Encoding("f") }
}

impl Encode for f64 {
	fn code() -> Encoding<f64> { Encoding("d") }
}

impl Encode for bool {
	fn code() -> Encoding<bool> { Encoding("B") }
}

impl Encode for () {
	fn code() -> Encoding<()> { Encoding("v") }
}

impl<'a, T: Message> Encode for &'a T {
	fn code() -> Encoding<&'a T> { Encoding("@") }
}

impl<'a, T: Message> Encode for &'a mut T {
	fn code() -> Encoding<&'a mut T> { Encoding("@") }
}

impl<T: Message> Encode for *const T {
	fn code() -> Encoding<*const T> { Encoding("@") }
}

impl<T: Message> Encode for *mut T {
	fn code() -> Encoding<*mut T> { Encoding("@") }
}

impl Encode for Sel {
	fn code() -> Encoding<Sel> { Encoding(":") }
}

pub fn encode<T: Encode>() -> &'static str {
	let Encoding(code): Encoding<T> = Encode::code();
	code
}

#[cfg(test)]
mod tests {
	use runtime::{Object, Sel};
	use super::encode;

	#[test]
	fn test_encode() {
		assert!(encode::<u32>() == "I");
		assert!(encode::<()>() == "v");
		assert!(encode::<&Object>() == "@");
		assert!(encode::<*mut Object>() == "@");
		assert!(encode::<Sel>() == ":");
	}
}
<commit_msg>Use cfg instead of size_of for encode.<commit_after>use runtime::{Message, Sel};

pub struct Encoding<T>(pub &'static str);

pub trait Encode {
	fn code() -> Encoding<Self>;
}

impl Encode for i8 {
	fn code() -> Encoding<i8> { Encoding("c") }
}

impl Encode for i16 {
	fn code() -> Encoding<i16> { Encoding("s") }
}

impl Encode for i32 {
	fn code() -> Encoding<i32> { Encoding("i") }
}

impl Encode for i64 {
	fn code() -> Encoding<i64> { Encoding("q") }
}

impl Encode for int {
	#[cfg(target_word_size = "32")]
	fn code() -> Encoding<int> { Encoding("i") }

	#[cfg(target_word_size = "64")]
	fn code() -> Encoding<int> { Encoding("q") }
}

impl Encode for u8 {
	fn code() -> Encoding<u8> { Encoding("C") }
}

impl Encode for u16 {
	fn code() -> Encoding<u16> { Encoding("S") }
}

impl Encode for u32 {
	fn code() -> Encoding<u32> { Encoding("I") }
}

impl Encode for u64 {
	fn code() -> Encoding<u64> { Encoding("Q") }
}

impl Encode for uint {
	#[cfg(target_word_size = "32")]
	fn code() -> Encoding<uint> { Encoding("I") }

	#[cfg(target_word_size = "64")]
	fn code() -> Encoding<uint> { Encoding("Q") }
}

impl Encode for f32 {
	fn code() -> Encoding<f32> { Encoding("f") }
}

impl Encode for f64 {
	fn code() -> Encoding<f64> { Encoding("d") }
}

impl Encode for bool {
	fn code() -> Encoding<bool> { Encoding("B") }
}

impl Encode for () {
	fn code() -> Encoding<()> { Encoding("v") }
}

impl<'a, T: Message> Encode for &'a T {
	fn code() -> Encoding<&'a T> { Encoding("@") }
}

impl<'a, T: Message> Encode for &'a mut T {
	fn code() -> Encoding<&'a mut T> { Encoding("@") }
}

impl<T: Message> Encode for *const T {
	fn code() -> Encoding<*const T> { Encoding("@") }
}

impl<T: Message> Encode for *mut T {
	fn code() -> Encoding<*mut T> { Encoding("@") }
}

impl Encode for Sel {
	fn code() -> Encoding<Sel> { Encoding(":") }
}

pub fn encode<T: Encode>() -> &'static str {
	let Encoding(code): Encoding<T> = Encode::code();
	code
}

#[cfg(test)]
mod tests {
	use runtime::{Object, Sel};
	use super::encode;

	#[test]
	fn test_encode() {
		assert!(encode::<u32>() == "I");
		assert!(encode::<()>() == "v");
		assert!(encode::<&Object>() == "@");
		assert!(encode::<*mut Object>() == "@");
		assert!(encode::<Sel>() == ":");
	}
}
<|endoftext|>


<commit_before><commit_msg>Don't create ~/.sherpa dir anymore<commit_after><|endoftext|>


<commit_before><commit_msg>Refine variable declarations<commit_after><|endoftext|>


<commit_before><commit_msg>Removing deprecated BoxFuture<commit_after><|endoftext|>


<commit_before><commit_msg>[No-auto] lib/domain/bookmark: Fix Clippy warnings<commit_after><|endoftext|>


<commit_before><commit_msg>Remove unused options<commit_after><|endoftext|>


<commit_before><commit_msg>Make Alert::expires optional<commit_after><|endoftext|>


<commit_before><commit_msg>move player movement to its own object<commit_after><|endoftext|>


<commit_before><commit_msg>Optimized daemon search<commit_after><|endoftext|>


<commit_before>import T = inst::T;

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;

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 }

#[doc = "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;
    }
}

#[doc = "Computes the bitwise complement"]
pure fn compl(i: T) -> T {
    -1 as T ^ i
}

#[doc = "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 }
}

#[doc = "
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;
    };
}

#[doc = "Parse a string to an int"]
fn from_str(s: str) -> option<T> { parse_buf(str::bytes(s), 10u) }

#[doc = "Convert to a string in a given base"]
fn to_str(n: T, radix: uint) -> str {
    assert (0u < radix && radix <= 16u);
    ret if n < 0 as T {
            "-" + uint::to_str(-n as uint, radix)
        } else { uint::to_str(n as uint, radix) };
}

fn to_str_bytes<U>(n: T, radix: uint, f: fn([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)
    }
}

#[doc = "Convert to a string"]
fn str(i: T) -> str { ret to_str(i, 10u); }

// FIXME: Has alignment issues on windows and 32-bit linux
#[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
#[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"));
}
<commit_msg>Shave off one more string append in a rare case.<commit_after>import T = inst::T;

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;

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 }

#[doc = "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;
    }
}

#[doc = "Computes the bitwise complement"]
pure fn compl(i: T) -> T {
    -1 as T ^ i
}

#[doc = "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 }
}

#[doc = "
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;
    };
}

#[doc = "Parse a string to an int"]
fn from_str(s: str) -> option<T> { parse_buf(str::bytes(s), 10u) }

#[doc = "Convert to a string in a given base"]
fn to_str(n: T, radix: uint) -> str unsafe {
    to_str_bytes(n, radix) {|slice|
        vec::unpack_slice(slice) {|p, len|
            str::unsafe::from_buf_len(p, len)
        }
    }
}

fn to_str_bytes<U>(n: T, radix: uint, f: fn([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)
    }
}

#[doc = "Convert to a string"]
fn str(i: T) -> str { ret to_str(i, 10u); }

// FIXME: Has alignment issues on windows and 32-bit linux
#[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
#[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"));
}
<|endoftext|>