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

//! Simplification of where clauses and parameter bounds into a prettier and
//! more canonical form.
//!
//! Currently all cross-crate-inlined function use `rustc::ty` to reconstruct
//! the AST (e.g. see all of `clean::inline`), but this is not always a
//! non-lossy transformation. The current format of storage for where clauses
//! for functions and such is simply a list of predicates. One example of this
//! is that the AST predicate of:
//!
//!     where T: Trait<Foo=Bar>
//!
//! is encoded as:
//!
//!     where T: Trait, <T as Trait>::Foo = Bar
//!
//! This module attempts to reconstruct the original where and/or parameter
//! bounds by special casing scenarios such as these. Fun!

use std::mem;
use std::collections::HashMap;

use rustc::hir::def_id::DefId;
use rustc::ty::subst;

use clean::PathParameters as PP;
use clean::WherePredicate as WP;
use clean::{self, Clean};
use core::DocContext;

pub fn where_clauses(cx: &DocContext, clauses: Vec<WP>) -> Vec<WP> {
    // First, partition the where clause into its separate components
    let mut params = HashMap::new();
    let mut lifetimes = Vec::new();
    let mut equalities = Vec::new();
    let mut tybounds = Vec::new();
    for clause in clauses {
        match clause {
            WP::BoundPredicate { ty, bounds } => {
                match ty {
                    clean::Generic(s) => params.entry(s).or_insert(Vec::new())
                                               .extend(bounds),
                    t => tybounds.push((t, ty_bounds(bounds))),
                }
            }
            WP::RegionPredicate { lifetime, bounds } => {
                lifetimes.push((lifetime, bounds));
            }
            WP::EqPredicate { lhs, rhs } => equalities.push((lhs, rhs)),
        }
    }

    // Simplify the type parameter bounds on all the generics
    let mut params = params.into_iter().map(|(k, v)| {
        (k, ty_bounds(v))
    }).collect::<HashMap<_, _>>();

    // Look for equality predicates on associated types that can be merged into
    // general bound predicates
    equalities.retain(|&(ref lhs, ref rhs)| {
        let (self_, trait_, name) = match *lhs {
            clean::QPath { ref self_type, ref trait_, ref name } => {
                (self_type, trait_, name)
            }
            _ => return true,
        };
        let generic = match **self_ {
            clean::Generic(ref s) => s,
            _ => return true,
        };
        let trait_did = match **trait_ {
            clean::ResolvedPath { did, .. } => did,
            _ => return true,
        };
        let bounds = match params.get_mut(generic) {
            Some(bound) => bound,
            None => return true,
        };
        !bounds.iter_mut().any(|b| {
            let trait_ref = match *b {
                clean::TraitBound(ref mut tr, _) => tr,
                clean::RegionBound(..) => return false,
            };
            let (did, path) = match trait_ref.trait_ {
                clean::ResolvedPath { did, ref mut path, ..} => (did, path),
                _ => return false,
            };
            // If this QPath's trait `trait_did` is the same as, or a supertrait
            // of, the bound's trait `did` then we can keep going, otherwise
            // this is just a plain old equality bound.
            if !trait_is_same_or_supertrait(cx, did, trait_did) {
                return false
            }
            let last = path.segments.last_mut().unwrap();
            match last.params {
                PP::AngleBracketed { ref mut bindings, .. } => {
                    bindings.push(clean::TypeBinding {
                        name: name.clone(),
                        ty: rhs.clone(),
                    });
                }
                PP::Parenthesized { ref mut output, .. } => {
                    assert!(output.is_none());
                    *output = Some(rhs.clone());
                }
            };
            true
        })
    });

    // And finally, let's reassemble everything
    let mut clauses = Vec::new();
    clauses.extend(lifetimes.into_iter().map(|(lt, bounds)| {
        WP::RegionPredicate { lifetime: lt, bounds: bounds }
    }));
    clauses.extend(params.into_iter().map(|(k, v)| {
        WP::BoundPredicate {
            ty: clean::Generic(k),
            bounds: v,
        }
    }));
    clauses.extend(tybounds.into_iter().map(|(ty, bounds)| {
        WP::BoundPredicate { ty: ty, bounds: bounds }
    }));
    clauses.extend(equalities.into_iter().map(|(lhs, rhs)| {
        WP::EqPredicate { lhs: lhs, rhs: rhs }
    }));
    clauses
}

pub fn ty_params(mut params: Vec<clean::TyParam>) -> Vec<clean::TyParam> {
    for param in &mut params {
        param.bounds = ty_bounds(mem::replace(&mut param.bounds, Vec::new()));
    }
    return params;
}

fn ty_bounds(bounds: Vec<clean::TyParamBound>) -> Vec<clean::TyParamBound> {
    bounds
}

fn trait_is_same_or_supertrait(cx: &DocContext, child: DefId,
                               trait_: DefId) -> bool {
    if child == trait_ {
        return true
    }
    let def = cx.tcx().lookup_trait_def(child);
    let predicates = cx.tcx().lookup_predicates(child);
    let generics = (&def.generics, &predicates, subst::TypeSpace).clean(cx);
    generics.where_predicates.iter().filter_map(|pred| {
        match *pred {
            clean::WherePredicate::BoundPredicate {
                ty: clean::Generic(ref s),
                ref bounds
            } if *s == "Self" => Some(bounds),
            _ => None,
        }
    }).flat_map(|bounds| bounds).any(|bound| {
        let poly_trait = match *bound {
            clean::TraitBound(ref t, _) => t,
            _ => return false,
        };
        match poly_trait.trait_ {
            clean::ResolvedPath { did, .. } => {
                trait_is_same_or_supertrait(cx, did, trait_)
            }
            _ => false,
        }
    })
}
<commit_msg>rustdoc: use btree map for where clauses<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.

//! Simplification of where clauses and parameter bounds into a prettier and
//! more canonical form.
//!
//! Currently all cross-crate-inlined function use `rustc::ty` to reconstruct
//! the AST (e.g. see all of `clean::inline`), but this is not always a
//! non-lossy transformation. The current format of storage for where clauses
//! for functions and such is simply a list of predicates. One example of this
//! is that the AST predicate of:
//!
//!     where T: Trait<Foo=Bar>
//!
//! is encoded as:
//!
//!     where T: Trait, <T as Trait>::Foo = Bar
//!
//! This module attempts to reconstruct the original where and/or parameter
//! bounds by special casing scenarios such as these. Fun!

use std::mem;
use std::collections::BTreeMap;

use rustc::hir::def_id::DefId;
use rustc::ty::subst;

use clean::PathParameters as PP;
use clean::WherePredicate as WP;
use clean::{self, Clean};
use core::DocContext;

pub fn where_clauses(cx: &DocContext, clauses: Vec<WP>) -> Vec<WP> {
    // First, partition the where clause into its separate components
    let mut params = BTreeMap::new();
    let mut lifetimes = Vec::new();
    let mut equalities = Vec::new();
    let mut tybounds = Vec::new();
    for clause in clauses {
        match clause {
            WP::BoundPredicate { ty, bounds } => {
                match ty {
                    clean::Generic(s) => params.entry(s).or_insert(Vec::new())
                                               .extend(bounds),
                    t => tybounds.push((t, ty_bounds(bounds))),
                }
            }
            WP::RegionPredicate { lifetime, bounds } => {
                lifetimes.push((lifetime, bounds));
            }
            WP::EqPredicate { lhs, rhs } => equalities.push((lhs, rhs)),
        }
    }

    // Simplify the type parameter bounds on all the generics
    let mut params = params.into_iter().map(|(k, v)| {
        (k, ty_bounds(v))
    }).collect::<BTreeMap<_, _>>();

    // Look for equality predicates on associated types that can be merged into
    // general bound predicates
    equalities.retain(|&(ref lhs, ref rhs)| {
        let (self_, trait_, name) = match *lhs {
            clean::QPath { ref self_type, ref trait_, ref name } => {
                (self_type, trait_, name)
            }
            _ => return true,
        };
        let generic = match **self_ {
            clean::Generic(ref s) => s,
            _ => return true,
        };
        let trait_did = match **trait_ {
            clean::ResolvedPath { did, .. } => did,
            _ => return true,
        };
        let bounds = match params.get_mut(generic) {
            Some(bound) => bound,
            None => return true,
        };
        !bounds.iter_mut().any(|b| {
            let trait_ref = match *b {
                clean::TraitBound(ref mut tr, _) => tr,
                clean::RegionBound(..) => return false,
            };
            let (did, path) = match trait_ref.trait_ {
                clean::ResolvedPath { did, ref mut path, ..} => (did, path),
                _ => return false,
            };
            // If this QPath's trait `trait_did` is the same as, or a supertrait
            // of, the bound's trait `did` then we can keep going, otherwise
            // this is just a plain old equality bound.
            if !trait_is_same_or_supertrait(cx, did, trait_did) {
                return false
            }
            let last = path.segments.last_mut().unwrap();
            match last.params {
                PP::AngleBracketed { ref mut bindings, .. } => {
                    bindings.push(clean::TypeBinding {
                        name: name.clone(),
                        ty: rhs.clone(),
                    });
                }
                PP::Parenthesized { ref mut output, .. } => {
                    assert!(output.is_none());
                    *output = Some(rhs.clone());
                }
            };
            true
        })
    });

    // And finally, let's reassemble everything
    let mut clauses = Vec::new();
    clauses.extend(lifetimes.into_iter().map(|(lt, bounds)| {
        WP::RegionPredicate { lifetime: lt, bounds: bounds }
    }));
    clauses.extend(params.into_iter().map(|(k, v)| {
        WP::BoundPredicate {
            ty: clean::Generic(k),
            bounds: v,
        }
    }));
    clauses.extend(tybounds.into_iter().map(|(ty, bounds)| {
        WP::BoundPredicate { ty: ty, bounds: bounds }
    }));
    clauses.extend(equalities.into_iter().map(|(lhs, rhs)| {
        WP::EqPredicate { lhs: lhs, rhs: rhs }
    }));
    clauses
}

pub fn ty_params(mut params: Vec<clean::TyParam>) -> Vec<clean::TyParam> {
    for param in &mut params {
        param.bounds = ty_bounds(mem::replace(&mut param.bounds, Vec::new()));
    }
    return params;
}

fn ty_bounds(bounds: Vec<clean::TyParamBound>) -> Vec<clean::TyParamBound> {
    bounds
}

fn trait_is_same_or_supertrait(cx: &DocContext, child: DefId,
                               trait_: DefId) -> bool {
    if child == trait_ {
        return true
    }
    let def = cx.tcx().lookup_trait_def(child);
    let predicates = cx.tcx().lookup_predicates(child);
    let generics = (&def.generics, &predicates, subst::TypeSpace).clean(cx);
    generics.where_predicates.iter().filter_map(|pred| {
        match *pred {
            clean::WherePredicate::BoundPredicate {
                ty: clean::Generic(ref s),
                ref bounds
            } if *s == "Self" => Some(bounds),
            _ => None,
        }
    }).flat_map(|bounds| bounds).any(|bound| {
        let poly_trait = match *bound {
            clean::TraitBound(ref t, _) => t,
            _ => return false,
        };
        match poly_trait.trait_ {
            clean::ResolvedPath { did, .. } => {
                trait_is_same_or_supertrait(cx, did, trait_)
            }
            _ => false,
        }
    })
}
<|endoftext|>


<commit_before><commit_msg>test job queue<commit_after><|endoftext|>


<commit_before>import libc::{c_double, c_int};
import f64::*;

fn to_c_int(v: &mut int) -> &mut c_int unsafe {
    unsafe::reinterpret_cast(v)
}

fn lgamma(n: c_double, value: &mut int) -> c_double {
  return m::lgamma(n, to_c_uint(value));
}

#[link_name = "m"]
#[abi = "cdecl"]
extern mod m {
    #[cfg(unix)]
    #[link_name="lgamma_r"] fn lgamma(n: c_double, sign: &mut c_int)
      -> c_double;
    #[cfg(windows)]
    #[link_name="__lgamma_r"] fn lgamma(n: c_double,
                                        sign: &mut c_int) -> c_double;

}

fn main() {
  let mut y: int = 5;
  let x: &mut int = &mut y;
  assert (lgamma(1.0 as c_double, x) == 0.0 as c_double);
}<commit_msg>fix compilation of 2214<commit_after>import libc::{c_double, c_int};
import f64::*;

fn to_c_int(v: &mut int) -> &mut c_int unsafe {
    unsafe::reinterpret_cast(v)
}

fn lgamma(n: c_double, value: &mut int) -> c_double {
  return m::lgamma(n, to_c_int(value));
}

#[link_name = "m"]
#[abi = "cdecl"]
extern mod m {
    #[cfg(unix)]
    #[link_name="lgamma_r"] fn lgamma(n: c_double, sign: &mut c_int)
      -> c_double;
    #[cfg(windows)]
    #[link_name="__lgamma_r"] fn lgamma(n: c_double,
                                        sign: &mut c_int) -> c_double;

}

fn main() {
  let mut y: int = 5;
  let x: &mut int = &mut y;
  assert (lgamma(1.0 as c_double, x) == 0.0 as c_double);
}<|endoftext|>


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

//! Base64 binary-to-text encoding

use core::iter;
use core::str;
use core::vec;

pub trait ToBase64 {
    fn to_base64(&self) -> ~str;
}

static CHARS: [char, ..64] = [
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
    'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
];

impl<'self> ToBase64 for &'self [u8] {
    /**
     * Turn a vector of `u8` bytes into a string representing them in base64.
     *
     * *Example*:
     *
     * ~~~~
     * extern mod std;
     * use std::base64::ToBase64;
     *
     * fn main () {
     *   let str = [52,32].to_base64();
     *   println(fmt!("%s", str));
     * }
     * ~~~~
     */
    fn to_base64(&self) -> ~str {
        let mut s = ~"";
        unsafe {
            let len = self.len();
            str::reserve(&mut s, ((len + 3u) / 4u) * 3u);

            let mut i = 0u;

            while i < len - (len % 3u) {
                let n = (self[i] as uint) << 16u |
                        (self[i + 1u] as uint) << 8u |
                        (self[i + 2u] as uint);

                // This 24-bit number gets separated into four 6-bit numbers.
                str::push_char(&mut s, CHARS[(n >> 18u) & 63u]);
                str::push_char(&mut s, CHARS[(n >> 12u) & 63u]);
                str::push_char(&mut s, CHARS[(n >> 6u) & 63u]);
                str::push_char(&mut s, CHARS[n & 63u]);

                i += 3u;
            }

            // Heh, would be cool if we knew this was exhaustive
            // (the dream of bounded integer types)
            match len % 3 {
              0 => (),
              1 => {
                let n = (self[i] as uint) << 16u;
                str::push_char(&mut s, CHARS[(n >> 18u) & 63u]);
                str::push_char(&mut s, CHARS[(n >> 12u) & 63u]);
                str::push_char(&mut s, '=');
                str::push_char(&mut s, '=');
              }
              2 => {
                let n = (self[i] as uint) << 16u |
                    (self[i + 1u] as uint) << 8u;
                str::push_char(&mut s, CHARS[(n >> 18u) & 63u]);
                str::push_char(&mut s, CHARS[(n >> 12u) & 63u]);
                str::push_char(&mut s, CHARS[(n >> 6u) & 63u]);
                str::push_char(&mut s, '=');
              }
              _ => fail!(~"Algebra is broken, please alert the math police")
            }
        }
        s
    }
}

impl<'self> ToBase64 for &'self str {
    /**
     * Convert any string (literal, `@`, `&`, `~`) to base64 encoding.
     *
     *
     * *Example*:
     *
     * ~~~~
     * extern mod std;
     * use std::base64::ToBase64;
     *
     * fn main () {
     *   let str = "Hello, World".to_base64();
     *   println(fmt!("%s",str));
     * }
     * ~~~~
     *
     */
    fn to_base64(&self) -> ~str {
        str::to_bytes(*self).to_base64()
    }
}

pub trait FromBase64 {
    fn from_base64(&self) -> ~[u8];
}

impl FromBase64 for ~[u8] {
    /**
     * Turn a vector of `u8`s representing characters
     * encoding byte values in base64 into the vector of `u8` byte values.
     *
     * *Example*:
     *
     * ~~~~
     * extern mod std;
     * use std::base64::ToBase64;
     * use std::base64::FromBase64;
     *
     * fn main () {
     *   let str = [52,32].to_base64();
     *   println(fmt!("%s", str));
     *   let bytes = str.from_base64();
     *   println(fmt!("%?",bytes));
     * }
     * ~~~~
     */
    fn from_base64(&self) -> ~[u8] {
        if self.len() % 4u != 0u { fail!(~"invalid base64 length"); }

        let len = self.len();
        let mut padding = 0u;

        if len != 0u {
            if self[len - 1u] == '=' as u8 { padding += 1u; }
            if self[len - 2u] == '=' as u8 { padding += 1u; }
        }

        let mut r = vec::with_capacity((len / 4u) * 3u - padding);

        unsafe {
            let mut i = 0u;
            while i < len {
                let mut n = 0u;

                for iter::repeat(4u) {
                    let ch = self[i] as char;
                    n <<= 6u;

                    if ch >= 'A' && ch <= 'Z' {
                        n |= (ch as uint) - 0x41u;
                    } else if ch >= 'a' && ch <= 'z' {
                        n |= (ch as uint) - 0x47u;
                    } else if ch >= '0' && ch <= '9' {
                        n |= (ch as uint) + 0x04u;
                    } else if ch == '+' {
                        n |= 0x3Eu;
                    } else if ch == '/' {
                        n |= 0x3Fu;
                    } else if ch == '=' {
                        match len - i {
                          1u => {
                            r.push(((n >> 16u) & 0xFFu) as u8);
                            r.push(((n >> 8u ) & 0xFFu) as u8);
                            return copy r;
                          }
                          2u => {
                            r.push(((n >> 10u) & 0xFFu) as u8);
                            return copy r;
                          }
                          _ => fail!(~"invalid base64 padding")
                        }
                    } else {
                        fail!(~"invalid base64 character");
                    }

                    i += 1u;
                };

                r.push(((n >> 16u) & 0xFFu) as u8);
                r.push(((n >> 8u ) & 0xFFu) as u8);
                r.push(((n       ) & 0xFFu) as u8);
            }
        }
        r
    }
}

impl FromBase64 for ~str {
    /**
     * Convert any string (literal, `@`, `&`, `~`)
     * that contains a base64 encoded value, to the byte values it encodes.
     *
     * You can use the `from_bytes` function in `core::str`
     * to turn a `[u8]` into a string with characters corresponding to those values.
     *
     * *Example*:
     *
     * This is an example of going from a string literal to the base64 encoding
     * and back to the same string.
     *
     * ~~~~
     * extern mod std;
     * use std::base64::ToBase64;
     * use std::base64::FromBase64;
     * use core::str;
     *
     * fn main () {
     *   let hello_str = "Hello, World".to_base64();
     *   println(fmt!("%s",hello_str));
     *   let bytes = hello_str.from_base64();
     *   println(fmt!("%?",bytes));
     *   let result_str = str::from_bytes(bytes);
     *   println(fmt!("%s",result_str));
     * }
     * ~~~~
     */
    fn from_base64(&self) -> ~[u8] {
        str::to_bytes(*self).from_base64()
    }
}

#[cfg(test)]
mod tests {
    use core::str;

    #[test]
    pub fn test_to_base64() {
        assert!((~"").to_base64()       == ~"");
        assert!((~"f").to_base64()      == ~"Zg==");
        assert!((~"fo").to_base64()     == ~"Zm8=");
        assert!((~"foo").to_base64()    == ~"Zm9v");
        assert!((~"foob").to_base64()   == ~"Zm9vYg==");
        assert!((~"fooba").to_base64()  == ~"Zm9vYmE=");
        assert!((~"foobar").to_base64() == ~"Zm9vYmFy");
    }

    #[test]
    pub fn test_from_base64() {
        assert!((~"").from_base64() == str::to_bytes(~""));
        assert!((~"Zg==").from_base64() == str::to_bytes(~"f"));
        assert!((~"Zm8=").from_base64() == str::to_bytes(~"fo"));
        assert!((~"Zm9v").from_base64() == str::to_bytes(~"foo"));
        assert!((~"Zm9vYg==").from_base64() == str::to_bytes(~"foob"));
        assert!((~"Zm9vYmE=").from_base64() == str::to_bytes(~"fooba"));
        assert!((~"Zm9vYmFy").from_base64() == str::to_bytes(~"foobar"));
    }
}
<commit_msg>Doc review, as requested :-).<commit_after>// Copyright 2012 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.

//! Base64 binary-to-text encoding

use core::iter;
use core::str;
use core::vec;

pub trait ToBase64 {
    fn to_base64(&self) -> ~str;
}

static CHARS: [char, ..64] = [
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
    'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
];

impl<'self> ToBase64 for &'self [u8] {
    /**
     * Turn a vector of `u8` bytes into a base64 string.
     *
     * *Example*:
     *
     * ~~~~
     * extern mod std;
     * use std::base64::ToBase64;
     *
     * fn main () {
     *   let str = [52,32].to_base64();
     *   println(fmt!("%s", str));
     * }
     * ~~~~
     */
    fn to_base64(&self) -> ~str {
        let mut s = ~"";
        unsafe {
            let len = self.len();
            str::reserve(&mut s, ((len + 3u) / 4u) * 3u);

            let mut i = 0u;

            while i < len - (len % 3u) {
                let n = (self[i] as uint) << 16u |
                        (self[i + 1u] as uint) << 8u |
                        (self[i + 2u] as uint);

                // This 24-bit number gets separated into four 6-bit numbers.
                str::push_char(&mut s, CHARS[(n >> 18u) & 63u]);
                str::push_char(&mut s, CHARS[(n >> 12u) & 63u]);
                str::push_char(&mut s, CHARS[(n >> 6u) & 63u]);
                str::push_char(&mut s, CHARS[n & 63u]);

                i += 3u;
            }

            // Heh, would be cool if we knew this was exhaustive
            // (the dream of bounded integer types)
            match len % 3 {
              0 => (),
              1 => {
                let n = (self[i] as uint) << 16u;
                str::push_char(&mut s, CHARS[(n >> 18u) & 63u]);
                str::push_char(&mut s, CHARS[(n >> 12u) & 63u]);
                str::push_char(&mut s, '=');
                str::push_char(&mut s, '=');
              }
              2 => {
                let n = (self[i] as uint) << 16u |
                    (self[i + 1u] as uint) << 8u;
                str::push_char(&mut s, CHARS[(n >> 18u) & 63u]);
                str::push_char(&mut s, CHARS[(n >> 12u) & 63u]);
                str::push_char(&mut s, CHARS[(n >> 6u) & 63u]);
                str::push_char(&mut s, '=');
              }
              _ => fail!(~"Algebra is broken, please alert the math police")
            }
        }
        s
    }
}

impl<'self> ToBase64 for &'self str {
    /**
     * Convert any string (literal, `@`, `&`, or `~`) to base64 encoding.
     *
     *
     * *Example*:
     *
     * ~~~~
     * extern mod std;
     * use std::base64::ToBase64;
     *
     * fn main () {
     *   let str = "Hello, World".to_base64();
     *   println(fmt!("%s",str));
     * }
     * ~~~~
     *
     */
    fn to_base64(&self) -> ~str {
        str::to_bytes(*self).to_base64()
    }
}

pub trait FromBase64 {
    fn from_base64(&self) -> ~[u8];
}

impl FromBase64 for ~[u8] {
    /**
     * Convert base64 `u8` vector into u8 byte values.
     * Every 4 encoded characters is converted into 3 octets, modulo padding.
     *
     * *Example*:
     *
     * ~~~~
     * extern mod std;
     * use std::base64::ToBase64;
     * use std::base64::FromBase64;
     *
     * fn main () {
     *   let str = [52,32].to_base64();
     *   println(fmt!("%s", str));
     *   let bytes = str.from_base64();
     *   println(fmt!("%?",bytes));
     * }
     * ~~~~
     */
    fn from_base64(&self) -> ~[u8] {
        if self.len() % 4u != 0u { fail!(~"invalid base64 length"); }

        let len = self.len();
        let mut padding = 0u;

        if len != 0u {
            if self[len - 1u] == '=' as u8 { padding += 1u; }
            if self[len - 2u] == '=' as u8 { padding += 1u; }
        }

        let mut r = vec::with_capacity((len / 4u) * 3u - padding);

        unsafe {
            let mut i = 0u;
            while i < len {
                let mut n = 0u;

                for iter::repeat(4u) {
                    let ch = self[i] as char;
                    n <<= 6u;

                    if ch >= 'A' && ch <= 'Z' {
                        n |= (ch as uint) - 0x41u;
                    } else if ch >= 'a' && ch <= 'z' {
                        n |= (ch as uint) - 0x47u;
                    } else if ch >= '0' && ch <= '9' {
                        n |= (ch as uint) + 0x04u;
                    } else if ch == '+' {
                        n |= 0x3Eu;
                    } else if ch == '/' {
                        n |= 0x3Fu;
                    } else if ch == '=' {
                        match len - i {
                          1u => {
                            r.push(((n >> 16u) & 0xFFu) as u8);
                            r.push(((n >> 8u ) & 0xFFu) as u8);
                            return copy r;
                          }
                          2u => {
                            r.push(((n >> 10u) & 0xFFu) as u8);
                            return copy r;
                          }
                          _ => fail!(~"invalid base64 padding")
                        }
                    } else {
                        fail!(~"invalid base64 character");
                    }

                    i += 1u;
                };

                r.push(((n >> 16u) & 0xFFu) as u8);
                r.push(((n >> 8u ) & 0xFFu) as u8);
                r.push(((n       ) & 0xFFu) as u8);
            }
        }
        r
    }
}

impl FromBase64 for ~str {
    /**
     * Convert any base64 encoded string (literal, `@`, `&`, or `~`)
     * to the byte values it encodes.
     *
     * You can use the `from_bytes` function in `core::str`
     * to turn a `[u8]` into a string with characters corresponding to those values.
     *
     * *Example*:
     *
     * This converts a string literal to base64 and back.
     *
     * ~~~~
     * extern mod std;
     * use std::base64::ToBase64;
     * use std::base64::FromBase64;
     * use core::str;
     *
     * fn main () {
     *   let hello_str = "Hello, World".to_base64();
     *   println(fmt!("%s",hello_str));
     *   let bytes = hello_str.from_base64();
     *   println(fmt!("%?",bytes));
     *   let result_str = str::from_bytes(bytes);
     *   println(fmt!("%s",result_str));
     * }
     * ~~~~
     */
    fn from_base64(&self) -> ~[u8] {
        str::to_bytes(*self).from_base64()
    }
}

#[cfg(test)]
mod tests {
    use core::str;

    #[test]
    pub fn test_to_base64() {
        assert!((~"").to_base64()       == ~"");
        assert!((~"f").to_base64()      == ~"Zg==");
        assert!((~"fo").to_base64()     == ~"Zm8=");
        assert!((~"foo").to_base64()    == ~"Zm9v");
        assert!((~"foob").to_base64()   == ~"Zm9vYg==");
        assert!((~"fooba").to_base64()  == ~"Zm9vYmE=");
        assert!((~"foobar").to_base64() == ~"Zm9vYmFy");
    }

    #[test]
    pub fn test_from_base64() {
        assert!((~"").from_base64() == str::to_bytes(~""));
        assert!((~"Zg==").from_base64() == str::to_bytes(~"f"));
        assert!((~"Zm8=").from_base64() == str::to_bytes(~"fo"));
        assert!((~"Zm9v").from_base64() == str::to_bytes(~"foo"));
        assert!((~"Zm9vYg==").from_base64() == str::to_bytes(~"foob"));
        assert!((~"Zm9vYmE=").from_base64() == str::to_bytes(~"fooba"));
        assert!((~"Zm9vYmFy").from_base64() == str::to_bytes(~"foobar"));
    }
}
<|endoftext|>


<commit_before><commit_msg>add missing `util` file<commit_after>use std::marker::PhantomData;

/// A little structure used to mark some type. This is often used when
/// we have some phantom type we wish to remember as part of a struct.
/// This doesn't represent "reachable data", and hence it is
/// considered sendable regardless of `T`, unlike `PhantomData`.
pub struct PhantomType<T> {
    data: PhantomData<T>
}

unsafe impl<T> Send for PhantomType<T> { }

unsafe impl<T> Sync for PhantomType<T> { }

impl<T> PhantomType<T> {
    pub fn new() -> PhantomType<T> {
        PhantomType { data: PhantomData }
    }
}
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #54812 - pnkfelix:issue-32382-index-assoc-type-with-lifetime, r=nikomatsakis<commit_after>#![feature(nll)]
// compile-pass

// rust-lang/rust#32382: Borrow checker used to complain about
// `foobar_3` in the `impl` below, presumably due to some interaction
// between the use of a lifetime in the associated type and the use of
// the overloaded operator[]. This regression test ensures that we do
// not resume complaining about it in the future.

use std::marker::PhantomData;
use std::ops::Index;

pub trait Context: Clone {
    type Container: ?Sized;
    fn foobar_1( container: &Self::Container ) -> &str;
    fn foobar_2( container: &Self::Container ) -> &str;
    fn foobar_3( container: &Self::Container ) -> &str;
}

#[derive(Clone)]
struct Foobar<'a> {
    phantom: PhantomData<&'a ()>
}

impl<'a> Context for Foobar<'a> {
    type Container = [&'a str];

    fn foobar_1<'r>( container: &'r [&'a str] ) -> &'r str {
        container[0]
    }

    fn foobar_2<'r>( container: &'r Self::Container ) -> &'r str {
        container.index( 0 )
    }

    fn foobar_3<'r>( container: &'r Self::Container ) -> &'r str {
        container[0]
    }
}

fn main() { }
<|endoftext|>


<commit_before><commit_msg>rust inline assembly lvi hardening test<commit_after>// Test LVI load hardening on SGX inline assembly code

// assembly-output: emit-asm
// compile-flags: --crate-type staticlib
// only-x86_64-fortanix-unknown-sgx

#![feature(asm)]

#[no_mangle]
pub extern fn get(ptr: *const u64) -> u64 {
    let value : u64;
    unsafe {
        asm!(".start_inline_asm:",
            "mov {}, [{}]",
            ".end_inline_asm:",
            out(reg) value,
            in(reg) ptr);
    }
    value
}

// CHECK: get
// CHECK: .start_inline_asm
// CHECK-NEXT: movq
// CHECK-NEXT: lfence
// CHECK-NEXT: .end_inline_asm

#[no_mangle]
pub extern fn myret() {
    unsafe {
        asm!(".start_myret_inline_asm:
            ret
            .end_myret_inline_asm:");
    }
}

// CHECK: myret
// CHECK: .start_myret_inline_asm
// CHECK-NEXT: shlq $0, (%rsp)
// CHECK-NEXT: lfence
// CHECK-NEXT: retq
<|endoftext|>


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

extern crate ser = "serialize";

use serialize = self::ser;
 //necessary for deriving(Encodable)
use ser::{Encodable, Encoder};
use ser::json;
use ser::ebml::writer;
use std::io::MemWriter;
use std::str::from_utf8_owned;

#[deriving(Encodable)]
struct Foo {
    baz: bool,
}

#[deriving(Encodable)]
struct Bar {
    froboz: uint,
}

enum WireProtocol {
    JSON,
    EBML,
    // ...
}

fn encode_json<'a,
               T: Encodable<json::Encoder<'a>,
                            std::io::IoError>>(val: &T,
                                               wr: &'a mut MemWriter) {
    let mut encoder = json::Encoder::new(wr);
    val.encode(&mut encoder);
}
fn encode_ebml<'a,
               T: Encodable<writer::Encoder<'a, MemWriter>,
                            std::io::IoError>>(val: &T,
                                               wr: &'a mut MemWriter) {
    let mut encoder = writer::Encoder(wr);
    val.encode(&mut encoder);
}

pub fn main() {
    let target = Foo{baz: false,};
    let mut wr = MemWriter::new();
    let proto = JSON;
    match proto {
        JSON => encode_json(&target, &mut wr),
        EBML => encode_ebml(&target, &mut wr)
    }
}
<|endoftext|>


<commit_before><commit_msg>Add regression test for #18075<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.

// exec-env:RUST_LOG=rustc::middle=debug

fn main() {
    let b = 1isize;
    println!("{}", b);
}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #29114 - apasel422:issue-27105, 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.

use std::cell::RefCell;
use std::rc::Rc;

pub struct Callbacks {
    callbacks: Vec<Rc<RefCell<FnMut(i32)>>>,
}

impl Callbacks {
    pub fn register<F: FnMut(i32)+'static>(&mut self, callback: F) {
        self.callbacks.push(Rc::new(RefCell::new(callback)));
    }
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Add comment block matching the type defines added by RS.<commit_after><|endoftext|>


<commit_before><commit_msg>Controls other than the mouse were jumping the camera orientation when disabling trajectory<commit_after><|endoftext|>


<commit_before><commit_msg>Remove use of deprecated to_option<commit_after><|endoftext|>


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

#[forbid(raw_pointer_derive)]
#[derive(Copy)]
struct Test(*const i32);

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #8982 - ehuss:fix-alt-target-tests, r=alexcrichton<commit_after><|endoftext|>


<commit_before><commit_msg>Add problem #108<commit_after>#[link(name = "prob0108", vers = "0.0")];
#[crate_type = "lib"];

extern mod math;
use std::iter;
use std::iter::MultiplicativeIterator;
use math::prime;

pub static EXPECTED_ANSWER: &'static str = "180180";

// 1/x + 1/y = 1/n
// a := x - n >= 0
// b := y - n >= 0
//
// 1/(n+a) + 1/(n+b) = 1/n
// n(n+b) + n(n+a) = (n+a)(n+b)
// 2n^2 + n(a+b) = n^2 + n(a+b) + ab
// n^2 = ab

fn num_pairs(n: uint) -> uint {
    (prime::factorize(n)
     .map(|(_base, exp)| 2 * (exp as uint) + 1)
     .product() - 1) / 2 + 1
}

pub fn solve() -> ~str {
    let n = 1000;
    iter::count(1u, 1).find(|&i| num_pairs(i) > n).unwrap().to_str()
}

#[cfg(test)]
mod test {
    #[test]
    fn test_num_pairs() {
        assert_eq!(super::num_pairs(4), 3);
    }
}
<|endoftext|>


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

use std::slice;
use std::ffi;

use htslib;

/// A BCF header.
pub struct Header {
    pub inner: *mut htslib::vcf::bcf_hdr_t,
}

impl Header {
    /// Create a new header.
    pub fn new() -> Self {
        Header { inner: unsafe { htslib::vcf::bcf_hdr_init(ffi::CString::new(&b"w"[..]).unwrap().as_ptr()) } }
    }

    pub fn with_template(header: &HeaderView) -> Self {
        Header { inner: unsafe { htslib::vcf::bcf_hdr_dup(header.inner) } }
    }

    pub fn push_sample(&mut self, sample: &[u8]) -> &mut Self {
        unsafe { htslib::vcf::bcf_hdr_add_sample(self.inner, ffi::CString::new(sample).unwrap().as_ptr()) };
        self
    }

    /// Add a record to the header.
    pub fn push_record(&mut self, record: &[u8]) -> &mut Self {
        unsafe { htslib::vcf::bcf_hdr_append(self.inner, ffi::CString::new(record).unwrap().as_ptr()) };
        self
    }
}

impl Drop for Header {
    fn drop(&mut self) {
        unsafe { htslib::vcf::bcf_hdr_destroy(self.inner) };
    }
}

pub struct HeaderView {
    pub inner: *mut htslib::vcf::bcf_hdr_t,
}

impl HeaderView {
    pub fn new(inner: *mut htslib::vcf::bcf_hdr_t) -> Self {
        HeaderView { inner: inner }
    }

    #[inline]
    fn inner(&self) -> htslib::vcf::bcf_hdr_t {
        unsafe { (*self.inner) }
    }

    pub fn sample_count(&self) -> u32 {
        self.inner().n[htslib::vcf::BCF_DT_SAMPLE as usize] as u32
    }

    pub fn samples(&self) -> Vec<&[u8]> {
        let names = unsafe { slice::from_raw_parts(self.inner().samples, self.sample_count() as usize) };
        names.iter().map(|name| unsafe { ffi::CStr::from_ptr(*name).to_bytes() }).collect()
    }
}
<|endoftext|>


<commit_before><commit_msg>Add some error handling exercises<commit_after><|endoftext|>


<commit_before><commit_msg>Fix wrong interpenetration resolution ratio<commit_after><|endoftext|>


<commit_before><commit_msg>Initial commit for find_package.rs<commit_after>use std::error::Error;
use std::fs::File;
use std::io::{BufReader, BufRead};
use std::path::Path;

macro_rules! custom_try {
    ($x:expr) => (match $x {
        Ok(x) => x,
        Err(why) => panic!("An error occured during package finding.", why),
    });
}

fn find_package(name: &str, list:&Path) -> Result<String, &str>
{
    let mut list = custom_try!(match File::open(list));
    let mut reader = BufReader::new(list);
    let mut buffer = String::new();

    //TODO: Use JSON.
}<|endoftext|>


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

use std::gc::Gc;
use syntax::{ast, ext};
use syntax::ext::build::AstBuilder;
use syntax::ext::deriving::generic;
use syntax::{attr, codemap};
use syntax::parse::token;

fn make_path_vec(cx: &mut ext::base::ExtCtxt, to: &str) -> Vec<ast::Ident> {
    vec![cx.ident_of("gfx"), cx.ident_of("attrib"), cx.ident_of(to)]
}

fn make_path_expr(cx: &mut ext::base::ExtCtxt, span: codemap::Span, to: &str) -> Gc<ast::Expr> {
    let vec = make_path_vec(cx, to);
    cx.expr_path(cx.path(span, vec))
}

#[deriving(PartialEq, Show)]
enum Modifier {
    ModNone,
    ModNormalized,
    ModAsFloat,
    ModAsDouble,
}

/// Scan through the field's attributes and extract a relevant modifier
fn find_modifier(cx: &mut ext::base::ExtCtxt, span: codemap::Span,
                 attributes: &[ast::Attribute]) -> Modifier {
    attributes.iter().fold(ModNone, |md, at| {
        match at.node.value.node {
            ast::MetaWord(ref s) => {
                let new_md = match s.get() {
                    "normalized" => ModNormalized,
                    "as_float"   => ModAsFloat,
                    "as_double"  => ModAsDouble,
                    _ => ModNone,
                };
                if new_md != ModNone {
                    attr::mark_used(at);
                    if md != ModNone {
                        cx.span_warn(span, format!(
                            "Extra attribute modifier detected: {}",
                            s.get()).as_slice()
                        );
                    }
                    new_md
                }else {
                    md
                }
            },
            _ => md,
        }
    })
}

/// Find a gfx::attrib::Type that describes a given type
fn decode_type(cx: &mut ext::base::ExtCtxt, span: codemap::Span,
               stype: &str, modifier: Modifier) -> Gc<ast::Expr> {
    let c0 = stype.char_at(0);
    let (type_vec, params) = match c0 {
        'f' => {
            let kind = match modifier {
                ModNone | ModAsFloat => "FloatDefault",
                ModAsDouble => "FloatPrecision",
                _ => {
                    cx.span_warn(span, format!(
                        "Incompatible float modifier: {}",
                        modifier).as_slice()
                        );
                    ""
                }
            };
            let sub_type = format!("F{}", stype.slice_from(1));
            (make_path_vec(cx, "Float"), vec![
                make_path_expr(cx, span, kind),
                make_path_expr(cx, span, sub_type.as_slice())
            ])
        },
        'u' | 'i' => {
            let sign = if c0=='i' {"Signed"} else {"Unsigned"};
            let kind = match modifier {
                ModNone => "IntRaw",
                ModNormalized => "IntNormalized",
                ModAsFloat => "IntAsFloat",
                _ => {
                    cx.span_warn(span, format!(
                        "Incompatible int modifier: {}",
                        modifier).as_slice()
                        );
                    ""
                }
            };
            let sub_type = format!("U{}", stype.slice_from(1));
            (make_path_vec(cx, "Int"), vec![
                make_path_expr(cx, span, kind),
                make_path_expr(cx, span, sub_type.as_slice()),
                make_path_expr(cx, span, sign)
            ])
        },
        _ => {
            cx.span_err(span, format!(
                "Unrecognized element type: {}",
                stype).as_slice()
                );
            (Vec::new(), Vec::new())
        },
    };
    cx.expr_call_global(span, type_vec, params)
}

fn decode_count_and_type(cx: &mut ext::base::ExtCtxt, span: codemap::Span,
                         field: &ast::StructField) -> (Gc<ast::Expr>, Gc<ast::Expr>) {
    let modifier = find_modifier(cx, span, field.node.attrs.as_slice());
    match field.node.ty.node {
        ast::TyPath(ref p, _, _) => (
            cx.expr_lit(span, ast::LitIntUnsuffixed(1)),
            decode_type(cx, span,
                p.segments[0].identifier.name.as_str(),
                modifier)
        ),
        ast::TyFixedLengthVec(pty, expr) => (expr, match pty.node {
            ast::TyPath(ref p, _, _) => decode_type(cx, span,
                p.segments[0].identifier.name.as_str(),
                modifier),
            _ => {
                cx.span_err(span, format!(
                    "Unsupported fixed vector sub-type: {}",
                    pty.node).as_slice()
                );
                cx.expr_lit(span, ast::LitNil)
            },
        }),
        _ => {
            cx.span_err(span, format!(
                    "Unsupported attribute type: {}",
                    field.node.ty.node
                ).as_slice()
            );
            (cx.expr_lit(span, ast::LitNil), cx.expr_lit(span, ast::LitNil))
        },
    }
}

/// Encode the following expression:
/// `unsafe { &(*(0u as *const $id_struct)).$id_field as *const _ as uint }`
fn make_offset_expr(cx: &mut ext::base::ExtCtxt, span: codemap::Span,
                    id_struct: ast::Ident, id_field: ast::Ident) -> Gc<ast::Expr> {
    let ex = cx.expr_cast(span,
        cx.expr_uint(span, 0),
        cx.ty(span, ast::TyPtr(ast::MutTy {
            ty: cx.ty_ident(span, id_struct),
            mutbl: ast::MutImmutable,
        }))
    );
    let ex = cx.expr(span, ast::ExprParen(
        cx.expr_deref(span, ex)
    ));
    let ex = cx.expr_addr_of(span,
        cx.expr_field_access(span, ex, id_field)
    );
    let ex = cx.expr_cast(span, ex,
        cx.ty(span, ast::TyPtr(ast::MutTy {
            ty: cx.ty_infer(span),
            mutbl: ast::MutImmutable
        }))
    );
    let offset = make_path_vec(cx, "Offset");
    let ex = cx.expr_cast(span, ex,
        cx.ty_path(cx.path(span, offset), None)
    );
    cx.expr_block(ast::P(ast::Block {
        view_items: Vec::new(),
        stmts: Vec::new(),
        expr: Some(ex),
        id: ast::DUMMY_NODE_ID,
        rules: ast::UnsafeBlock(ast::UserProvided),
        span: span,
    }))
}

/// `generate()` method generating code
fn method_generate(cx: &mut ext::base::ExtCtxt, span: codemap::Span,
                   substr: &generic::Substructure) -> Gc<ast::Expr> {
    match *substr.fields {
        generic::StaticStruct(ref definition, generic::Named(ref fields)) => {
            let mut statements = Vec::new();
            let id_at = cx.ident_of("at");
            let ex_new = cx.expr_call(span, cx.expr_path(cx.path(span,
                    vec![cx.ident_of("Vec"), cx.ident_of("with_capacity")]
                )), vec![cx.expr_uint(span, fields.len())]
            );
            statements.push(cx.stmt_let(span, true, id_at, ex_new));
            let path_stride = make_path_vec(cx, "Stride");
            let ex_stride = cx.expr_cast(span,
                cx.expr_call(span,
                    cx.expr_path(cx.path_all(
                        span,
                        true,
                        vec![
                            cx.ident_of("std"),
                            cx.ident_of("mem"),
                            cx.ident_of("size_of")
                        ],
                        Vec::new(),
                        vec![cx.ty_ident(span, substr.type_ident)]
                    )),
                    Vec::new()
                ),
                cx.ty_path(cx.path_global(span, path_stride), None)
            );
            for (def, &(ident, _)) in definition.fields.iter().zip(fields.iter()) {
                let (ex_count, ex_type) = decode_count_and_type(cx, span, def);
                let ex_offset = make_offset_expr(cx, span, substr.type_ident, ident);
                let ex_struct = cx.expr_struct(span,
                    cx.path(span, vec![
                        cx.ident_of("gfx"),
                        cx.ident_of("Attribute")
                        ]),
                    vec![
                        cx.field_imm(span, cx.ident_of("buffer"), substr.nonself_args[1]),
                        cx.field_imm(span, cx.ident_of("elem_count"), ex_count),
                        cx.field_imm(span, cx.ident_of("elem_type"), ex_type),
                        cx.field_imm(span, cx.ident_of("offset"), ex_offset),
                        cx.field_imm(span, cx.ident_of("stride"), ex_stride),
                        cx.field_imm(span, cx.ident_of("name"), cx.expr_method_call(span,
                            cx.expr_str(span, token::get_ident(ident)),
                            cx.ident_of("to_string"), Vec::new()))
                    ]
                );
                statements.push(cx.stmt_expr(cx.expr_method_call(
                    span,
                    cx.expr_ident(span, id_at),
                    cx.ident_of("push"),
                    vec![ex_struct]
                    )));
            }
            cx.expr_block(cx.block_all(
                span,
                Vec::new(),
                statements,
                Some(cx.expr_ident(span, id_at))
                ))
        },
        _ => {
            cx.span_err(span, "Unable to implement `generate()` on a non-structure");
            cx.expr_lit(span, ast::LitNil)
        }
    }
}

/// Decorator for `vertex_format` attribute
pub fn expand_vertex_format(context: &mut ext::base::ExtCtxt, span: codemap::Span,
                            meta_item: Gc<ast::MetaItem>, item: Gc<ast::Item>,
                            push: |Gc<ast::Item>|) {
    let trait_def = generic::TraitDef {
        span: span,
        attributes: Vec::new(),
        path: generic::ty::Path {
            path: vec!["gfx", "VertexFormat"],
            lifetime: None,
            params: Vec::new(),
            global: true,
        },
        additional_bounds: Vec::new(),
        generics: generic::ty::LifetimeBounds::empty(),
        methods: vec![
            generic::MethodDef {
                name: "generate",
                generics: generic::ty::LifetimeBounds::empty(),
                explicit_self: None,
                args: vec![
                    generic::ty::Literal(generic::ty::Path {
                        path: vec!["Option"],
                        lifetime: None,
                        params: vec![box generic::ty::Self],
                        global: false,
                    }),
                    generic::ty::Literal(generic::ty::Path::new(
                        vec!["gfx", "BufferHandle"]
                    )),
                ],
                ret_ty: generic::ty::Literal(
                    generic::ty::Path {
                        path: vec!["Vec"],
                        lifetime: None,
                        params: vec![
                            box generic::ty::Literal(generic::ty::Path::new(
                                vec!["gfx", "Attribute"])),
                        ],
                        global: false,
                    },
                ),
                attributes: Vec::new(),
                combine_substructure: generic::combine_substructure(method_generate),
            },
        ],
    };
    trait_def.expand(context, meta_item, item, push);
}
<commit_msg>Clean up code in gfx_macro::mesh and make gfx_macro::mesh::decode_type more robust.<commit_after>// Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::fmt;
use std::from_str::FromStr;
use std::gc::Gc;
use syntax::{ast, ext};
use syntax::ext::build::AstBuilder;
use syntax::ext::deriving::generic;
use syntax::{attr, codemap};
use syntax::parse::token;

fn make_path_vec(cx: &mut ext::base::ExtCtxt, to: &str) -> Vec<ast::Ident> {
    vec![cx.ident_of("gfx"), cx.ident_of("attrib"), cx.ident_of(to)]
}

fn make_path_expr(cx: &mut ext::base::ExtCtxt, span: codemap::Span, to: &str) -> Gc<ast::Expr> {
    let vec = make_path_vec(cx, to);
    cx.expr_path(cx.path(span, vec))
}

#[deriving(PartialEq)]
enum Modifier {
    Normalized,
    AsFloat,
    AsDouble,
}

impl fmt::Show for Modifier {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Normalized => write!(f, "normalized"),
            AsFloat => write!(f, "as_float"),
            AsDouble => write!(f, "as_double"),
        }
    }
}

impl FromStr for Modifier {
    fn from_str(src: &str) -> Option<Modifier> {
        match src {
            "normalized" => Some(Normalized),
            "as_float" => Some(AsFloat),
            "as_double" => Some(AsDouble),
            _ => None,
        }
    }
}

/// Scan through the field's attributes and extract a relevant modifier
fn find_modifier(cx: &mut ext::base::ExtCtxt, span: codemap::Span,
                 attributes: &[ast::Attribute]) -> Option<Modifier> {
    attributes.iter().fold(None, |modifier, attribute| {
        match attribute.node.value.node {
            ast::MetaWord(ref word) => {
                from_str(word.get()).and_then(|new_modifier| {
                    attr::mark_used(attribute);
                    modifier.map_or(Some(new_modifier), |modifier| {
                        cx.span_warn(span, format!(
                            "Extra attribute modifier detected: `#[{}]` - \
                            ignoring in favour of `#[{}]`.", new_modifier, modifier
                        ).as_slice());
                        None
                    })
                }).or(modifier)
            },
            _ => modifier,
        }
    })
}

/// Find a gfx::attrib::Type that describes a given type
fn decode_type(cx: &mut ext::base::ExtCtxt, span: codemap::Span,
               ty_ident: &ast::Ident, modifier: Option<Modifier>) -> Gc<ast::Expr> {
    let ty_str = ty_ident.name.as_str();
    let (type_vec, params) = match ty_str {
        "f32" | "f64" => {
            let kind = match modifier {
                None | Some(AsFloat) => "FloatDefault",
                Some(AsDouble) => "FloatPrecision",
                Some(Normalized) => {
                    cx.span_warn(span, format!(
                        "Incompatible float modifier attribute: `#[{}]`", modifier
                    ).as_slice());
                    ""
                }
            };
            let sub_type = format!("F{}", ty_str.slice_from(1));
            (make_path_vec(cx, "Float"), vec![
                make_path_expr(cx, span, kind),
                make_path_expr(cx, span, sub_type.as_slice())
            ])
        },
        "u8" | "u16" | "u32" | "u64" | "uint" |
        "i8" | "i16" | "i32" | "i64" | "int" => {
            let sign = if ty_str.starts_with("i") { "Signed" } else { "Unsigned" };
            let kind = match modifier {
                None => "IntRaw",
                Some(Normalized) => "IntNormalized",
                Some(AsFloat) => "IntAsFloat",
                Some(AsDouble) => {
                    cx.span_warn(span, format!(
                        "Incompatible int modifier attribute: `#[{}]`", modifier
                    ).as_slice());
                    ""
                }
            };
            let sub_type = format!("U{}", ty_str.slice_from(1));
            (make_path_vec(cx, "Int"), vec![
                make_path_expr(cx, span, kind),
                make_path_expr(cx, span, sub_type.as_slice()),
                make_path_expr(cx, span, sign)
            ])
        },
        ty_str => {
            cx.span_err(span, format!("Unrecognized component type: `{}`", ty_str).as_slice());
            (Vec::new(), Vec::new())
        },
    };
    cx.expr_call_global(span, type_vec, params)
}

fn decode_count_and_type(cx: &mut ext::base::ExtCtxt, span: codemap::Span,
                         field: &ast::StructField) -> (Gc<ast::Expr>, Gc<ast::Expr>) {
    let modifier = find_modifier(cx, span, field.node.attrs.as_slice());
    match field.node.ty.node {
        ast::TyPath(ref p, _, _) => (
            cx.expr_lit(span, ast::LitIntUnsuffixed(1)),
            decode_type(cx, span, &p.segments[0].identifier, modifier),
        ),
        ast::TyFixedLengthVec(pty, expr) => (expr, match pty.node {
            ast::TyPath(ref p, _, _) => {
                decode_type(cx, span, &p.segments[0].identifier, modifier)
            },
            _ => {
                cx.span_err(span, format!(
                    "Unsupported fixed vector sub-type: `{}`",
                    pty.node).as_slice()
                );
                cx.expr_lit(span, ast::LitNil)
            },
        }),
        _ => {
            cx.span_err(span, format!(
                    "Unsupported attribute type: `{}`",
                    field.node.ty.node
                ).as_slice()
            );
            (cx.expr_lit(span, ast::LitNil), cx.expr_lit(span, ast::LitNil))
        },
    }
}

/// Encode the following expression:
/// `unsafe { &(*(0u as *const $id_struct)).$id_field as *const _ as uint }`
fn make_offset_expr(cx: &mut ext::base::ExtCtxt, span: codemap::Span,
                    id_struct: ast::Ident, id_field: ast::Ident) -> Gc<ast::Expr> {
    let ex = cx.expr_cast(span,
        cx.expr_uint(span, 0),
        cx.ty(span, ast::TyPtr(ast::MutTy {
            ty: cx.ty_ident(span, id_struct),
            mutbl: ast::MutImmutable,
        }))
    );
    let ex = cx.expr(span, ast::ExprParen(
        cx.expr_deref(span, ex)
    ));
    let ex = cx.expr_addr_of(span,
        cx.expr_field_access(span, ex, id_field)
    );
    let ex = cx.expr_cast(span, ex,
        cx.ty(span, ast::TyPtr(ast::MutTy {
            ty: cx.ty_infer(span),
            mutbl: ast::MutImmutable
        }))
    );
    let offset = make_path_vec(cx, "Offset");
    let ex = cx.expr_cast(span, ex,
        cx.ty_path(cx.path(span, offset), None)
    );
    cx.expr_block(ast::P(ast::Block {
        view_items: Vec::new(),
        stmts: Vec::new(),
        expr: Some(ex),
        id: ast::DUMMY_NODE_ID,
        rules: ast::UnsafeBlock(ast::UserProvided),
        span: span,
    }))
}

/// `generate()` method generating code
fn method_generate(cx: &mut ext::base::ExtCtxt, span: codemap::Span,
                   substr: &generic::Substructure) -> Gc<ast::Expr> {
    match *substr.fields {
        generic::StaticStruct(ref definition, generic::Named(ref fields)) => {
            let mut statements = Vec::new();
            let id_at = cx.ident_of("at");
            let ex_new = cx.expr_call(span, cx.expr_path(cx.path(span,
                    vec![cx.ident_of("Vec"), cx.ident_of("with_capacity")]
                )), vec![cx.expr_uint(span, fields.len())]
            );
            statements.push(cx.stmt_let(span, true, id_at, ex_new));
            let path_stride = make_path_vec(cx, "Stride");
            let ex_stride = cx.expr_cast(span,
                cx.expr_call(span,
                    cx.expr_path(cx.path_all(
                        span,
                        true,
                        vec![
                            cx.ident_of("std"),
                            cx.ident_of("mem"),
                            cx.ident_of("size_of")
                        ],
                        Vec::new(),
                        vec![cx.ty_ident(span, substr.type_ident)]
                    )),
                    Vec::new()
                ),
                cx.ty_path(cx.path_global(span, path_stride), None)
            );
            for (def, &(ident, _)) in definition.fields.iter().zip(fields.iter()) {
                let (ex_count, ex_type) = decode_count_and_type(cx, span, def);
                let ex_offset = make_offset_expr(cx, span, substr.type_ident, ident);
                let ex_struct = cx.expr_struct(span,
                    cx.path(span, vec![
                        cx.ident_of("gfx"),
                        cx.ident_of("Attribute")
                        ]),
                    vec![
                        cx.field_imm(span, cx.ident_of("buffer"), substr.nonself_args[1]),
                        cx.field_imm(span, cx.ident_of("elem_count"), ex_count),
                        cx.field_imm(span, cx.ident_of("elem_type"), ex_type),
                        cx.field_imm(span, cx.ident_of("offset"), ex_offset),
                        cx.field_imm(span, cx.ident_of("stride"), ex_stride),
                        cx.field_imm(span, cx.ident_of("name"), cx.expr_method_call(span,
                            cx.expr_str(span, token::get_ident(ident)),
                            cx.ident_of("to_string"), Vec::new()))
                    ]
                );
                statements.push(cx.stmt_expr(cx.expr_method_call(
                    span,
                    cx.expr_ident(span, id_at),
                    cx.ident_of("push"),
                    vec![ex_struct]
                    )));
            }
            cx.expr_block(cx.block_all(
                span,
                Vec::new(),
                statements,
                Some(cx.expr_ident(span, id_at))
                ))
        },
        _ => {
            cx.span_err(span, "Unable to implement `generate()` on a non-structure");
            cx.expr_lit(span, ast::LitNil)
        }
    }
}

/// Decorator for `vertex_format` attribute
pub fn expand_vertex_format(context: &mut ext::base::ExtCtxt, span: codemap::Span,
                            meta_item: Gc<ast::MetaItem>, item: Gc<ast::Item>,
                            push: |Gc<ast::Item>|) {
    let trait_def = generic::TraitDef {
        span: span,
        attributes: Vec::new(),
        path: generic::ty::Path {
            path: vec!["gfx", "VertexFormat"],
            lifetime: None,
            params: Vec::new(),
            global: true,
        },
        additional_bounds: Vec::new(),
        generics: generic::ty::LifetimeBounds::empty(),
        methods: vec![
            generic::MethodDef {
                name: "generate",
                generics: generic::ty::LifetimeBounds::empty(),
                explicit_self: None,
                args: vec![
                    generic::ty::Literal(generic::ty::Path {
                        path: vec!["Option"],
                        lifetime: None,
                        params: vec![box generic::ty::Self],
                        global: false,
                    }),
                    generic::ty::Literal(generic::ty::Path::new(
                        vec!["gfx", "BufferHandle"]
                    )),
                ],
                ret_ty: generic::ty::Literal(
                    generic::ty::Path {
                        path: vec!["Vec"],
                        lifetime: None,
                        params: vec![
                            box generic::ty::Literal(generic::ty::Path::new(
                                vec!["gfx", "Attribute"])),
                        ],
                        global: false,
                    },
                ),
                attributes: Vec::new(),
                combine_substructure: generic::combine_substructure(method_generate),
            },
        ],
    };
    trait_def.expand(context, meta_item, item, push);
}
<|endoftext|>


<commit_before><commit_msg>Test for melted ICE #4121<commit_after>use std::mem;

pub struct Foo<A, B>(A, B);

impl<A, B> Foo<A, B> {
    const HOST_SIZE: usize = mem::size_of::<B>();

    pub fn crash() -> bool {
        Self::HOST_SIZE == 0
    }
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>languages/rust/rust-book/3-chapter/25-code/multiple_phrases/src/english/farewells.rs<commit_after><|endoftext|>


<commit_before><commit_msg>test(vm): Add a test to check that marshalled references cannot escape<commit_after>extern crate embed_lang;
use embed_lang::new_vm;
use embed_lang::vm::vm::Value;
use embed_lang::vm::api::{VMType, Getable};
use embed_lang::vm::gc::Traverseable;

use std::cell::Cell;

struct Test<'vm>(Cell<&'vm str>);

impl<'vm> Traverseable for Test<'vm> { }
impl<'vm> VMType for Test<'vm> {
    type Type = Test<'static>;
}

fn f<'vm>(test: &'vm Test<'vm>, s: &'vm str) {
    test.0.set(s);
}

fn main() {
    let vm = new_vm();
    vm.define_global("f", f as fn (_, _));
    //~^ Error `vm` does not live long enough
}
<|endoftext|>


<commit_before><commit_msg>rs: DNA to RNA Conversion (8 kyu)<commit_after><|endoftext|>


<commit_before><commit_msg>Fix bug in bounds calculation logic.<commit_after><|endoftext|>


<commit_before><commit_msg>Advent cleanups<commit_after><|endoftext|>


<commit_before><commit_msg>Add initial benchmark to execute 100k cycles<commit_after>#![feature(test)]

extern crate test;
extern crate r68k_emu;
use test::Bencher;

use r68k_emu::cpu::{Core, ProcessingState, Result, Cycles, Exception, Callbacks};
use r68k_emu::cpu::ops::handlers;

struct LogAllExceptions {
    count: isize
}
impl Callbacks for LogAllExceptions {
    fn exception_callback(&mut self, _: &mut Core, ex: Exception) -> Result<Cycles> {
        println!("{:?}", ex);
        self.count += 1;
        Err(ex)
    }
}

#[bench]
fn bench_100k_cycles(b: &mut Bencher) {
    let mut cpu = Core::new_auto();
    let regregops = [handlers::OP_ADD_16_ER_DN, handlers::OP_SUB_16_ER_DN, handlers::OP_AND_16_ER_DN, handlers::OP_OR_16_ER_DN];
    let pc_base = 0x1000;
    // write an instruction sequence of simple reg-to-reg operations
    for i in 0..0x10000 {
        cpu.write_program_word(pc_base + i*2, regregops[(i % regregops.len() as u32) as usize]).unwrap();
    }
    cpu.write_program_long(0, 0x100000).unwrap(); // SSP
    cpu.write_program_long(4, pc_base).unwrap(); // PC

    let generic_handler = 0x900;
    for exception in 2..256 {
        cpu.write_data_long(exception * 4, generic_handler).unwrap(); // set up exception vector
    }
    cpu.write_data_word(generic_handler, handlers::OP_RTE_32).unwrap(); // handler is just RTE
    let cycles_per_instruction = 4;
    let num_instructions = 25_000;
    let bytes_per_instruction = 2;
    let mut handler = LogAllExceptions { count: 0 };
    cpu.reset();
    assert_eq!(pc_base, cpu.pc);
    b.iter(|| {
        cpu.pc = pc_base;
        cpu.execute_with_state(num_instructions * cycles_per_instruction, &mut handler);
    });
    assert_eq!(0, handler.count);
    assert_eq!(ProcessingState::Normal, cpu.processing_state);
    assert_eq!(pc_base + (num_instructions * bytes_per_instruction) as u32, cpu.pc);
}<|endoftext|>


<commit_before><commit_msg>Move server to subfolder to accomodate submodules<commit_after>//! The server-side implementation of `multipart/form-data` requests.
//!
//! Use this when you are implementing a server on top of Hyper and want to
//! to parse and serve POST `multipart/form-data` requests.
//!
//! See the `Multipart` struct for more info.

use hyper::header::common::content_type::ContentType;
use hyper::server::request::Request;

use mime::{Mime, TopLevel, SubLevel, Attr, Value};

use super::{MultipartField, MultipartFile};

use std::cmp;

use std::collections::HashMap;

use std::io::{IoError, IoResult, EndOfFile, standard_error, OtherIoError};

pub use self::handler::*;

mod handler;

fn is_multipart_formdata(req: &Request) -> bool {
    use mime::{Multipart};

    req.headers.get::<ContentType>().map_or(false, |ct| {
        let ContentType(ref mime) = *ct;

        debug!("Content-Type: {}", mime);

        match *mime {
            Mime(TopLevel::Multipart, SubLevel::FormData, _) => true,
            _ => false,
        }
    })
}

fn get_boundary(ct: &ContentType) -> Option<String> {
    let ContentType(ref mime) = *ct;
    let Mime(_, _, ref params) = *mime;

    params.iter().find(|&&(ref name, _)|
        if let Attr::Ext(ref name) = *name {
            name[] == "boundary"
        } else { false }
    ).and_then(|&(_, ref val)|
        if let Value::Ext(ref val) = *val {
            Some(val.clone())
        } else { None }
    )
}

/// A server-side `multipart/form-data` requests.
///
/// Create this with `Multipart::from_request()` passing a `server::Request` object from Hyper,
/// then read individual entries with `.read_entry()` or process them all at once with
/// `.foreach_entry()`.
pub struct Multipart<'a> {
    source: BoundaryReader<Request<'a>>,
    tmp_dir: String,
}

macro_rules! try_find(
    ($haystack:expr, $f:ident, $needle:expr, $err:expr, $line:expr) => (
        try!($haystack.$f($needle).ok_or(line_error($err, $line.clone())))
    )
)

impl<'a> Multipart<'a> {

    /// If the given `Request` is of `Content-Type: multipart/form-data`, return
    /// the wrapped request as `Ok(Multipart)`, otherwise `Err(Request)`.
    pub fn from_request(req: Request<'a>) -> Result<Multipart<'a>, Request<'a>> {
        if !is_multipart_formdata(&req) { return Err(req); }

        let boundary = if let Some(boundary) = req.headers.get::<ContentType>()
            .and_then(get_boundary) { boundary } else { return Err(req); };

        debug!("Boundary: {}", boundary);

        Ok(Multipart { source: BoundaryReader::from_reader(req, format!("--{}\r\n", boundary)), tmp_dir: ::random_alphanumeric(10) })
    }

    /// Read an entry from this multipart request, returning a pair with the field's name and
    /// contents. This will return an End of File error if there are no more entries.
    ///
    /// To get to the data, you will need to match on `MultipartField`:
    ///
    /// ```rust
    /// fn process_request(req: &mut Request, res: &mut Response) -> HttpResult<()> {
    ///
    /// }
    /// ```
    ///
    /// ##Warning
    /// If the last returned entry had contents of type `MultipartField::File`,
    /// calling this again will discard any unread contents of that entry!
    pub fn read_entry(&'a mut self) -> IoResult<(String, MultipartField<'a>)> {
        try!(self.source.consume_boundary());
        let (disp_type, field_name, filename) = try!(self.read_content_disposition());

        if &*disp_type != "form-data" {
            return Err(IoError {
                    kind: OtherIoError,
                    desc: "Content-Disposition value was not \"form-data\"",
                    detail: Some(format!("Content-Disposition: {}", disp_type)),
                });
        }

        if let Some(content_type) = try!(self.read_content_type()) {
            let _ = try!(self.source.read_line()); // Consume empty line
            Ok((field_name,
                MultipartField::File(
                    MultipartFile::from_octet(filename, &mut self.source, content_type[], self.tmp_dir[])
                )
            ))
        } else {
            // Empty line consumed by read_content_type()
            let text = try!(self.source.read_to_string());
            // The last two characters are "\r\n".
            // We can't do a simple trim because the content might be terminated
            // with line separators we want to preserve.
            Ok((field_name, MultipartField::Text(text[..text.len() - 2].into_string())))
        }
    }

    /// Call `f` for each entry in the multipart request.
    /// This is a substitute for `Multipart` implementing `Iterator`,
    /// since `Iterator::next()` can't use bound lifetimes.
    ///
    /// See https://www.reddit.com/r/rust/comments/2lkk4i/concrete_lifetime_vs_bound_lifetime/
    pub fn foreach_entry<F: for<'a> FnMut(String, MultipartField<'a>)>(&mut self, mut f: F) {
        loop {
            match self.read_entry() {
                Ok((name, field)) => f(name, field),
                Err(err) => {
                    if err.kind != EndOfFile {
                        error!("Error reading Multipart: {}", err);
                    }

                    break;
                },
            }
        }
    }

    fn read_content_disposition(&mut self) -> IoResult<(String, String, Option<String>)> {
        let line = try!(self.source.read_line());

        // Find the end of CONT_DISP in the line
        let disp_type = {
            const CONT_DISP: &'static str = "Content-Disposition:";

            let disp_idx = try_find!(line[], find_str, CONT_DISP,
                "Content-Disposition subheader not found!", line) + CONT_DISP.len();

            let disp_type_end = try_find!(line[disp_idx..], find, ';',
                "Error parsing Content-Disposition value!", line);

            line[disp_idx .. disp_idx + disp_type_end].trim().into_string()
        };

        let field_name = {
            const NAME: &'static str = "name=\"";

            let name_idx = try_find!(line[], find_str, NAME,
                "Error parsing field name!", line) + NAME.len();

            let name_end = try_find!(line[name_idx ..], find, '"',
                "Error parsing field name!", line);

            line[name_idx .. name_idx + name_end].into_string() // No trim here since it's in quotes.
        };

        let filename = {
            const FILENAME: &'static str = "filename=\"";

            let filename_idx = line[].find_str(FILENAME).map(|idx| idx + FILENAME.len());
            let filename_idxs = with(filename_idx, |&start| line[start ..].find('"'));

            filename_idxs.map(|(start, end)| line[start .. start + end].into_string())
        };

        Ok((disp_type, field_name, filename))
    }

    fn read_content_type(&mut self) -> IoResult<Option<String>> {
        debug!("Read content type!");
        let line = try!(self.source.read_line());

        const CONTENT_TYPE: &'static str = "Content-Type:";

        let type_idx = (&*line).find_str(CONTENT_TYPE);

        // FIXME Will not properly parse for multiple files!
        // Does not expect boundary=<boundary>
        Ok(type_idx.map(|start| line[start + CONTENT_TYPE.len()..].trim().into_string()))
    }

    /// Read the request fully, parsing all fields and saving all files to the given directory or a
    /// temporary, and return the result.
    ///
    /// If `dir` is none, chooses a random subdirectory under `std::os::tmpdir()`.
    pub fn save_all(mut self, dir: Option<&Path>) -> IoResult<Entries> {
        let dir = dir.map_or_else(|| ::std::os::tmpdir().join(self.tmp_dir[]), |path| path.clone());

        let mut entries = Entries::with_path(dir);

        loop {
            match self.read_entry() {
                Ok((name, MultipartField::Text(text))) => { entries.fields.insert(name, text); },
                Ok((name, MultipartField::File(mut file))) => {
                    let path = try!(file.save_in(&entries.dir));
                    entries.files.insert(name, path);
                },
                Err(err) => {
                    if err.kind != EndOfFile {
                        error!("Error reading Multipart: {}", err);
                    }

                    break;
                },
            }
        }

        Ok(entries)
    }
}

fn with<T, U>(left: Option<T>, right: |&T| -> Option<U>) -> Option<(T, U)> {
    let temp = left.as_ref().and_then(right);
    match (left, temp) {
        (Some(lval), Some(rval)) => Some((lval, rval)),
        _ => None,
    }
}

fn line_error(msg: &'static str, line: String) -> IoError {
    IoError {
        kind: OtherIoError,
        desc: msg,
        detail: Some(line),
    }
}

/// A result of `Multipart::save_all()`.
pub struct Entries {
    pub fields: HashMap<String, String>,
    pub files: HashMap<String, Path>,
    /// The directory the files were saved under.
    pub dir: Path,
}

impl Entries {
    fn with_path(path: Path) -> Entries {
        Entries {
            fields: HashMap::new(),
            files: HashMap::new(),
            dir: path,
        }
    }
}

/* FIXME: Can't have an iterator return a borrowed reference
impl<'a> Iterator<(String, MultipartField<'a>)> for Multipart<'a> {
    fn next(&mut self) -> Option<(String, MultipartField<'a>)> {
        match self.read_entry() {
            Ok(ok) => Some(ok),
            Err(err) => {
                if err.kind != EndOfFile {
                    error!("Error reading Multipart: {}", err);
                }

                None
             },
        }
    }
}
*/

/// A `Reader` that will yield bytes until it sees a given sequence.
pub struct BoundaryReader<S> {
    reader: S,
    boundary: Vec<u8>,
    last_search_idx: uint,
    boundary_read: bool,
    buf: Vec<u8>,
    buf_len: uint,
}

fn eof<T>() -> IoResult<T> {
    Err(standard_error(EndOfFile))
}

const BUF_SIZE: uint = 1024 * 64; // 64k buffer

impl<S> BoundaryReader<S> where S: Reader {
    fn from_reader(reader: S, boundary: String) -> BoundaryReader<S> {
        let mut buf = Vec::with_capacity(BUF_SIZE);
        unsafe { buf.set_len(BUF_SIZE); }

        BoundaryReader {
            reader: reader,
            boundary: boundary.into_bytes(),
            last_search_idx: 0,
            boundary_read: false,
            buf: buf,
            buf_len: 0,
        }
    }

    fn read_to_boundary(&mut self) -> IoResult<()> {
         if !self.boundary_read {
            try!(self.true_fill_buf());

            if self.buf_len == 0 { return eof(); }

            let lookahead = self.buf[self.last_search_idx .. self.buf_len];

            let search_idx = lookahead.position_elem(&self.boundary[0])
                .unwrap_or(lookahead.len() - 1);

            debug!("Search idx: {}", search_idx);

            self.boundary_read = lookahead[search_idx..]
                .starts_with(self.boundary[]);

            self.last_search_idx += search_idx;

            if !self.boundary_read {
                self.last_search_idx += 1;
            }

        } else if self.last_search_idx == 0 {
            return Err(standard_error(EndOfFile))
        }

        Ok(())
    }

    /// Read bytes until the reader is full
    fn true_fill_buf(&mut self) -> IoResult<()> {
        let mut bytes_read = 1u;

        while bytes_read != 0 {
            bytes_read = match self.reader.read(self.buf[mut self.buf_len..]) {
                Ok(read) => read,
                Err(err) => if err.kind == EndOfFile { break; } else { return Err(err); },
            };

            self.buf_len += bytes_read;
        }

        Ok(())
    }

    fn _consume(&mut self, amt: uint) {
        use std::ptr::copy_memory;

        assert!(amt <= self.buf_len);

        let src = self.buf[amt..].as_ptr();
        let dest = self.buf[mut].as_mut_ptr();

        unsafe { copy_memory(dest, src, self.buf_len - amt); }

        self.buf_len -= amt;
        self.last_search_idx -= amt;
    }

    fn consume_boundary(&mut self) -> IoResult<()> {
        while !self.boundary_read {
            match self.read_to_boundary() {
                Ok(_) => (),
                Err(e) => if e.kind == EndOfFile {
                    break;
                } else {
                    return Err(e);
                }
            }
        }

        let consume_amt = cmp::min(self.buf_len, self.last_search_idx + self.boundary.len());

        debug!("Consume amt: {} Buf len: {}", consume_amt, self.buf_len);

        self._consume(consume_amt);
        self.last_search_idx = 0;
        self.boundary_read = false;

        Ok(())
    }

    #[allow(unused)]
    fn set_boundary(&mut self, boundary: String) {
        self.boundary = boundary.into_bytes();
    }
}

impl<S> Reader for BoundaryReader<S> where S: Reader {
    fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
        use std::cmp;
        use std::slice::bytes::copy_memory;

        try!(self.read_to_boundary());

        let trunc_len = cmp::min(buf.len(), self.last_search_idx);
        copy_memory(buf, self.buf[..trunc_len]);

        self._consume(trunc_len);

        Ok(trunc_len)
    }
}

impl<S> Buffer for BoundaryReader<S> where S: Reader {
    fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]> {
        try!(self.read_to_boundary());

        let buf = self.buf[..self.last_search_idx];

        Ok(buf)
    }

    fn consume(&mut self, amt: uint) {
        assert!(amt <= self.last_search_idx);
        self._consume(amt);
    }
}

#[test]
fn test_boundary() {
    use std::io::BufReader;

    const BOUNDARY: &'static str = "--boundary\r\n";
    const TEST_VAL: &'static str = "\r
--boundary\r
dashed-value-1\r
--boundary\r
dashed-value-2\r
--boundary\r
";

    let test_reader = BufReader::new(TEST_VAL.as_bytes());
    let mut reader = BoundaryReader::from_reader(test_reader, BOUNDARY.into_string());

    debug!("Read 1");
    let string = reader.read_to_string().unwrap();
    debug!("{}", string);
    assert!(string[].trim().is_empty());

    debug!("Consume 1");
    reader.consume_boundary().unwrap();

    debug!("Read 2");
    assert_eq!(reader.read_to_string().unwrap()[].trim(), "dashed-value-1");

    debug!("Consume 2");
    reader.consume_boundary().unwrap();

    debug!("Read 3");
    assert_eq!(reader.read_to_string().unwrap()[].trim(), "dashed-value-2");

    debug!("Consume 3");
    reader.consume_boundary().unwrap();

}

<|endoftext|>


<commit_before>use core::str::StrExt;

use syscall::call::sys_debug;

pub fn db(byte: u8) {
    unsafe {
        sys_debug(byte);
    }
}

pub fn dbh(byte: u8) {
    let mut high = byte / 16;
    if high <= 9 {
        high += '0' as u8;
    } else {
        high -= 10;
        high += 'A' as u8;
    }
    db(high);

    let mut low = byte % 16;
    if low <= 9 {
        low += '0' as u8;
    } else {
        low -= 10;
        low += 'A' as u8;
    }
    db(low);
}

pub fn dh(num: usize) {
    if num >= 256 {
        dh(num / 256);
    }
    dbh((num % 256) as u8);
}

pub fn dd(num: usize) {
    if num >= 10 {
        dd(num / 10);
    }
    db('0' as u8 + (num % 10) as u8);
}

pub fn ds(num: isize) {
    if num >= 0 {
        dd(num as usize);
    } else {
        dc('-');
        dd((-num) as usize);
    }
}

pub fn dc(character: char) {
    db(character as u8);
}

pub fn dl() {
    dc('\n');
}

pub fn d(text: &str) {
    for character in text.chars() {
        dc(character);
    }
}
<commit_msg>Trim out more mut<commit_after>use core::str::StrExt;

use syscall::call::sys_debug;

pub fn db(byte: u8) {
    unsafe {
        sys_debug(byte);
    }
}

pub fn dbh(byte: u8) {
    let high = {
        let temp: u8 = byte / 16;
        if temp <= 9 {
            temp + ('0' as u8)
        } else {
            temp - 10 + ('A' as u8)
        }
    };
    db(high);

    let low = {
        let temp = byte % 16;
        if temp <= 9 {
            temp + ('0' as u8)
        } else {
            temp - 10 + ('A' as u8)
        }
    };
    db(low);
}

pub fn dh(num: usize) {
    if num >= 256 {
        dh(num / 256);
    }
    dbh((num % 256) as u8);
}

pub fn dd(num: usize) {
    if num >= 10 {
        dd(num / 10);
    }
    db('0' as u8 + (num % 10) as u8);
}

pub fn ds(num: isize) {
    if num >= 0 {
        dd(num as usize);
    } else {
        dc('-');
        dd((-num) as usize);
    }
}

pub fn dc(character: char) {
    db(character as u8);
}

pub fn dl() {
    dc('\n');
}

pub fn d(text: &str) {
    for character in text.chars() {
        dc(character);
    }
}
<|endoftext|>


<commit_before><commit_msg>2019: Day 4, part 2.<commit_after>use std::collections::HashSet;
use std::io;

use nom;

mod parse;

fn main() -> io::Result<()> {
    let mut input = String::new();
    io::stdin().read_line(&mut input)?;
    let (_, (start, end)) =
        parse(&input).map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{:?}", err)))?;

    let valid: HashSet<u32> = (start..end + 1)
        .map(to_digits)
        .filter(exactly_two_adjacent_digits_are_the_same)
        .filter(digits_never_decrease)
        .map(from_digits)
        .collect();

    println!("{}", valid.len());

    Ok(())
}

fn exactly_two_adjacent_digits_are_the_same(digits: &Vec<u32>) -> bool {
    let mut group_counts: Vec<u32> = Vec::new();
    let mut last_digit: Option<u32> = None;
    for digit in digits {
        if last_digit != Some(*digit) {
            group_counts.push(0);
        }
        let last_index = group_counts.len() - 1;
        group_counts[last_index] += 1;
        last_digit = Some(*digit);
    }
    group_counts.iter().any(|count| *count == 2)
}

fn digits_never_decrease(digits: &Vec<u32>) -> bool {
    digits.windows(2).all(|window| window[1] >= window[0])
}

fn parse(input: &str) -> nom::IResult<&str, (u32, u32)> {
    nom::sequence::tuple((
        nom::sequence::terminated(parse::digits, nom::character::complete::char('-')),
        parse::digits,
    ))(input)
}

fn to_digits(number: u32) -> Vec<u32> {
    format!("{}", number)
        .chars()
        .map(|digit| digit.to_digit(10).unwrap())
        .collect::<Vec<u32>>()
}

fn from_digits(digits: Vec<u32>) -> u32 {
    digits
        .iter()
        .rfold((0, 1), |(accumulator, multiplier), digit| {
            (accumulator + digit * multiplier, multiplier * 10)
        })
        .0
}
<|endoftext|>


<commit_before><commit_msg>Commit the mutable module<commit_after>use errors::Errors;
use state::State;
use strain::Strain;

pub trait Event<T: State> {
  fn precondition(&self, state: &T) -> Result<(), Errors>;

  fn postcondition(&self, state: &T) -> Result<(), Errors>;

  fn action(&self, state: &mut T) -> Result<(), Errors>;
}

pub trait MutableStrain<T: State> {
  fn feed(&mut self, event: &Event<T>) -> Result<(), Errors>;
}

impl<T: State> MutableStrain<T> for Strain<T> {
  fn feed(&mut self, event: &Event<T>) -> Result<(), Errors>{
    event.precondition(self.state).and_then(|_| {
      event.action(self.state).and_then(|_| {
        event.postcondition(self.state)
      })
    })
  }
}<|endoftext|>


<commit_before><commit_msg>Implement VSU envelopes<commit_after><|endoftext|>


<commit_before><commit_msg>Fix typo in hello_ranks example.<commit_after><|endoftext|>


<commit_before><commit_msg>Implement pipe magic in libimagrt<commit_after><|endoftext|>


<commit_before><commit_msg>added mod with structs<commit_after>mod struct_mod {

    pub struct WhiteBox<T> {
        pub contents: T
    }

    #[allow(dead_code)]
    pub struct BlackBox<T> {
        contents: T
    }

    impl<T> BlackBox<T> {
        pub fn new (contents: T) -> BlackBox<T> {
            BlackBox {
                contents: contents
            }
        }
    }
}

fn main() {
    let white_box = struct_mod::WhiteBox { contents: "Public data"};
    println!("white box: {}", white_box.contents);

    // let black_box = struct_mod::BlackBox { contents: "private data"}; // ERROR: field `contents` is private
    let black_box = struct_mod::BlackBox::new("private data"); // works as new is pub
    // println!("black box: {}", black_box.contents); // ERROR: error: field `contents` of struct `struct_mod::BlackBox` is private

}
<|endoftext|>


<commit_before><commit_msg>examplar use of `Peekable::peek`<commit_after>use futures::executor::block_on;
use futures::pin_mut;
use futures::stream::{self, Peekable, StreamExt};

#[test]
fn peekable() {
    block_on(async {
        let peekable: Peekable<_> = stream::iter(vec![1u8, 2, 3]).peekable();
        pin_mut!(peekable);
        assert_eq!(peekable.as_mut().peek().await, Some(&1u8));
        assert_eq!(peekable.collect::<Vec<u8>>().await, vec![1, 2, 3]);
    });
}
<|endoftext|>


<commit_before><commit_msg>Add new get_size example<commit_after>#[cfg(windows)]
fn run() {
    use std::os::windows::io::RawHandle;
    use winapi::um::processenv::GetStdHandle;
    use winapi::um::winbase::{STD_ERROR_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE};

    let stdout = unsafe { GetStdHandle(STD_OUTPUT_HANDLE) } as RawHandle;
    println!(
        "Size from terminal_size_using_handle(stdout): {:?}",
        terminal_size::terminal_size_using_handle(stdout)
    );

    let stderr = unsafe { GetStdHandle(STD_ERROR_HANDLE) } as RawHandle;
    println!(
        "Size from terminal_size_using_handle(stderr): {:?}",
        terminal_size::terminal_size_using_handle(stderr)
    );

    let stdin = unsafe { GetStdHandle(STD_INPUT_HANDLE) } as RawHandle;
    println!(
        "Size from terminal_size_using_handle(stdin):  {:?}",
        terminal_size::terminal_size_using_handle(stdin)
    );
}

#[cfg(not(windows))]
fn run() {
    println!(
        "Size from terminal_size_using_fd(stdout):     {:?}",
        terminal_size::terminal_size_using_fd(libc::STDOUT_FILENO)
    );
    println!(
        "Size from terminal_size_using_fd(stderr):     {:?}",
        terminal_size::terminal_size_using_fd(libc::STDERR_FILENO)
    );
    println!(
        "Size from terminal_size_using_fd(stdin):      {:?}",
        terminal_size::terminal_size_using_fd(libc::STDIN_FILENO)
    );
}

fn main() {
    println!(
        "Size from terminal_size():                    {:?}",
        terminal_size::terminal_size()
    );

    run();
}
<|endoftext|>


<commit_before><commit_msg>Port session.rs to ruma_api_macro<commit_after><|endoftext|>


<commit_before><commit_msg>Clean up renderervk.rs warnings<commit_after><|endoftext|>


<commit_before><commit_msg>Fix bugs in grain where values could go out of bounds.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix: Drop habit before getting instances<commit_after><|endoftext|>


<commit_before><commit_msg>Remove repetitive code by abstracting it<commit_after><|endoftext|>


<commit_before><commit_msg>allow agent to draw on screen without destroying next frame<commit_after><|endoftext|>


<commit_before><commit_msg>Switch to functional notation for readability<commit_after><|endoftext|>


<commit_before><commit_msg>chore: deletion<commit_after><|endoftext|>


<commit_before><commit_msg>1/2 tests cases are working.<commit_after><|endoftext|>


<commit_before><commit_msg>This time include the actual src<commit_after>extern crate regex;
use regex::Regex;

fn main() {
    let re = Regex::new(r"^1\d2\d3\d4\d5\d6\d7\d8\d9\d0$").unwrap();
    let min_square = 1020304050607080900_i64;
    let mut i = (((min_square as f64).sqrt() / 10.0).floor() as i64) * 10;
    loop {
        let s = (i * i).to_string();
        if re.is_match(&s) {
            println!("{} => {}", i, s);
            break;
        }
        i += 10;
    }
}
<|endoftext|>