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

//! A module for representing spans (in an interval tree), useful for rich text
//! annotations. It is parameterized over a data type, so can be used for
//! storing different annotations.

use std::marker::PhantomData;
use std::mem;

use tree::{Leaf, Node, NodeInfo, TreeBuilder, Cursor};
use delta::Transformer;
use interval::Interval;

const MIN_LEAF: usize = 32;
const MAX_LEAF: usize = 64;

pub type Spans<T> = Node<SpansInfo<T>>;

#[derive(Clone)]
pub struct Span<T: Clone> {
    iv: Interval,
    data: T,
}

#[derive(Clone, Default)]
pub struct SpansLeaf<T: Clone> {
    len: usize,  // measured in base units
    spans: Vec<Span<T>>,
}

#[derive(Clone)]
pub struct SpansInfo<T> {
    n_spans: usize,
    iv: Interval,
    phantom: PhantomData<T>,
}

impl<T: Clone + Default> Leaf for SpansLeaf<T> {
    fn len(&self) -> usize {
        self.len
    }

    fn is_ok_child(&self) -> bool {
        self.spans.len() >= MIN_LEAF
    }

    fn push_maybe_split(&mut self, other: &Self, iv: Interval) -> Option<Self> {
        let iv_start = iv.start();
        for span in &other.spans {
            let span_iv = span.iv.intersect(iv).translate_neg(iv_start).translate(self.len);
            if !span_iv.is_empty() {
                self.spans.push(Span {
                    iv: span_iv,
                    data: span.data.clone(),
                });
            }
        }
        self.len += iv.size();

        if self.spans.len() <= MAX_LEAF {
            None
        } else {
            let splitpoint = self.spans.len() / 2;  // number of spans
            let splitpoint_units = self.spans[splitpoint].iv.start();
            let mut new = self.spans.split_off(splitpoint);
            for span in &mut new {
                span.iv = span.iv.translate_neg(splitpoint_units);
            }
            let new_len = self.len - splitpoint_units;
            self.len = splitpoint_units;
            Some(SpansLeaf {
                len: new_len,
                spans: new,
            })
        }
    }
}

impl<T: Clone + Default> NodeInfo for SpansInfo<T> {
    type L = SpansLeaf<T>;

    fn accumulate(&mut self, other: &Self) {
        self.n_spans += other.n_spans;
        self.iv = self.iv.union(other.iv);
    }

    fn compute_info(l: &SpansLeaf<T>) -> Self {
        let mut iv = Interval::new_closed_open(0, 0);  // should be Interval::default?
        for span in &l.spans {
            iv = iv.union(span.iv);
        }
        SpansInfo {
            n_spans: l.spans.len(),
            iv: iv,
            phantom: PhantomData,
        }
    }
}

pub struct SpansBuilder<T: Clone + Default> {
    b: TreeBuilder<SpansInfo<T>>,
    leaf: SpansLeaf<T>,
    len: usize,
    total_len: usize,
}

impl<T: Clone + Default> SpansBuilder<T> {
    pub fn new(total_len: usize) -> Self {
        SpansBuilder {
            b: TreeBuilder::new(),
            leaf: SpansLeaf::default(),
            len: 0,
            total_len: total_len,
        }
    }

    // Precondition: spans must be added in nondecreasing start order.
    // Maybe take Span struct instead of separate iv, data args?
    pub fn add_span(&mut self, iv: Interval, data: T) {
        if self.leaf.spans.len() == MAX_LEAF {
            let mut leaf = mem::replace(&mut self.leaf, SpansLeaf::default());
            leaf.len = iv.start() - self.len;
            self.len = iv.start();
            self.b.push(Node::from_leaf(leaf));
        }
        self.leaf.spans.push(Span {
            iv: iv.translate_neg(self.len),
            data: data,
        })
    }

    // Would make slightly more implementation sense to take total_len as an argument
    // here, but that's not quite the usual builder pattern.
    pub fn build(mut self) -> Spans<T> {
        self.leaf.len = self.total_len - self.len;
        self.b.push(Node::from_leaf(self.leaf));
        self.b.build()
    }
}

pub struct SpanIter<'a, T: 'a + Clone + Default> {
    cursor: Cursor<'a, SpansInfo<T>>,
    ix: usize,
}

impl<T: Clone + Default> Spans<T> {
    /// Perform operational transformation on a spans object intended to be edited into
    /// a sequence at the given offset.

    // Note: this implementation is not efficient for very large Spans objects, as it
    // traverses all spans linearly. A more sophisticated approach would be to traverse
    // the tree, and only delve into subtrees that are transformed.
    pub fn transform<N: NodeInfo>(&self, base_start: usize, base_end: usize,
            xform: &mut Transformer<N>) -> Self {
        // TODO: maybe should take base as an Interval and figure out "after" from that
        let new_start = xform.transform(base_start, false);
        let new_end = xform.transform(base_end, true);
        let mut builder = SpansBuilder::new(new_end - new_start);
        for (iv, data) in self.iter() {
            let (start_closed, end_closed) = (iv.is_start_closed(), iv.is_end_closed());
            let start = xform.transform(iv.start() + base_start, !start_closed) - new_start;
            let end = xform.transform(iv.end() + base_start, end_closed) - new_start;
            if start < end || (start_closed && end_closed) {
                let iv = Interval::new(start, start_closed, end, end_closed);
                // TODO: could imagine using a move iterator and avoiding clone, but it's not easy.
                builder.add_span(iv, data.clone());
            }
        }
        builder.build()
    }

    /// Creates a new Spans instance by merging spans from `other` with `self`,
    /// using a closure to transform values.
    ///
    /// New spans are created from non-overlapping regions of existing spans,
    /// and by combining overlapping regions into new spans. In all cases,
    /// new values are generated by calling a closure that transforms the
    /// value of the existing span or spans.
    ///
    /// # Panics
    ///
    /// Panics if `self` and `other` have different lengths.
    ///
    pub fn merge<F, O>(&self, other: &Self, mut f: F) -> Spans<O>
        where F: FnMut(&T, Option<&T>) -> O,
              O: Clone + Default,
    {
        //TODO: confirm that this is sensible behaviour
        assert_eq!(self.len(), other.len());
        let mut sb = SpansBuilder::new(self.len());

        // red/blue is just a better name than one/two or me/other
        let mut iter_red = self.iter();
        let mut iter_blue = other.iter();

        let mut next_red = iter_red.next();
        let mut next_blue = iter_blue.next();

        loop {
            // exit conditions:
            if next_red.is_none() && next_blue.is_none() {
                // all merged.
                break
            } else if next_red.is_none() != next_blue.is_none() {
                // one side is exhausted; append remaining items from other side.
                let iter = if next_red.is_some() { iter_red } else { iter_blue };
                // add this item
                let (iv, val) = next_red.or(next_blue).unwrap();
                sb.add_span(iv, f(val, None));

                for (iv, val) in iter {
                    sb.add_span(iv, f(val, None))
                }
                break
            }

            // body:
            let (mut red_iv, red_val) = next_red.unwrap();
            let (mut blue_iv, blue_val) = next_blue.unwrap();

            if red_iv.intersect(blue_iv).is_empty() {
                // the spans do not overlap. Add and advance the leftmost.
                if red_iv.is_before(blue_iv.start()) {
                    sb.add_span(red_iv, f(red_val, None));
                    next_red = iter_red.next();
                } else {
                    sb.add_span(blue_iv, f(blue_val, None));
                    next_blue = iter_blue.next();
                }
                continue
            }
            assert!(!red_iv.intersect(blue_iv).is_empty());

            // if these two spans do not share a start point, create a new span from
            // the prefix of the leading span.
            if red_iv.start() < blue_iv.start() {
                let iv = red_iv.prefix(blue_iv);
                sb.add_span(iv, f(red_val, None));
                red_iv = red_iv.suffix(iv);
            }
            else if blue_iv.start() < red_iv.start() {
                let iv = blue_iv.prefix(red_iv);
                sb.add_span(iv, f(blue_val, None));
                blue_iv = blue_iv.suffix(iv);
            }

            assert!(red_iv.start() == blue_iv.start());
            // create a new span by merging the overlapping regions.
            let iv = red_iv.intersect(blue_iv);
            assert!(!iv.is_empty());
            sb.add_span(iv, f(red_val, Some(blue_val)));

            // if an old span was consumed by this new span, advance
            // else manually set next_, for the next loop iteration
            red_iv = red_iv.suffix(iv);
            blue_iv = blue_iv.suffix(iv);
            assert!(red_iv.is_empty() || blue_iv.is_empty());

            if red_iv.is_empty() {
                next_red = iter_red.next();
            } else {
                next_red = Some((red_iv, red_val));
            }

            if blue_iv.is_empty() {
                next_blue = iter_blue.next();
            } else {
                next_blue = Some((blue_iv, blue_val));
            }
        }
        sb.build()
    }

    // possible future: an iterator that takes an interval, so results are the same as
    // taking a subseq on the spans object. Would require specialized Cursor.
    pub fn iter(&self) -> SpanIter<T> {
        SpanIter {
            cursor: Cursor::new(self, 0),
            ix: 0,
        }
    }
}

impl<'a, T: Clone + Default> Iterator for SpanIter<'a, T> {
    type Item = (Interval, &'a T);

    fn next(&mut self) -> Option<(Interval, &'a T)> {
        if let Some((leaf, start_pos)) = self.cursor.get_leaf() {
            if leaf.spans.is_empty() { return None; }
            let leaf_start = self.cursor.pos() - start_pos;
            let span = &leaf.spans[self.ix];
            self.ix += 1;
            if self.ix == leaf.spans.len() {
                let _ = self.cursor.next_leaf();
                self.ix = 0;
            }
            return Some((span.iv.translate(leaf_start), &span.data));
        }
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_merge() {
        // merging 1 1 1 1 1 1 1 1 1 16
        // with    2 2 4 4     8 8
        // ==      3 3 5 5 1 1 9 9 1 16
       let mut sb = SpansBuilder::new(10);
       sb.add_span(Interval::new_open_closed(0, 9), 1u32);
       sb.add_span(Interval::new_open_closed(9, 10), 16);
       let red = sb.build();

       let mut sb = SpansBuilder::new(10);
       sb.add_span(Interval::new_open_closed(0, 2), 2);
       sb.add_span(Interval::new_open_closed(2, 4), 4);
       sb.add_span(Interval::new_open_closed(6, 8), 8);
       let blue = sb.build();
       let merged = red.merge(&blue, |r, b| b.map(|b| b + r).unwrap_or(*r));

       let mut merged_iter = merged.iter();
       let (iv, val) = merged_iter.next().unwrap();
       assert_eq!(iv, Interval::new_open_closed(0, 2));
       assert_eq!(*val, 3);

       let (iv, val) = merged_iter.next().unwrap();
       assert_eq!(iv, Interval::new_open_closed(2, 4));
       assert_eq!(*val, 5);

       let (iv, val) = merged_iter.next().unwrap();
       assert_eq!(iv, Interval::new_open_closed(4, 6));
       assert_eq!(*val, 1);

       let (iv, val) = merged_iter.next().unwrap();
       assert_eq!(iv, Interval::new_open_closed(6, 8));
       assert_eq!(*val, 9);

       let (iv, val) = merged_iter.next().unwrap();
       assert_eq!(iv, Interval::new_open_closed(8, 9));
       assert_eq!(*val, 1);

       let (iv, val) = merged_iter.next().unwrap();
       assert_eq!(iv, Interval::new_open_closed(9, 10));
       assert_eq!(*val, 16);

       assert!(merged_iter.next().is_none());
    }
}
<commit_msg>Added another test case for span merging<commit_after>// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! A module for representing spans (in an interval tree), useful for rich text
//! annotations. It is parameterized over a data type, so can be used for
//! storing different annotations.

use std::marker::PhantomData;
use std::mem;

use tree::{Leaf, Node, NodeInfo, TreeBuilder, Cursor};
use delta::Transformer;
use interval::Interval;

const MIN_LEAF: usize = 32;
const MAX_LEAF: usize = 64;

pub type Spans<T> = Node<SpansInfo<T>>;

#[derive(Clone)]
pub struct Span<T: Clone> {
    iv: Interval,
    data: T,
}

#[derive(Clone, Default)]
pub struct SpansLeaf<T: Clone> {
    len: usize,  // measured in base units
    spans: Vec<Span<T>>,
}

#[derive(Clone)]
pub struct SpansInfo<T> {
    n_spans: usize,
    iv: Interval,
    phantom: PhantomData<T>,
}

impl<T: Clone + Default> Leaf for SpansLeaf<T> {
    fn len(&self) -> usize {
        self.len
    }

    fn is_ok_child(&self) -> bool {
        self.spans.len() >= MIN_LEAF
    }

    fn push_maybe_split(&mut self, other: &Self, iv: Interval) -> Option<Self> {
        let iv_start = iv.start();
        for span in &other.spans {
            let span_iv = span.iv.intersect(iv).translate_neg(iv_start).translate(self.len);
            if !span_iv.is_empty() {
                self.spans.push(Span {
                    iv: span_iv,
                    data: span.data.clone(),
                });
            }
        }
        self.len += iv.size();

        if self.spans.len() <= MAX_LEAF {
            None
        } else {
            let splitpoint = self.spans.len() / 2;  // number of spans
            let splitpoint_units = self.spans[splitpoint].iv.start();
            let mut new = self.spans.split_off(splitpoint);
            for span in &mut new {
                span.iv = span.iv.translate_neg(splitpoint_units);
            }
            let new_len = self.len - splitpoint_units;
            self.len = splitpoint_units;
            Some(SpansLeaf {
                len: new_len,
                spans: new,
            })
        }
    }
}

impl<T: Clone + Default> NodeInfo for SpansInfo<T> {
    type L = SpansLeaf<T>;

    fn accumulate(&mut self, other: &Self) {
        self.n_spans += other.n_spans;
        self.iv = self.iv.union(other.iv);
    }

    fn compute_info(l: &SpansLeaf<T>) -> Self {
        let mut iv = Interval::new_closed_open(0, 0);  // should be Interval::default?
        for span in &l.spans {
            iv = iv.union(span.iv);
        }
        SpansInfo {
            n_spans: l.spans.len(),
            iv: iv,
            phantom: PhantomData,
        }
    }
}

pub struct SpansBuilder<T: Clone + Default> {
    b: TreeBuilder<SpansInfo<T>>,
    leaf: SpansLeaf<T>,
    len: usize,
    total_len: usize,
}

impl<T: Clone + Default> SpansBuilder<T> {
    pub fn new(total_len: usize) -> Self {
        SpansBuilder {
            b: TreeBuilder::new(),
            leaf: SpansLeaf::default(),
            len: 0,
            total_len: total_len,
        }
    }

    // Precondition: spans must be added in nondecreasing start order.
    // Maybe take Span struct instead of separate iv, data args?
    pub fn add_span(&mut self, iv: Interval, data: T) {
        if self.leaf.spans.len() == MAX_LEAF {
            let mut leaf = mem::replace(&mut self.leaf, SpansLeaf::default());
            leaf.len = iv.start() - self.len;
            self.len = iv.start();
            self.b.push(Node::from_leaf(leaf));
        }
        self.leaf.spans.push(Span {
            iv: iv.translate_neg(self.len),
            data: data,
        })
    }

    // Would make slightly more implementation sense to take total_len as an argument
    // here, but that's not quite the usual builder pattern.
    pub fn build(mut self) -> Spans<T> {
        self.leaf.len = self.total_len - self.len;
        self.b.push(Node::from_leaf(self.leaf));
        self.b.build()
    }
}

pub struct SpanIter<'a, T: 'a + Clone + Default> {
    cursor: Cursor<'a, SpansInfo<T>>,
    ix: usize,
}

impl<T: Clone + Default> Spans<T> {
    /// Perform operational transformation on a spans object intended to be edited into
    /// a sequence at the given offset.

    // Note: this implementation is not efficient for very large Spans objects, as it
    // traverses all spans linearly. A more sophisticated approach would be to traverse
    // the tree, and only delve into subtrees that are transformed.
    pub fn transform<N: NodeInfo>(&self, base_start: usize, base_end: usize,
            xform: &mut Transformer<N>) -> Self {
        // TODO: maybe should take base as an Interval and figure out "after" from that
        let new_start = xform.transform(base_start, false);
        let new_end = xform.transform(base_end, true);
        let mut builder = SpansBuilder::new(new_end - new_start);
        for (iv, data) in self.iter() {
            let (start_closed, end_closed) = (iv.is_start_closed(), iv.is_end_closed());
            let start = xform.transform(iv.start() + base_start, !start_closed) - new_start;
            let end = xform.transform(iv.end() + base_start, end_closed) - new_start;
            if start < end || (start_closed && end_closed) {
                let iv = Interval::new(start, start_closed, end, end_closed);
                // TODO: could imagine using a move iterator and avoiding clone, but it's not easy.
                builder.add_span(iv, data.clone());
            }
        }
        builder.build()
    }

    /// Creates a new Spans instance by merging spans from `other` with `self`,
    /// using a closure to transform values.
    ///
    /// New spans are created from non-overlapping regions of existing spans,
    /// and by combining overlapping regions into new spans. In all cases,
    /// new values are generated by calling a closure that transforms the
    /// value of the existing span or spans.
    ///
    /// # Panics
    ///
    /// Panics if `self` and `other` have different lengths.
    ///
    pub fn merge<F, O>(&self, other: &Self, mut f: F) -> Spans<O>
        where F: FnMut(&T, Option<&T>) -> O,
              O: Clone + Default,
    {
        //TODO: confirm that this is sensible behaviour
        assert_eq!(self.len(), other.len());
        let mut sb = SpansBuilder::new(self.len());

        // red/blue is just a better name than one/two or me/other
        let mut iter_red = self.iter();
        let mut iter_blue = other.iter();

        let mut next_red = iter_red.next();
        let mut next_blue = iter_blue.next();

        loop {
            // exit conditions:
            if next_red.is_none() && next_blue.is_none() {
                // all merged.
                break
            } else if next_red.is_none() != next_blue.is_none() {
                // one side is exhausted; append remaining items from other side.
                let iter = if next_red.is_some() { iter_red } else { iter_blue };
                // add this item
                let (iv, val) = next_red.or(next_blue).unwrap();
                sb.add_span(iv, f(val, None));

                for (iv, val) in iter {
                    sb.add_span(iv, f(val, None))
                }
                break
            }

            // body:
            let (mut red_iv, red_val) = next_red.unwrap();
            let (mut blue_iv, blue_val) = next_blue.unwrap();

            if red_iv.intersect(blue_iv).is_empty() {
                // the spans do not overlap. Add and advance the leftmost.
                if red_iv.is_before(blue_iv.start()) {
                    sb.add_span(red_iv, f(red_val, None));
                    next_red = iter_red.next();
                } else {
                    sb.add_span(blue_iv, f(blue_val, None));
                    next_blue = iter_blue.next();
                }
                continue
            }
            assert!(!red_iv.intersect(blue_iv).is_empty());

            // if these two spans do not share a start point, create a new span from
            // the prefix of the leading span.
            if red_iv.start() < blue_iv.start() {
                let iv = red_iv.prefix(blue_iv);
                sb.add_span(iv, f(red_val, None));
                red_iv = red_iv.suffix(iv);
            }
            else if blue_iv.start() < red_iv.start() {
                let iv = blue_iv.prefix(red_iv);
                sb.add_span(iv, f(blue_val, None));
                blue_iv = blue_iv.suffix(iv);
            }

            assert!(red_iv.start() == blue_iv.start());
            // create a new span by merging the overlapping regions.
            let iv = red_iv.intersect(blue_iv);
            assert!(!iv.is_empty());
            sb.add_span(iv, f(red_val, Some(blue_val)));

            // if an old span was consumed by this new span, advance
            // else manually set next_, for the next loop iteration
            red_iv = red_iv.suffix(iv);
            blue_iv = blue_iv.suffix(iv);
            assert!(red_iv.is_empty() || blue_iv.is_empty());

            if red_iv.is_empty() {
                next_red = iter_red.next();
            } else {
                next_red = Some((red_iv, red_val));
            }

            if blue_iv.is_empty() {
                next_blue = iter_blue.next();
            } else {
                next_blue = Some((blue_iv, blue_val));
            }
        }
        sb.build()
    }

    // possible future: an iterator that takes an interval, so results are the same as
    // taking a subseq on the spans object. Would require specialized Cursor.
    pub fn iter(&self) -> SpanIter<T> {
        SpanIter {
            cursor: Cursor::new(self, 0),
            ix: 0,
        }
    }
}

impl<'a, T: Clone + Default> Iterator for SpanIter<'a, T> {
    type Item = (Interval, &'a T);

    fn next(&mut self) -> Option<(Interval, &'a T)> {
        if let Some((leaf, start_pos)) = self.cursor.get_leaf() {
            if leaf.spans.is_empty() { return None; }
            let leaf_start = self.cursor.pos() - start_pos;
            let span = &leaf.spans[self.ix];
            self.ix += 1;
            if self.ix == leaf.spans.len() {
                let _ = self.cursor.next_leaf();
                self.ix = 0;
            }
            return Some((span.iv.translate(leaf_start), &span.data));
        }
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_merge() {
        // merging 1 1 1 1 1 1 1 1 1 16
        // with    2 2 4 4     8 8
        // ==      3 3 5 5 1 1 9 9 1 16
       let mut sb = SpansBuilder::new(10);
       sb.add_span(Interval::new_open_closed(0, 9), 1u32);
       sb.add_span(Interval::new_open_closed(9, 10), 16);
       let red = sb.build();

       let mut sb = SpansBuilder::new(10);
       sb.add_span(Interval::new_open_closed(0, 2), 2);
       sb.add_span(Interval::new_open_closed(2, 4), 4);
       sb.add_span(Interval::new_open_closed(6, 8), 8);
       let blue = sb.build();
       let merged = red.merge(&blue, |r, b| b.map(|b| b + r).unwrap_or(*r));

       let mut merged_iter = merged.iter();
       let (iv, val) = merged_iter.next().unwrap();
       assert_eq!(iv, Interval::new_open_closed(0, 2));
       assert_eq!(*val, 3);

       let (iv, val) = merged_iter.next().unwrap();
       assert_eq!(iv, Interval::new_open_closed(2, 4));
       assert_eq!(*val, 5);

       let (iv, val) = merged_iter.next().unwrap();
       assert_eq!(iv, Interval::new_open_closed(4, 6));
       assert_eq!(*val, 1);

       let (iv, val) = merged_iter.next().unwrap();
       assert_eq!(iv, Interval::new_open_closed(6, 8));
       assert_eq!(*val, 9);

       let (iv, val) = merged_iter.next().unwrap();
       assert_eq!(iv, Interval::new_open_closed(8, 9));
       assert_eq!(*val, 1);

       let (iv, val) = merged_iter.next().unwrap();
       assert_eq!(iv, Interval::new_open_closed(9, 10));
       assert_eq!(*val, 16);

       assert!(merged_iter.next().is_none());
    }

    #[test]
    fn test_merge_2() {
        // 1 1 1   4 4
        //   2 2 2 2     8 9
        let mut sb = SpansBuilder::new(9);
        sb.add_span(Interval::new_open_closed(0, 3), 1);
        sb.add_span(Interval::new_open_closed(4, 6), 4);
        let blue = sb.build();

        let mut sb = SpansBuilder::new(9);
        sb.add_span(Interval::new_open_closed(1, 5), 2);
        sb.add_span(Interval::new_open_closed(7, 8), 8);
        sb.add_span(Interval::new_open_closed(8, 9), 9);
        let red = sb.build();

       let merged = red.merge(&blue, |r, b| b.map(|b| b + r).unwrap_or(*r));

       let mut merged_iter = merged.iter();
       let (iv, val) = merged_iter.next().unwrap();
       assert_eq!(iv, Interval::new_open_closed(0, 1));
       assert_eq!(*val, 1);

       let (iv, val) = merged_iter.next().unwrap();
       assert_eq!(iv, Interval::new_open_closed(1, 3));
       assert_eq!(*val, 3);

       let (iv, val) = merged_iter.next().unwrap();
       assert_eq!(iv, Interval::new_open_closed(3, 4));
       assert_eq!(*val, 2);

       let (iv, val) = merged_iter.next().unwrap();
       assert_eq!(iv, Interval::new_open_closed(4, 5));
       assert_eq!(*val, 6);

       let (iv, val) = merged_iter.next().unwrap();
       assert_eq!(iv, Interval::new_open_closed(5, 6));
       assert_eq!(*val, 4);

       let (iv, val) = merged_iter.next().unwrap();
       assert_eq!(iv, Interval::new_open_closed(7, 8));
       assert_eq!(*val, 8);

       let (iv, val) = merged_iter.next().unwrap();
       assert_eq!(iv, Interval::new_open_closed(8, 9));
       assert_eq!(*val, 9);

       assert!(merged_iter.next().is_none());
    }
}
<|endoftext|>


<commit_before><commit_msg>make sure we catch alignment problems even with intrptrcast<commit_after>// Validation makes this fail in the wrong place
// compile-flags: -Zmiri-disable-validation -Zmiri-seed=0000000000000000

// Even with intptrcast and without validation, we want to be *sure* to catch bugs
// that arise from pointers being insufficiently aligned. The only way to achieve
// that is not not let programs exploit integer information for alignment, so here
// we test that this is indeed the case.
fn main() {
    let x = &mut [0u8; 3];
    let base_addr = x as *mut _ as usize;
    let u16_ref = unsafe { if base_addr % 2 == 0 {
        &mut *(base_addr as *mut u16)
    } else {
        &mut *((base_addr+1) as *mut u16)
    } };
    *u16_ref = 2; //~ ERROR tried to access memory with alignment 1, but alignment 2 is required
    println!("{:?}", x);
}
<|endoftext|>


<commit_before><commit_msg>benches: add learning benchmarks<commit_after>#![feature(test)]

extern crate test;
extern crate lipsum;

use test::Bencher;

#[bench]
fn learn_lorem_ipsum(b: &mut Bencher) {
    b.iter(|| {
        let mut chain = lipsum::MarkovChain::new();
        chain.learn(lipsum::LOREM_IPSUM)
    })
}

#[bench]
fn learn_liber_primus(b: &mut Bencher) {
    b.iter(|| {
        let mut chain = lipsum::MarkovChain::new();
        chain.learn(lipsum::LIBER_PRIMUS)
    })
}
<|endoftext|>


<commit_before><commit_msg>Add problem #88<commit_after>use core::hashmap::{ HashSet };
use common::problem::{ Problem };

pub static problem: Problem<'static> = Problem {
    id: 88,
    answer: "7587457",
    solver: solve
};

fn each_sum_product(start: uint, end: uint, f: &fn(uint, uint, uint) -> bool) {
    for sub(start, end, 0, 1, 0) |sum, prod, len| {
        if !f(sum, prod, len) { return; }
    }

    fn sub(start: uint, end: uint, sum: uint, prod: uint, len: uint,
           f: &fn(uint, uint, uint) -> bool) {
        for uint::range(start, end / prod + 1) |n| {
            if len > 0 {
                if !f(sum + n, prod * n, len + 1) { return; }
            }

            for sub(n, end, sum + n, prod * n, len + 1) |sum1, prod1, len1| {
                if !f(sum1, prod1, len1) { return; }
            }
        }
    }
}

fn solve() -> ~str {
    let limit = 12000;

    let start = 2;
    let mut end = 4;
    let mut cnt = limit - 1;
    let mut nums = vec::from_elem(limit + 1, uint::max_value);

    while cnt > 0 {
        for each_sum_product(start, end) |sum, prod, len| {
            let k = prod - sum + len;
            if k <= limit && prod < nums[k] {
                if nums[k] == uint::max_value { cnt -= 1; }
                nums[k] = prod;
            }
        }
        end *= 2;
    }

    let mut set = HashSet::new();
    for nums.each |&n| {
        if n != uint::max_value { set.insert(n); }
    }

    let mut sum = 0;
    for set.each |&n| { sum += n; }
    return sum.to_str();
}
<|endoftext|>


<commit_before><commit_msg>Add lints<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.

// Detecting lib features (i.e. features that are not lang features).
//
// These are declared using stability attributes (e.g. `#[stable(..)]`
// and `#[unstable(..)]`), but are not declared in one single location
// (unlike lang features), which means we need to collect them instead.

use ty::TyCtxt;
use syntax::symbol::Symbol;
use syntax::ast::{Attribute, MetaItem, MetaItemKind};
use syntax_pos::{Span, DUMMY_SP};
use hir;
use hir::itemlikevisit::ItemLikeVisitor;
use rustc_data_structures::fx::{FxHashSet, FxHashMap};
use errors::DiagnosticId;

pub struct LibFeatures {
    // A map from feature to stabilisation version.
    pub stable: FxHashMap<Symbol, Symbol>,
    pub unstable: FxHashSet<Symbol>,
}

impl LibFeatures {
    fn new() -> LibFeatures {
        LibFeatures {
            stable: FxHashMap(),
            unstable: FxHashSet(),
        }
    }

    pub fn iter(&self) -> Vec<(Symbol, Option<Symbol>)> {
        self.stable.iter().map(|(f, s)| (*f, Some(*s)))
            .chain(self.unstable.iter().map(|f| (*f, None)))
            .collect()
    }
}

pub struct LibFeatureCollector<'a, 'tcx: 'a> {
    tcx: TyCtxt<'a, 'tcx, 'tcx>,
    lib_features: LibFeatures,
}

impl<'a, 'tcx> LibFeatureCollector<'a, 'tcx> {
    fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LibFeatureCollector<'a, 'tcx> {
        LibFeatureCollector {
            tcx,
            lib_features: LibFeatures::new(),
        }
    }

    fn extract(&self, attrs: &[Attribute]) -> Vec<(Symbol, Option<Symbol>, Span)> {
        let stab_attrs = vec!["stable", "unstable", "rustc_const_unstable"];
        let mut features = vec![];

        for attr in attrs {
            // FIXME(varkor): the stability attribute might be behind a `#[cfg]` attribute.

            // Find a stability attribute (i.e. `#[stable(..)]`, `#[unstable(..)]`,
            // `#[rustc_const_unstable(..)]`).
            if stab_attrs.iter().any(|stab_attr| attr.check_name(stab_attr)) {
                let meta_item = attr.meta();
                if let Some(MetaItem { node: MetaItemKind::List(ref metas), .. }) = meta_item {
                    let mut feature = None;
                    let mut since = None;
                    for meta in metas {
                        if let Some(mi) = meta.meta_item() {
                            // Find the `feature = ".."` meta-item.
                            match (&*mi.name().as_str(), mi.value_str()) {
                                ("feature", val) => feature = val,
                                ("since", val) => since = val,
                                _ => {}
                            }
                        }
                    }
                    if let Some(feature) = feature {
                        features.push((feature, since, attr.span));
                    }
                    // We need to iterate over the other attributes, because
                    // `rustc_const_unstable` is not mutually exclusive with
                    // the other stability attributes, so we can't just `break`
                    // here.
                }
            }
        }

        features
    }

    fn collect_feature(&mut self, feature: Symbol, since: Option<Symbol>, span: Span) {
        let already_in_stable = self.lib_features.stable.contains_key(&feature);
        let already_in_unstable = self.lib_features.unstable.contains(&feature);

        match (since, already_in_stable, already_in_unstable) {
            (Some(since), _, false) => {
                self.lib_features.stable.insert(feature, since);
            }
            (None, false, _) => {
                self.lib_features.unstable.insert(feature);
            }
            (Some(_), _, true) | (None, true, _) => {
                let msg = format!(
                    "feature `{}` is declared {}, but was previously declared {}",
                    feature,
                    if since.is_some() { "stable"} else { "unstable" },
                    if since.is_none() { "stable"} else { "unstable" },
                );
                self.tcx.sess.struct_span_err_with_code(span, &msg,
                    DiagnosticId::Error("E0711".into())).emit();
            }
        }
    }

    fn collect_from_attrs(&mut self, attrs: &[Attribute]) {
        for (feature, stable, span) in self.extract(attrs) {
            self.collect_feature(feature, stable, span);
        }
    }
}

impl<'a, 'v, 'tcx> ItemLikeVisitor<'v> for LibFeatureCollector<'a, 'tcx> {
    fn visit_item(&mut self, item: &hir::Item) {
        self.collect_from_attrs(&item.attrs);
    }

    fn visit_trait_item(&mut self, trait_item: &hir::TraitItem) {
        self.collect_from_attrs(&trait_item.attrs);
    }

    fn visit_impl_item(&mut self, impl_item: &hir::ImplItem) {
        self.collect_from_attrs(&impl_item.attrs);
    }
}

pub fn collect<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LibFeatures {
    let mut collector = LibFeatureCollector::new(tcx);
    for &cnum in tcx.crates().iter() {
        for &(feature, since) in tcx.defined_lib_features(cnum).iter() {
            collector.collect_feature(feature, since, DUMMY_SP);
        }
    }
    collector.collect_from_attrs(&tcx.hir.krate().attrs);
    tcx.hir.krate().visit_all_item_likes(&mut collector);
    collector.lib_features
}
<commit_msg>Add error for inconsistent stability `since` value<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.

// Detecting lib features (i.e. features that are not lang features).
//
// These are declared using stability attributes (e.g. `#[stable(..)]`
// and `#[unstable(..)]`), but are not declared in one single location
// (unlike lang features), which means we need to collect them instead.

use ty::TyCtxt;
use syntax::symbol::Symbol;
use syntax::ast::{Attribute, MetaItem, MetaItemKind};
use syntax_pos::{Span, DUMMY_SP};
use hir;
use hir::itemlikevisit::ItemLikeVisitor;
use rustc_data_structures::fx::{FxHashSet, FxHashMap};
use errors::DiagnosticId;

pub struct LibFeatures {
    // A map from feature to stabilisation version.
    pub stable: FxHashMap<Symbol, Symbol>,
    pub unstable: FxHashSet<Symbol>,
}

impl LibFeatures {
    fn new() -> LibFeatures {
        LibFeatures {
            stable: FxHashMap(),
            unstable: FxHashSet(),
        }
    }

    pub fn iter(&self) -> Vec<(Symbol, Option<Symbol>)> {
        self.stable.iter().map(|(f, s)| (*f, Some(*s)))
            .chain(self.unstable.iter().map(|f| (*f, None)))
            .collect()
    }
}

pub struct LibFeatureCollector<'a, 'tcx: 'a> {
    tcx: TyCtxt<'a, 'tcx, 'tcx>,
    lib_features: LibFeatures,
}

impl<'a, 'tcx> LibFeatureCollector<'a, 'tcx> {
    fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LibFeatureCollector<'a, 'tcx> {
        LibFeatureCollector {
            tcx,
            lib_features: LibFeatures::new(),
        }
    }

    fn extract(&self, attrs: &[Attribute]) -> Vec<(Symbol, Option<Symbol>, Span)> {
        let stab_attrs = vec!["stable", "unstable", "rustc_const_unstable"];
        let mut features = vec![];

        for attr in attrs {
            // FIXME(varkor): the stability attribute might be behind a `#[cfg]` attribute.

            // Find a stability attribute (i.e. `#[stable(..)]`, `#[unstable(..)]`,
            // `#[rustc_const_unstable(..)]`).
            if stab_attrs.iter().any(|stab_attr| attr.check_name(stab_attr)) {
                let meta_item = attr.meta();
                if let Some(MetaItem { node: MetaItemKind::List(ref metas), .. }) = meta_item {
                    let mut feature = None;
                    let mut since = None;
                    for meta in metas {
                        if let Some(mi) = meta.meta_item() {
                            // Find the `feature = ".."` meta-item.
                            match (&*mi.name().as_str(), mi.value_str()) {
                                ("feature", val) => feature = val,
                                ("since", val) => since = val,
                                _ => {}
                            }
                        }
                    }
                    if let Some(feature) = feature {
                        features.push((feature, since, attr.span));
                    }
                    // We need to iterate over the other attributes, because
                    // `rustc_const_unstable` is not mutually exclusive with
                    // the other stability attributes, so we can't just `break`
                    // here.
                }
            }
        }

        features
    }

    fn collect_feature(&mut self, feature: Symbol, since: Option<Symbol>, span: Span) {
        let already_in_stable = self.lib_features.stable.contains_key(&feature);
        let already_in_unstable = self.lib_features.unstable.contains(&feature);

        match (since, already_in_stable, already_in_unstable) {
            (Some(since), _, false) => {
                if let Some(prev_since) = self.lib_features.stable.get(&feature) {
                    if *prev_since != since {
                        let msg = format!(
                            "feature `{}` is declared stable since {}, \
                             but was previously declared stable since {}",
                            feature,
                            since,
                            prev_since,
                        );
                        self.tcx.sess.struct_span_err_with_code(span, &msg,
                            DiagnosticId::Error("E0711".into())).emit();
                        return;
                    }
                }

                self.lib_features.stable.insert(feature, since);
            }
            (None, false, _) => {
                self.lib_features.unstable.insert(feature);
            }
            (Some(_), _, true) | (None, true, _) => {
                let msg = format!(
                    "feature `{}` is declared {}, but was previously declared {}",
                    feature,
                    if since.is_some() { "stable"} else { "unstable" },
                    if since.is_none() { "stable"} else { "unstable" },
                );
                self.tcx.sess.struct_span_err_with_code(span, &msg,
                    DiagnosticId::Error("E0711".into())).emit();
            }
        }
    }

    fn collect_from_attrs(&mut self, attrs: &[Attribute]) {
        for (feature, stable, span) in self.extract(attrs) {
            self.collect_feature(feature, stable, span);
        }
    }
}

impl<'a, 'v, 'tcx> ItemLikeVisitor<'v> for LibFeatureCollector<'a, 'tcx> {
    fn visit_item(&mut self, item: &hir::Item) {
        self.collect_from_attrs(&item.attrs);
    }

    fn visit_trait_item(&mut self, trait_item: &hir::TraitItem) {
        self.collect_from_attrs(&trait_item.attrs);
    }

    fn visit_impl_item(&mut self, impl_item: &hir::ImplItem) {
        self.collect_from_attrs(&impl_item.attrs);
    }
}

pub fn collect<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LibFeatures {
    let mut collector = LibFeatureCollector::new(tcx);
    for &cnum in tcx.crates().iter() {
        for &(feature, since) in tcx.defined_lib_features(cnum).iter() {
            collector.collect_feature(feature, since, DUMMY_SP);
        }
    }
    collector.collect_from_attrs(&tcx.hir.krate().attrs);
    tcx.hir.krate().visit_all_item_likes(&mut collector);
    collector.lib_features
}
<|endoftext|>


<commit_before><commit_msg>add example for texture wrapping<commit_after>extern crate graphics;
extern crate image as im;
extern crate opengl_graphics;
extern crate piston;
extern crate sdl2_window;

use opengl_graphics::{GlGraphics, Texture, TextureSettings, Wrap};
use piston::event_loop::*;
use piston::input::*;
use piston::window::WindowSettings;
use sdl2_window::{OpenGL, Sdl2Window};
use std::path::Path;

fn main() {
    println!("Press S to change the texture wrap mode for the s coordinate");
    println!("Press T to change the texture wrap mode for the t coordinate");

    let opengl = OpenGL::V3_2;
    let (w, h) = (640, 480);
    let mut window: Sdl2Window = WindowSettings::new("opengl_graphics: draw_state", [w, h])
        .exit_on_esc(true)
        .graphics_api(opengl)
        .build()
        .unwrap();

    // Set up wrap modes
    let wrap_modes = [
        Wrap::ClampToEdge,
        Wrap::ClampToBorder,
        Wrap::Repeat,
        Wrap::MirroredRepeat,
    ];
    let mut ix_s = 0;
    let mut ix_t = 0;
    let mut texture_settings = TextureSettings::new();
    texture_settings.set_border_color([0.0, 0.0, 0.0, 1.0]);

    // Set up texture
    let path = Path::new("./assets/rust.png");
    let img = match im::open(path) {
        Ok(img) => img,
        Err(e) => {
            panic!("Could not load '{:?}': {:?}", path.file_name().unwrap(), e);
        }
    };
    let img = match img {
        im::DynamicImage::ImageRgba8(img) => img,
        x => x.to_rgba(),
    };
    let mut rust_logo = Texture::from_image(&img, &texture_settings);

    let mut gl = GlGraphics::new(opengl);
    let mut events = Events::new(EventSettings::new().lazy(true));
    while let Some(e) = events.next(&mut window) {
        if let Some(args) = e.render_args() {
            use graphics::*;
            gl.draw(args.viewport(), |_c, g| {
                clear([1.0; 4], g);
                let points = [[0.5, 0.5], [-0.5, 0.5], [-0.5, -0.5], [0.5, -0.5]];
                // (0, 1, 2) and (0, 2, 3)
                let uvs = [
                    [4.0, 0.0],
                    [0.0, 0.0],
                    [0.0, 4.0],
                    [4.0, 0.0],
                    [0.0, 4.0],
                    [4.0, 4.0],
                ];
                let mut verts = [[0.0, 0.0]; 6];
                let indices_points: [usize; 6] = [0, 1, 2, 0, 2, 3];
                for (ixv, &ixp) in (0..6).zip(indices_points.into_iter()) {
                    verts[ixv] = points[ixp];
                }
                g.tri_list_uv(&DrawState::new_alpha(), &[1.0; 4], &rust_logo, |f| {
                    f(&verts, &uvs)
                });
            });
        }

        if let Some(Button::Keyboard(Key::S)) = e.press_args() {
            ix_s = (ix_s + 1) % wrap_modes.len();
            texture_settings.set_wrap_s(wrap_modes[ix_s]);
            rust_logo = Texture::from_image(&img, &texture_settings);
            println!(
                "Changed texture wrap mode for s coordinate to: {:?}",
                wrap_modes[ix_s]
            );
        }

        if let Some(Button::Keyboard(Key::T)) = e.press_args() {
            ix_t = (ix_t + 1) % wrap_modes.len();
            texture_settings.set_wrap_t(wrap_modes[ix_t]);
            rust_logo = Texture::from_image(&img, &texture_settings);
            println!(
                "Changed texture wrap mode for t coordinate to: {:?}",
                wrap_modes[ix_t]
            );
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Readded return of reference in the builder<commit_after><|endoftext|>


<commit_before><commit_msg>Simple bencher for write_to_bytes<commit_after>// `cargo test --benches` and `#[feature(test)]` work only in nightly
#![cfg(rustc_nightly)]
#![feature(test)]

extern crate test;

use protobuf::well_known_types::value;
use protobuf::well_known_types::Struct;
use protobuf::well_known_types::Value;
use protobuf::Message;
use test::Bencher;

#[bench]
fn write_to_bytes(b: &mut Bencher) {
    let mut value = Value::new();
    value.kind = Some(value::Kind::number_value(10.0));
    let mut value2 = Value::new();
    value2.kind = Some(value::Kind::bool_value(true));
    let mut s = Struct::new();
    s.fields.insert("foo".to_owned(), value);
    s.fields.insert("bar".to_owned(), value2);
    b.iter(|| s.write_to_bytes());
}
<|endoftext|>


<commit_before>import std::{io, term};
import io::writer_util;
import syntax::codemap;
import codemap::span;

export emit_warning, emit_error, emit_note;
export handler, mk_codemap_handler;

iface handler {
    fn span_fatal(sp: span, msg: str) -> !;
    fn fatal(msg: str) -> !;
    fn span_err(sp: span, msg: str);
    fn err(msg: str);
    fn has_errors() -> bool;
    fn abort_if_errors();
    fn span_warn(sp: span, msg: str);
    fn warn(msg: str);
    fn span_note(sp: span, msg: str);
    fn note(msg: str);
    fn span_bug(sp: span, msg: str) -> !;
    fn bug(msg: str) -> !;
    fn span_unimpl(sp: span, msg: str) -> !;
    fn unimpl(msg: str) -> !;
}

type codemap_t = @{
    cm: codemap::codemap,
    mutable err_count: uint
};

impl codemap_handler of handler for codemap_t {
    fn span_fatal(sp: span, msg: str) -> ! {
        emit_error(some((self.cm, sp)), msg);
        fail;
    }
    fn fatal(msg: str) -> ! {
        emit_error(none, msg);
        fail;
    }
    fn span_err(sp: span, msg: str) {
        emit_error(some((self.cm, sp)), msg);
        self.err_count += 1u;
    }
    fn err(msg: str) {
        emit_error(none, msg);
        self.err_count += 1u;
    }
    fn has_errors() -> bool { self.err_count > 0u }
    fn abort_if_errors() {
        if self.err_count > 0u {
            self.fatal("aborting due to previous errors");
        }
    }
    fn span_warn(sp: span, msg: str) {
        emit_warning(some((self.cm, sp)), msg);
    }
    fn warn(msg: str) {
        emit_warning(none, msg);
    }
    fn span_note(sp: span, msg: str) {
        emit_note(some((self.cm, sp)), msg);
    }
    fn note(msg: str) {
        emit_note(none, msg);
    }
    fn span_bug(sp: span, msg: str) -> ! {
        self.span_fatal(sp, #fmt["internal compiler error %s", msg]);
    }
    fn bug(msg: str) -> ! {
        self.fatal(#fmt["internal compiler error %s", msg]);
    }
    fn span_unimpl(sp: span, msg: str) -> ! {
        self.span_bug(sp, "unimplemented " + msg);
    }
    fn unimpl(msg: str) -> ! { self.bug("unimplemented " + msg); }
}

fn mk_codemap_handler(cm: codemap::codemap) -> handler {
    @{
        cm: cm,
        mutable err_count: 0u,
    } as handler
}

tag diagnostictype {
    warning;
    error;
    note;
}

fn diagnosticstr(t: diagnostictype) -> str {
    alt t {
      warning. { "warning" }
      error. { "error" }
      note. { "note" }
    }
}

fn diagnosticcolor(t: diagnostictype) -> u8 {
    alt t {
      warning. { term::color_bright_yellow }
      error. { term::color_bright_red }
      note. { term::color_bright_green }
    }
}

fn print_diagnostic(topic: str, t: diagnostictype, msg: str) {
    if str::is_not_empty(topic) {
        io::stdout().write_str(#fmt["%s ", topic]);
    }
    if term::color_supported() {
        term::fg(io::stdout(), diagnosticcolor(t));
    }
    io::stdout().write_str(#fmt["%s:", diagnosticstr(t)]);
    if term::color_supported() {
        term::reset(io::stdout());
    }
    io::stdout().write_str(#fmt[" %s\n", msg]);
}

fn emit_diagnostic(cmsp: option<(codemap::codemap, span)>,
                   msg: str, t: diagnostictype) {
    alt cmsp {
      some((cm, sp)) {
        let ss = codemap::span_to_str(sp, cm);
        let lines = codemap::span_to_lines(sp, cm);
        print_diagnostic(ss, t, msg);
        highlight_lines(cm, sp, lines);
      }
      none. {
        print_diagnostic("", t, msg);
      }
    }
}

fn highlight_lines(cm: codemap::codemap, sp: span,
                   lines: @codemap::file_lines) {

    // If we're not looking at a real file then we can't re-open it to
    // pull out the lines
    if lines.name == "-" { ret; }

    // FIXME: reading in the entire file is the worst possible way to
    //        get access to the necessary lines.
    let file = alt io::read_whole_file_str(lines.name) {
      result::ok(file) { file }
      result::err(e) {
        emit_error(none, e);
        fail;
      }
    };
    let fm = codemap::get_filemap(cm, lines.name);

    // arbitrarily only print up to six lines of the error
    let max_lines = 6u;
    let elided = false;
    let display_lines = lines.lines;
    if vec::len(display_lines) > max_lines {
        display_lines = vec::slice(display_lines, 0u, max_lines);
        elided = true;
    }
    // Print the offending lines
    for line: uint in display_lines {
        io::stdout().write_str(#fmt["%s:%u ", fm.name, line + 1u]);
        let s = codemap::get_line(fm, line as int, file);
        if !str::ends_with(s, "\n") { s += "\n"; }
        io::stdout().write_str(s);
    }
    if elided {
        let last_line = display_lines[vec::len(display_lines) - 1u];
        let s = #fmt["%s:%u ", fm.name, last_line + 1u];
        let indent = str::char_len(s);
        let out = "";
        while indent > 0u { out += " "; indent -= 1u; }
        out += "...\n";
        io::stdout().write_str(out);
    }

    // If there's one line at fault we can easily point to the problem
    if vec::len(lines.lines) == 1u {
        let lo = codemap::lookup_char_pos(cm, sp.lo);
        let digits = 0u;
        let num = (lines.lines[0] + 1u) / 10u;

        // how many digits must be indent past?
        while num > 0u { num /= 10u; digits += 1u; }

        // indent past |name:## | and the 0-offset column location
        let left = str::char_len(fm.name) + digits + lo.col + 3u;
        let s = "";
        while left > 0u { str::push_char(s, ' '); left -= 1u; }

        s += "^";
        let hi = codemap::lookup_char_pos(cm, sp.hi);
        if hi.col != lo.col {
            // the ^ already takes up one space
            let width = hi.col - lo.col - 1u;
            while width > 0u { str::push_char(s, '~'); width -= 1u; }
        }
        io::stdout().write_str(s + "\n");
    }
}

fn emit_warning(cmsp: option<(codemap::codemap, span)>, msg: str) {
    emit_diagnostic(cmsp, msg, warning);
}
fn emit_error(cmsp: option<(codemap::codemap, span)>, msg: str) {
    emit_diagnostic(cmsp, msg, error);
}
fn emit_note(cmsp: option<(codemap::codemap, span)>, msg: str) {
    emit_diagnostic(cmsp, msg, note);
}
<commit_msg>rustc: Add a distinct fatal diagnostic level<commit_after>import std::{io, term};
import io::writer_util;
import syntax::codemap;
import codemap::span;

export emit_warning, emit_error, emit_note;
export handler, mk_codemap_handler;

iface handler {
    fn span_fatal(sp: span, msg: str) -> !;
    fn fatal(msg: str) -> !;
    fn span_err(sp: span, msg: str);
    fn err(msg: str);
    fn has_errors() -> bool;
    fn abort_if_errors();
    fn span_warn(sp: span, msg: str);
    fn warn(msg: str);
    fn span_note(sp: span, msg: str);
    fn note(msg: str);
    fn span_bug(sp: span, msg: str) -> !;
    fn bug(msg: str) -> !;
    fn span_unimpl(sp: span, msg: str) -> !;
    fn unimpl(msg: str) -> !;
}

type codemap_t = @{
    cm: codemap::codemap,
    mutable err_count: uint
};

impl codemap_handler of handler for codemap_t {
    fn span_fatal(sp: span, msg: str) -> ! {
        emit_fatal(some((self.cm, sp)), msg);
        fail;
    }
    fn fatal(msg: str) -> ! {
        emit_fatal(none, msg);
        fail;
    }
    fn span_err(sp: span, msg: str) {
        emit_error(some((self.cm, sp)), msg);
        self.err_count += 1u;
    }
    fn err(msg: str) {
        emit_error(none, msg);
        self.err_count += 1u;
    }
    fn has_errors() -> bool { self.err_count > 0u }
    fn abort_if_errors() {
        if self.err_count > 0u {
            self.fatal("aborting due to previous errors");
        }
    }
    fn span_warn(sp: span, msg: str) {
        emit_warning(some((self.cm, sp)), msg);
    }
    fn warn(msg: str) {
        emit_warning(none, msg);
    }
    fn span_note(sp: span, msg: str) {
        emit_note(some((self.cm, sp)), msg);
    }
    fn note(msg: str) {
        emit_note(none, msg);
    }
    fn span_bug(sp: span, msg: str) -> ! {
        self.span_fatal(sp, #fmt["internal compiler error %s", msg]);
    }
    fn bug(msg: str) -> ! {
        self.fatal(#fmt["internal compiler error %s", msg]);
    }
    fn span_unimpl(sp: span, msg: str) -> ! {
        self.span_bug(sp, "unimplemented " + msg);
    }
    fn unimpl(msg: str) -> ! { self.bug("unimplemented " + msg); }
}

fn mk_codemap_handler(cm: codemap::codemap) -> handler {
    @{
        cm: cm,
        mutable err_count: 0u,
    } as handler
}

tag diagnostictype {
    fatal;
    error;
    warning;
    note;
}

fn diagnosticstr(t: diagnostictype) -> str {
    alt t {
      fatal. { "error" }
      error. { "error" }
      warning. { "warning" }
      note. { "note" }
    }
}

fn diagnosticcolor(t: diagnostictype) -> u8 {
    alt t {
      fatal. { term::color_bright_red }
      error. { term::color_bright_red }
      warning. { term::color_bright_yellow }
      note. { term::color_bright_green }
    }
}

fn print_diagnostic(topic: str, t: diagnostictype, msg: str) {
    if str::is_not_empty(topic) {
        io::stdout().write_str(#fmt["%s ", topic]);
    }
    if term::color_supported() {
        term::fg(io::stdout(), diagnosticcolor(t));
    }
    io::stdout().write_str(#fmt["%s:", diagnosticstr(t)]);
    if term::color_supported() {
        term::reset(io::stdout());
    }
    io::stdout().write_str(#fmt[" %s\n", msg]);
}

fn emit_diagnostic(cmsp: option<(codemap::codemap, span)>,
                   msg: str, t: diagnostictype) {
    alt cmsp {
      some((cm, sp)) {
        let ss = codemap::span_to_str(sp, cm);
        let lines = codemap::span_to_lines(sp, cm);
        print_diagnostic(ss, t, msg);
        highlight_lines(cm, sp, lines);
      }
      none. {
        print_diagnostic("", t, msg);
      }
    }
}

fn highlight_lines(cm: codemap::codemap, sp: span,
                   lines: @codemap::file_lines) {

    // If we're not looking at a real file then we can't re-open it to
    // pull out the lines
    if lines.name == "-" { ret; }

    // FIXME: reading in the entire file is the worst possible way to
    //        get access to the necessary lines.
    let file = alt io::read_whole_file_str(lines.name) {
      result::ok(file) { file }
      result::err(e) {
        emit_error(none, e);
        fail;
      }
    };
    let fm = codemap::get_filemap(cm, lines.name);

    // arbitrarily only print up to six lines of the error
    let max_lines = 6u;
    let elided = false;
    let display_lines = lines.lines;
    if vec::len(display_lines) > max_lines {
        display_lines = vec::slice(display_lines, 0u, max_lines);
        elided = true;
    }
    // Print the offending lines
    for line: uint in display_lines {
        io::stdout().write_str(#fmt["%s:%u ", fm.name, line + 1u]);
        let s = codemap::get_line(fm, line as int, file);
        if !str::ends_with(s, "\n") { s += "\n"; }
        io::stdout().write_str(s);
    }
    if elided {
        let last_line = display_lines[vec::len(display_lines) - 1u];
        let s = #fmt["%s:%u ", fm.name, last_line + 1u];
        let indent = str::char_len(s);
        let out = "";
        while indent > 0u { out += " "; indent -= 1u; }
        out += "...\n";
        io::stdout().write_str(out);
    }

    // If there's one line at fault we can easily point to the problem
    if vec::len(lines.lines) == 1u {
        let lo = codemap::lookup_char_pos(cm, sp.lo);
        let digits = 0u;
        let num = (lines.lines[0] + 1u) / 10u;

        // how many digits must be indent past?
        while num > 0u { num /= 10u; digits += 1u; }

        // indent past |name:## | and the 0-offset column location
        let left = str::char_len(fm.name) + digits + lo.col + 3u;
        let s = "";
        while left > 0u { str::push_char(s, ' '); left -= 1u; }

        s += "^";
        let hi = codemap::lookup_char_pos(cm, sp.hi);
        if hi.col != lo.col {
            // the ^ already takes up one space
            let width = hi.col - lo.col - 1u;
            while width > 0u { str::push_char(s, '~'); width -= 1u; }
        }
        io::stdout().write_str(s + "\n");
    }
}

fn emit_fatal(cmsp: option<(codemap::codemap, span)>, msg: str) {
    emit_diagnostic(cmsp, msg, fatal);
}
fn emit_error(cmsp: option<(codemap::codemap, span)>, msg: str) {
    emit_diagnostic(cmsp, msg, error);
}
fn emit_warning(cmsp: option<(codemap::codemap, span)>, msg: str) {
    emit_diagnostic(cmsp, msg, warning);
}
fn emit_note(cmsp: option<(codemap::codemap, span)>, msg: str) {
    emit_diagnostic(cmsp, msg, note);
}
<|endoftext|>


<commit_before><commit_msg>	modified:   src/main.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Passing time in nanos (#8)<commit_after><|endoftext|>


<commit_before><commit_msg>Without cargo package version metadata is absent<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed lock acquisition for condvar and predicate variable.<commit_after><|endoftext|>


<commit_before>use core::{fmt, mem, ptr, slice, str};
use panic::panic_impl;
use env::{args_init, args_destroy};
use system::syscall::sys_exit;
use vec::Vec;

pub fn begin_unwind(string: &'static str, file_line: &(&'static str, u32)) -> ! {
    let &(file, line) = file_line;
    panic_impl(format_args!("{}", string), file, line)
}

pub fn begin_unwind_fmt(fmt: fmt::Arguments, file_line: &(&'static str, u32)) -> ! {
    let &(file, line) = file_line;
    panic_impl(fmt, file, line)
}

#[no_mangle]
#[inline(never)]
#[naked]
#[cfg(target_arch = "x86")]
pub unsafe fn _start() {
    extern "C" {
        fn main(argc: usize, argv: *const *const u8) -> usize;
    }

    //asm!("xchg bx, bx" : : : "memory" : "intel", "volatile");

    let sp: usize;
    asm!("mov $0, esp" : "=r"(sp) : : "memory" : "intel", "volatile");
    let stack = sp as *const usize;

    let _ = sys_exit(main(*stack, stack.offset(1) as *const *const u8));
}

#[no_mangle]
#[inline(never)]
#[naked]
#[cfg(target_arch = "x86_64")]
pub unsafe fn _start() {
    extern "C" {
        fn main(argc: usize, argv: *const *const u8) -> usize;
    }

    //asm!("xchg bx, bx" : : : "memory" : "intel", "volatile");

    let sp: usize;
    asm!("mov $0, rsp" : "=r"(sp) : : "memory" : "intel", "volatile");
    let stack = sp as *const usize;

    let _ = sys_exit(main(*stack, stack.offset(1) as *const *const u8));
}

#[lang = "start"]
fn lang_start(main: *const u8, argc: usize, argv: *const *const u8) -> usize {
    unsafe {
        let mut args: Vec<&'static str> = Vec::new();
        for i in 0..argc as isize {
            let arg = ptr::read(argv.offset(i));
            if arg as usize > 0 {
                let mut len = 0;
                for j in 0..4096 {
                    len = j;
                    if ptr::read(arg.offset(j)) == 0 {
                        break;
                    }
                }
                let utf8: &'static [u8] = slice::from_raw_parts(arg, len as usize);
                args.push(str::from_utf8_unchecked(utf8));
            }
        }

        args_init(args);

        mem::transmute::<_, fn()>(main)();

        args_destroy();
    }

    0
}
<commit_msg>Fix start code<commit_after>use core::{fmt, mem, ptr, slice, str};
use panic::panic_impl;
use env::{args_init, args_destroy};
use system::syscall::sys_exit;
use vec::Vec;

pub fn begin_unwind(string: &'static str, file_line: &(&'static str, u32)) -> ! {
    let &(file, line) = file_line;
    panic_impl(format_args!("{}", string), file, line)
}

pub fn begin_unwind_fmt(fmt: fmt::Arguments, file_line: &(&'static str, u32)) -> ! {
    let &(file, line) = file_line;
    panic_impl(fmt, file, line)
}

#[no_mangle]
#[naked]
#[cfg(target_arch = "x86")]
pub unsafe fn _start() {
    asm!("push esp
        call _start_stack
        pop esp"
        :
        :
        : "memory"
        : "intel", "volatile");
    let _ = sys_exit(0);
}

#[no_mangle]
#[naked]
#[cfg(target_arch = "x86_64")]
pub unsafe fn _start() {
    asm!("push rsp
        call _start_stack
        pop rsp"
        :
        :
        : "memory"
        : "intel", "volatile");
    let _ = sys_exit(0);
}

#[no_mangle]
pub unsafe extern "C" fn _start_stack(sp: usize){
    extern "C" {
        fn main(argc: usize, argv: *const *const u8) -> usize;
    }

    //asm!("xchg bx, bx" : : : "memory" : "intel", "volatile");

    let stack = sp as *const usize;
    let argc = *stack;
    let argv = stack.offset(1) as *const *const u8;
    let _ = sys_exit(main(argc, argv));
}

#[lang = "start"]
fn lang_start(main: *const u8, argc: usize, argv: *const *const u8) -> usize {
    unsafe {
        let mut args: Vec<&'static str> = Vec::new();
        for i in 0..argc as isize {
            let arg = ptr::read(argv.offset(i));
            if arg as usize > 0 {
                let mut len = 0;
                for j in 0..4096 {
                    len = j;
                    if ptr::read(arg.offset(j)) == 0 {
                        break;
                    }
                }
                let utf8: &'static [u8] = slice::from_raw_parts(arg, len as usize);
                args.push(str::from_utf8_unchecked(utf8));
            }
        }

        args_init(args);

        mem::transmute::<_, fn()>(main)();

        args_destroy();
    }

    0
}
<|endoftext|>


<commit_before><commit_msg>Make sure category is linked when setting it<commit_after><|endoftext|>


<commit_before><commit_msg>flat views for all start menu cards<commit_after><|endoftext|>


<commit_before><commit_msg>add link<commit_after><|endoftext|>


<commit_before><commit_msg>languages/rust/learn-rust/3-chapter/2-code.rs<commit_after><|endoftext|>


<commit_before><commit_msg>languages/rust/rust-book/3-chapter/33-code.rs<commit_after><|endoftext|>


<commit_before><commit_msg>blank message<commit_after><|endoftext|>


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


<commit_before><commit_msg>Partially working GTK UI for search state.<commit_after>use std::str::FromStr;

extern crate thud;
use ::thud::actions;
use ::thud::board;
use ::thud::game;
use ::thud::gtk_ui;
use ::thud::mcts;

extern crate gtk;
use gtk::traits::*;
use gtk::signal::Inhibit;

extern crate rand;

pub fn initialize_search(state: game::State, graph: &mut mcts::Graph) {
    let actions: Vec<actions::Action> = state.role_actions(state.active_player().role()).collect();
    let mut adder = graph.add_root(state, Default::default()).to_child_adder();
    for a in actions.into_iter() {
        adder.add(mcts::EdgeData::new(a));
    }
}

fn main() {
    let mut rng = rand::thread_rng();
    let state = game::State::new(board::Cells::default(), String::from_str("Player 1").ok().unwrap(), String::from_str("Player 2").ok().unwrap());
    let mut graph = mcts::Graph::new();
    initialize_search(state.clone(), &mut graph);
    for _ in 0..1000 {
        mcts::iterate_search(state.clone(), &mut graph, &mut rng, 1.0);
    }

    if gtk::init().is_err() {
        println!("Failed to initialize GTK");
        return
    }

    let window = gtk::Window::new(gtk::WindowType::Toplevel).unwrap();

    window.set_title("Search tree");
    window.connect_delete_event(|_, _| {
        gtk::main_quit();
        Inhibit(false)
    });

    let columns = [gtk_ui::SearchGraphColumn::Id,
                   gtk_ui::SearchGraphColumn::Action,
                   gtk_ui::SearchGraphColumn::Statistics,
                   gtk_ui::SearchGraphColumn::EdgeStatus,
                   gtk_ui::SearchGraphColumn::EdgeTarget];
    let mut store = gtk_ui::SearchGraphStore::new(&columns);
    store.update(&graph.get_node(&state).unwrap());
    let tree = gtk::TreeView::new_with_model(&store.model()).unwrap();
    for (i, c) in columns.iter().enumerate() {
        tree.append_column(&c.new_view_column(i as i32));
    }

    let scrolled = gtk::ScrolledWindow::new(None, None).unwrap();
    scrolled.add(&tree);
    window.add(&scrolled);

    window.show_all();
    gtk::main();
}
<|endoftext|>


<commit_before><commit_msg>Test expression-and<commit_after>extern crate xpath;

use xpath::XPathValue;
use xpath::Boolean;
use xpath::Node;
use xpath::expression::XPathExpression;
use xpath::expression::ExpressionAnd;
use xpath::XPathEvaluationContext;

struct StubExpression {
    value: XPathValue,
}

impl XPathExpression for StubExpression {
    fn evaluate(&self, _: &XPathEvaluationContext) -> XPathValue {
        self.value
    }
}

struct FailExpression;

impl XPathExpression for FailExpression {
    fn evaluate(&self, _: &XPathEvaluationContext) -> XPathValue {
        fail!("Should never be called");
    }
}

#[test]
fn expression_and_returns_logical_and() {
    let left  = box StubExpression{value: Boolean(true)};
    let right = box StubExpression{value: Boolean(true)};

    let node = Node::new();
    let context = XPathEvaluationContext {node: &node};
    let expr = ExpressionAnd{left: left, right: right};

    let res = expr.evaluate(&context);

    assert_eq!(res, Boolean(true));
}

#[test]
fn expression_and_short_circuits_when_left_argument_is_false() {
    let left  = box StubExpression{value: Boolean(false)};
    let right = box FailExpression;

    let node = Node::new();
    let context = XPathEvaluationContext {node: &node};
    let expr = ExpressionAnd{left: left, right: right};

    expr.evaluate(&context);
    // assert_not_fail
}
<|endoftext|>


<commit_before><commit_msg>Add destroy method<commit_after><|endoftext|>


<commit_before>//! A drag controller.

use event::{
    FocusEvent,
    GenericEvent,
    MouseCursorEvent,
    PressEvent,
    ReleaseEvent,
};
use input::{
    mouse,
    Mouse,
};

/// Describes a drag.
pub enum Drag {
    /// When the drag is interrupted by something,
    /// for example when the window is defocused.
    /// By returning true, the drag will continue when
    /// the window retrieves focus.
    InterruptDrag,
    /// Starts the drag.
    StartDrag(f64, f64),
    /// Moves the drag.
    MoveDrag(f64, f64),
    /// Ends the drag.
    EndDrag(f64, f64),
}

/// Controls dragging.
pub struct DragController {
    /// Whether to drag or not.
    pub drag: bool,
    /// The current positon of dragging.
    pub pos: [f64, ..2],
}

impl DragController {
    /// Creates a new drag controller.
    pub fn new() -> DragController {
        DragController {
            drag: false,
            pos: [0.0, 0.0],
        }
    }

    /// Handles event.
    ///
    /// Calls closure when events for dragging happen.
    /// If the drag event callback returns `false`, it will cancel dragging.
    pub fn event<E: GenericEvent>(&mut self, e: &E, f: |Drag| -> bool) {
        e.mouse_cursor(|x, y| {
            self.pos = [x, y];
            if self.drag {
                self.drag = f(MoveDrag(x, y));
            }
        });
        e.press(|button| {
            match button {
                Mouse(mouse::Left) => {
                    if !self.drag {
                        self.drag = f(StartDrag(self.pos[0], self.pos[1]));
                    }
                }
                _ => {}
            }
        });
        e.release(|button| {
            match button {
                Mouse(mouse::Left) => {
                    if self.drag {
                        f(EndDrag(self.pos[0], self.pos[1]));
                    }
                    self.drag = false;
                }
                _ => {}
            }
        });
        e.focus(|focused| {
            if focused == false {
                self.drag = f(InterruptDrag);
            }
        });
    }
}
<commit_msg>Fix bug<commit_after>//! A drag controller.

use event::{
    FocusEvent,
    GenericEvent,
    MouseCursorEvent,
    PressEvent,
    ReleaseEvent,
};
use input::{
    mouse,
    Mouse,
};

/// Describes a drag.
pub enum Drag {
    /// When the drag is interrupted by something,
    /// for example when the window is defocused.
    /// By returning true, the drag will continue when
    /// the window retrieves focus.
    InterruptDrag,
    /// Starts the drag.
    StartDrag(f64, f64),
    /// Moves the drag.
    MoveDrag(f64, f64),
    /// Ends the drag.
    EndDrag(f64, f64),
}

/// Controls dragging.
pub struct DragController {
    /// Whether to drag or not.
    pub drag: bool,
    /// The current positon of dragging.
    pub pos: [f64, ..2],
}

impl DragController {
    /// Creates a new drag controller.
    pub fn new() -> DragController {
        DragController {
            drag: false,
            pos: [0.0, 0.0],
        }
    }

    /// Handles event.
    ///
    /// Calls closure when events for dragging happen.
    /// If the drag event callback returns `false`, it will cancel dragging.
    pub fn event<E: GenericEvent>(&mut self, e: &E, f: |Drag| -> bool) {
        e.mouse_cursor(|x, y| {
            self.pos = [x, y];
            if self.drag {
                self.drag = f(MoveDrag(x, y));
            }
        });
        e.press(|button| {
            match button {
                Mouse(mouse::Left) => {
                    if !self.drag {
                        self.drag = f(StartDrag(self.pos[0], self.pos[1]));
                    }
                }
                _ => {}
            }
        });

        // Rest of the event are only handled when dragging.
        if !self.drag { return; }

        e.release(|button| {
            match button {
                Mouse(mouse::Left) => {
                    if self.drag {
                        f(EndDrag(self.pos[0], self.pos[1]));
                    }
                    self.drag = false;
                }
                _ => {}
            }
        });
        e.focus(|focused| {
            if focused == false {
                self.drag = f(InterruptDrag);
            }
        });
    }
}
<|endoftext|>


<commit_before><commit_msg>Warning police.<commit_after><|endoftext|>


<commit_before><commit_msg>Added a bunch of definitions for elf files<commit_after>//! Elf data type definitions
//!
//! Based on http://flint.cs.yale.edu/cs422/doc/ELF_Format.pdf
//!
//! It only contains definitions sufficient to load an executable ELF.

/// Unsigned program address
pub type Elf32Addr = usize;
/// Unsigned medium integer
pub type Elf32Half = u16;
/// Unsinged file offset
pub type Elf32Off = usize;
/// Signed large integer
pub type Elf32Sword = isize;
/// Unsigned large interger
pub type Elf32Word = usize;

/// The ELF header of an ELF file
pub struct Elf32Ehdr {
    /// The initial bytes of the file mark it as an ELF file, give the type,
    /// and provide information about how to interpret the contents.
    e_ident:        [u8; EI_NIDENT],
    /// What type of ELF file is this?
    e_type:         Elf32Half,
    /// What type of machine is the ELF designed for?
    e_machine:      Elf32Half,
    /// What version of the ELF spec?
    e_version:      Elf32Word,
    /// The virtual address of the first instruction of the code to run
    e_entry:        Elf32Addr,
    /// The program header table's file offset in bytes
    e_phoff:        Elf32Off,
    /// The section header table's file offset in bytes
    e_shoff:        Elf32Off,
    /// Processor-specific flags
    e_flags:        Elf32Word,
    /// Size of the ELF header
    e_ehsize:       Elf32Half,
    /// Size of an entry in the program header table
    e_phentsize:    Elf32Half,
    /// Number of program headers
    e_phnum:        Elf32Half,
    /// Size of an entry in the section header table
    e_shentsize:    Elf32Half,
    /// Number of section headers
    e_shnum:        Elf32Half,
    /// The section header table index of the entry associated with the
    /// section name string table.
    e_shstrndx:     Elf32Half,
}

/// Possible values for e_type. The e_type is still defined
/// as a Elf32Half above, though, for compatibility. The same
/// holds for the enums defined in the rest of this module.
pub enum EType {
    /// No file type
    ET_NONE = 0,
    /// Relocatable file
    ET_REL = 1,
    /// Executable file
    ET_EXEC = 2,
    /// Shared object file
    ET_DYN = 3,
    /// Corefile
    ET_CORE = 4,
    /// Processor-specific
    ET_LOPROC = 0xff00,
    /// Processor-specific
    ET_HIPROC = 0xffff,
}

/// Possible values for e_machine
pub enum EMachine {
    /// No machine
    EM_NONE = 0,
    /// AT&T WE 32100
    EM_M32 = 1,
    /// SPARC
    EM_SPARC = 2,
    /// Intel 80386
    EM_386 = 3,
    /// Motorola 68000
    EM_68K = 4,
    /// Motorola 88000
    EM_88K = 5,
    /// Intel 80860
    EM_860 = 6,
    /// MIPS RS3000
    EM_MIPS = 7,
}

/// Possible value for e_version
pub enum EVersion {
    /// Invalid version
    EV_NONE = 0,
    /// Current version
    EV_CURRENT = 1,
}

/// Size of e_ident
pub const EI_NIDENT: usize = 16;

/// Indices of e_ident
pub enum EIdent {
    /// Magic byte 0
    EI_MAG0 = 0,
    /// Magic byte 1
    EI_MAG1 = 1,
    /// Magic byte 2
    EI_MAG2 = 2,
    /// Magic byte 3
    EI_MAG3 = 3,
    /// File class
    EI_CLASS = 4,
    /// Data encoding
    EI_DATA = 5,
    /// File version
    EI_VERSION = 6,
    /// Start of padding bytes
    EI_PAD = 7,
}

/// Magic bytes
pub enum EMagic {
    ELFMAG0 = 0x7f,
    ELFMAG1 = 'E',
    ELFMAG2 = 'L',
    ELFMAG3 = 'F',
}

/// Possible file classes
pub enum EClass {
    /// Invalid class
    ELFCLASSNONE = 0,
    /// 32-bit objects
    ELFCLASS32 = 1,
    /// 64-bit objects
    ELFCLASS64 = 2,
}

/// Possible data encodings
pub enum EData {
    /// Invalid encoding
    ELFDATANONE = 0,
    /// 2's complement, little endian
    ELFDATA2LSB = 1,
    /// 2's complement, big endian
    ELFDATA2MSB = 2,
}

/// A single program header in the program header table
pub struct Elf32Phdr{
    /// What kind of segment is this?
    p_type:     Elf32Word,
    /// The segment's file offset in bytes
    p_offset:   Elf32Off,
    /// The virtual address at which the first byte of the segment goes in memory
    p_vaddr:    Elf32Addr,
    /// Allows the linker to request a physical address
    p_paddr:    Elf32Addr,
    /// Number of bytes in the file image of the segment
    p_filesz:   Elf32Word,
    /// Number of bytes in the memory image of the segment
    p_memsz:    Elf32Word,
    /// Flags for the segment
    p_flags:    Elf32Word,
    /// Request alignment for the segment
    p_align:    Elf32Word,
}

/// Possible values of p_type
pub enum PType {
    /// Null (unused) header
    PT_NULL = 0,
    /// Loadable segment
    PT_LOAD = 1,
    /// Dynamic linking information
    PT_DYNAMIC = 2,
    /// Specifies path to interpreter
    PT_INTERP = 3,
    /// Specifies location of auxiliary information
    PT_NOTE = 4,
    /// Reserved but has unknown semantics
    PT_SHLIB = 5,
    /// The entry specifies the location of the Program header table itself
    PT_PHDR = 6,
    /// PT_LOPROC through PT_HIPROC is an inclusive range reserved for processor
    /// specific semantics
    PT_LOPROC = 0x7000_0000,
    PT_HIPROC = 0x7fff_ffff,
}
<|endoftext|>


<commit_before><commit_msg>Remove #link attribute since its no longer recognized by rustc<commit_after><|endoftext|>


<commit_before><commit_msg>Factor some of the dynamic uniform setting into a function<commit_after><|endoftext|>


<commit_before><commit_msg>Create rust-src-for-codingame.rs<commit_after>// solution for as cii art

use std::io;

macro_rules! parse_input {
    ($x:expr, $t:ident) => ($x.trim().parse::<$t>().unwrap())
}

/**
 * Auto-generated code below aims at helping you parse
 * the standard input according to the problem statement.
 **/
fn main() {
    //let mut input_line = String::new();
    //io::stdin().read_line(&mut input_line).unwrap();
    let mut input_line = get_line_as_string();
    let asc_len = parse_input!(input_line, i32);

    input_line = get_line_as_string();
    let asc_hei = parse_input!(input_line, i32);

    input_line = get_line_as_string();
    let t: Vec<char> = input_line.trim_right().to_uppercase().chars().collect();

    let mut char_lines: Vec<String> = vec![];
    for i in 0..asc_hei as usize {
        let mut input_line = get_line_as_string();
        let row = input_line.to_string();
        char_lines.push(row);
    }

    for (row_index, chr_row) in char_lines.iter().enumerate() {
        let mut res_str = String::new();
        for chr in &t {
            let apos = 'A' as i32;
            let mut cn = *chr as i32 - apos;
            if (cn < 0 || cn > 25) {
                cn = 26;
            }
            let start = (cn * asc_len) as usize;
            let end = start + asc_len as usize;
            res_str.push_str( &chr_row[start..end] );
         }
        println!("{}", res_str);
    }
}

fn get_line_as_string() -> String {
    let mut stln = String::new();
    io::stdin().read_line(&mut stln).unwrap();
    return stln;
}
<|endoftext|>


<commit_before>extern crate regex;
use std::env::*;
use std::fs::File;
use std::path::Path;
use std::error::Error;
use std::io::prelude::*;

#[derive(Clone, Debug)]
pub struct AWSCredentials {
    key: String,
    secret: String
}

impl AWSCredentials {
    pub fn new(key:&str, secret:&str) -> AWSCredentials {
        AWSCredentials {
            key: key.to_string(),
            secret: secret.to_string()
        }
    }

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

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

pub trait AWSCredentialsProvider {
	fn get_credentials(&self) -> &AWSCredentials;
	fn refresh(&mut self);
}

pub struct EnvironmentCredentialsProvider;

pub struct DefaultAWSCredentialsProviderChain {
	credentials: AWSCredentials
}

impl AWSCredentialsProvider for DefaultAWSCredentialsProviderChain {
	fn refresh(&mut self) {
		let env_creds = DefaultAWSCredentialsProviderChain::creds_from_env();
		if env_creds.is_ok() {
			self.credentials = env_creds.unwrap();
			return;
		}

		//let file_creds = DefaultAWSCredentialsProviderChain::creds_from_profile();
	}

	fn get_credentials(&self) -> &AWSCredentials {
		&self.credentials
	}

}

struct ProfileCredentialsError;

// From http://blogs.aws.amazon.com/security/post/Tx3D6U6WSFGOK2H/A-New-and-Standardized-Way-to-Manage-Credentials-in-the-AWS-SDKs
// 1. environment variables
// 2. central credentials file (named profile is supplied, otherwise default)
// 3. IAM role (if running on an EC2 instance)
impl DefaultAWSCredentialsProviderChain {

    // fn get_credentials() -> Result<AWSCredentials, VarError> {
    //     let usable_creds : AWSCredentials;
    //     match DefaultAWSCredentialsProviderChain::creds_from_env() {
    //         Ok(creds) => usable_creds = creds,
    //         Err(why) => println!("Couldn't get environment credentials."),
    //     }
    //
    //     return Ok(usable_creds);
    // }

	fn creds_from_env() -> Result<AWSCredentials, VarError> {
		let env_key = try!(var("AWS_ACCESS_KEY_ID"));
		let env_secret = try!(var("AWS_SECRET_KEY"));

		Ok(AWSCredentials { key: env_key, secret: env_secret });
	}

	// fn creds_from_profile() -> Result<AWSCredentials, ProfileCredentialsError> {
    //     let path = Path::new("sample-credentials");
    //     let display = path.display();
    //
    //     let mut file = match File::open(&path) {
    //         Err(why) => panic!("couldn't open {}: {}", display,
    //                                                    Error::description(&why)),
    //         Ok(file) => file,
    //     };
    //
    //     let mut contents = String::new();
    //     match file.read_to_string(&mut contents) {
    //         Err(why) => panic!("couldn't read {}: {}", display,
    //                                                    Error::description(&why)),
    //         Ok(_) => {},
    //     }
    //
    //     let profile_key = String::from("foo");
    //     let secret_key = String::from("bar");
    //
    //     return Ok(AWSCredentials{ key: profile_key, secret: secret_key });
    //
	// 	// Err(ProfileCredentialsError)
	// }

    // IAM role
}
<commit_msg>Much hack and slash churn in an attempt to learn more about errors and function returns.<commit_after>extern crate regex;
use std::env::*;
use std::fs::File;
use std::path::Path;
use std::error::Error;
use std::io::prelude::*;

#[derive(Clone, Debug)]
pub struct AWSCredentials {
    key: String,
    secret: String
}

#[derive(Debug)]
enum CredentialErr {
    NoEnvironmentVariables,
    NoCredentialsFile,
}

impl AWSCredentials {
    pub fn new(key:&str, secret:&str) -> AWSCredentials {
        AWSCredentials {
            key: key.to_string(),
            secret: secret.to_string()
        }
    }

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

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

pub trait AWSCredentialsProvider {
	fn get_credentials(&self) -> &AWSCredentials;
	fn refresh(&mut self);
}

pub struct EnvironmentCredentialsProvider;

pub struct DefaultAWSCredentialsProviderChain {
	credentials: AWSCredentials
}

impl AWSCredentialsProvider for DefaultAWSCredentialsProviderChain {
	fn refresh(&mut self) {
		let env_creds = DefaultAWSCredentialsProviderChain::get_credentials();
        match env_creds {
            Ok(creds) => {
                self.credentials = creds;
	            return;
            }
            Err(why) => panic!("Couldn't open credentials anywhere."),
        }

		//let file_creds = DefaultAWSCredentialsProviderChain::creds_from_profile();
	}

	fn get_credentials(&self) -> &AWSCredentials {
		&self.credentials
	}

}

struct ProfileCredentialsError;

// From http://blogs.aws.amazon.com/security/post/Tx3D6U6WSFGOK2H/A-New-and-Standardized-Way-to-Manage-Credentials-in-the-AWS-SDKs
// 1. environment variables
// 2. central credentials file (named profile is supplied, otherwise default)
// 3. IAM role (if running on an EC2 instance)
impl DefaultAWSCredentialsProviderChain {

    fn get_credentials() -> Result<AWSCredentials, CredentialErr> {
        let usable_creds : AWSCredentials;

        let env_return = match DefaultAWSCredentialsProviderChain::creds_from_env() {
            Ok(v) => {
                println!("working with version: {:?}", v);
            }
            Err(e) => {
                println!("error parsing header: {:?}", e);
            }
        };

        // Ok(usable_creds)
    }

	fn creds_from_env() -> Result<AWSCredentials, CredentialErr> {
        // these except to be able to return a VarError if things go poorly:
		let env_key = try!(var("AWS_ACCESS_KEY_ID"));
		let env_secret = try!(var("AWS_SECRET_KEY"));

        if env_key.len() <= 0 || env_secret.len() <= 0 {
            return Err(CredentialErr::NoEnvironmentVariables);
        }

		Ok(AWSCredentials { key: env_key, secret: env_secret })
	}

	// fn creds_from_profile() -> Result<AWSCredentials, ProfileCredentialsError> {
    //     let path = Path::new("sample-credentials");
    //     let display = path.display();
    //
    //     let mut file = match File::open(&path) {
    //         Err(why) => panic!("couldn't open {}: {}", display,
    //                                                    Error::description(&why)),
    //         Ok(file) => file,
    //     };
    //
    //     let mut contents = String::new();
    //     match file.read_to_string(&mut contents) {
    //         Err(why) => panic!("couldn't read {}: {}", display,
    //                                                    Error::description(&why)),
    //         Ok(_) => {},
    //     }
    //
    //     let profile_key = String::from("foo");
    //     let secret_key = String::from("bar");
    //
    //     return Ok(AWSCredentials{ key: profile_key, secret: secret_key });
    //
	// 	// Err(ProfileCredentialsError)
	// }

    // IAM role
}
<|endoftext|>


<commit_before><commit_msg>Solution for Dot Product<commit_after>// Implements http://rosettacode.org/wiki/Dot_product

use std::ops::{Add,Mul};
use std::num::Zero;

fn dotp<'a,T:Add<T,T>+Mul<T,T>+Zero+Copy>(this:&'a [T], other:&'a [T]) -> T {
  if this.len() != other.len() {
    fail!("The dimensions must be equal!");
  }
  let zero: T = Zero::zero();
  this.iter().zip(other.iter()).map(|(&a,&b)|a*b).fold(zero,|sum,n|sum+n)
}

#[cfg(not(test))]
fn main() {
  let a = [1.0, 3.0, -5.0];
  let b = [4.0, -2.0, -1.0];
  println!("{}", dotp(a.as_slice(),b.as_slice()));
}

#[test]
fn testDotp() {
  assert_eq!(dotp([1,3,-5].as_slice(),[4,-2,-1].as_slice()),3);
}
<|endoftext|>


<commit_before><commit_msg>Implement unbias RNG<commit_after>#![feature(inclusive_range_syntax)]

extern crate rand;

use rand::Rng;

fn rand_n<R: Rng>(rng: &mut R, n: u32) -> usize {
    rng.gen_weighted_bool(n) as usize // maps `false` to 0 and `true` to 1
}

fn unbiased<R: Rng>(rng: &mut R, n: u32) -> usize {
    let mut bit = rand_n(rng, n);
    while bit == rand_n(rng, n) {
        bit = rand_n(rng, n);
    }
    bit
}

fn main() {
    const SAMPLES: usize = 100_000;
    let mut rng = rand::weak_rng();

    println!(" Bias    rand_n  unbiased");
    for n in 3..=6 {
        let mut count_biased = 0;
        let mut count_unbiased = 0;
        for _ in 0..SAMPLES {
            count_biased += rand_n(&mut rng, n);
            count_unbiased += unbiased(&mut rng, n);
        }

        let b_percentage = 100.0 * count_biased as f64 / SAMPLES as f64;
        let ub_percentage = 100.0 * count_unbiased as f64 / SAMPLES as f64;
        println!(
            "bias {}:  {:0.2}%   {:0.2}%",
            n, b_percentage, ub_percentage
        );
    }
}

#[test]
fn test_unbiased() {
    let mut rng = rand::weak_rng();
    const SAMPLES: usize = 10_000;

    for n in 3..=6 {
        let mut count = 0;
        for _ in 0..SAMPLES {
            count += unbiased(&mut rng, n);
        }

        let ratio = 1000 * count / SAMPLES;
        assert!(ratio > 490 && ratio < 510, "{}", ratio);
    }
}
<|endoftext|>


<commit_before><commit_msg>Fix bug: assume all exprs in block should terminated by `;`.<commit_after><|endoftext|>