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

#![macro_escape]
#![doc(hidden)]

macro_rules! uint_module (($T:ty, $T_SIGNED:ty, $bits:expr) => (

pub static BITS : uint = $bits;
pub static BYTES : uint = ($bits / 8);

pub static MIN: $T = 0 as $T;
pub static MAX: $T = 0 as $T - 1 as $T;

#[cfg(not(test))]
impl Ord for $T {
    #[inline]
    fn lt(&self, other: &$T) -> bool { *self < *other }
}
#[cfg(not(test))]
impl TotalEq for $T {}
#[cfg(not(test))]
impl Eq for $T {
    #[inline]
    fn eq(&self, other: &$T) -> bool { *self == *other }
}
#[cfg(not(test))]
impl TotalOrd for $T {
    #[inline]
    fn cmp(&self, other: &$T) -> Ordering {
        if *self < *other { Less }
        else if *self > *other { Greater }
        else { Equal }
    }
}

impl Num for $T {}

impl Zero for $T {
    #[inline]
    fn zero() -> $T { 0 }

    #[inline]
    fn is_zero(&self) -> bool { *self == 0 }
}

impl One for $T {
    #[inline]
    fn one() -> $T { 1 }
}

#[cfg(not(test))]
impl Add<$T,$T> for $T {
    #[inline]
    fn add(&self, other: &$T) -> $T { *self + *other }
}

#[cfg(not(test))]
impl Sub<$T,$T> for $T {
    #[inline]
    fn sub(&self, other: &$T) -> $T { *self - *other }
}

#[cfg(not(test))]
impl Mul<$T,$T> for $T {
    #[inline]
    fn mul(&self, other: &$T) -> $T { *self * *other }
}

#[cfg(not(test))]
impl Div<$T,$T> for $T {
    #[inline]
    fn div(&self, other: &$T) -> $T { *self / *other }
}

#[cfg(not(test))]
impl Rem<$T,$T> for $T {
    #[inline]
    fn rem(&self, other: &$T) -> $T { *self % *other }
}

#[cfg(not(test))]
impl Neg<$T> for $T {
    #[inline]
    fn neg(&self) -> $T { -*self }
}

impl Unsigned for $T {}

#[cfg(not(test))]
impl BitOr<$T,$T> for $T {
    #[inline]
    fn bitor(&self, other: &$T) -> $T { *self | *other }
}

#[cfg(not(test))]
impl BitAnd<$T,$T> for $T {
    #[inline]
    fn bitand(&self, other: &$T) -> $T { *self & *other }
}

#[cfg(not(test))]
impl BitXor<$T,$T> for $T {
    #[inline]
    fn bitxor(&self, other: &$T) -> $T { *self ^ *other }
}

#[cfg(not(test))]
impl Shl<$T,$T> for $T {
    #[inline]
    fn shl(&self, other: &$T) -> $T { *self << *other }
}

#[cfg(not(test))]
impl Shr<$T,$T> for $T {
    #[inline]
    fn shr(&self, other: &$T) -> $T { *self >> *other }
}

#[cfg(not(test))]
impl Not<$T> for $T {
    #[inline]
    fn not(&self) -> $T { !*self }
}

impl Bounded for $T {
    #[inline]
    fn min_value() -> $T { MIN }

    #[inline]
    fn max_value() -> $T { MAX }
}

impl Bitwise for $T {
    /// Returns the number of ones in the binary representation of the number.
    #[inline]
    fn count_ones(&self) -> $T {
        (*self as $T_SIGNED).count_ones() as $T
    }

    /// Returns the number of leading zeros in the in the binary representation
    /// of the number.
    #[inline]
    fn leading_zeros(&self) -> $T {
        (*self as $T_SIGNED).leading_zeros() as $T
    }

    /// Returns the number of trailing zeros in the in the binary representation
    /// of the number.
    #[inline]
    fn trailing_zeros(&self) -> $T {
        (*self as $T_SIGNED).trailing_zeros() as $T
    }
}

impl CheckedDiv for $T {
    #[inline]
    fn checked_div(&self, v: &$T) -> Option<$T> {
        if *v == 0 {
            None
        } else {
            Some(self / *v)
        }
    }
}

impl Int for $T {}

impl Primitive for $T {}

impl Default for $T {
    #[inline]
    fn default() -> $T { 0 }
}

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

    use num;
    use num::CheckedDiv;
    use num::Bitwise;

    #[test]
    fn test_overflows() {
        assert!(MAX > 0);
        assert!(MIN <= 0);
        assert!(MIN + MAX + 1 == 0);
    }

    #[test]
    fn test_num() {
        num::test_num(10 as $T, 2 as $T);
    }

    #[test]
    fn test_bitwise() {
        assert!(0b1110 as $T == (0b1100 as $T).bitor(&(0b1010 as $T)));
        assert!(0b1000 as $T == (0b1100 as $T).bitand(&(0b1010 as $T)));
        assert!(0b0110 as $T == (0b1100 as $T).bitxor(&(0b1010 as $T)));
        assert!(0b1110 as $T == (0b0111 as $T).shl(&(1 as $T)));
        assert!(0b0111 as $T == (0b1110 as $T).shr(&(1 as $T)));
        assert!(MAX - (0b1011 as $T) == (0b1011 as $T).not());
    }

    #[test]
    fn test_count_ones() {
        assert!((0b0101100 as $T).count_ones() == 3);
        assert!((0b0100001 as $T).count_ones() == 2);
        assert!((0b1111001 as $T).count_ones() == 5);
    }

    #[test]
    fn test_count_zeros() {
        assert!((0b0101100 as $T).count_zeros() == BITS as $T - 3);
        assert!((0b0100001 as $T).count_zeros() == BITS as $T - 2);
        assert!((0b1111001 as $T).count_zeros() == BITS as $T - 5);
    }

    #[test]
    fn test_unsigned_checked_div() {
        assert!(10u.checked_div(&2) == Some(5));
        assert!(5u.checked_div(&0) == None);
    }
}

))
<commit_msg>core: Fix an unsigned negation warning<commit_after>// Copyright 2012-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.

#![macro_escape]
#![doc(hidden)]

macro_rules! uint_module (($T:ty, $T_SIGNED:ty, $bits:expr) => (

pub static BITS : uint = $bits;
pub static BYTES : uint = ($bits / 8);

pub static MIN: $T = 0 as $T;
pub static MAX: $T = 0 as $T - 1 as $T;

#[cfg(not(test))]
impl Ord for $T {
    #[inline]
    fn lt(&self, other: &$T) -> bool { *self < *other }
}
#[cfg(not(test))]
impl TotalEq for $T {}
#[cfg(not(test))]
impl Eq for $T {
    #[inline]
    fn eq(&self, other: &$T) -> bool { *self == *other }
}
#[cfg(not(test))]
impl TotalOrd for $T {
    #[inline]
    fn cmp(&self, other: &$T) -> Ordering {
        if *self < *other { Less }
        else if *self > *other { Greater }
        else { Equal }
    }
}

impl Num for $T {}

impl Zero for $T {
    #[inline]
    fn zero() -> $T { 0 }

    #[inline]
    fn is_zero(&self) -> bool { *self == 0 }
}

impl One for $T {
    #[inline]
    fn one() -> $T { 1 }
}

#[cfg(not(test))]
impl Add<$T,$T> for $T {
    #[inline]
    fn add(&self, other: &$T) -> $T { *self + *other }
}

#[cfg(not(test))]
impl Sub<$T,$T> for $T {
    #[inline]
    fn sub(&self, other: &$T) -> $T { *self - *other }
}

#[cfg(not(test))]
impl Mul<$T,$T> for $T {
    #[inline]
    fn mul(&self, other: &$T) -> $T { *self * *other }
}

#[cfg(not(test))]
impl Div<$T,$T> for $T {
    #[inline]
    fn div(&self, other: &$T) -> $T { *self / *other }
}

#[cfg(not(test))]
impl Rem<$T,$T> for $T {
    #[inline]
    fn rem(&self, other: &$T) -> $T { *self % *other }
}

#[cfg(not(test))]
impl Neg<$T> for $T {
    #[inline]
    fn neg(&self) -> $T { -(*self as $T_SIGNED) as $T }
}

impl Unsigned for $T {}

#[cfg(not(test))]
impl BitOr<$T,$T> for $T {
    #[inline]
    fn bitor(&self, other: &$T) -> $T { *self | *other }
}

#[cfg(not(test))]
impl BitAnd<$T,$T> for $T {
    #[inline]
    fn bitand(&self, other: &$T) -> $T { *self & *other }
}

#[cfg(not(test))]
impl BitXor<$T,$T> for $T {
    #[inline]
    fn bitxor(&self, other: &$T) -> $T { *self ^ *other }
}

#[cfg(not(test))]
impl Shl<$T,$T> for $T {
    #[inline]
    fn shl(&self, other: &$T) -> $T { *self << *other }
}

#[cfg(not(test))]
impl Shr<$T,$T> for $T {
    #[inline]
    fn shr(&self, other: &$T) -> $T { *self >> *other }
}

#[cfg(not(test))]
impl Not<$T> for $T {
    #[inline]
    fn not(&self) -> $T { !*self }
}

impl Bounded for $T {
    #[inline]
    fn min_value() -> $T { MIN }

    #[inline]
    fn max_value() -> $T { MAX }
}

impl Bitwise for $T {
    /// Returns the number of ones in the binary representation of the number.
    #[inline]
    fn count_ones(&self) -> $T {
        (*self as $T_SIGNED).count_ones() as $T
    }

    /// Returns the number of leading zeros in the in the binary representation
    /// of the number.
    #[inline]
    fn leading_zeros(&self) -> $T {
        (*self as $T_SIGNED).leading_zeros() as $T
    }

    /// Returns the number of trailing zeros in the in the binary representation
    /// of the number.
    #[inline]
    fn trailing_zeros(&self) -> $T {
        (*self as $T_SIGNED).trailing_zeros() as $T
    }
}

impl CheckedDiv for $T {
    #[inline]
    fn checked_div(&self, v: &$T) -> Option<$T> {
        if *v == 0 {
            None
        } else {
            Some(self / *v)
        }
    }
}

impl Int for $T {}

impl Primitive for $T {}

impl Default for $T {
    #[inline]
    fn default() -> $T { 0 }
}

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

    use num;
    use num::CheckedDiv;
    use num::Bitwise;

    #[test]
    fn test_overflows() {
        assert!(MAX > 0);
        assert!(MIN <= 0);
        assert!(MIN + MAX + 1 == 0);
    }

    #[test]
    fn test_num() {
        num::test_num(10 as $T, 2 as $T);
    }

    #[test]
    fn test_bitwise() {
        assert!(0b1110 as $T == (0b1100 as $T).bitor(&(0b1010 as $T)));
        assert!(0b1000 as $T == (0b1100 as $T).bitand(&(0b1010 as $T)));
        assert!(0b0110 as $T == (0b1100 as $T).bitxor(&(0b1010 as $T)));
        assert!(0b1110 as $T == (0b0111 as $T).shl(&(1 as $T)));
        assert!(0b0111 as $T == (0b1110 as $T).shr(&(1 as $T)));
        assert!(MAX - (0b1011 as $T) == (0b1011 as $T).not());
    }

    #[test]
    fn test_count_ones() {
        assert!((0b0101100 as $T).count_ones() == 3);
        assert!((0b0100001 as $T).count_ones() == 2);
        assert!((0b1111001 as $T).count_ones() == 5);
    }

    #[test]
    fn test_count_zeros() {
        assert!((0b0101100 as $T).count_zeros() == BITS as $T - 3);
        assert!((0b0100001 as $T).count_zeros() == BITS as $T - 2);
        assert!((0b1111001 as $T).count_zeros() == BITS as $T - 5);
    }

    #[test]
    fn test_unsigned_checked_div() {
        assert!(10u.checked_div(&2) == Some(5));
        assert!(5u.checked_div(&0) == None);
    }
}

))
<|endoftext|>


<commit_before><commit_msg>Clean up menu example<commit_after><|endoftext|>


<commit_before>use crate::{
    attrs::{Attrs, Kind, Name, DEFAULT_CASING, DEFAULT_ENV_CASING},
    derives::{from_arg_matches, into_app},
    dummies,
    utils::{is_simple_ty, subty_if_name, Sp},
};

use proc_macro2::{Ident, Span, TokenStream};
use proc_macro_error::{abort, abort_call_site};
use quote::{quote, quote_spanned};
use syn::{
    punctuated::Punctuated, spanned::Spanned, Attribute, Data, DataEnum, DeriveInput,
    FieldsUnnamed, Token, Variant,
};

pub fn derive_subcommand(input: &DeriveInput) -> TokenStream {
    let ident = &input.ident;

    dummies::subcommand(ident);

    match input.data {
        Data::Enum(ref e) => gen_for_enum(ident, &input.attrs, e),
        _ => abort_call_site!("`#[derive(Subcommand)]` only supports enums"),
    }
}

pub fn gen_for_enum(name: &Ident, attrs: &[Attribute], e: &DataEnum) -> TokenStream {
    let attrs = Attrs::from_struct(
        Span::call_site(),
        attrs,
        Name::Derived(name.clone()),
        Sp::call_site(DEFAULT_CASING),
        Sp::call_site(DEFAULT_ENV_CASING),
    );

    let from_subcommand = gen_from_subcommand(name, &e.variants, &attrs);
    let augment_subcommands = gen_augment_subcommands(&e.variants, &attrs);
    let augment_update_subcommands = gen_augment_update_subcommands(&e.variants, &attrs);
    let update_from_subcommand = gen_update_from_subcommand(name, &e.variants, &attrs);

    quote! {
        #[allow(dead_code, unreachable_code, unused_variables)]
        #[allow(
            clippy::style,
            clippy::complexity,
            clippy::pedantic,
            clippy::restriction,
            clippy::perf,
            clippy::deprecated,
            clippy::nursery,
            clippy::cargo
        )]
        #[deny(clippy::correctness)]
        impl ::clap::Subcommand for #name {
            #augment_subcommands
            #from_subcommand
            #augment_update_subcommands
            #update_from_subcommand
        }
    }
}

fn gen_augment_subcommands(
    variants: &Punctuated<Variant, Token![,]>,
    parent_attribute: &Attrs,
) -> TokenStream {
    gen_augment("augment_subcommands", variants, parent_attribute, false)
}

fn gen_augment_update_subcommands(
    variants: &Punctuated<Variant, Token![,]>,
    parent_attribute: &Attrs,
) -> TokenStream {
    gen_augment(
        "augment_update_subcommands",
        variants,
        parent_attribute,
        true,
    )
}

fn gen_augment(
    fn_name: &str,
    variants: &Punctuated<Variant, Token![,]>,
    parent_attribute: &Attrs,
    override_required: bool,
) -> TokenStream {
    use syn::Fields::*;

    let subcommands: Vec<_> = variants
        .iter()
        .map(|variant| {
            let attrs = Attrs::from_struct(
                variant.span(),
                &variant.attrs,
                Name::Derived(variant.ident.clone()),
                parent_attribute.casing(),
                parent_attribute.env_casing(),
            );
            let kind = attrs.kind();

            match &*kind {
                Kind::ExternalSubcommand => {
                    quote_spanned! { kind.span()=>
                        let app = app.setting(::clap::AppSettings::AllowExternalSubcommands);
                    }
                }

                Kind::Flatten => match variant.fields {
                    Unnamed(FieldsUnnamed { ref unnamed, .. }) if unnamed.len() == 1 => {
                        let ty = &unnamed[0];
                        quote! {
                            let app = <#ty as ::clap::Subcommand>::augment_subcommands(app);
                        }
                    }
                    _ => abort!(
                        variant,
                        "`flatten` is usable only with single-typed tuple variants"
                    ),
                },

                _ => {
                    let app_var = Ident::new("subcommand", Span::call_site());
                    let arg_block = match variant.fields {
                        Named(ref fields) => into_app::gen_app_augmentation(
                            &fields.named,
                            &app_var,
                            &attrs,
                            override_required,
                        ),
                        Unit => quote!( #app_var ),
                        Unnamed(FieldsUnnamed { ref unnamed, .. }) if unnamed.len() == 1 => {
                            let ty = &unnamed[0];
                            quote_spanned! { ty.span()=>
                                {
                                    <#ty as ::clap::IntoApp>::augment_clap(#app_var)
                                }
                            }
                        }
                        Unnamed(..) => {
                            abort!(variant, "non single-typed tuple enums are not supported")
                        }
                    };

                    let name = attrs.cased_name();
                    let from_attrs = attrs.top_level_methods();
                    let version = attrs.version();
                    quote! {
                        let app = app.subcommand({
                            let #app_var = ::clap::App::new(#name);
                            let #app_var = #arg_block;
                            #app_var#from_attrs#version
                        });
                    }
                }
            }
        })
        .collect();

    let app_methods = parent_attribute.top_level_methods();
    let version = parent_attribute.version();
    let fn_name = Ident::new(fn_name, Span::call_site());
    quote! {
        fn #fn_name <'b>(app: ::clap::App<'b>) -> ::clap::App<'b> {
            let app = app #app_methods;
            #( #subcommands )*;
            app #version
        }
    }
}

fn gen_from_subcommand(
    name: &Ident,
    variants: &Punctuated<Variant, Token![,]>,
    parent_attribute: &Attrs,
) -> TokenStream {
    use syn::Fields::*;

    let mut ext_subcmd = None;

    let (flatten_variants, variants): (Vec<_>, Vec<_>) = variants
        .iter()
        .filter_map(|variant| {
            let attrs = Attrs::from_struct(
                variant.span(),
                &variant.attrs,
                Name::Derived(variant.ident.clone()),
                parent_attribute.casing(),
                parent_attribute.env_casing(),
            );

            if let Kind::ExternalSubcommand = &*attrs.kind() {
                if ext_subcmd.is_some() {
                    abort!(
                        attrs.kind().span(),
                        "Only one variant can be marked with `external_subcommand`, \
                         this is the second"
                    );
                }

                let ty = match variant.fields {
                    Unnamed(ref fields) if fields.unnamed.len() == 1 => &fields.unnamed[0].ty,

                    _ => abort!(
                        variant,
                        "The enum variant marked with `external_attribute` must be \
                         a single-typed tuple, and the type must be either `Vec<String>` \
                         or `Vec<OsString>`."
                    ),
                };

                let (span, str_ty, values_of) = match subty_if_name(ty, "Vec") {
                    Some(subty) => {
                        if is_simple_ty(subty, "String") {
                            (
                                subty.span(),
                                quote!(::std::string::String),
                                quote!(values_of),
                            )
                        } else if is_simple_ty(subty, "OsString") {
                            (
                                subty.span(),
                                quote!(::std::ffi::OsString),
                                quote!(values_of_os),
                            )
                        } else {
                            abort!(
                                ty.span(),
                                "The type must be either `Vec<String>` or `Vec<OsString>` \
                                 to be used with `external_subcommand`."
                            );
                        }
                    }

                    None => abort!(
                        ty.span(),
                        "The type must be either `Vec<String>` or `Vec<OsString>` \
                         to be used with `external_subcommand`."
                    ),
                };

                ext_subcmd = Some((span, &variant.ident, str_ty, values_of));
                None
            } else {
                Some((variant, attrs))
            }
        })
        .partition(|(_, attrs)| {
            let kind = attrs.kind();
            matches!(&*kind, Kind::Flatten)
        });

    let match_arms = variants.iter().map(|(variant, attrs)| {
        let sub_name = attrs.cased_name();
        let variant_name = &variant.ident;
        let constructor_block = match variant.fields {
            Named(ref fields) => from_arg_matches::gen_constructor(&fields.named, &attrs),
            Unit => quote!(),
            Unnamed(ref fields) if fields.unnamed.len() == 1 => {
                let ty = &fields.unnamed[0];
                quote!( ( <#ty as ::clap::FromArgMatches>::from_arg_matches(matches) ) )
            }
            Unnamed(..) => abort_call_site!("{}: tuple enums are not supported", variant.ident),
        };

        quote! {
            Some((#sub_name, matches)) => {
                Some(#name :: #variant_name #constructor_block)
            }
        }
    });
    let child_subcommands = flatten_variants.iter().map(|(variant, _attrs)| {
        let variant_name = &variant.ident;
        match variant.fields {
            Unnamed(ref fields) if fields.unnamed.len() == 1 => {
                let ty = &fields.unnamed[0];
                quote! {
                    if let Some(res) = <#ty as ::clap::Subcommand>::from_subcommand(other) {
                        return Some(#name :: #variant_name (res));
                    }
                }
            }
            _ => abort!(
                variant,
                "`flatten` is usable only with single-typed tuple variants"
            ),
        }
    });

    let wildcard = match ext_subcmd {
        Some((span, var_name, str_ty, values_of)) => quote_spanned! { span=>
            None => ::std::option::Option::None,

            Some((external, matches)) => {
                ::std::option::Option::Some(#name::#var_name(
                    ::std::iter::once(#str_ty::from(external))
                    .chain(
                        matches.#values_of("").into_iter().flatten().map(#str_ty::from)
                    )
                    .collect::<::std::vec::Vec<_>>()
                ))
            }
        },

        None => quote!(_ => None),
    };

    quote! {
        fn from_subcommand(subcommand: Option<(&str, &::clap::ArgMatches)>) -> Option<Self> {
            match subcommand {
                #( #match_arms, )*
                other => {
                    #( #child_subcommands )else*

                    match other {
                        #wildcard
                    }
                }
            }
        }
    }
}

fn gen_update_from_subcommand(
    name: &Ident,
    variants: &Punctuated<Variant, Token![,]>,
    parent_attribute: &Attrs,
) -> TokenStream {
    use syn::Fields::*;

    let (flatten_variants, variants): (Vec<_>, Vec<_>) = variants
        .iter()
        .filter_map(|variant| {
            let attrs = Attrs::from_struct(
                variant.span(),
                &variant.attrs,
                Name::Derived(variant.ident.clone()),
                parent_attribute.casing(),
                parent_attribute.env_casing(),
            );

            if let Kind::ExternalSubcommand = &*attrs.kind() {
                None
            } else {
                Some((variant, attrs))
            }
        })
        .partition(|(_, attrs)| {
            let kind = attrs.kind();
            matches!(&*kind, Kind::Flatten)
        });

    let subcommands = variants.iter().map(|(variant, attrs)| {
        let sub_name = attrs.cased_name();
        let variant_name = &variant.ident;
        let (pattern, updater) = match variant.fields {
            Named(ref fields) => {
                let (fields, update): (Vec<_>, Vec<_>) = fields
                    .named
                    .iter()
                    .map(|field| {
                        let attrs = Attrs::from_field(
                            field,
                            parent_attribute.casing(),
                            parent_attribute.env_casing(),
                        );
                        let field_name = field.ident.as_ref().unwrap();
                        (
                            quote!( ref mut #field_name ),
                            from_arg_matches::gen_updater(&fields.named, &attrs, false),
                        )
                    })
                    .unzip();
                (quote!( { #( #fields, )* }), quote!( { #( #update )* } ))
            }
            Unit => (quote!(), quote!({})),
            Unnamed(ref fields) => {
                if fields.unnamed.len() == 1 {
                    (
                        quote!((ref mut arg)),
                        quote!(::clap::FromArgMatches::update_from_arg_matches(
                            arg, matches
                        )),
                    )
                } else {
                    abort_call_site!("{}: tuple enums are not supported", variant.ident)
                }
            }
        };

        quote! {
            (#sub_name, #name :: #variant_name #pattern) => { #updater }
        }
    });

    let child_subcommands = flatten_variants.iter().map(|(variant, attrs)| {
        let sub_name = attrs.cased_name();
        let variant_name = &variant.ident;
        let (pattern, updater) = match variant.fields {
            Unnamed(ref fields) if fields.unnamed.len() == 1 => {
                let ty = &fields.unnamed[0];
                (
                    quote!((ref mut arg)),
                    quote! {
                        <#ty as ::clap::Subcommand>::update_from_subcommand(arg, Some((name, matches)));
                    },
                )
            }
            _ => abort!(
                variant,
                "`flatten` is usable only with single-typed tuple variants"
            ),
        };
        quote! {
            (#sub_name, #name :: #variant_name #pattern) => { #updater }
        }
    });

    quote! {
        fn update_from_subcommand<'b>(
            &mut self,
            subcommand: Option<(&str, &::clap::ArgMatches)>
        ) {
            if let Some((name, matches)) = subcommand {
                match (name, self) {
                    #( #subcommands ),*
                    #( #child_subcommands ),*
                    (_, s) => if let Some(sub) = <Self as ::clap::Subcommand>::from_subcommand(Some((name, matches))) {
                        *s = sub;
                    }
                }
            }
        }
    }
}
<commit_msg>Avoid a level of indirection for augment_*subcommand<commit_after>use crate::{
    attrs::{Attrs, Kind, Name, DEFAULT_CASING, DEFAULT_ENV_CASING},
    derives::{from_arg_matches, into_app},
    dummies,
    utils::{is_simple_ty, subty_if_name, Sp},
};

use proc_macro2::{Ident, Span, TokenStream};
use proc_macro_error::{abort, abort_call_site};
use quote::{quote, quote_spanned};
use syn::{
    punctuated::Punctuated, spanned::Spanned, Attribute, Data, DataEnum, DeriveInput,
    FieldsUnnamed, Token, Variant,
};

pub fn derive_subcommand(input: &DeriveInput) -> TokenStream {
    let ident = &input.ident;

    dummies::subcommand(ident);

    match input.data {
        Data::Enum(ref e) => gen_for_enum(ident, &input.attrs, e),
        _ => abort_call_site!("`#[derive(Subcommand)]` only supports enums"),
    }
}

pub fn gen_for_enum(name: &Ident, attrs: &[Attribute], e: &DataEnum) -> TokenStream {
    let attrs = Attrs::from_struct(
        Span::call_site(),
        attrs,
        Name::Derived(name.clone()),
        Sp::call_site(DEFAULT_CASING),
        Sp::call_site(DEFAULT_ENV_CASING),
    );

    let augment_subcommands = gen_augment("augment_subcommands", &e.variants, &attrs, false);
    let augment_update_subcommands =
        gen_augment("augment_update_subcommands", &e.variants, &attrs, true);
    let from_subcommand = gen_from_subcommand(name, &e.variants, &attrs);
    let update_from_subcommand = gen_update_from_subcommand(name, &e.variants, &attrs);

    quote! {
        #[allow(dead_code, unreachable_code, unused_variables)]
        #[allow(
            clippy::style,
            clippy::complexity,
            clippy::pedantic,
            clippy::restriction,
            clippy::perf,
            clippy::deprecated,
            clippy::nursery,
            clippy::cargo
        )]
        #[deny(clippy::correctness)]
        impl ::clap::Subcommand for #name {
            #augment_subcommands
            #from_subcommand
            #augment_update_subcommands
            #update_from_subcommand
        }
    }
}

fn gen_augment(
    fn_name: &str,
    variants: &Punctuated<Variant, Token![,]>,
    parent_attribute: &Attrs,
    override_required: bool,
) -> TokenStream {
    use syn::Fields::*;

    let subcommands: Vec<_> = variants
        .iter()
        .map(|variant| {
            let attrs = Attrs::from_struct(
                variant.span(),
                &variant.attrs,
                Name::Derived(variant.ident.clone()),
                parent_attribute.casing(),
                parent_attribute.env_casing(),
            );
            let kind = attrs.kind();

            match &*kind {
                Kind::ExternalSubcommand => {
                    quote_spanned! { kind.span()=>
                        let app = app.setting(::clap::AppSettings::AllowExternalSubcommands);
                    }
                }

                Kind::Flatten => match variant.fields {
                    Unnamed(FieldsUnnamed { ref unnamed, .. }) if unnamed.len() == 1 => {
                        let ty = &unnamed[0];
                        quote! {
                            let app = <#ty as ::clap::Subcommand>::augment_subcommands(app);
                        }
                    }
                    _ => abort!(
                        variant,
                        "`flatten` is usable only with single-typed tuple variants"
                    ),
                },

                _ => {
                    let app_var = Ident::new("subcommand", Span::call_site());
                    let arg_block = match variant.fields {
                        Named(ref fields) => into_app::gen_app_augmentation(
                            &fields.named,
                            &app_var,
                            &attrs,
                            override_required,
                        ),
                        Unit => quote!( #app_var ),
                        Unnamed(FieldsUnnamed { ref unnamed, .. }) if unnamed.len() == 1 => {
                            let ty = &unnamed[0];
                            quote_spanned! { ty.span()=>
                                {
                                    <#ty as ::clap::IntoApp>::augment_clap(#app_var)
                                }
                            }
                        }
                        Unnamed(..) => {
                            abort!(variant, "non single-typed tuple enums are not supported")
                        }
                    };

                    let name = attrs.cased_name();
                    let from_attrs = attrs.top_level_methods();
                    let version = attrs.version();
                    quote! {
                        let app = app.subcommand({
                            let #app_var = ::clap::App::new(#name);
                            let #app_var = #arg_block;
                            #app_var#from_attrs#version
                        });
                    }
                }
            }
        })
        .collect();

    let app_methods = parent_attribute.top_level_methods();
    let version = parent_attribute.version();
    let fn_name = Ident::new(fn_name, Span::call_site());
    quote! {
        fn #fn_name <'b>(app: ::clap::App<'b>) -> ::clap::App<'b> {
            let app = app #app_methods;
            #( #subcommands )*;
            app #version
        }
    }
}

fn gen_from_subcommand(
    name: &Ident,
    variants: &Punctuated<Variant, Token![,]>,
    parent_attribute: &Attrs,
) -> TokenStream {
    use syn::Fields::*;

    let mut ext_subcmd = None;

    let (flatten_variants, variants): (Vec<_>, Vec<_>) = variants
        .iter()
        .filter_map(|variant| {
            let attrs = Attrs::from_struct(
                variant.span(),
                &variant.attrs,
                Name::Derived(variant.ident.clone()),
                parent_attribute.casing(),
                parent_attribute.env_casing(),
            );

            if let Kind::ExternalSubcommand = &*attrs.kind() {
                if ext_subcmd.is_some() {
                    abort!(
                        attrs.kind().span(),
                        "Only one variant can be marked with `external_subcommand`, \
                         this is the second"
                    );
                }

                let ty = match variant.fields {
                    Unnamed(ref fields) if fields.unnamed.len() == 1 => &fields.unnamed[0].ty,

                    _ => abort!(
                        variant,
                        "The enum variant marked with `external_attribute` must be \
                         a single-typed tuple, and the type must be either `Vec<String>` \
                         or `Vec<OsString>`."
                    ),
                };

                let (span, str_ty, values_of) = match subty_if_name(ty, "Vec") {
                    Some(subty) => {
                        if is_simple_ty(subty, "String") {
                            (
                                subty.span(),
                                quote!(::std::string::String),
                                quote!(values_of),
                            )
                        } else if is_simple_ty(subty, "OsString") {
                            (
                                subty.span(),
                                quote!(::std::ffi::OsString),
                                quote!(values_of_os),
                            )
                        } else {
                            abort!(
                                ty.span(),
                                "The type must be either `Vec<String>` or `Vec<OsString>` \
                                 to be used with `external_subcommand`."
                            );
                        }
                    }

                    None => abort!(
                        ty.span(),
                        "The type must be either `Vec<String>` or `Vec<OsString>` \
                         to be used with `external_subcommand`."
                    ),
                };

                ext_subcmd = Some((span, &variant.ident, str_ty, values_of));
                None
            } else {
                Some((variant, attrs))
            }
        })
        .partition(|(_, attrs)| {
            let kind = attrs.kind();
            matches!(&*kind, Kind::Flatten)
        });

    let match_arms = variants.iter().map(|(variant, attrs)| {
        let sub_name = attrs.cased_name();
        let variant_name = &variant.ident;
        let constructor_block = match variant.fields {
            Named(ref fields) => from_arg_matches::gen_constructor(&fields.named, &attrs),
            Unit => quote!(),
            Unnamed(ref fields) if fields.unnamed.len() == 1 => {
                let ty = &fields.unnamed[0];
                quote!( ( <#ty as ::clap::FromArgMatches>::from_arg_matches(matches) ) )
            }
            Unnamed(..) => abort_call_site!("{}: tuple enums are not supported", variant.ident),
        };

        quote! {
            Some((#sub_name, matches)) => {
                Some(#name :: #variant_name #constructor_block)
            }
        }
    });
    let child_subcommands = flatten_variants.iter().map(|(variant, _attrs)| {
        let variant_name = &variant.ident;
        match variant.fields {
            Unnamed(ref fields) if fields.unnamed.len() == 1 => {
                let ty = &fields.unnamed[0];
                quote! {
                    if let Some(res) = <#ty as ::clap::Subcommand>::from_subcommand(other) {
                        return Some(#name :: #variant_name (res));
                    }
                }
            }
            _ => abort!(
                variant,
                "`flatten` is usable only with single-typed tuple variants"
            ),
        }
    });

    let wildcard = match ext_subcmd {
        Some((span, var_name, str_ty, values_of)) => quote_spanned! { span=>
            None => ::std::option::Option::None,

            Some((external, matches)) => {
                ::std::option::Option::Some(#name::#var_name(
                    ::std::iter::once(#str_ty::from(external))
                    .chain(
                        matches.#values_of("").into_iter().flatten().map(#str_ty::from)
                    )
                    .collect::<::std::vec::Vec<_>>()
                ))
            }
        },

        None => quote!(_ => None),
    };

    quote! {
        fn from_subcommand(subcommand: Option<(&str, &::clap::ArgMatches)>) -> Option<Self> {
            match subcommand {
                #( #match_arms, )*
                other => {
                    #( #child_subcommands )else*

                    match other {
                        #wildcard
                    }
                }
            }
        }
    }
}

fn gen_update_from_subcommand(
    name: &Ident,
    variants: &Punctuated<Variant, Token![,]>,
    parent_attribute: &Attrs,
) -> TokenStream {
    use syn::Fields::*;

    let (flatten_variants, variants): (Vec<_>, Vec<_>) = variants
        .iter()
        .filter_map(|variant| {
            let attrs = Attrs::from_struct(
                variant.span(),
                &variant.attrs,
                Name::Derived(variant.ident.clone()),
                parent_attribute.casing(),
                parent_attribute.env_casing(),
            );

            if let Kind::ExternalSubcommand = &*attrs.kind() {
                None
            } else {
                Some((variant, attrs))
            }
        })
        .partition(|(_, attrs)| {
            let kind = attrs.kind();
            matches!(&*kind, Kind::Flatten)
        });

    let subcommands = variants.iter().map(|(variant, attrs)| {
        let sub_name = attrs.cased_name();
        let variant_name = &variant.ident;
        let (pattern, updater) = match variant.fields {
            Named(ref fields) => {
                let (fields, update): (Vec<_>, Vec<_>) = fields
                    .named
                    .iter()
                    .map(|field| {
                        let attrs = Attrs::from_field(
                            field,
                            parent_attribute.casing(),
                            parent_attribute.env_casing(),
                        );
                        let field_name = field.ident.as_ref().unwrap();
                        (
                            quote!( ref mut #field_name ),
                            from_arg_matches::gen_updater(&fields.named, &attrs, false),
                        )
                    })
                    .unzip();
                (quote!( { #( #fields, )* }), quote!( { #( #update )* } ))
            }
            Unit => (quote!(), quote!({})),
            Unnamed(ref fields) => {
                if fields.unnamed.len() == 1 {
                    (
                        quote!((ref mut arg)),
                        quote!(::clap::FromArgMatches::update_from_arg_matches(
                            arg, matches
                        )),
                    )
                } else {
                    abort_call_site!("{}: tuple enums are not supported", variant.ident)
                }
            }
        };

        quote! {
            (#sub_name, #name :: #variant_name #pattern) => { #updater }
        }
    });

    let child_subcommands = flatten_variants.iter().map(|(variant, attrs)| {
        let sub_name = attrs.cased_name();
        let variant_name = &variant.ident;
        let (pattern, updater) = match variant.fields {
            Unnamed(ref fields) if fields.unnamed.len() == 1 => {
                let ty = &fields.unnamed[0];
                (
                    quote!((ref mut arg)),
                    quote! {
                        <#ty as ::clap::Subcommand>::update_from_subcommand(arg, Some((name, matches)));
                    },
                )
            }
            _ => abort!(
                variant,
                "`flatten` is usable only with single-typed tuple variants"
            ),
        };
        quote! {
            (#sub_name, #name :: #variant_name #pattern) => { #updater }
        }
    });

    quote! {
        fn update_from_subcommand<'b>(
            &mut self,
            subcommand: Option<(&str, &::clap::ArgMatches)>
        ) {
            if let Some((name, matches)) = subcommand {
                match (name, self) {
                    #( #subcommands ),*
                    #( #child_subcommands ),*
                    (_, s) => if let Some(sub) = <Self as ::clap::Subcommand>::from_subcommand(Some((name, matches))) {
                        *s = sub;
                    }
                }
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Ignore routes where the train does not call at the anchor locations.<commit_after><|endoftext|>


<commit_before><commit_msg>Added a little bit of documentation<commit_after><|endoftext|>


<commit_before><commit_msg>add simple CLI<commit_after>extern crate sea_canal;

use std::io;

use sea_canal::{Analyze, Analyzer};

fn main() {
    let stdin = io::stdin();
    let mut buf = String::new();
    stdin.read_line(&mut buf).expect("Unable to read input");
    let split = buf.split_whitespace();
    let nums : Vec<_> = split.map(|s| i32::from_str_radix(s, 10).expect("Invalid numeric input")).collect();
    let analyzer = Analyzer::from_slice(&nums);
    let length = nums.len();
    let x = length - 1;
    let y = length / 2 + 1;
    let n = if y < x { y } else { x };

    println!("----------");

    match analyzer.find_any_pattern(n) {
        Some(pat) => println!("{}", pat),
        None => println!("No pattern found")
    };
}
<|endoftext|>


<commit_before><commit_msg>add nonfunctional controls.rs - but it does compile<commit_after>//use serde;
// use serde::de::Deserialize;

extern crate serde_json;
extern crate serde;

// create from initial json spec file.
// update individual controls from state update msgs.
// create a json message containing the state of all ctrls.

/*
trait Control : Deserialize {
  fn controlType(&self) -> String;
  // tojson
  // fromjson
  // updatefromjson
}

*/

#[derive(Deserialize)]
pub struct Slider {
  controlid: String,
  name: String,
  pressed: bool,
}

/*
impl Control for Slider {
  // tojson
  // fromjson
  // updatefromjson
}
*/

#[derive(Deserialize)]
pub struct Button {
  controlid: String,
  name: String,
  pressed: bool,
}

/*
#[derive(Deserialize)]
pub struct Sizer {
  controlid: String,
  controls: Vec<Control>,
}

#[derive(Deserialize)]
pub struct Root {
  title: String,
  rootControl: Control,
}
*/
<|endoftext|>


<commit_before><commit_msg>Add missing controls.rs<commit_after><|endoftext|>


<commit_before>use crossbeam;

use std::fs::{self, File};
use std::io::{self, Write, ErrorKind};
use std::path::{Path, PathBuf};
use std::ffi::OsStr;
use liquid::Value;
use walkdir::{WalkDir, DirEntry, WalkDirIterator};
use document::Document;
use error::{Error, Result};
use config::Config;
use chrono::{UTC, FixedOffset};
use chrono::offset::TimeZone;
use rss::{Channel, Rss};
use std::sync::Arc;
use glob::Pattern;

fn ignore_filter(entry: &DirEntry, source: &Path, ignore: &[Pattern]) -> bool {
    if compare_paths(entry.path(), source) {
        return true;
    }
    let path = entry.path().strip_prefix(&source).unwrap_or(entry.path());
    let file_name = entry.file_name().to_str().unwrap_or("");
    if file_name.starts_with('_') || file_name.starts_with('.') {
        return false;
    }
    !ignore.iter().any(|p| p.matches_path(path))
}

fn compare_paths(a: &Path, b: &Path) -> bool {
    match (fs::canonicalize(a), fs::canonicalize(b)) {
        (Ok(p), Ok(p2)) => p == p2,
        _ => false,
    }
}

/// The primary build function that tranforms a directory into a site
pub fn build(config: &Config) -> Result<()> {
    trace!("Build configuration: {:?}", config);

    // join("") makes sure path has a trailing slash
    let source = PathBuf::from(&config.source).join("");
    let source = source.as_path();
    let dest = PathBuf::from(&config.dest).join("");
    let dest = dest.as_path();

    let template_extensions: Vec<&OsStr> = config.template_extensions
        .iter()
        .map(OsStr::new)
        .collect();

    let layouts = source.join(&config.layouts);
    let layouts = layouts.as_path();
    let posts = source.join(&config.posts);
    let posts = posts.as_path();

    debug!("Layouts directory: {:?}", layouts);
    debug!("posts directory: {:?}", posts);

    let mut documents = vec![];

    let walker = WalkDir::new(&source)
        .into_iter()
        .filter_entry(|e| {
            (ignore_filter(e, source, &config.ignore) || compare_paths(e.path(), posts)) &&
            !compare_paths(e.path(), dest)
        })
        .filter_map(|e| e.ok());

    for entry in walker {
        let extension = &entry.path().extension().unwrap_or(OsStr::new(""));
        if template_extensions.contains(extension) {
            // if the document is in the posts folder it's considered a post
            let is_post = entry.path().parent().map(|p| compare_paths(p, posts)).unwrap_or(false);

            let doc = try!(Document::parse(&entry.path(), &source, is_post, &config.post_path));
            documents.push(doc);
        }
    }

    // January 1, 1970 0:00:00 UTC, the beginning of time
    let default_date = UTC.timestamp(0, 0).with_timezone(&FixedOffset::east(0));

    // sort documents by date, if there's no date (none was provided or it couldn't be read) then
    // fall back to the default date
    documents.sort_by(|a, b| {
        b.date.unwrap_or(default_date).cmp(&a.date.unwrap_or(default_date))
    });

    // check if we should create an RSS file and create it!
    if let &Some(ref path) = &config.rss {
        try!(create_rss(path, dest, &config, &documents));
    }

    // these are the attributes of all documents that are posts, so that they can be
    // passed to the renderer
    // TODO: do we have to clone these?
    let post_data: Vec<Value> = documents.iter()
        .filter(|x| x.is_post)
        .map(|x| Value::Object(x.attributes.clone()))
        .collect();

    // thread handles to join later
    let mut handles = vec![];

    // generate documents (in parallel)
    crossbeam::scope(|scope| {
        let post_data = Arc::new(post_data);

        for doc in &documents {
            trace!("Generating {}", doc.path);
            let post_data = post_data.clone();

            let handle = scope.spawn(move || {
                let content = try!(doc.as_html(&source, &post_data, &layouts));
                create_document_file(content, &doc.path, dest)
            });
            handles.push(handle);
        }
    });

    for handle in handles {
        try!(handle.join());
    }

    // copy all remaining files in the source to the destination
    if !compare_paths(source, dest) {
        info!("Copying remaining assets");
        let source_str = try!(source.to_str()
            .ok_or(format!("Cannot convert pathname {:?} to UTF-8", source)));

        let walker = WalkDir::new(&source)
            .into_iter()
            .filter_entry(|e| {
                ignore_filter(e, source, &config.ignore) &&
                !template_extensions.contains(&e.path()
                    .extension()
                    .unwrap_or(OsStr::new(""))) && !compare_paths(e.path(), dest)
            })
            .filter_map(|e| e.ok());

        for entry in walker {
            let entry_path = try!(entry.path()
                .to_str()
                .ok_or(format!("Cannot convert pathname {:?} to UTF-8", entry.path())));

            let relative = try!(entry_path.split(source_str)
                .last()
                .ok_or(format!("Empty path")));

            if try!(entry.metadata()).is_dir() {
                try!(fs::create_dir_all(&dest.join(relative)));
                debug!("Created new directory {:?}", dest.join(relative));
            } else {
                if let Some(ref parent) = Path::new(relative).parent() {
                    try!(fs::create_dir_all(&dest.join(parent)));
                }

                try!(fs::copy(entry.path(), &dest.join(relative))
                    .map_err(|e| format!("Could not copy {:?}: {}", entry.path(), e)));
                debug!("Copied {:?} to {:?}", entry.path(), dest.join(relative));
            }
        }
    }

    Ok(())
}

// creates a new RSS file with the contents of the site blog
fn create_rss(path: &str, dest: &Path, config: &Config, documents: &[Document]) -> Result<()> {
    match (&config.name, &config.description, &config.link) {
        // these three fields are mandatory in the RSS standard
        (&Some(ref name), &Some(ref description), &Some(ref link)) => {
            trace!("Generating RSS data");

            let items = documents.iter()
                .filter(|x| x.is_post)
                .map(|doc| doc.to_rss(link))
                .collect();

            let channel = Channel {
                title: name.to_owned(),
                link: link.to_owned(),
                description: description.to_owned(),
                items: items,
                ..Default::default()
            };

            let rss = Rss(channel);
            let rss_string = rss.to_string();
            trace!("RSS data: {}", rss_string);

            let rss_path = dest.join(path);

            let mut rss_file = try!(File::create(&rss_path));
            try!(rss_file.write_all(&rss_string.into_bytes()));

            info!("Created RSS file at {}", rss_path.display());
            Ok(())
        }
        _ => {
            Err(Error::from("name, description and link need to be defined in the config file to \
                             generate RSS"))
        }
    }
}

/// A slightly less efficient implementation of fs::create_dir_all
/// that eliminates the race condition problems of the original
fn create_dir_all(path: &Path) -> io::Result<()> {
    let mut new_path = PathBuf::new();
    for component in path {
        new_path.push(component);
        match fs::create_dir(&new_path) {
            Ok(_) => {}
            Err(ref e) if e.kind() == ErrorKind::AlreadyExists => {}
            Err(e) => return Err(e),
        }
    }
    Ok(())
}

fn create_document_file<T: AsRef<Path>>(content: String, path: T, dest: &Path) -> Result<()> {
    // construct target path
    let file_path_buf = dest.join(path);
    let file_path = file_path_buf.as_path();

    // create target directories if any exist
    if let Some(parent) = file_path.parent() {
        try!(create_dir_all(parent).map_err(|e| format!("Could not create {:?}: {}", parent, e)));
    }

    let mut file = try!(File::create(&file_path)
        .map_err(|e| format!("Could not create {:?}: {}", file_path, e)));

    try!(file.write_all(&content.into_bytes()));
    info!("Created {}", file_path.display());
    Ok(())
}
<commit_msg>Fix rustfmt complaint<commit_after>use crossbeam;

use std::fs::{self, File};
use std::io::{self, Write, ErrorKind};
use std::path::{Path, PathBuf};
use std::ffi::OsStr;
use liquid::Value;
use walkdir::{WalkDir, DirEntry, WalkDirIterator};
use document::Document;
use error::{Error, Result};
use config::Config;
use chrono::{UTC, FixedOffset};
use chrono::offset::TimeZone;
use rss::{Channel, Rss};
use std::sync::Arc;
use glob::Pattern;

fn ignore_filter(entry: &DirEntry, source: &Path, ignore: &[Pattern]) -> bool {
    if compare_paths(entry.path(), source) {
        return true;
    }
    let path = entry.path().strip_prefix(&source).unwrap_or(entry.path());
    let file_name = entry.file_name().to_str().unwrap_or("");
    if file_name.starts_with('_') || file_name.starts_with('.') {
        return false;
    }
    !ignore.iter().any(|p| p.matches_path(path))
}

fn compare_paths(a: &Path, b: &Path) -> bool {
    match (fs::canonicalize(a), fs::canonicalize(b)) {
        (Ok(p), Ok(p2)) => p == p2,
        _ => false,
    }
}

/// The primary build function that tranforms a directory into a site
pub fn build(config: &Config) -> Result<()> {
    trace!("Build configuration: {:?}", config);

    // join("") makes sure path has a trailing slash
    let source = PathBuf::from(&config.source).join("");
    let source = source.as_path();
    let dest = PathBuf::from(&config.dest).join("");
    let dest = dest.as_path();

    let template_extensions: Vec<&OsStr> = config.template_extensions
        .iter()
        .map(OsStr::new)
        .collect();

    let layouts = source.join(&config.layouts);
    let layouts = layouts.as_path();
    let posts = source.join(&config.posts);
    let posts = posts.as_path();

    debug!("Layouts directory: {:?}", layouts);
    debug!("posts directory: {:?}", posts);

    let mut documents = vec![];

    let walker = WalkDir::new(&source)
        .into_iter()
        .filter_entry(|e| {
            (ignore_filter(e, source, &config.ignore) || compare_paths(e.path(), posts)) &&
            !compare_paths(e.path(), dest)
        })
        .filter_map(|e| e.ok());

    for entry in walker {
        let extension = &entry.path().extension().unwrap_or(OsStr::new(""));
        if template_extensions.contains(extension) {
            // if the document is in the posts folder it's considered a post
            let is_post = entry.path().parent().map(|p| compare_paths(p, posts)).unwrap_or(false);

            let doc = try!(Document::parse(&entry.path(), &source, is_post, &config.post_path));
            documents.push(doc);
        }
    }

    // January 1, 1970 0:00:00 UTC, the beginning of time
    let default_date = UTC.timestamp(0, 0).with_timezone(&FixedOffset::east(0));

    // sort documents by date, if there's no date (none was provided or it couldn't be read) then
    // fall back to the default date
    documents.sort_by(|a, b| b.date.unwrap_or(default_date).cmp(&a.date.unwrap_or(default_date)));

    // check if we should create an RSS file and create it!
    if let &Some(ref path) = &config.rss {
        try!(create_rss(path, dest, &config, &documents));
    }

    // these are the attributes of all documents that are posts, so that they can be
    // passed to the renderer
    // TODO: do we have to clone these?
    let post_data: Vec<Value> = documents.iter()
        .filter(|x| x.is_post)
        .map(|x| Value::Object(x.attributes.clone()))
        .collect();

    // thread handles to join later
    let mut handles = vec![];

    // generate documents (in parallel)
    crossbeam::scope(|scope| {
        let post_data = Arc::new(post_data);

        for doc in &documents {
            trace!("Generating {}", doc.path);
            let post_data = post_data.clone();

            let handle = scope.spawn(move || {
                let content = try!(doc.as_html(&source, &post_data, &layouts));
                create_document_file(content, &doc.path, dest)
            });
            handles.push(handle);
        }
    });

    for handle in handles {
        try!(handle.join());
    }

    // copy all remaining files in the source to the destination
    if !compare_paths(source, dest) {
        info!("Copying remaining assets");
        let source_str = try!(source.to_str()
            .ok_or(format!("Cannot convert pathname {:?} to UTF-8", source)));

        let walker = WalkDir::new(&source)
            .into_iter()
            .filter_entry(|e| {
                ignore_filter(e, source, &config.ignore) &&
                !template_extensions.contains(&e.path()
                    .extension()
                    .unwrap_or(OsStr::new(""))) && !compare_paths(e.path(), dest)
            })
            .filter_map(|e| e.ok());

        for entry in walker {
            let entry_path = try!(entry.path()
                .to_str()
                .ok_or(format!("Cannot convert pathname {:?} to UTF-8", entry.path())));

            let relative = try!(entry_path.split(source_str)
                .last()
                .ok_or(format!("Empty path")));

            if try!(entry.metadata()).is_dir() {
                try!(fs::create_dir_all(&dest.join(relative)));
                debug!("Created new directory {:?}", dest.join(relative));
            } else {
                if let Some(ref parent) = Path::new(relative).parent() {
                    try!(fs::create_dir_all(&dest.join(parent)));
                }

                try!(fs::copy(entry.path(), &dest.join(relative))
                    .map_err(|e| format!("Could not copy {:?}: {}", entry.path(), e)));
                debug!("Copied {:?} to {:?}", entry.path(), dest.join(relative));
            }
        }
    }

    Ok(())
}

// creates a new RSS file with the contents of the site blog
fn create_rss(path: &str, dest: &Path, config: &Config, documents: &[Document]) -> Result<()> {
    match (&config.name, &config.description, &config.link) {
        // these three fields are mandatory in the RSS standard
        (&Some(ref name), &Some(ref description), &Some(ref link)) => {
            trace!("Generating RSS data");

            let items = documents.iter()
                .filter(|x| x.is_post)
                .map(|doc| doc.to_rss(link))
                .collect();

            let channel = Channel {
                title: name.to_owned(),
                link: link.to_owned(),
                description: description.to_owned(),
                items: items,
                ..Default::default()
            };

            let rss = Rss(channel);
            let rss_string = rss.to_string();
            trace!("RSS data: {}", rss_string);

            let rss_path = dest.join(path);

            let mut rss_file = try!(File::create(&rss_path));
            try!(rss_file.write_all(&rss_string.into_bytes()));

            info!("Created RSS file at {}", rss_path.display());
            Ok(())
        }
        _ => {
            Err(Error::from("name, description and link need to be defined in the config file to \
                             generate RSS"))
        }
    }
}

/// A slightly less efficient implementation of fs::create_dir_all
/// that eliminates the race condition problems of the original
fn create_dir_all(path: &Path) -> io::Result<()> {
    let mut new_path = PathBuf::new();
    for component in path {
        new_path.push(component);
        match fs::create_dir(&new_path) {
            Ok(_) => {}
            Err(ref e) if e.kind() == ErrorKind::AlreadyExists => {}
            Err(e) => return Err(e),
        }
    }
    Ok(())
}

fn create_document_file<T: AsRef<Path>>(content: String, path: T, dest: &Path) -> Result<()> {
    // construct target path
    let file_path_buf = dest.join(path);
    let file_path = file_path_buf.as_path();

    // create target directories if any exist
    if let Some(parent) = file_path.parent() {
        try!(create_dir_all(parent).map_err(|e| format!("Could not create {:?}: {}", parent, e)));
    }

    let mut file = try!(File::create(&file_path)
        .map_err(|e| format!("Could not create {:?}: {}", file_path, e)));

    try!(file.write_all(&content.into_bytes()));
    info!("Created {}", file_path.display());
    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>Include config file<commit_after><|endoftext|>


<commit_before><commit_msg>Added benchmarks.<commit_after>#![feature(test)]

extern crate cuckoofilter;
extern crate test;
extern crate rand;
#[cfg(feature = "fnv")]
extern crate fnv;
#[cfg(feature = "farmhash")]
extern crate farmhash;

use self::cuckoofilter::*;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::error::Error;

fn get_words() -> String {
  let path = Path::new("/usr/share/dict/words");
  let display = path.display();

  // Open the path in read-only mode, returns `io::Result<File>`
  let mut file = match File::open(&path) {
    // The `description` method of `io::Error` returns a string that
    // describes the error
    Err(why) => panic!("couldn't open {}: {}", display,
                                               Error::description(&why)),
    Ok(file) => file,
  };

  let mut contents = String::new();
  if let Err(why) = file.read_to_string(&mut contents) {
    panic!("couldn't read {}: {}", display, Error::description(&why));
  }
  contents
}

fn perform_insertions<H: std::hash::Hasher + Default>(b: &mut test::Bencher) {
  let contents = get_words();
  let split: Vec<&str> = contents.split("\n").take(1000).collect();
  let mut cf = CuckooFilter::<H>::with_capacity((split.len() * 2) as u64);

  b.iter(|| {
    for s in &split {
      test::black_box(cf.test_and_add(s));
    }
  });
}

#[bench]
fn bench_new(b: &mut test::Bencher) {
  b.iter(|| {
    test::black_box(CuckooFilter::new());
  });
}

#[cfg(feature = "farmhash")]
#[bench]
fn bench_insertion_farmhash(b: &mut test::Bencher) {
  perform_insertions::<farmhash::FarmHasher>(b);
}

#[cfg(feature = "fnv")]
#[bench]
fn bench_insertion_fnv(b: &mut test::Bencher) {
  perform_insertions::<fnv::FnvHasher>(b);
}

#[bench]
fn bench_insertion_sip(b: &mut test::Bencher) {
  perform_insertions::<std::hash::SipHasher>(b);
}
<|endoftext|>


<commit_before><commit_msg>Attempt bigfile.nbt test.<commit_after><|endoftext|>


<commit_before><commit_msg>Add an example for counted flags.<commit_after>extern crate serialize;
extern crate docopt;

use docopt::Docopt;

// This shows how to implement multiple levels of verbosity.
//
// When you have multiple patterns, I think the only way to carry the
// repeated flag through all of them is to specify it for each pattern
// explicitly.
//
// This is unfortunate.
static USAGE: &'static str = "
Usage: cp [options] [-v | -vv | -vvv] <source> <dest>
       cp [options] [-v | -vv | -vvv] <source>... <dir>

Options:
    -a, --archive  Copy everything.
    -v, --verbose  Show extra log output.
";

#[deriving(Decodable, Show)]
struct Args {
    arg_source: Vec<String>,
    arg_dest: String,
    arg_dir: String,
    flag_archive: bool,
    flag_verbose: uint,
}

fn main() {
    let args: Args = Docopt::new(USAGE)
                            .and_then(|d| d.decode())
                            .unwrap_or_else(|e| e.exit());
    println!("{}", args);
}
<|endoftext|>


<commit_before><commit_msg>Fix warning in rustc f09279395 2014-11-17.<commit_after><|endoftext|>


<commit_before><commit_msg>Add new alert fields, fix `Alert::expires` type<commit_after><|endoftext|>


<commit_before><commit_msg>packet: handle ID encoding/decoding in the Packet enums for each state/direction combination<commit_after><|endoftext|>


<commit_before><commit_msg>Added Sized trait bound for traits that requite it<commit_after><|endoftext|>


<commit_before><commit_msg>Use a disabled fallback user when username unknown.<commit_after><|endoftext|>


<commit_before><commit_msg>refactor(scanner): use to_owned instead of clone<commit_after><|endoftext|>


<commit_before>#[macro_use]
extern crate gfx;

gfx_vertex!(_Foo {
    x@ _x: i8,
    y@ _y: f32,
    z@ _z: [u32; 4],
});

gfx_parameters!(_Bar {
    x@ _x: i32,
    y@ _y: [f32; 4],
    b@ _b: gfx::handle::RawBuffer<R>,
    t@ _t: gfx::shade::TextureParam<R>,
});

gfx_structure!(Vertex {
    x@ _x: i8,
    y@ _y: f32,
});

gfx_structure!(Instance {
    alpha@ _alpha: f32,
});

gfx_structure!(Local {
    pos@ _pos: [u32; 4],
});

gfx_tex_format!(Rgba = gfx::tex::RGBA8);
gfx_tex_format!(Depth = gfx::tex::Format::DEPTH24);
/// These should not be allowed, TODO
impl gfx::DepthStencilFormat for Depth {}
impl gfx::DepthFormat for Depth {}

gfx_pipeline_init!( _Data _Meta _Init {
    _vertex: gfx::VertexBuffer<Vertex> = gfx::PER_VERTEX,
    _instance: gfx::VertexBuffer<Instance> = gfx::PER_INSTANCE,
    _const_locals: gfx::ConstantBuffer<Local> = "Locals",
    _gobal: gfx::Constant<[f32; 4]> = "Global",
    //tex_diffuse: TextureView<Dim2, Float4>,
    //tex_normal: TextureView<Dim2, Float3>,
    //sampler_linear: Sampler,
    //buf_noise: BufferView<Int4>,
    //buf_frequency: UnorderedView<Dim2, Int>,
    //pixel_color: gfx::RenderTarget<Rgba> = ("Color", gfx::state::MASK_ALL),
    //depth: gfx::DepthTarget<Depth> = gfx::state::Depth {
    //    fun: gfx::state::Comparison::LessEqual,
    //    write: false,
    //},
});
<commit_msg>PSO - added a compile-time PSO creation test<commit_after>#[macro_use]
extern crate gfx;

gfx_vertex!(_Foo {
    x@ _x: i8,
    y@ _y: f32,
    z@ _z: [u32; 4],
});

gfx_parameters!(_Bar {
    x@ _x: i32,
    y@ _y: [f32; 4],
    b@ _b: gfx::handle::RawBuffer<R>,
    t@ _t: gfx::shade::TextureParam<R>,
});

gfx_structure!(Vertex {
    x@ _x: i8,
    y@ _y: f32,
});

gfx_structure!(Instance {
    alpha@ _alpha: f32,
});

gfx_structure!(Local {
    pos@ _pos: [u32; 4],
});

gfx_tex_format!(Rgba = gfx::tex::RGBA8);
gfx_tex_format!(Depth = gfx::tex::Format::DEPTH24);
/// These should not be allowed, TODO
impl gfx::DepthStencilFormat for Depth {}
impl gfx::DepthFormat for Depth {}

gfx_pipeline_init!( _Data _Meta _Init {
    _vertex: gfx::VertexBuffer<Vertex> = gfx::PER_VERTEX,
    _instance: gfx::VertexBuffer<Instance> = gfx::PER_INSTANCE,
    _const_locals: gfx::ConstantBuffer<Local> = "Locals",
    _gobal: gfx::Constant<[f32; 4]> = "Global",
    //tex_diffuse: TextureView<Dim2, Float4>,
    //tex_normal: TextureView<Dim2, Float3>,
    //sampler_linear: Sampler,
    //buf_noise: BufferView<Int4>,
    //buf_frequency: UnorderedView<Dim2, Int>,
    //pixel_color: gfx::RenderTarget<Rgba> = ("Color", gfx::state::MASK_ALL),
    //depth: gfx::DepthTarget<Depth> = gfx::state::Depth {
    //    fun: gfx::state::Comparison::LessEqual,
    //    write: false,
    //},
});

fn _test_pso<R, F>(factory: &mut F, shaders: &gfx::ShaderSet<R>)
             -> gfx::PipelineState<R, _Meta>  where
    R: gfx::Resources,
    F: gfx::traits::FactoryExt<R>,
{
    use std::default::Default;
    factory.create_pipeline_state(shaders, gfx::Primitive::Point,
        Default::default(), &_Init::new()).unwrap()
}
<|endoftext|>


<commit_before><commit_msg>Back to usize<commit_after><|endoftext|>


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

//! Syntax extensions in the Rust compiler.

#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
       html_root_url = "https://doc.rust-lang.org/nightly/")]

#![feature(proc_macro_internals)]
#![feature(decl_macro)]
#![feature(str_escape)]

#![feature(rustc_diagnostic_macros)]

extern crate fmt_macros;
#[macro_use]
extern crate syntax;
extern crate syntax_pos;
extern crate proc_macro;
extern crate rustc_data_structures;
extern crate rustc_errors as errors;
extern crate rustc_target;

mod diagnostics;

#[macro_use]
// for custom_derive
pub mod deriving;

mod asm;
mod assert;
mod cfg;
mod compile_error;
mod concat;
mod concat_idents;
mod env;
mod format;
mod format_foreign;
mod global_asm;
mod log_syntax;
mod trace_macros;

pub mod proc_macro_registrar;

pub mod proc_macro_impl;

use rustc_data_structures::sync::Lrc;
use syntax::ast;
use syntax::ext::base::{MacroExpanderFn, NormalTT, NamedSyntaxExtension};
use syntax::ext::hygiene;
use syntax::symbol::Symbol;

pub fn register_builtins(resolver: &mut dyn syntax::ext::base::Resolver,
                         user_exts: Vec<NamedSyntaxExtension>,
                         enable_quotes: bool) {
    deriving::register_builtin_derives(resolver);

    let mut register = |name, ext| {
        resolver.add_builtin(ast::Ident::with_empty_ctxt(name), Lrc::new(ext));
    };

    macro_rules! register {
        ($( $name:ident: $f:expr, )*) => { $(
            register(Symbol::intern(stringify!($name)),
                     NormalTT {
                        expander: Box::new($f as MacroExpanderFn),
                        def_info: None,
                        allow_internal_unstable: false,
                        allow_internal_unsafe: false,
                        local_inner_macros: false,
                        unstable_feature: None,
                        edition: hygiene::default_edition(),
                    });
        )* }
    }

    if enable_quotes {
        use syntax::ext::quote::*;
        register! {
            quote_tokens: expand_quote_tokens,
            quote_expr: expand_quote_expr,
            quote_ty: expand_quote_ty,
            quote_item: expand_quote_item,
            quote_pat: expand_quote_pat,
            quote_arm: expand_quote_arm,
            quote_stmt: expand_quote_stmt,
            quote_attr: expand_quote_attr,
            quote_arg: expand_quote_arg,
            quote_block: expand_quote_block,
            quote_meta_item: expand_quote_meta_item,
            quote_path: expand_quote_path,
        }
    }

    use syntax::ext::source_util::*;
    register! {
        line: expand_line,
        __rust_unstable_column: expand_column_gated,
        column: expand_column,
        file: expand_file,
        stringify: expand_stringify,
        include: expand_include,
        include_str: expand_include_str,
        include_bytes: expand_include_bytes,
        module_path: expand_mod,

        asm: asm::expand_asm,
        global_asm: global_asm::expand_global_asm,
        cfg: cfg::expand_cfg,
        concat: concat::expand_syntax_ext,
        concat_idents: concat_idents::expand_syntax_ext,
        env: env::expand_env,
        option_env: env::expand_option_env,
        log_syntax: log_syntax::expand_syntax_ext,
        trace_macros: trace_macros::expand_trace_macros,
        compile_error: compile_error::expand_compile_error,
        assert: assert::expand_assert,
    }

    // format_args uses `unstable` things internally.
    register(Symbol::intern("format_args"),
             NormalTT {
                expander: Box::new(format::expand_format_args),
                def_info: None,
                allow_internal_unstable: true,
                allow_internal_unsafe: false,
                local_inner_macros: false,
                unstable_feature: None,
                edition: hygiene::default_edition(),
            });
    register(Symbol::intern("format_args_nl"),
             NormalTT {
                 expander: Box::new(format::expand_format_args_nl),
                 def_info: None,
                 allow_internal_unstable: true,
                 allow_internal_unsafe: false,
                 local_inner_macros: false,
                 unstable_feature: None,
                 edition: hygiene::default_edition(),
             });

    for (name, ext) in user_exts {
        register(name, ext);
    }
}
<commit_msg>[nll] libsyntax_ext: enable feature(nll) for bootstrap<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.

//! Syntax extensions in the Rust compiler.

#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
       html_root_url = "https://doc.rust-lang.org/nightly/")]

#![feature(proc_macro_internals)]
#![feature(decl_macro)]
#![cfg_attr(not(stage0), feature(nll))]
#![feature(str_escape)]

#![feature(rustc_diagnostic_macros)]

extern crate fmt_macros;
#[macro_use]
extern crate syntax;
extern crate syntax_pos;
extern crate proc_macro;
extern crate rustc_data_structures;
extern crate rustc_errors as errors;
extern crate rustc_target;

mod diagnostics;

#[macro_use]
// for custom_derive
pub mod deriving;

mod asm;
mod assert;
mod cfg;
mod compile_error;
mod concat;
mod concat_idents;
mod env;
mod format;
mod format_foreign;
mod global_asm;
mod log_syntax;
mod trace_macros;

pub mod proc_macro_registrar;

pub mod proc_macro_impl;

use rustc_data_structures::sync::Lrc;
use syntax::ast;
use syntax::ext::base::{MacroExpanderFn, NormalTT, NamedSyntaxExtension};
use syntax::ext::hygiene;
use syntax::symbol::Symbol;

pub fn register_builtins(resolver: &mut dyn syntax::ext::base::Resolver,
                         user_exts: Vec<NamedSyntaxExtension>,
                         enable_quotes: bool) {
    deriving::register_builtin_derives(resolver);

    let mut register = |name, ext| {
        resolver.add_builtin(ast::Ident::with_empty_ctxt(name), Lrc::new(ext));
    };

    macro_rules! register {
        ($( $name:ident: $f:expr, )*) => { $(
            register(Symbol::intern(stringify!($name)),
                     NormalTT {
                        expander: Box::new($f as MacroExpanderFn),
                        def_info: None,
                        allow_internal_unstable: false,
                        allow_internal_unsafe: false,
                        local_inner_macros: false,
                        unstable_feature: None,
                        edition: hygiene::default_edition(),
                    });
        )* }
    }

    if enable_quotes {
        use syntax::ext::quote::*;
        register! {
            quote_tokens: expand_quote_tokens,
            quote_expr: expand_quote_expr,
            quote_ty: expand_quote_ty,
            quote_item: expand_quote_item,
            quote_pat: expand_quote_pat,
            quote_arm: expand_quote_arm,
            quote_stmt: expand_quote_stmt,
            quote_attr: expand_quote_attr,
            quote_arg: expand_quote_arg,
            quote_block: expand_quote_block,
            quote_meta_item: expand_quote_meta_item,
            quote_path: expand_quote_path,
        }
    }

    use syntax::ext::source_util::*;
    register! {
        line: expand_line,
        __rust_unstable_column: expand_column_gated,
        column: expand_column,
        file: expand_file,
        stringify: expand_stringify,
        include: expand_include,
        include_str: expand_include_str,
        include_bytes: expand_include_bytes,
        module_path: expand_mod,

        asm: asm::expand_asm,
        global_asm: global_asm::expand_global_asm,
        cfg: cfg::expand_cfg,
        concat: concat::expand_syntax_ext,
        concat_idents: concat_idents::expand_syntax_ext,
        env: env::expand_env,
        option_env: env::expand_option_env,
        log_syntax: log_syntax::expand_syntax_ext,
        trace_macros: trace_macros::expand_trace_macros,
        compile_error: compile_error::expand_compile_error,
        assert: assert::expand_assert,
    }

    // format_args uses `unstable` things internally.
    register(Symbol::intern("format_args"),
             NormalTT {
                expander: Box::new(format::expand_format_args),
                def_info: None,
                allow_internal_unstable: true,
                allow_internal_unsafe: false,
                local_inner_macros: false,
                unstable_feature: None,
                edition: hygiene::default_edition(),
            });
    register(Symbol::intern("format_args_nl"),
             NormalTT {
                 expander: Box::new(format::expand_format_args_nl),
                 def_info: None,
                 allow_internal_unstable: true,
                 allow_internal_unsafe: false,
                 local_inner_macros: false,
                 unstable_feature: None,
                 edition: hygiene::default_edition(),
             });

    for (name, ext) in user_exts {
        register(name, ext);
    }
}
<|endoftext|>


<commit_before>import dom::base::{nk_div, nk_img, node_data, node_kind, node};
import dom::rcu;
import dom::rcu::reader_methods;
import gfx::geom;
import gfx::geom::{size, rect, point, au};
import util::{tree};

enum box = {
    tree: tree::fields<@box>,
    node: node,
    mut bounds: geom::rect<au>
};

enum ntree { ntree }
impl of tree::rd_tree_ops<node> for ntree {
    fn each_child(node: node, f: fn(node) -> bool) {
        tree::each_child(self, node, f)
    }

    fn with_tree_fields<R>(n: node, f: fn(tree::fields<node>) -> R) -> R {
        n.rd { |n| f(n.tree) }
    }
}

enum btree { btree }
impl of tree::rd_tree_ops<@box> for btree {
    fn each_child(node: @box, f: fn(&&@box) -> bool) {
        tree::each_child(self, node, f)
    }

    fn with_tree_fields<R>(b: @box, f: fn(tree::fields<@box>) -> R) -> R {
        f(b.tree)
    }
}

impl of tree::wr_tree_ops<@box> for btree {
    fn add_child(node: @box, child: @box) {
        tree::add_child(self, node, child)
    }

    fn with_tree_fields<R>(b: @box, f: fn(tree::fields<@box>) -> R) -> R {
        f(b.tree)
    }
}

fn new_box(n: node) -> @box {
    @box({tree: tree::empty(),
          node: n,
          mut bounds: geom::zero_rect_au()})
}

fn linked_box(n: node) -> @box {
    let b = new_box(n);
    n.set_aux(b);
    ret b;
}

fn linked_subtree(p: node) -> @box {
    #debug["linked_subtree root=%?", p.rd() { |r| r.kind }];
    let p_box = linked_box(p);
    for ntree.each_child(p) { |c|
        let c_box = linked_subtree(c);
        btree.add_child(p_box, c_box);
    }
    ret p_box;
}

fn reflow_block(root: @box, available_width: au) {
    // Root here is the root of the reflow, not necessarily the doc as
    // a whole.
    //
    // This routine:
    // - generates root.bounds.size
    // - generates root.bounds.origin for each child
    // - and recursively computes the bounds for each child

    let k = root.node.rd() { |r| r.kind };
    #debug["reflow_block root=%?", k];
    alt k {
      nk_img(size) {
        root.bounds.size = size;
        ret;
      }

      nk_div { /* fallthrough */ }
    }

    let mut current_height = 0;
    for tree::each_child(btree, root) {|c|
        let mut blk_available_width = available_width;
        // FIXME subtract borders, margins, etc
        c.bounds.origin = {mut x: au(0), mut y: au(current_height)};
        reflow_block(c, blk_available_width);
        current_height += *c.bounds.size.height;
    }

    root.bounds.size = {mut width: available_width, // FIXME
                        mut height: au(current_height)};
}

#[cfg(test)]
mod test {
    import dom::base::{nk_img, node_data, node_kind, node, methods,
                       wr_tree_ops};
    import dom::rcu::scope;

    /*
    use sdl;
    import sdl::video;

    fn with_screen(f: fn(*sdl::surface)) {
        let screen = video::set_video_mode(
            320, 200, 32,
            [video::hwsurface], [video::doublebuf]);
        assert screen != ptr::null();

        f(screen);

        video::free_surface(screen);
    }
    */

    fn flat_bounds(root: @box) -> [geom::rect<au>] {
        let mut r = [];
        for tree::each_child(btree, root) {|c|
            r += flat_bounds(c);
        }
        ret r + [root.bounds];
    }

    #[test]
    fn do_layout() {
        let s = scope();

        let n0 = s.new_node(nk_img(size(au(10),au(10))));
        let n1 = s.new_node(nk_img(size(au(10),au(15))));
        let n2 = s.new_node(nk_img(size(au(10),au(20))));
        let n3 = s.new_node(nk_div);

        tree::add_child(s, n3, n0);
        tree::add_child(s, n3, n1);
        tree::add_child(s, n3, n2);

        let b0 = linked_box(n0);
        let b1 = linked_box(n1);
        let b2 = linked_box(n2);
        let b3 = linked_box(n3);

        tree::add_child(btree, b3, b0);
        tree::add_child(btree, b3, b1);
        tree::add_child(btree, b3, b2);

        reflow_block(b3, au(100));
        let fb = flat_bounds(b3);
        #debug["fb=%?", fb];
        assert fb == [geom::box(au(0), au(0), au(10), au(10)),   // n0
                      geom::box(au(0), au(10), au(10), au(15)),  // n1
                      geom::box(au(0), au(25), au(10), au(20)),  // n2
                      geom::box(au(0), au(0), au(100), au(45))]; // n3
    }
}

<commit_msg>better debugging<commit_after>import dom::base::{nk_div, nk_img, node_data, node_kind, node};
import dom::rcu;
import dom::rcu::reader_methods;
import gfx::geom;
import gfx::geom::{size, rect, point, au};
import util::{tree};

enum box = {
    tree: tree::fields<@box>,
    node: node,
    mut bounds: geom::rect<au>
};

enum ntree { ntree }
impl of tree::rd_tree_ops<node> for ntree {
    fn each_child(node: node, f: fn(node) -> bool) {
        tree::each_child(self, node, f)
    }

    fn with_tree_fields<R>(n: node, f: fn(tree::fields<node>) -> R) -> R {
        n.rd { |n| f(n.tree) }
    }
}

enum btree { btree }
impl of tree::rd_tree_ops<@box> for btree {
    fn each_child(node: @box, f: fn(&&@box) -> bool) {
        tree::each_child(self, node, f)
    }

    fn with_tree_fields<R>(b: @box, f: fn(tree::fields<@box>) -> R) -> R {
        f(b.tree)
    }
}

impl of tree::wr_tree_ops<@box> for btree {
    fn add_child(node: @box, child: @box) {
        tree::add_child(self, node, child)
    }

    fn with_tree_fields<R>(b: @box, f: fn(tree::fields<@box>) -> R) -> R {
        f(b.tree)
    }
}

fn new_box(n: node) -> @box {
    @box({tree: tree::empty(),
          node: n,
          mut bounds: geom::zero_rect_au()})
}

fn linked_box(n: node) -> @box {
    let b = new_box(n);
    n.set_aux(b);
    ret b;
}

fn linked_subtree(p: node) -> @box {
    let p_box = linked_box(p);
    for ntree.each_child(p) { |c|
        let c_box = linked_subtree(c);
        btree.add_child(p_box, c_box);
    }
    ret p_box;
}

fn reflow_block(root: @box, available_width: au) {
    // Root here is the root of the reflow, not necessarily the doc as
    // a whole.
    //
    // This routine:
    // - generates root.bounds.size
    // - generates root.bounds.origin for each child
    // - and recursively computes the bounds for each child

    let k = root.node.rd() { |r| r.kind };
    alt k {
      nk_img(size) {
        root.bounds.size = size;
        ret;
      }

      nk_div { /* fallthrough */ }
    }

    let mut current_height = 0;
    for tree::each_child(btree, root) {|c|
        let mut blk_available_width = available_width;
        // FIXME subtract borders, margins, etc
        c.bounds.origin = {mut x: au(0), mut y: au(current_height)};
        reflow_block(c, blk_available_width);
        current_height += *c.bounds.size.height;
    }

    root.bounds.size = {mut width: available_width, // FIXME
                        mut height: au(current_height)};

    #debug["reflow_block root=%? size=%?", k, root.bounds];
}

#[cfg(test)]
mod test {
    import dom::base::{nk_img, node_data, node_kind, node, methods,
                       wr_tree_ops};
    import dom::rcu::scope;

    /*
    use sdl;
    import sdl::video;

    fn with_screen(f: fn(*sdl::surface)) {
        let screen = video::set_video_mode(
            320, 200, 32,
            [video::hwsurface], [video::doublebuf]);
        assert screen != ptr::null();

        f(screen);

        video::free_surface(screen);
    }
    */

    fn flat_bounds(root: @box) -> [geom::rect<au>] {
        let mut r = [];
        for tree::each_child(btree, root) {|c|
            r += flat_bounds(c);
        }
        ret r + [root.bounds];
    }

    #[test]
    fn do_layout() {
        let s = scope();

        let n0 = s.new_node(nk_img(size(au(10),au(10))));
        let n1 = s.new_node(nk_img(size(au(10),au(15))));
        let n2 = s.new_node(nk_img(size(au(10),au(20))));
        let n3 = s.new_node(nk_div);

        tree::add_child(s, n3, n0);
        tree::add_child(s, n3, n1);
        tree::add_child(s, n3, n2);

        let b0 = linked_box(n0);
        let b1 = linked_box(n1);
        let b2 = linked_box(n2);
        let b3 = linked_box(n3);

        tree::add_child(btree, b3, b0);
        tree::add_child(btree, b3, b1);
        tree::add_child(btree, b3, b2);

        reflow_block(b3, au(100));
        let fb = flat_bounds(b3);
        #debug["fb=%?", fb];
        assert fb == [geom::box(au(0), au(0), au(10), au(10)),   // n0
                      geom::box(au(0), au(10), au(10), au(15)),  // n1
                      geom::box(au(0), au(25), au(10), au(20)),  // n2
                      geom::box(au(0), au(0), au(100), au(45))]; // n3
    }
}

<|endoftext|>


<commit_before><commit_msg>Add test: Takuzu (A.K.A. Binairo).<commit_after>//! Takuzu (A.K.A. Binairo).
//!
//! https://en.wikipedia.org/wiki/Takuzu

extern crate puzzle_solver;

use std::iter;
use std::rc::Rc;
use puzzle_solver::*;

const X: Val = -1;

/*--------------------------------------------------------------*/

struct BinaryRepr {
    // value = sum_i 2^i bits[i]
    value: VarToken,
    bits: Vec<VarToken>,
}

impl Constraint for BinaryRepr {
    fn vars<'a>(&'a self) -> Box<Iterator<Item=&'a VarToken> + 'a> {
        Box::new(iter::once(&self.value).chain(&self.bits))
    }

    fn on_assigned(&self, search: &mut PuzzleSearch, var: VarToken, val: Val)
            -> PsResult<()> {
        if var == self.value {
            let mut val = val;
            for &var in self.bits.iter() {
                try!(search.set_candidate(var, val & 1));
                val = val >> 1;
            }
        } else if let Some(bitpos) = self.bits.iter().position(|&v| v == var) {
            let bit = 1 << bitpos;
            let discard = search.get_unassigned(self.value)
                .filter(|c| c & bit != val * bit)
                .collect::<Vec<_>>();

            for c in discard.into_iter() {
                try!(search.remove_candidate(self.value, c));
            }
        }

        Ok(())
    }

    fn substitute(&self, _from: VarToken, _to: VarToken)
            -> PsResult<Rc<Constraint>> {
        unimplemented!();
    }
}

/*--------------------------------------------------------------*/

fn make_sums(size: usize) -> Vec<Val> {
    let mut vec = Vec::new();

    for val in 0..(1 << size) {
        let mut count = 0;
        let mut v = val as usize;

        while v > 0 {
            count = count + (v & 1);
            v = v >> 1;
        }

        if count == size / 2 {
            vec.push(val);
        }
    }

    vec
}

fn make_takuzu(puzzle: &Vec<Vec<Val>>) -> (Puzzle, Vec<Vec<VarToken>>) {
    let height = puzzle.len();
    assert!(height > 0 && height % 2 == 0);
    let width = puzzle[0].len();
    assert!(width > 0 && width % 2 == 0);

    let row_candidates = make_sums(height);
    let col_candidates = make_sums(width);

    let mut sys = Puzzle::new();
    let vars = sys.new_vars_with_candidates_2d(width, height, &[0,1]);
    let row_values = sys.new_vars_with_candidates_1d(height, &row_candidates);
    let col_values = sys.new_vars_with_candidates_1d(width, &col_candidates);

    for y in 0..height {
        let total = (height as Val) / 2;
        sys.equals(total, vars[y].iter().fold(LinExpr::from(0), |sum, &x| sum + x));
        sys.add_constraint(BinaryRepr {
            value: row_values[y],
            bits: vars[y].clone(),
        });
    }

    for x in 0..width {
        let total = (width as Val) / 2;
        sys.equals(total, vars.iter().fold(LinExpr::from(0), |sum, row| sum + row[x]));
        sys.add_constraint(BinaryRepr {
            value: col_values[x],
            bits: (0..height).map(|y| vars[y][x]).collect(),
        });
    }

    // No three in a row, i.e. not: 000, 111.
    for y in 0..height {
        for window in vars[y].windows(3) {
            let disjunction = sys.new_var_with_candidates(&[1,2]);
            sys.equals(window[0] + window[1] + window[2], disjunction);
        }
    }

    for x in 0..width {
        for y in 0..(height - 2) {
            let disjunction = sys.new_var_with_candidates(&[1,2]);
            sys.equals(vars[y + 0][x] + vars[y + 1][x] + vars[y + 2][x], disjunction);
        }
    }

    sys.all_different(&row_values);
    sys.all_different(&col_values);

    for y in 0..height {
        for x in 0..width {
            if puzzle[y][x] != X {
                sys.set_value(vars[y][x], puzzle[y][x]);
            }
        }
    }

    (sys, vars)
}

fn print_takuzu(dict: &Solution, vars: &Vec<Vec<VarToken>>) {
    for row in vars.iter() {
        let sum = row.iter().fold(0, |sum, &var| 2 * sum + dict[var]);
        for &var in row.iter() {
            print!("{}", dict[var]);
        }
        println!(" = {}", sum);
    }
}

fn verify_takuzu(dict: &Solution, vars: &Vec<Vec<VarToken>>, expected: &[Val]) {
    for (row, &expected) in vars.iter().zip(expected) {
        let sum = row.iter().fold(0, |sum, &var| 2 * sum + dict[var]);
        assert_eq!(sum, expected);
    }
}

#[test]
fn takuzu_grid1() {
    let puzzle = vec![
        vec![ X,1,0,X,X,X ],
        vec![ 1,X,X,X,0,X ],
        vec![ X,X,0,X,X,X ],
        vec![ 1,1,X,X,1,0 ],
        vec![ X,X,X,X,0,X ],
        vec![ X,X,X,X,X,X ] ];

    let (mut sys, vars) = make_takuzu(&puzzle);
    let solutions = sys.solve_all();
    assert_eq!(solutions.len(), 6);

    print_takuzu(&solutions[0], &vars);
    println!("takuzu_grid1: {} guesses", sys.num_guesses());
}

#[test]
fn takuzu_grid2() {
    let puzzle = vec![
        vec![ 0,X,X,X,X,1,1,X,X,0,X,X ],
        vec![ X,X,X,1,X,X,X,0,X,X,X,X ],
        vec![ X,0,X,X,X,X,1,X,X,X,0,0 ],
        vec![ 1,X,X,1,X,X,1,1,X,X,X,1 ],
        vec![ X,X,X,X,X,X,X,X,X,1,X,X ],
        vec![ 0,X,0,X,X,X,1,X,X,X,X,X ],
        vec![ X,X,X,X,0,X,X,X,X,X,X,X ],
        vec![ X,X,X,X,0,1,X,0,X,X,X,X ],
        vec![ X,X,0,0,X,X,0,X,0,X,X,0 ],
        vec![ X,X,X,X,X,1,X,X,X,X,1,X ],
        vec![ 1,0,X,0,X,X,X,X,X,X,X,X ],
        vec![ X,X,1,X,X,X,X,1,X,X,0,0 ] ];

    let expected = [
        0b_010101101001,
        0b_010101001011,
        0b_101010110100,
        0b_100100110011,
        0b_011011001100,
        0b_010010110011,
        0b_101100101010,
        0b_001101001101,
        0b_110010010110,
        0b_010101101010,
        0b_101010010101,
        0b_101011010100 ];

    let (mut sys, vars) = make_takuzu(&puzzle);
    let dict = sys.solve_unique().expect("solution");
    print_takuzu(&dict, &vars);
    verify_takuzu(&dict, &vars, &expected);
    println!("takuzu_grid2: {} guesses", sys.num_guesses());
}

#[test]
fn takuzu_grid3() {
    let puzzle = vec![
        vec![ X,X,X,0,X,0,X,X,X,X,0,X ],
        vec![ 1,X,X,X,X,X,X,1,X,X,X,1 ],
        vec![ X,X,1,1,X,X,X,X,X,X,0,X ],
        vec![ X,0,X,X,X,X,X,X,X,X,X,0 ],
        vec![ X,X,X,0,X,X,1,1,0,X,X,X ],
        vec![ 0,X,0,0,X,0,X,1,X,X,0,X ],
        vec![ X,X,X,X,X,X,0,X,X,X,0,X ],
        vec![ 1,X,1,X,0,X,X,X,X,X,X,X ],
        vec![ X,X,X,X,X,X,1,0,1,X,0,X ],
        vec![ X,1,X,X,0,X,X,X,X,0,0,X ],
        vec![ X,X,X,1,X,X,X,0,X,X,X,X ],
        vec![ X,X,X,X,X,1,1,X,X,1,X,X ] ];

    let expected = [
        0b_101010011001,
        0b_110010010011,
        0b_001101101100,
        0b_101101001010,
        0b_010010110011,
        0b_010010110101,
        0b_101101001100,
        0b_101101010010,
        0b_010010101101,
        0b_011001011001,
        0b_100110100110,
        0b_010101100110 ];

    let (mut sys, vars) = make_takuzu(&puzzle);
    let dict = sys.solve_unique().expect("solution");
    print_takuzu(&dict, &vars);
    verify_takuzu(&dict, &vars, &expected);
    println!("takuzu_grid3: {} guesses", sys.num_guesses());
}

#[test]
fn takuzu_grid4() {
    let puzzle = vec![
        vec![ X,X,X,X,X,1,1,X,X,0,X,X ],
        vec![ X,X,X,1,X,X,X,0,X,X,X,X ],
        vec![ X,0,X,X,X,X,1,X,X,X,0,0 ],
        vec![ X,X,X,1,X,X,1,1,X,X,X,1 ],
        vec![ X,X,X,X,X,X,X,X,X,1,X,X ],
        vec![ X,X,0,X,X,X,1,X,X,X,X,X ],
        vec![ X,X,X,X,0,X,X,X,X,X,X,X ],
        vec![ X,X,X,X,0,1,X,0,X,X,X,X ],
        vec![ X,X,0,0,X,X,0,X,0,X,X,0 ],
        vec![ X,X,X,X,X,1,X,X,X,X,1,X ],
        vec![ X,X,X,0,X,X,X,X,X,X,X,X ],
        vec![ X,X,1,X,X,X,X,1,X,X,0,0 ] ];

    let (mut sys, vars) = make_takuzu(&puzzle);
    let dict = &sys.solve_any().expect("solution");
    print_takuzu(&dict, &vars);
    println!("takuzu_grid4: {} guesses", sys.num_guesses());
}
<|endoftext|>


<commit_before><commit_msg>added pangram.rs<commit_after>use std::io;
fn isPangram(s: String) -> bool {
    let mut small_alpha = 0;
    let mut stripped = String::new();
    for i in s.chars() {
        if i.is_alphabetic() {
            if stripped.contains(i.to_lowercase().next().unwrap()) {
            } else {
                stripped.push(i.to_lowercase().next().unwrap());
            }
        }
    }
    for i in stripped.chars() {
        match i {
            'a' ... 'z' => small_alpha+=1,
            _ => {},
        }
    }
    println!("{:?}",small_alpha );
    if small_alpha == 26 {true} else {false}
}
fn main() {
    let mut phrase = String::new();
    phrase.push_str("The quick br87686576own fox #$%%$^#jumps over the lazy dog");
    if isPangram(phrase) {
        println!("Yes\n");
    }
    else {
        println!("No\n");
    }
}
<|endoftext|>


<commit_before><commit_msg>Create prime.rs<commit_after>use std::io;

fn is_prime(n: i32) -> bool {
    for a in 2..n {
        if n % a == 0 {
            return false;
        }
    }
    true
}

fn main() {
    println!("Enter value");
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    let n: i32 = input.trim().parse().unwrap();
    for i in 2..n{
        if(is_prime(i)){
            println!("{}", i);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Remove unnecessary print arg<commit_after><|endoftext|>


<commit_before><commit_msg>Emu time should be delta from start time<commit_after><|endoftext|>


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


<commit_before><commit_msg>Fail if the shutdown task fails.<commit_after><|endoftext|>


<commit_before><commit_msg>Add 2015 day 11 solution<commit_after>fn get_alphabet() -> Vec<char> {
    "abcdefghijklmnopqrstuvwxyz".chars().collect()
}

struct AlphaIterator {
    alphabet: Vec<char>,
    value: String
}

impl AlphaIterator {
    fn new(init_value: &str) -> AlphaIterator {
        AlphaIterator {
            alphabet: get_alphabet(),
            value: init_value.to_string()
        }
    }
}

impl Iterator for AlphaIterator {
    type Item = String;

    fn next(&mut self) -> Option<Self::Item> {
        let mut chars = self.value.chars().collect::<Vec<_>>();
        if chars.len() == 0 {
            return Some("a".to_string());
        }

        let mut bump = true;

        for i in (0..chars.len()).rev() {
            if !bump {
                break;
            }

            let c = chars[i];
            let index = self.alphabet.iter().position(|&a| a == c).unwrap();

            bump = index + 1 == self.alphabet.len();
            let c = self.alphabet[(index + 1) % self.alphabet.len()];

            chars[i] = c;
        }

        self.value = chars.into_iter().fold(String::new(), |mut acc, c| {
            acc.push(c);
            acc
        });

        Some(self.value.clone())
    }
}

fn valid_pwd(alphabet: &Vec<char>, string: &str) -> bool {
    // Passwords must include one increasing straight of at least three letters
    alphabet.windows(3).map(|window| {
        window.iter().fold(String::new(), |mut acc, &c| {
            acc.push(c);
            acc
        })
    }).any(|abc| string.contains(&abc))

    // Passwords may not contain certain letters
    && ['i', 'o', 'l'].iter().all(|&c| !string.contains(c))

    // Passwords must contain at least two different, non-overlapping pairs of letters
    && {
        let chars = string.chars().collect::<Vec<_>>();

        (0..chars.len() - 3).any(|i| {
            chars[i] == chars[i + 1]
            && (i + 2..chars.len() - 1).any(|j| {
                chars[j] == chars[j + 1]
            })
        })
    }
}

fn main() {
    let input = "hxbxwxba";
    let alphabet = get_alphabet();
    let iterator = AlphaIterator::new(input);

    let mut passwords = iterator
        .filter(|string| valid_pwd(&alphabet, &string));

    println!("Part 1: {}", passwords.nth(0).unwrap());
    println!("Part 2: {}", passwords.nth(0).unwrap());
}
<|endoftext|>


<commit_before><commit_msg>Define data types for 2015 day 22<commit_after>use EffectClass::*;

#[derive(Debug, Copy, Clone)]
struct Character {
    hp: i32,
    mana: i32,
    damage: i32
}

impl Character {
    fn new(hp: i32) -> Character {
        Character {hp, mana: 0, damage: 0}
    }
}

#[derive(Debug, Copy, Clone, PartialEq)]
enum EffectClass {
    Shield,
    Poison,
    Recharge
}

#[derive(Debug, Copy, Clone)]
struct Effect {
    turns: i32,
    intensity: i32,
    class: EffectClass
}

#[derive(Debug, Copy, Clone)]
struct Spell {
    cost: i32,
    damage: i32,
    healing: i32,
    effect: Option<Effect>
}

#[derive(Debug, Clone)]
struct State {
    player: Character,
    boss: Character,
    effects: Vec<Effect>
}

fn main() {
    let spells = vec![
        Spell {
            cost: 53,
            damage: 4,
            healing: 0,
            effect: None
        },
        Spell {
            cost: 73,
            damage: 2,
            healing: 2,
            effect: None
        },
        Spell {
            cost: 113,
            damage: 0,
            healing: 0,
            effect: Some(Effect {turns: 6, intensity: 7, class: Shield})
        },
        Spell {
            cost: 173,
            damage: 0,
            healing: 0,
            effect: Some(Effect {turns: 6, intensity: 3, class: Poison})
        },
        Spell {
            cost: 229,
            damage: 0,
            healing: 0,
            effect: Some(Effect {turns: 5, intensity: 101, class: Recharge})
        }
    ];

    let boss = Character {
        hp: 51,
        mana: 0,
        damage: 9
    };

    let player = Character {
        hp: 50,
        mana: 500,
        damage: 0
    };
}
<|endoftext|>


<commit_before><commit_msg>Fix: Collapse nested if<commit_after><|endoftext|>


<commit_before><commit_msg>Test case for issue #115.<commit_after>//xfail-stage1
//xfail-stage2
//xfail-stage3

// Test case for issue #115.
type base =
  obj {
    fn foo();
  };

obj derived() {
  fn foo() {}
  fn bar() {}
}

fn main() {
  let d = derived();
  let b:base = d as base;
}
<|endoftext|>