<commit_before><commit_msg>Add integration test for appending to files<commit_after>// Hound -- A wav encoding and decoding library in Rust
// Copyright 2018 Ruud van Asseldonk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// A copy of the License has been included in the root of the repository.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::fs;

extern crate hound;

fn assert_contents(fname: &str, expected: &[i16]) {
    let mut reader = hound::WavReader::open(fname).unwrap();
    let samples: Vec<i16> = reader.samples().map(|s| s.unwrap()).collect();
    assert_eq!(&samples[..], expected);
}

#[test]
fn append_works_on_files_not_just_in_memory() {
    let spec = hound::WavSpec {
        channels: 1,
        sample_rate: 44100,
        bits_per_sample: 16,
        sample_format: hound::SampleFormat::Int,
    };

    let mut writer = hound::WavWriter::create("append.wav", spec).unwrap();
    writer.write_sample(11_i16).unwrap();
    writer.write_sample(13_i16).unwrap();
    writer.write_sample(17_i16).unwrap();
    writer.finalize().unwrap();

    assert_contents("append.wav", &[11, 13, 17]);

    let len = fs::metadata("append.wav").unwrap().len();

    let mut appender = hound::WavWriter::append("append.wav").unwrap();

    appender.write_sample(19_i16).unwrap();
    appender.write_sample(23_i16).unwrap();
    appender.finalize().unwrap();

    // We appended four bytes of audio data (2 16-bit samples), so the file
    // should have grown by 4 bytes.
    assert_eq!(fs::metadata("append.wav").unwrap().len(), len + 4);

    assert_contents("append.wav", &[11, 13, 17, 19, 23]);
}
<|endoftext|>


<commit_before>#![crate_name = "serde_macros"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]

#![feature(plugin_registrar, quote)]

extern crate syntax;
extern crate rustc;

use std::gc::Gc;

use syntax::ast::{
    Ident,
    MetaItem,
    Item,
    Expr,
    MutMutable,
    LitNil,
};
use syntax::ast;
use syntax::codemap::Span;
use syntax::ext::base::{ExtCtxt, ItemDecorator};
use syntax::ext::build::AstBuilder;
use syntax::ext::deriving::generic::{
    EnumMatching,
    FieldInfo,
    MethodDef,
    Named,
    StaticFields,
    StaticStruct,
    StaticEnum,
    Struct,
    Substructure,
    TraitDef,
    Unnamed,
    combine_substructure,
};
use syntax::ext::deriving::generic::ty::{
    Borrowed,
    LifetimeBounds,
    Literal,
    Path,
    Ptr,
    Self,
    Tuple,
    borrowed_explicit_self,
};
use syntax::parse::token;

use rustc::plugin::Registry;

#[plugin_registrar]
#[doc(hidden)]
pub fn plugin_registrar(reg: &mut Registry) {
    reg.register_syntax_extension(
        token::intern("deriving_serializable"),
        ItemDecorator(expand_deriving_serializable));

    reg.register_syntax_extension(
        token::intern("deriving_deserializable"),
        ItemDecorator(expand_deriving_deserializable));
}

fn expand_deriving_serializable(cx: &mut ExtCtxt,
                                sp: Span,
                                mitem: Gc<MetaItem>,
                                item: Gc<Item>,
                                push: |Gc<ast::Item>|) {
    let inline = cx.meta_word(sp, token::InternedString::new("inline"));
    let attrs = vec!(cx.attribute(sp, inline));

    let trait_def = TraitDef {
        span: sp,
        attributes: vec!(),
        path: Path::new(vec!("serde", "ser", "Serializable")),
        additional_bounds: Vec::new(),
        generics: LifetimeBounds::empty(),
        methods: vec!(
            MethodDef {
                name: "serialize",
                generics: LifetimeBounds {
                    lifetimes: Vec::new(),
                    bounds: vec!(
                        (
                            "__S",
                            None,
                            vec!(
                                Path::new_(
                                    vec!("serde", "ser", "Serializer"),
                                    None,
                                    vec!(box Literal(Path::new_local("__E"))),
                                    true
                                )
                            ),
                        ),
                        (
                            "__E",
                            None,
                            vec!(),
                        ),
                    )
                },
                explicit_self: borrowed_explicit_self(),
                args: vec!(Ptr(box Literal(Path::new_local("__S")),
                            Borrowed(None, MutMutable))),
                ret_ty: Literal(
                    Path::new_(
                        vec!("std", "result", "Result"),
                        None,
                        vec!(
                            box Tuple(Vec::new()),
                            box Literal(Path::new_local("__E"))
                        ),
                        true
                    )
                ),
                attributes: attrs,
                combine_substructure: combine_substructure(|a, b, c| {
                    serializable_substructure(a, b, c)
                }),
            })
    };

    trait_def.expand(cx, mitem, item, push)
}

fn serializable_substructure(cx: &ExtCtxt, span: Span,
                          substr: &Substructure) -> Gc<Expr> {
    let serializer = substr.nonself_args[0];

    return match *substr.fields {
        Struct(ref fields) => {
            if fields.is_empty() {
                // unit structs have no fields and need to return `Ok()`
                quote_expr!(cx, Ok(()))
            } else {
                let type_name = cx.expr_str(
                    span,
                    token::get_ident(substr.type_ident)
                );
                let len = fields.len();

                let mut stmts: Vec<Gc<ast::Stmt>> = fields.iter()
                    .enumerate()
                    .map(|(i, &FieldInfo { name, self_, span, .. })| {
                        let name = match name {
                            Some(id) => token::get_ident(id),
                            None => token::intern_and_get_ident(format!("_field{}", i).as_slice()),
                        };

                        let name = cx.expr_str(span, name);

                        quote_stmt!(
                            cx,
                            try!($serializer.serialize_struct_elt($name, &$self_))
                        )
                    })
                    .collect();

                quote_expr!(cx, {
                    try!($serializer.serialize_struct_start($type_name, $len));
                    $stmts
                    $serializer.serialize_struct_end()
                })
            }
        }

        EnumMatching(_idx, variant, ref fields) => {
            let type_name = cx.expr_str(
                span,
                token::get_ident(substr.type_ident)
            );
            let variant_name = cx.expr_str(
                span,
                token::get_ident(variant.node.name)
            );
            let len = fields.len();

            let stmts: Vec<Gc<ast::Stmt>> = fields.iter()
                .map(|&FieldInfo { self_, span, .. }| {
                    quote_stmt!(
                        cx,
                        try!($serializer.serialize_enum_elt(&$self_))
                    )
                })
                .collect();

            quote_expr!(cx, {
                try!($serializer.serialize_enum_start($type_name, $variant_name, $len));
                $stmts
                $serializer.serialize_enum_end()
            })
        }

        _ => cx.bug("expected Struct or EnumMatching in deriving_serializable")
    }
}

pub fn expand_deriving_deserializable(cx: &mut ExtCtxt,
                                      span: Span,
                                      mitem: Gc<MetaItem>,
                                      item: Gc<Item>,
                                      push: |Gc<Item>|) {
    let trait_def = TraitDef {
        span: span,
        attributes: Vec::new(),
        path: Path::new(vec!("serde", "de", "Deserializable")),
        additional_bounds: Vec::new(),
        generics: LifetimeBounds::empty(),
        methods: vec!(
            MethodDef {
                name: "deserialize_token",
                generics: LifetimeBounds {
                    lifetimes: Vec::new(),
                    bounds: vec!(
                        (
                            "__D",
                            None,
                            vec!(
                                Path::new_(
                                    vec!("serde", "de", "Deserializer"),
                                    None,
                                    vec!(
                                        box Literal(Path::new_local("__E"))
                                    ),
                                    true
                                )
                            )
                        ),
                        (
                            "__E",
                            None,
                            vec!(),
                        ),
                    )
                },
                explicit_self: None,
                args: vec!(
                    Ptr(
                        box Literal(Path::new_local("__D")),
                        Borrowed(None, MutMutable)
                    ),
                    Literal(Path::new(vec!("serde", "de", "Token"))),
                ),
                ret_ty: Literal(
                    Path::new_(
                        vec!("std", "result", "Result"),
                        None,
                        vec!(
                            box Self,
                            box Literal(Path::new_local("__E"))
                        ),
                        true
                    )
                ),
                attributes: Vec::new(),
                combine_substructure: combine_substructure(|a, b, c| {
                    deserializable_substructure(a, b, c)
                }),
            })
    };

    trait_def.expand(cx, mitem, item, push)
}

fn deserializable_substructure(cx: &mut ExtCtxt, span: Span,
                               substr: &Substructure) -> Gc<Expr> {
    let deserializer = substr.nonself_args[0];
    let token = substr.nonself_args[1];

    match *substr.fields {
        StaticStruct(_, ref fields) => {
            deserialize_struct(
                cx,
                span,
                substr.type_ident,
                fields,
                deserializer,
                token)
        }
        StaticEnum(_, ref fields) => {
            deserialize_enum(
                cx,
                span,
                substr.type_ident,
                fields.as_slice(),
                deserializer,
                token)
        }
        _ => cx.bug("expected StaticEnum or StaticStruct in deriving(Deserializable)")
    }
}

fn deserialize_struct(
    cx: &ExtCtxt,
    span: Span,
    type_ident: Ident,
    fields: &StaticFields,
    deserializer: Gc<ast::Expr>,
    token: Gc<ast::Expr>
) -> Gc<ast::Expr> {
    let struct_block = deserialize_struct_from_struct(
        cx,
        span,
        type_ident,
        fields,
        deserializer
    );

    let map_block = deserialize_struct_from_map(
        cx,
        span,
        type_ident,
        fields,
        deserializer
    );

    quote_expr!(
        cx,
        match $token {
            ::serde::de::StructStart(_, _) => $struct_block,
            ::serde::de::MapStart(_) => $map_block,
            _ => $deserializer.syntax_error(),
        }
    )
}

fn deserialize_struct_from_struct(
    cx: &ExtCtxt,
    span: Span,
    type_ident: Ident,
    fields: &StaticFields,
    deserializer: Gc<ast::Expr>
) -> Gc<ast::Expr> {
    let mut stmts = vec!();

    let expect_struct_field = cx.ident_of("expect_struct_field");

    let call = deserializable_static_fields(
        cx,
        span,
        type_ident,
        fields,
        |cx, span, name| {
            cx.expr_try(span,
                cx.expr_method_call(
                    span,
                    deserializer,
                    expect_struct_field,
                    vec!(
                        cx.expr_str(span, name),
                    )
                )
            )
        }
    );

    let result = cx.ident_of("result");

    stmts.push(
        cx.stmt_let(span, false, result, call)
    );

    let call = cx.expr_method_call(
        span,
        deserializer,
        cx.ident_of("expect_struct_end"),
        vec!()
    );
    let call = cx.expr_try(span, call);
    stmts.push(cx.stmt_expr(call));

    let expr = cx.expr_ok(span, cx.expr_ident(span, result));

    cx.expr_block(
        cx.block(
            span,
            stmts,
            Some(expr)
        )
    )
}

fn deserialize_struct_from_map(
    cx: &ExtCtxt,
    span: Span,
    type_ident: Ident,
    fields: &StaticFields,
    deserializer: Gc<ast::Expr>
) -> Gc<ast::Expr> {
    let fields = match *fields {
        Unnamed(_) => fail!(),
        Named(ref fields) => fields.as_slice(),
    };

    // Declare each field.
    let let_fields: Vec<Gc<ast::Stmt>> = fields.iter()
        .map(|&(name, span)| {
            quote_stmt!(cx, let mut $name = None)
        })
        .collect();

    // Declare key arms.
    let key_arms: Vec<ast::Arm> = fields.iter()
        .map(|&(name, span)| {
            let s = cx.expr_str(span, token::get_ident(name));
            quote_arm!(cx,
                $s => {
                    $name = Some(
                        try!(::serde::de::Deserializable::deserialize($deserializer))
                    );
                })
        })
        .collect();

    let fields_tuple = cx.expr_tuple(
        span,
        fields.iter()
            .map(|&(name, span)| {
                cx.expr_ident(span, name)
            })
            .collect()
    );

    let fields_pats: Vec<Gc<ast::Pat>> = fields.iter()
        .map(|&(name, span)| {
            quote_pat!(cx, Some($name))
        })
        .collect();

    let fields_pat = cx.pat_tuple(span, fields_pats);

    let result = cx.expr_struct_ident(
        span,
        type_ident,
        fields.iter()
            .map(|&(name, span)| {
                cx.field_imm(span, name, cx.expr_ident(span, name))
            })
            .collect()
    );

    quote_expr!(cx, {
        $let_fields

        loop {
            let token = match try!($deserializer.expect_token()) {
                ::serde::de::End => { break; }
                token => token,
            };

            let key = match token {
                ::serde::de::Str(s) => s,
                ::serde::de::String(ref s) => s.as_slice(),
                _ => { return $deserializer.syntax_error(); }
            };

            match key {
                $key_arms
                _ => { return $deserializer.syntax_error(); }
            }
        }

        let result = match $fields_tuple {
            $fields_pat => $result,
            _ => { return $deserializer.syntax_error(); }
        };

        try!($deserializer.expect_struct_end());

        Ok(result)
    })
}

fn deserialize_enum(
    cx: &ExtCtxt,
    span: Span,
    type_ident: Ident,
    fields: &[(Ident, Span, StaticFields)],
    deserializer: Gc<ast::Expr>,
    token: Gc<ast::Expr>
) -> Gc<ast::Expr> {
    let type_name = cx.expr_str(span, token::get_ident(type_ident));

    let variants = fields.iter()
        .map(|&(name, span, _)| {
            cx.expr_str(span, token::get_ident(name))
        })
        .collect();

    let variants = cx.expr_vec(span, variants);

    let arms: Vec<ast::Arm> = fields.iter()
        .enumerate()
        .map(|(i, &(name, span, ref parts))| {
            let call = deserializable_static_fields(
                cx,
                span,
                name,
                parts,
                |cx, span, _| {
                    quote_expr!(cx, try!($deserializer.expect_enum_elt()))
                }
            );

            quote_arm!(cx, $i => $call,)
        })
        .collect();

    quote_expr!(cx, {
        let i = try!($deserializer.expect_enum_start($token, $type_name, $variants));

        let result = match i {
            $arms
            _ => { unreachable!() }
        };

        try!($deserializer.expect_enum_end());

        Ok(result)
    })
}

/// Create a deserializer for a single enum variant/struct:
/// - `outer_pat_ident` is the name of this enum variant/struct
/// - `getarg` should retrieve the `uint`-th field with name `&str`.
fn deserializable_static_fields(
    cx: &ExtCtxt,
    span: Span,
    outer_pat_ident: Ident,
    fields: &StaticFields,
    getarg: |&ExtCtxt, Span, token::InternedString| -> Gc<Expr>
) -> Gc<Expr> {
    match *fields {
        Unnamed(ref fields) => {
            if fields.is_empty() {
                cx.expr_ident(span, outer_pat_ident)
            } else {
                let fields = fields.iter().enumerate().map(|(i, &span)| {
                    getarg(
                        cx,
                        span,
                        token::intern_and_get_ident(format!("_field{}", i).as_slice())
                    )
                }).collect();

                cx.expr_call_ident(span, outer_pat_ident, fields)
            }
        }
        Named(ref fields) => {
            // use the field's span to get nicer error messages.
            let fields = fields.iter().map(|&(name, span)| {
                let arg = getarg(
                    cx,
                    span,
                    token::get_ident(name)
                );
                cx.field_imm(span, name, arg)
            }).collect();

            cx.expr_struct_ident(span, outer_pat_ident, fields)
        }
    }
}
<commit_msg>More simplifications<commit_after>#![crate_name = "serde_macros"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]

#![feature(plugin_registrar, quote)]

extern crate syntax;
extern crate rustc;

use std::gc::Gc;

use syntax::ast::{
    Ident,
    MetaItem,
    Item,
    Expr,
    MutMutable,
    LitNil,
};
use syntax::ast;
use syntax::codemap::Span;
use syntax::ext::base::{ExtCtxt, ItemDecorator};
use syntax::ext::build::AstBuilder;
use syntax::ext::deriving::generic::{
    EnumMatching,
    FieldInfo,
    MethodDef,
    Named,
    StaticFields,
    StaticStruct,
    StaticEnum,
    Struct,
    Substructure,
    TraitDef,
    Unnamed,
    combine_substructure,
};
use syntax::ext::deriving::generic::ty::{
    Borrowed,
    LifetimeBounds,
    Literal,
    Path,
    Ptr,
    Self,
    Tuple,
    borrowed_explicit_self,
};
use syntax::parse::token;

use rustc::plugin::Registry;

#[plugin_registrar]
#[doc(hidden)]
pub fn plugin_registrar(reg: &mut Registry) {
    reg.register_syntax_extension(
        token::intern("deriving_serializable"),
        ItemDecorator(expand_deriving_serializable));

    reg.register_syntax_extension(
        token::intern("deriving_deserializable"),
        ItemDecorator(expand_deriving_deserializable));
}

fn expand_deriving_serializable(cx: &mut ExtCtxt,
                                sp: Span,
                                mitem: Gc<MetaItem>,
                                item: Gc<Item>,
                                push: |Gc<ast::Item>|) {
    let inline = cx.meta_word(sp, token::InternedString::new("inline"));
    let attrs = vec!(cx.attribute(sp, inline));

    let trait_def = TraitDef {
        span: sp,
        attributes: vec!(),
        path: Path::new(vec!("serde", "ser", "Serializable")),
        additional_bounds: Vec::new(),
        generics: LifetimeBounds::empty(),
        methods: vec!(
            MethodDef {
                name: "serialize",
                generics: LifetimeBounds {
                    lifetimes: Vec::new(),
                    bounds: vec!(
                        (
                            "__S",
                            None,
                            vec!(
                                Path::new_(
                                    vec!("serde", "ser", "Serializer"),
                                    None,
                                    vec!(box Literal(Path::new_local("__E"))),
                                    true
                                )
                            ),
                        ),
                        (
                            "__E",
                            None,
                            vec!(),
                        ),
                    )
                },
                explicit_self: borrowed_explicit_self(),
                args: vec!(Ptr(box Literal(Path::new_local("__S")),
                            Borrowed(None, MutMutable))),
                ret_ty: Literal(
                    Path::new_(
                        vec!("std", "result", "Result"),
                        None,
                        vec!(
                            box Tuple(Vec::new()),
                            box Literal(Path::new_local("__E"))
                        ),
                        true
                    )
                ),
                attributes: attrs,
                combine_substructure: combine_substructure(|a, b, c| {
                    serializable_substructure(a, b, c)
                }),
            })
    };

    trait_def.expand(cx, mitem, item, push)
}

fn serializable_substructure(cx: &ExtCtxt, span: Span,
                          substr: &Substructure) -> Gc<Expr> {
    let serializer = substr.nonself_args[0];

    return match *substr.fields {
        Struct(ref fields) => {
            if fields.is_empty() {
                // unit structs have no fields and need to return `Ok()`
                quote_expr!(cx, Ok(()))
            } else {
                let type_name = cx.expr_str(
                    span,
                    token::get_ident(substr.type_ident)
                );
                let len = fields.len();

                let mut stmts: Vec<Gc<ast::Stmt>> = fields.iter()
                    .enumerate()
                    .map(|(i, &FieldInfo { name, self_, span, .. })| {
                        let name = match name {
                            Some(id) => token::get_ident(id),
                            None => token::intern_and_get_ident(format!("_field{}", i).as_slice()),
                        };

                        let name = cx.expr_str(span, name);

                        quote_stmt!(
                            cx,
                            try!($serializer.serialize_struct_elt($name, &$self_))
                        )
                    })
                    .collect();

                quote_expr!(cx, {
                    try!($serializer.serialize_struct_start($type_name, $len));
                    $stmts
                    $serializer.serialize_struct_end()
                })
            }
        }

        EnumMatching(_idx, variant, ref fields) => {
            let type_name = cx.expr_str(
                span,
                token::get_ident(substr.type_ident)
            );
            let variant_name = cx.expr_str(
                span,
                token::get_ident(variant.node.name)
            );
            let len = fields.len();

            let stmts: Vec<Gc<ast::Stmt>> = fields.iter()
                .map(|&FieldInfo { self_, span, .. }| {
                    quote_stmt!(
                        cx,
                        try!($serializer.serialize_enum_elt(&$self_))
                    )
                })
                .collect();

            quote_expr!(cx, {
                try!($serializer.serialize_enum_start($type_name, $variant_name, $len));
                $stmts
                $serializer.serialize_enum_end()
            })
        }

        _ => cx.bug("expected Struct or EnumMatching in deriving_serializable")
    }
}

pub fn expand_deriving_deserializable(cx: &mut ExtCtxt,
                                      span: Span,
                                      mitem: Gc<MetaItem>,
                                      item: Gc<Item>,
                                      push: |Gc<Item>|) {
    let trait_def = TraitDef {
        span: span,
        attributes: Vec::new(),
        path: Path::new(vec!("serde", "de", "Deserializable")),
        additional_bounds: Vec::new(),
        generics: LifetimeBounds::empty(),
        methods: vec!(
            MethodDef {
                name: "deserialize_token",
                generics: LifetimeBounds {
                    lifetimes: Vec::new(),
                    bounds: vec!(
                        (
                            "__D",
                            None,
                            vec!(
                                Path::new_(
                                    vec!("serde", "de", "Deserializer"),
                                    None,
                                    vec!(
                                        box Literal(Path::new_local("__E"))
                                    ),
                                    true
                                )
                            )
                        ),
                        (
                            "__E",
                            None,
                            vec!(),
                        ),
                    )
                },
                explicit_self: None,
                args: vec!(
                    Ptr(
                        box Literal(Path::new_local("__D")),
                        Borrowed(None, MutMutable)
                    ),
                    Literal(Path::new(vec!("serde", "de", "Token"))),
                ),
                ret_ty: Literal(
                    Path::new_(
                        vec!("std", "result", "Result"),
                        None,
                        vec!(
                            box Self,
                            box Literal(Path::new_local("__E"))
                        ),
                        true
                    )
                ),
                attributes: Vec::new(),
                combine_substructure: combine_substructure(|a, b, c| {
                    deserializable_substructure(a, b, c)
                }),
            })
    };

    trait_def.expand(cx, mitem, item, push)
}

fn deserializable_substructure(cx: &mut ExtCtxt, span: Span,
                               substr: &Substructure) -> Gc<Expr> {
    let deserializer = substr.nonself_args[0];
    let token = substr.nonself_args[1];

    match *substr.fields {
        StaticStruct(_, ref fields) => {
            deserialize_struct(
                cx,
                span,
                substr.type_ident,
                fields,
                deserializer,
                token)
        }
        StaticEnum(_, ref fields) => {
            deserialize_enum(
                cx,
                span,
                substr.type_ident,
                fields.as_slice(),
                deserializer,
                token)
        }
        _ => cx.bug("expected StaticEnum or StaticStruct in deriving(Deserializable)")
    }
}

fn deserialize_struct(
    cx: &ExtCtxt,
    span: Span,
    type_ident: Ident,
    fields: &StaticFields,
    deserializer: Gc<ast::Expr>,
    token: Gc<ast::Expr>
) -> Gc<ast::Expr> {
    let struct_block = deserialize_struct_from_struct(
        cx,
        span,
        type_ident,
        fields,
        deserializer
    );

    let map_block = deserialize_struct_from_map(
        cx,
        span,
        type_ident,
        fields,
        deserializer
    );

    quote_expr!(
        cx,
        match $token {
            ::serde::de::StructStart(_, _) => $struct_block,
            ::serde::de::MapStart(_) => $map_block,
            _ => $deserializer.syntax_error(),
        }
    )
}

fn deserialize_struct_from_struct(
    cx: &ExtCtxt,
    span: Span,
    type_ident: Ident,
    fields: &StaticFields,
    deserializer: Gc<ast::Expr>
) -> Gc<ast::Expr> {
    let expect_struct_field = cx.ident_of("expect_struct_field");

    let call = deserializable_static_fields(
        cx,
        span,
        type_ident,
        fields,
        |cx, span, name| {
            let name = cx.expr_str(span, name);
            quote_expr!(
                cx,
                try!($deserializer.expect_struct_field($name))
            )
        }
    );

    quote_expr!(cx, {
        let result = $call;
        try!($deserializer.expect_struct_end());
        Ok(result)
    })
}

fn deserialize_struct_from_map(
    cx: &ExtCtxt,
    span: Span,
    type_ident: Ident,
    fields: &StaticFields,
    deserializer: Gc<ast::Expr>
) -> Gc<ast::Expr> {
    let fields = match *fields {
        Unnamed(_) => fail!(),
        Named(ref fields) => fields.as_slice(),
    };

    // Declare each field.
    let let_fields: Vec<Gc<ast::Stmt>> = fields.iter()
        .map(|&(name, span)| {
            quote_stmt!(cx, let mut $name = None)
        })
        .collect();

    // Declare key arms.
    let key_arms: Vec<ast::Arm> = fields.iter()
        .map(|&(name, span)| {
            let s = cx.expr_str(span, token::get_ident(name));
            quote_arm!(cx,
                $s => {
                    $name = Some(
                        try!(::serde::de::Deserializable::deserialize($deserializer))
                    );
                })
        })
        .collect();

    let fields_tuple = cx.expr_tuple(
        span,
        fields.iter()
            .map(|&(name, span)| {
                cx.expr_ident(span, name)
            })
            .collect()
    );

    let fields_pats: Vec<Gc<ast::Pat>> = fields.iter()
        .map(|&(name, span)| {
            quote_pat!(cx, Some($name))
        })
        .collect();

    let fields_pat = cx.pat_tuple(span, fields_pats);

    let result = cx.expr_struct_ident(
        span,
        type_ident,
        fields.iter()
            .map(|&(name, span)| {
                cx.field_imm(span, name, cx.expr_ident(span, name))
            })
            .collect()
    );

    quote_expr!(cx, {
        $let_fields

        loop {
            let token = match try!($deserializer.expect_token()) {
                ::serde::de::End => { break; }
                token => token,
            };

            let key = match token {
                ::serde::de::Str(s) => s,
                ::serde::de::String(ref s) => s.as_slice(),
                _ => { return $deserializer.syntax_error(); }
            };

            match key {
                $key_arms
                _ => { return $deserializer.syntax_error(); }
            }
        }

        let result = match $fields_tuple {
            $fields_pat => $result,
            _ => { return $deserializer.syntax_error(); }
        };

        try!($deserializer.expect_struct_end());

        Ok(result)
    })
}

fn deserialize_enum(
    cx: &ExtCtxt,
    span: Span,
    type_ident: Ident,
    fields: &[(Ident, Span, StaticFields)],
    deserializer: Gc<ast::Expr>,
    token: Gc<ast::Expr>
) -> Gc<ast::Expr> {
    let type_name = cx.expr_str(span, token::get_ident(type_ident));

    let variants = fields.iter()
        .map(|&(name, span, _)| {
            cx.expr_str(span, token::get_ident(name))
        })
        .collect();

    let variants = cx.expr_vec(span, variants);

    let arms: Vec<ast::Arm> = fields.iter()
        .enumerate()
        .map(|(i, &(name, span, ref parts))| {
            let call = deserializable_static_fields(
                cx,
                span,
                name,
                parts,
                |cx, span, _| {
                    quote_expr!(cx, try!($deserializer.expect_enum_elt()))
                }
            );

            quote_arm!(cx, $i => $call,)
        })
        .collect();

    quote_expr!(cx, {
        let i = try!($deserializer.expect_enum_start($token, $type_name, $variants));

        let result = match i {
            $arms
            _ => { unreachable!() }
        };

        try!($deserializer.expect_enum_end());

        Ok(result)
    })
}

/// Create a deserializer for a single enum variant/struct:
/// - `outer_pat_ident` is the name of this enum variant/struct
/// - `getarg` should retrieve the `uint`-th field with name `&str`.
fn deserializable_static_fields(
    cx: &ExtCtxt,
    span: Span,
    outer_pat_ident: Ident,
    fields: &StaticFields,
    getarg: |&ExtCtxt, Span, token::InternedString| -> Gc<Expr>
) -> Gc<Expr> {
    match *fields {
        Unnamed(ref fields) => {
            if fields.is_empty() {
                cx.expr_ident(span, outer_pat_ident)
            } else {
                let fields = fields.iter().enumerate().map(|(i, &span)| {
                    getarg(
                        cx,
                        span,
                        token::intern_and_get_ident(format!("_field{}", i).as_slice())
                    )
                }).collect();

                cx.expr_call_ident(span, outer_pat_ident, fields)
            }
        }
        Named(ref fields) => {
            // use the field's span to get nicer error messages.
            let fields = fields.iter().map(|&(name, span)| {
                let arg = getarg(
                    cx,
                    span,
                    token::get_ident(name)
                );
                cx.field_imm(span, name, arg)
            }).collect();

            cx.expr_struct_ident(span, outer_pat_ident, fields)
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>integration test for no_send_after_close<commit_after>//! Verifies that we can read data messages even if we have initiated a close handshake,
//! but before we got confirmation.

use std::net::TcpListener;
use std::process::exit;
use std::thread::{sleep, spawn};
use std::time::Duration;

use tungstenite::{accept, connect, Error, Message};
use url::Url;

#[test]
fn test_no_send_after_close() {
    env_logger::init();

    spawn(|| {
        sleep(Duration::from_secs(5));
        println!("Unit test executed too long, perhaps stuck on WOULDBLOCK...");
        exit(1);
    });

    let server = TcpListener::bind("127.0.0.1:3013").unwrap();

    let client_thread = spawn(move || {
        let (mut client, _) = connect(Url::parse("ws://localhost:3013/socket").unwrap()).unwrap();

        let message = client.read_message().unwrap(); // receive close from server
        assert!(message.is_close());

        let err = client.read_message().unwrap_err(); // now we should get ConnectionClosed
        match err {
            Error::ConnectionClosed => {}
            _ => panic!("unexpected error: {:?}", err),
        }
    });

    let client_handler = server.incoming().next().unwrap();
    let mut client_handler = accept(client_handler.unwrap()).unwrap();

    client_handler.close(None).unwrap(); // send close to client

    let err = client_handler
        .write_message(Message::Text("Hello WebSocket".into()));

    assert!( err.is_err() );

    match err.unwrap_err() {
        Error::Protocol(s) => { assert_eq!( "Sending after closing is not allowed", s )}
        e => panic!("unexpected error: {:?}", e),
    }

    drop(client_handler);

    client_thread.join().unwrap();
}
<|endoftext|>


<commit_before><commit_msg>long overdue rustup<commit_after><|endoftext|>


<commit_before><commit_msg>Small fix<commit_after><|endoftext|>


<commit_before><commit_msg>Update Debug for Cache.<commit_after><|endoftext|>


<commit_before>//! Error and result types.

use std::fmt;
use std::error::Error;
use std::io::Error as IoError;

use chrono::format::ParseError as ChronoParseError;
use serde_json::{Value, from_str};

use xmlutil::XmlParseError;

/// An error produced when AWS API calls are unsuccessful.
#[derive(Debug, PartialEq)]
pub struct AwsError {
    message: String
}

pub fn parse_json_protocol_error(body: &str) -> AwsError {
    match from_str::<Value>(body) {
        Ok(json) => {
            let error_type: &str = match json.find("__type") {
                Some(error_type) => error_type.as_string().unwrap_or("Unknown error"),
                None => "Unknown error",
            };

            let error_message: &str = match json.find("message") {
                Some(error_message) => error_message.as_string().unwrap_or(body),
                None => body,
            };

            AwsError::new(format!("{}: {}", error_type, error_message))
        }
        Err(err) => AwsError::new(
            format!("Failed to parse error as JSON: {}.\nRaw error:\n{}", err, body)
        ),
    }
}

impl AwsError {
    /// Create a new error with the given message.
    pub fn new<S>(message: S) -> AwsError where S: Into<String> {
        AwsError {
            message: message.into(),
        }
    }
}

impl Error for AwsError {
    fn description(&self) -> &str {
        &self.message
    }
}

impl From<ChronoParseError> for AwsError {
    fn from(err: ChronoParseError) -> AwsError {
        AwsError::new(format!("{}", err))
    }
}

impl From<IoError> for AwsError {
    fn from(err: IoError) -> AwsError {
        AwsError::new(format!("{}", err))
    }
}

impl From<XmlParseError> for AwsError {
    fn from(err: XmlParseError) -> AwsError {
        AwsError::new(format!("{:?}", err))
    }
}

impl fmt::Display for AwsError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

/// The result type produced by AWS API calls.
pub type AwsResult<T> = Result<T, AwsError>;
<commit_msg>make AwsError.message public<commit_after>//! Error and result types.

use std::fmt;
use std::error::Error;
use std::io::Error as IoError;

use chrono::format::ParseError as ChronoParseError;
use serde_json::{Value, from_str};

use xmlutil::XmlParseError;

/// An error produced when AWS API calls are unsuccessful.
#[derive(Debug, PartialEq)]
pub struct AwsError {
    pub message: String
}

pub fn parse_json_protocol_error(body: &str) -> AwsError {
    match from_str::<Value>(body) {
        Ok(json) => {
            let error_type: &str = match json.find("__type") {
                Some(error_type) => error_type.as_string().unwrap_or("Unknown error"),
                None => "Unknown error",
            };

            let error_message: &str = match json.find("message") {
                Some(error_message) => error_message.as_string().unwrap_or(body),
                None => body,
            };

            AwsError::new(format!("{}: {}", error_type, error_message))
        }
        Err(err) => AwsError::new(
            format!("Failed to parse error as JSON: {}.\nRaw error:\n{}", err, body)
        ),
    }
}

impl AwsError {
    /// Create a new error with the given message.
    pub fn new<S>(message: S) -> AwsError where S: Into<String> {
        AwsError {
            message: message.into(),
        }
    }
}

impl Error for AwsError {
    fn description(&self) -> &str {
        &self.message
    }
}

impl From<ChronoParseError> for AwsError {
    fn from(err: ChronoParseError) -> AwsError {
        AwsError::new(format!("{}", err))
    }
}

impl From<IoError> for AwsError {
    fn from(err: IoError) -> AwsError {
        AwsError::new(format!("{}", err))
    }
}

impl From<XmlParseError> for AwsError {
    fn from(err: XmlParseError) -> AwsError {
        AwsError::new(format!("{:?}", err))
    }
}

impl fmt::Display for AwsError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

/// The result type produced by AWS API calls.
pub type AwsResult<T> = Result<T, AwsError>;
<|endoftext|>


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

#[deriving(Eq, IterBytes)]
pub struct EnumSet<E> {
    // We must maintain the invariant that no bits are set
    // for which no variant exists
    priv bits: uint
}

pub trait CLike {
    pub fn to_uint(&self) -> uint;
    pub fn from_uint(uint) -> Self;
}

fn bit<E:CLike>(e: E) -> uint {
    1 << e.to_uint()
}

impl<E:CLike> EnumSet<E> {
    pub fn empty() -> EnumSet<E> {
        EnumSet {bits: 0}
    }

    pub fn is_empty(&self) -> bool {
        self.bits == 0
    }

    pub fn intersects(&self, e: EnumSet<E>) -> bool {
        (self.bits & e.bits) != 0
    }

    pub fn intersection(&self, e: EnumSet<E>) -> EnumSet<E> {
        EnumSet {bits: self.bits & e.bits}
    }

    pub fn contains(&self, e: EnumSet<E>) -> bool {
        (self.bits & e.bits) == e.bits
    }

    pub fn union(&self, e: EnumSet<E>) -> EnumSet<E> {
        EnumSet {bits: self.bits | e.bits}
    }

    pub fn add(&mut self, e: E) {
        self.bits |= bit(e);
    }

    pub fn contains_elem(&self, e: E) -> bool {
        (self.bits & bit(e)) != 0
    }

    pub fn each(&self, f: &fn(E) -> bool) -> bool {
        let mut bits = self.bits;
        let mut index = 0;
        while bits != 0 {
            if (bits & 1) != 0 {
                let e = CLike::from_uint(index);
                if !f(e) {
                    return false;
                }
            }
            index += 1;
            bits >>= 1;
        }
        return true;
    }
}

impl<E:CLike> Sub<EnumSet<E>, EnumSet<E>> for EnumSet<E> {
    fn sub(&self, e: &EnumSet<E>) -> EnumSet<E> {
        EnumSet {bits: self.bits & !e.bits}
    }
}

impl<E:CLike> BitOr<EnumSet<E>, EnumSet<E>> for EnumSet<E> {
    fn bitor(&self, e: &EnumSet<E>) -> EnumSet<E> {
        EnumSet {bits: self.bits | e.bits}
    }
}

impl<E:CLike> BitAnd<EnumSet<E>, EnumSet<E>> for EnumSet<E> {
    fn bitand(&self, e: &EnumSet<E>) -> EnumSet<E> {
        EnumSet {bits: self.bits & e.bits}
    }
}

#[cfg(test)]
mod test {

    use std::cast;
    use std::iter;

    use util::enum_set::*;

    #[deriving(Eq)]
    enum Foo {
        A, B, C
    }

    impl CLike for Foo {
        pub fn to_uint(&self) -> uint {
            *self as uint
        }

        pub fn from_uint(v: uint) -> Foo {
            unsafe { cast::transmute(v) }
        }
    }

    #[test]
    fn test_empty() {
        let e: EnumSet<Foo> = EnumSet::empty();
        assert!(e.is_empty());
    }

    ///////////////////////////////////////////////////////////////////////////
    // intersect

    #[test]
    fn test_two_empties_do_not_intersect() {
        let e1: EnumSet<Foo> = EnumSet::empty();
        let e2: EnumSet<Foo> = EnumSet::empty();
        assert!(!e1.intersects(e2));
    }

    #[test]
    fn test_empty_does_not_intersect_with_full() {
        let e1: EnumSet<Foo> = EnumSet::empty();

        let mut e2: EnumSet<Foo> = EnumSet::empty();
        e2.add(A);
        e2.add(B);
        e2.add(C);

        assert!(!e1.intersects(e2));
    }

    #[test]
    fn test_disjoint_intersects() {
        let mut e1: EnumSet<Foo> = EnumSet::empty();
        e1.add(A);

        let mut e2: EnumSet<Foo> = EnumSet::empty();
        e2.add(B);

        assert!(!e1.intersects(e2));
    }

    #[test]
    fn test_overlapping_intersects() {
        let mut e1: EnumSet<Foo> = EnumSet::empty();
        e1.add(A);

        let mut e2: EnumSet<Foo> = EnumSet::empty();
        e2.add(A);
        e2.add(B);

        assert!(e1.intersects(e2));
    }

    ///////////////////////////////////////////////////////////////////////////
    // contains and contains_elem

    #[test]
    fn test_contains() {
        let mut e1: EnumSet<Foo> = EnumSet::empty();
        e1.add(A);

        let mut e2: EnumSet<Foo> = EnumSet::empty();
        e2.add(A);
        e2.add(B);

        assert!(!e1.contains(e2));
        assert!(e2.contains(e1));
    }

    #[test]
    fn test_contains_elem() {
        let mut e1: EnumSet<Foo> = EnumSet::empty();
        e1.add(A);
        assert!(e1.contains_elem(A));
        assert!(!e1.contains_elem(B));
        assert!(!e1.contains_elem(C));

        e1.add(A);
        e1.add(B);
        assert!(e1.contains_elem(A));
        assert!(e1.contains_elem(B));
        assert!(!e1.contains_elem(C));
    }

    ///////////////////////////////////////////////////////////////////////////
    // each

    #[test]
    fn test_each() {
        let mut e1: EnumSet<Foo> = EnumSet::empty();

        assert_eq!(~[], iter::FromIter::from_iter::<Foo, ~[Foo]>(|f| e1.each(f)))

        e1.add(A);
        assert_eq!(~[A], iter::FromIter::from_iter::<Foo, ~[Foo]>(|f| e1.each(f)))

        e1.add(C);
        assert_eq!(~[A,C], iter::FromIter::from_iter::<Foo, ~[Foo]>(|f| e1.each(f)))

        e1.add(C);
        assert_eq!(~[A,C], iter::FromIter::from_iter::<Foo, ~[Foo]>(|f| e1.each(f)))

        e1.add(B);
        assert_eq!(~[A,B,C], iter::FromIter::from_iter::<Foo, ~[Foo]>(|f| e1.each(f)))
    }

    ///////////////////////////////////////////////////////////////////////////
    // operators

    #[test]
    fn test_operators() {
        let mut e1: EnumSet<Foo> = EnumSet::empty();
        e1.add(A);
        e1.add(C);

        let mut e2: EnumSet<Foo> = EnumSet::empty();
        e2.add(B);
        e2.add(C);

        let e_union = e1 | e2;
        assert_eq!(~[A,B,C], iter::FromIter::from_iter::<Foo, ~[Foo]>(|f| e_union.each(f)))

        let e_intersection = e1 & e2;
        assert_eq!(~[C], iter::FromIter::from_iter::<Foo, ~[Foo]>(|f| e_intersection.each(f)))

        let e_subtract = e1 - e2;
        assert_eq!(~[A], iter::FromIter::from_iter::<Foo, ~[Foo]>(|f| e_subtract.each(f)))
    }
}
<commit_msg>Add an EnumSetIterator and EnumSet::iter<commit_after>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::iterator::Iterator;

#[deriving(Eq, IterBytes)]
pub struct EnumSet<E> {
    // We must maintain the invariant that no bits are set
    // for which no variant exists
    priv bits: uint
}

pub trait CLike {
    pub fn to_uint(&self) -> uint;
    pub fn from_uint(uint) -> Self;
}

fn bit<E:CLike>(e: E) -> uint {
    1 << e.to_uint()
}

impl<E:CLike> EnumSet<E> {
    pub fn empty() -> EnumSet<E> {
        EnumSet {bits: 0}
    }

    pub fn is_empty(&self) -> bool {
        self.bits == 0
    }

    pub fn intersects(&self, e: EnumSet<E>) -> bool {
        (self.bits & e.bits) != 0
    }

    pub fn intersection(&self, e: EnumSet<E>) -> EnumSet<E> {
        EnumSet {bits: self.bits & e.bits}
    }

    pub fn contains(&self, e: EnumSet<E>) -> bool {
        (self.bits & e.bits) == e.bits
    }

    pub fn union(&self, e: EnumSet<E>) -> EnumSet<E> {
        EnumSet {bits: self.bits | e.bits}
    }

    pub fn add(&mut self, e: E) {
        self.bits |= bit(e);
    }

    pub fn contains_elem(&self, e: E) -> bool {
        (self.bits & bit(e)) != 0
    }

    pub fn each(&self, f: &fn(E) -> bool) -> bool {
        let mut bits = self.bits;
        let mut index = 0;
        while bits != 0 {
            if (bits & 1) != 0 {
                let e = CLike::from_uint(index);
                if !f(e) {
                    return false;
                }
            }
            index += 1;
            bits >>= 1;
        }
        return true;
    }

    pub fn iter(&self) -> EnumSetIterator<E> {
        EnumSetIterator::new(self.bits)
    }
}

impl<E:CLike> Sub<EnumSet<E>, EnumSet<E>> for EnumSet<E> {
    fn sub(&self, e: &EnumSet<E>) -> EnumSet<E> {
        EnumSet {bits: self.bits & !e.bits}
    }
}

impl<E:CLike> BitOr<EnumSet<E>, EnumSet<E>> for EnumSet<E> {
    fn bitor(&self, e: &EnumSet<E>) -> EnumSet<E> {
        EnumSet {bits: self.bits | e.bits}
    }
}

impl<E:CLike> BitAnd<EnumSet<E>, EnumSet<E>> for EnumSet<E> {
    fn bitand(&self, e: &EnumSet<E>) -> EnumSet<E> {
        EnumSet {bits: self.bits & e.bits}
    }
}

pub struct EnumSetIterator<E> {
    priv index: uint,
    priv bits: uint,
}

impl<E:CLike> EnumSetIterator<E> {
    fn new(bits: uint) -> EnumSetIterator<E> {
        EnumSetIterator { index: 0, bits: bits }
    }
}

impl<E:CLike> Iterator<E> for EnumSetIterator<E> {
    fn next(&mut self) -> Option<E> {
        if (self.bits == 0) {
            return None;
        }

        while (self.bits & 1) == 0 {
            self.index += 1;
            self.bits >>= 1;
        }
        let elem = CLike::from_uint(self.index);
        self.index += 1;
        self.bits >>= 1;
        Some(elem)
    }

    fn size_hint(&self) -> (Option<uint>, Option<uint>) {
        let exact = Some(self.bits.population_count());
        (exact, exact)
    }
}

#[cfg(test)]
mod test {

    use std::cast;
    use std::iter;

    use util::enum_set::*;

    #[deriving(Eq)]
    enum Foo {
        A, B, C
    }

    impl CLike for Foo {
        pub fn to_uint(&self) -> uint {
            *self as uint
        }

        pub fn from_uint(v: uint) -> Foo {
            unsafe { cast::transmute(v) }
        }
    }

    #[test]
    fn test_empty() {
        let e: EnumSet<Foo> = EnumSet::empty();
        assert!(e.is_empty());
    }

    ///////////////////////////////////////////////////////////////////////////
    // intersect

    #[test]
    fn test_two_empties_do_not_intersect() {
        let e1: EnumSet<Foo> = EnumSet::empty();
        let e2: EnumSet<Foo> = EnumSet::empty();
        assert!(!e1.intersects(e2));
    }

    #[test]
    fn test_empty_does_not_intersect_with_full() {
        let e1: EnumSet<Foo> = EnumSet::empty();

        let mut e2: EnumSet<Foo> = EnumSet::empty();
        e2.add(A);
        e2.add(B);
        e2.add(C);

        assert!(!e1.intersects(e2));
    }

    #[test]
    fn test_disjoint_intersects() {
        let mut e1: EnumSet<Foo> = EnumSet::empty();
        e1.add(A);

        let mut e2: EnumSet<Foo> = EnumSet::empty();
        e2.add(B);

        assert!(!e1.intersects(e2));
    }

    #[test]
    fn test_overlapping_intersects() {
        let mut e1: EnumSet<Foo> = EnumSet::empty();
        e1.add(A);

        let mut e2: EnumSet<Foo> = EnumSet::empty();
        e2.add(A);
        e2.add(B);

        assert!(e1.intersects(e2));
    }

    ///////////////////////////////////////////////////////////////////////////
    // contains and contains_elem

    #[test]
    fn test_contains() {
        let mut e1: EnumSet<Foo> = EnumSet::empty();
        e1.add(A);

        let mut e2: EnumSet<Foo> = EnumSet::empty();
        e2.add(A);
        e2.add(B);

        assert!(!e1.contains(e2));
        assert!(e2.contains(e1));
    }

    #[test]
    fn test_contains_elem() {
        let mut e1: EnumSet<Foo> = EnumSet::empty();
        e1.add(A);
        assert!(e1.contains_elem(A));
        assert!(!e1.contains_elem(B));
        assert!(!e1.contains_elem(C));

        e1.add(A);
        e1.add(B);
        assert!(e1.contains_elem(A));
        assert!(e1.contains_elem(B));
        assert!(!e1.contains_elem(C));
    }

    ///////////////////////////////////////////////////////////////////////////
    // iterator

    #[test]
    fn test_iterator() {
        let mut e1: EnumSet<Foo> = EnumSet::empty();

        let elems: ~[Foo] = e1.iter().collect();
        assert_eq!(~[], elems)

        e1.add(A);
        let elems: ~[Foo] = e1.iter().collect();
        assert_eq!(~[A], elems)

        e1.add(C);
        let elems: ~[Foo] = e1.iter().collect();
        assert_eq!(~[A,C], elems)

        e1.add(C);
        let elems: ~[Foo] = e1.iter().collect();
        assert_eq!(~[A,C], elems)

        e1.add(B);
        let elems: ~[Foo] = e1.iter().collect();
        assert_eq!(~[A,B,C], elems)
    }

    fn collect(e: EnumSet<Foo>) -> ~[Foo] {
        let mut elems = ~[];
        e.each(|elem| {
           elems.push(elem);
           true
        });
        elems
    }

    #[test]
    fn test_each() {
        let mut e1: EnumSet<Foo> = EnumSet::empty();

        assert_eq!(~[], collect(e1))

        e1.add(A);
        assert_eq!(~[A], collect(e1))

        e1.add(C);
        assert_eq!(~[A,C], collect(e1))

        e1.add(C);
        assert_eq!(~[A,C], collect(e1))

        e1.add(B);
        assert_eq!(~[A,B,C], collect(e1))
    }

    ///////////////////////////////////////////////////////////////////////////
    // operators

    #[test]
    fn test_operators() {
        let mut e1: EnumSet<Foo> = EnumSet::empty();
        e1.add(A);
        e1.add(C);

        let mut e2: EnumSet<Foo> = EnumSet::empty();
        e2.add(B);
        e2.add(C);

        let e_union = e1 | e2;
        let elems: ~[Foo] = e_union.iter().collect();
        assert_eq!(~[A,B,C], elems)

        let e_intersection = e1 & e2;
        let elems: ~[Foo] = e_intersection.iter().collect();
        assert_eq!(~[C], elems)

        let e_subtract = e1 - e2;
        let elems: ~[Foo] = e_subtract.iter().collect();
        assert_eq!(~[A], elems)
    }
}
<|endoftext|>


<commit_before><commit_msg>Add yield<commit_after><|endoftext|>


<commit_before><commit_msg>adds the entity repository to the state<commit_after><|endoftext|>


<commit_before><commit_msg>added union.rd.<commit_after>extern crate num;

use std::mem;

type c32 = num::Complex<f32>;
type c64 = num::Complex<f64>;

const UNION_SIZE : usize = 8; //mem::size_of::<usize>();

#[repr(C)]
struct Union {
    data: [usize; UNION_SIZE]
}

type c32_vec = Vec<c32>;
type c64_vec = Vec<c64>;

impl Union {
    unsafe fn as_c32_vec(&self) -> *const c32_vec {
        let p = self as *const _ as *const c32_vec;
        p
    }

    unsafe fn as_c64_vec(&self) -> *const c64_vec {
        let p = self as *const _ as *const c64_vec;
        p
    }

    //unsafe fn as_c32_vec_mut(&self) -> *mut c32_vec {
    //    let p = self as *mut _ as *mut c32_vec;
    //    &mut p
    //}

    //unsafe fn as_c64_vec_mut(&self) -> *mut c64_vec {
    //    let p = self as *mut _ as *mut c64_vec;
    //    &mut p
    //}

}

fn main() {
    println!("Rust union test");

}
<|endoftext|>


<commit_before><commit_msg>Add a simple converter example, handy for testing<commit_after>//! An example of opening an image.
extern crate image;

use std::env;
use std::path::Path;

fn main() {
    let (from, into) = if env::args_os().count() == 3 {
        (env::args_os().nth(1).unwrap(), env::args_os().nth(2).unwrap())
    } else {
        println!("Please enter a from and into path.");
        std::process::exit(1);
    };

    // Use the open function to load an image from a Path.
    // ```open``` returns a dynamic image.
    let im = image::open(&Path::new(&from)).unwrap();
    // Write the contents of this image using extension guessing.
    im.save(&Path::new(&into)).unwrap();
}
<|endoftext|>


<commit_before>extern crate orbital;

use orbital::Color;

use std::fs::File;
use std::io::{Read, Write};
use std::sync::{Arc, Mutex};
use std::syscall::*;
use std::thread;

use window::ConsoleWindow;

mod window;

macro_rules! readln {
    () => ({
        let mut buffer = String::new();
        match std::io::stdin().read_line(&mut buffer) {
            Ok(_) => Some(buffer),
            Err(_) => None
        }
    });
}

pub fn pipe() -> [usize; 2] {
    let mut fds = [0; 2];
    SysError::demux(unsafe { sys_pipe2(fds.as_mut_ptr(), 0) }).unwrap();
    fds
}

#[no_mangle] pub fn main() {
    let to_shell_fds = pipe();
    let from_shell_fds = pipe();

    unsafe {
        if SysError::demux(sys_clone(0)).unwrap() == 0{
            //Close STDIO
            sys_close(2);
            sys_close(1);
            sys_close(0);

            //Create piped STDIO
            sys_dup(to_shell_fds[0]);
            sys_dup(from_shell_fds[1]);
            sys_dup(from_shell_fds[1]);

            //Close extra pipes
            sys_close(to_shell_fds[0]);
            sys_close(to_shell_fds[1]);
            sys_close(from_shell_fds[0]);
            sys_close(from_shell_fds[1]);

            //Execute the shell
            let shell = "file:/apps/shell/main.bin\0";
            sys_execve(shell.as_ptr(), 0 as *const *const u8);
            panic!("Shell not found");
        } else{
            //Close extra pipes
            sys_close(to_shell_fds[0]);
            sys_close(from_shell_fds[1]);
        }
    };

    let mut window = ConsoleWindow::new(-1, -1, 576, 400, "Terminal");

    let mut from_shell = unsafe { File::from_fd(from_shell_fds[0]).unwrap() };
    loop {
        let mut output = String::new();
        if let Ok(_) = from_shell.read_to_string(&mut output) {
            window.print(&output, Color::rgb(255, 255, 255));
            window.sync();
        } else {
            break;
        }
    }
}
<commit_msg>Cleanup missing spaces in terminal<commit_after>extern crate orbital;

use orbital::Color;

use std::fs::File;
use std::io::{Read, Write};
use std::sync::{Arc, Mutex};
use std::syscall::*;
use std::thread;

use window::ConsoleWindow;

mod window;

macro_rules! readln {
    () => ({
        let mut buffer = String::new();
        match std::io::stdin().read_line(&mut buffer) {
            Ok(_) => Some(buffer),
            Err(_) => None
        }
    });
}

pub fn pipe() -> [usize; 2] {
    let mut fds = [0; 2];
    SysError::demux(unsafe { sys_pipe2(fds.as_mut_ptr(), 0) }).unwrap();
    fds
}

#[no_mangle]
pub fn main() {
    let to_shell_fds = pipe();
    let from_shell_fds = pipe();

    unsafe {
        if SysError::demux(sys_clone(0)).unwrap() == 0 {
            // Close STDIO
            sys_close(2);
            sys_close(1);
            sys_close(0);

            // Create piped STDIO
            sys_dup(to_shell_fds[0]);
            sys_dup(from_shell_fds[1]);
            sys_dup(from_shell_fds[1]);

            // Close extra pipes
            sys_close(to_shell_fds[0]);
            sys_close(to_shell_fds[1]);
            sys_close(from_shell_fds[0]);
            sys_close(from_shell_fds[1]);

            // Execute the shell
            let shell = "file:/apps/shell/main.bin\0";
            sys_execve(shell.as_ptr(), 0 as *const *const u8);
            panic!("Shell not found");
        } else {
            // Close extra pipes
            sys_close(to_shell_fds[0]);
            sys_close(from_shell_fds[1]);
        }
    };

    let mut window = ConsoleWindow::new(-1, -1, 576, 400, "Terminal");

    let mut from_shell = unsafe { File::from_fd(from_shell_fds[0]).unwrap() };
    loop {
        let mut output = String::new();
        if let Ok(_) = from_shell.read_to_string(&mut output) {
            window.print(&output, Color::rgb(255, 255, 255));
            window.sync();
        } else {
            break;
        }
    }
}
<|endoftext|>


<commit_before>use renderer::html_handlebars::helpers;
use renderer::Renderer;
use book::MDBook;
use book::bookitem::BookItem;
use {utils, theme};

use std::path::{Path, PathBuf};
use std::fs::{self, File};
use std::error::Error;
use std::io::{self, Read, Write};
use std::collections::BTreeMap;

use handlebars::Handlebars;

use serde_json;
use serde_json::value::ToJson;

pub struct HtmlHandlebars;

impl HtmlHandlebars {
    pub fn new() -> Self {
        HtmlHandlebars
    }
}

impl Renderer for HtmlHandlebars {
    fn render(&self, book: &MDBook) -> Result<(), Box<Error>> {
        debug!("[fn]: render");
        let mut handlebars = Handlebars::new();

        // Load theme
        let theme = theme::Theme::new(book.get_theme_path());

        // Register template
        debug!("[*]: Register handlebars template");
        try!(handlebars.register_template_string("index", try!(String::from_utf8(theme.index))));

        // Register helpers
        debug!("[*]: Register handlebars helpers");
        handlebars.register_helper("toc", Box::new(helpers::toc::RenderToc));
        handlebars.register_helper("previous", Box::new(helpers::navigation::previous));
        handlebars.register_helper("next", Box::new(helpers::navigation::next));

        let mut data = try!(make_data(book));

        // Print version
        let mut print_content: String = String::new();

        // Check if dest directory exists
        debug!("[*]: Check if destination directory exists");
        if let Err(_) = fs::create_dir_all(book.get_dest()) {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other,
                                               "Unexpected error when constructing destination path")));
        }

        // Render a file for every entry in the book
        let mut index = true;
        for item in book.iter() {

            match *item {
                BookItem::Chapter(_, ref ch) |
                BookItem::Affix(ref ch) => {
                    if ch.path != PathBuf::new() {

                        let path = book.get_src().join(&ch.path);

                        debug!("[*]: Opening file: {:?}", path);
                        let mut f = try!(File::open(&path));
                        let mut content: String = String::new();

                        debug!("[*]: Reading file");
                        try!(f.read_to_string(&mut content));

                        // Parse for playpen links
                        if let Some(p) = path.parent() {
                            content = helpers::playpen::render_playpen(&content, p);
                        }

                        // Render markdown using the pulldown-cmark crate
                        content = utils::render_markdown(&content);
                        print_content.push_str(&content);

                        // Update the context with data for this file
                        match ch.path.to_str() {
                            Some(p) => {
                                data.insert("path".to_owned(), p.to_json());
                            },
                            None => {
                                return Err(Box::new(io::Error::new(io::ErrorKind::Other,
                                                                   "Could not convert path to str")))
                            },
                        }
                        data.insert("content".to_owned(), content.to_json());
                        data.insert("chapter_title".to_owned(), ch.name.to_json());
                        data.insert("path_to_root".to_owned(), utils::fs::path_to_root(&ch.path).to_json());

                        // Render the handlebars template with the data
                        debug!("[*]: Render template");
                        let rendered = try!(handlebars.render("index", &data));

                        debug!("[*]: Create file {:?}", &book.get_dest().join(&ch.path).with_extension("html"));
                        // Write to file
                        let mut file =
                            try!(utils::fs::create_file(&book.get_dest().join(&ch.path).with_extension("html")));
                        info!("[*] Creating {:?} ✓", &book.get_dest().join(&ch.path).with_extension("html"));

                        try!(file.write_all(&rendered.into_bytes()));

                        // Create an index.html from the first element in SUMMARY.md
                        if index {
                            debug!("[*]: index.html");

                            let mut index_file = try!(File::create(book.get_dest().join("index.html")));
                            let mut content = String::new();
                            let _source = try!(File::open(book.get_dest().join(&ch.path.with_extension("html"))))
                                .read_to_string(&mut content);

                            // This could cause a problem when someone displays code containing <base href=...>
                            // on the front page, however this case should be very very rare...
                            content = content.lines()
                                .filter(|line| !line.contains("<base href="))
                                .collect::<Vec<&str>>()
                                .join("\n");

                            try!(index_file.write_all(content.as_bytes()));

                            info!("[*] Creating index.html from {:?} ✓",
                                  book.get_dest().join(&ch.path.with_extension("html")));
                            index = false;
                        }
                    }
                },
                _ => {},
            }
        }

        // Print version

        // Update the context with data for this file
        data.insert("path".to_owned(), "print.md".to_json());
        data.insert("content".to_owned(), print_content.to_json());
        data.insert("path_to_root".to_owned(), utils::fs::path_to_root(Path::new("print.md")).to_json());

        // Render the handlebars template with the data
        debug!("[*]: Render template");
        let rendered = try!(handlebars.render("index", &data));
        let mut file = try!(utils::fs::create_file(&book.get_dest().join("print").with_extension("html")));
        try!(file.write_all(&rendered.into_bytes()));
        info!("[*] Creating print.html ✓");

        // Copy static files (js, css, images, ...)

        debug!("[*] Copy static files");
        // JavaScript
        let mut js_file = if let Ok(f) = File::create(book.get_dest().join("book.js")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create book.js")));
        };
        try!(js_file.write_all(&theme.js));

        // Css
        let mut css_file = if let Ok(f) = File::create(book.get_dest().join("book.css")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create book.css")));
        };
        try!(css_file.write_all(&theme.css));

        // Favicon
        let mut favicon_file = if let Ok(f) = File::create(book.get_dest().join("favicon.png")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create favicon.png")));
        };
        try!(favicon_file.write_all(&theme.favicon));

        // JQuery local fallback
        let mut jquery = if let Ok(f) = File::create(book.get_dest().join("jquery.js")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create jquery.js")));
        };
        try!(jquery.write_all(&theme.jquery));

        // syntax highlighting
        let mut highlight_css = if let Ok(f) = File::create(book.get_dest().join("highlight.css")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create highlight.css")));
        };
        try!(highlight_css.write_all(&theme.highlight_css));

        let mut tomorrow_night_css = if let Ok(f) = File::create(book.get_dest().join("tomorrow-night.css")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create tomorrow-night.css")));
        };
        try!(tomorrow_night_css.write_all(&theme.tomorrow_night_css));

        let mut highlight_js = if let Ok(f) = File::create(book.get_dest().join("highlight.js")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create highlight.js")));
        };
        try!(highlight_js.write_all(&theme.highlight_js));

        // Font Awesome local fallback
        let mut font_awesome = if let Ok(f) = utils::fs::create_file(&book.get_dest()
            .join("_FontAwesome/css/font-awesome.css")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create font-awesome.css")));
        };
        try!(font_awesome.write_all(theme::FONT_AWESOME));
        let mut font_awesome = if let Ok(f) = utils::fs::create_file(&book.get_dest()
            .join("_FontAwesome/fonts/fontawesome-webfont.eot")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create fontawesome-webfont.eot")));
        };
        try!(font_awesome.write_all(theme::FONT_AWESOME_EOT));
        let mut font_awesome = if let Ok(f) = utils::fs::create_file(&book.get_dest()
            .join("_FontAwesome/fonts/fontawesome-webfont.svg")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create fontawesome-webfont.svg")));
        };
        try!(font_awesome.write_all(theme::FONT_AWESOME_SVG));
        let mut font_awesome = if let Ok(f) = utils::fs::create_file(&book.get_dest()
            .join("_FontAwesome/fonts/fontawesome-webfont.ttf")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create fontawesome-webfont.ttf")));
        };
        try!(font_awesome.write_all(theme::FONT_AWESOME_TTF));
        let mut font_awesome = if let Ok(f) = utils::fs::create_file(&book.get_dest()
            .join("_FontAwesome/fonts/fontawesome-webfont.woff")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create fontawesome-webfont.woff")));
        };
        try!(font_awesome.write_all(theme::FONT_AWESOME_WOFF));
        let mut font_awesome = if let Ok(f) = utils::fs::create_file(&book.get_dest()
            .join("_FontAwesome/fonts/fontawesome-webfont.woff2")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create fontawesome-webfont.woff2")));
        };
        try!(font_awesome.write_all(theme::FONT_AWESOME_WOFF2));
        let mut font_awesome = if let Ok(f) = utils::fs::create_file(&book.get_dest()
            .join("_FontAwesome/fonts/FontAwesome.ttf")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create FontAwesome.ttf")));
        };
        try!(font_awesome.write_all(theme::FONT_AWESOME_TTF));

        // Copy all remaining files
        try!(utils::fs::copy_files_except_ext(book.get_src(), book.get_dest(), true, &["md"]));

        Ok(())
    }
}

fn make_data(book: &MDBook) -> Result<serde_json::Map<String, serde_json::Value>, Box<Error>> {
    debug!("[fn]: make_data");

    let mut data = serde_json::Map::new();
    data.insert("language".to_owned(), "en".to_json());
    data.insert("title".to_owned(), book.get_title().to_json());
    data.insert("description".to_owned(), book.get_description().to_json());
    data.insert("favicon".to_owned(), "favicon.png".to_json());
    if let Some(livereload) = book.get_livereload() {
        data.insert("livereload".to_owned(), livereload.to_json());
    }

    let mut chapters = vec![];

    for item in book.iter() {
        // Create the data to inject in the template
        let mut chapter = BTreeMap::new();

        match *item {
            BookItem::Affix(ref ch) => {
                chapter.insert("name".to_owned(), ch.name.to_json());
                match ch.path.to_str() {
                    Some(p) => {
                        chapter.insert("path".to_owned(), p.to_json());
                    },
                    None => return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not convert path to str"))),
                }
            },
            BookItem::Chapter(ref s, ref ch) => {
                chapter.insert("section".to_owned(), s.to_json());
                chapter.insert("name".to_owned(), ch.name.to_json());
                match ch.path.to_str() {
                    Some(p) => {
                        chapter.insert("path".to_owned(), p.to_json());
                    },
                    None => return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not convert path to str"))),
                }
            },
            BookItem::Spacer => {
                chapter.insert("spacer".to_owned(), "_spacer_".to_json());
            },

        }

        chapters.push(chapter);
    }

    data.insert("chapters".to_owned(), chapters.to_json());

    debug!("[*]: JSON constructed");
    Ok(data)
}
<commit_msg>Simplify some as_str error handling code<commit_after>use renderer::html_handlebars::helpers;
use renderer::Renderer;
use book::MDBook;
use book::bookitem::BookItem;
use {utils, theme};

use std::path::{Path, PathBuf};
use std::fs::{self, File};
use std::error::Error;
use std::io::{self, Read, Write};
use std::collections::BTreeMap;

use handlebars::Handlebars;

use serde_json;
use serde_json::value::ToJson;

pub struct HtmlHandlebars;

impl HtmlHandlebars {
    pub fn new() -> Self {
        HtmlHandlebars
    }
}

impl Renderer for HtmlHandlebars {
    fn render(&self, book: &MDBook) -> Result<(), Box<Error>> {
        debug!("[fn]: render");
        let mut handlebars = Handlebars::new();

        // Load theme
        let theme = theme::Theme::new(book.get_theme_path());

        // Register template
        debug!("[*]: Register handlebars template");
        try!(handlebars.register_template_string("index", try!(String::from_utf8(theme.index))));

        // Register helpers
        debug!("[*]: Register handlebars helpers");
        handlebars.register_helper("toc", Box::new(helpers::toc::RenderToc));
        handlebars.register_helper("previous", Box::new(helpers::navigation::previous));
        handlebars.register_helper("next", Box::new(helpers::navigation::next));

        let mut data = try!(make_data(book));

        // Print version
        let mut print_content: String = String::new();

        // Check if dest directory exists
        debug!("[*]: Check if destination directory exists");
        if let Err(_) = fs::create_dir_all(book.get_dest()) {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other,
                                               "Unexpected error when constructing destination path")));
        }

        // Render a file for every entry in the book
        let mut index = true;
        for item in book.iter() {

            match *item {
                BookItem::Chapter(_, ref ch) |
                BookItem::Affix(ref ch) => {
                    if ch.path != PathBuf::new() {

                        let path = book.get_src().join(&ch.path);

                        debug!("[*]: Opening file: {:?}", path);
                        let mut f = try!(File::open(&path));
                        let mut content: String = String::new();

                        debug!("[*]: Reading file");
                        try!(f.read_to_string(&mut content));

                        // Parse for playpen links
                        if let Some(p) = path.parent() {
                            content = helpers::playpen::render_playpen(&content, p);
                        }

                        // Render markdown using the pulldown-cmark crate
                        content = utils::render_markdown(&content);
                        print_content.push_str(&content);

                        // Update the context with data for this file
                        let path = ch.path.to_str().ok_or(io::Error::new(io::ErrorKind::Other,
                                                          "Could not convert path to str"))?;
                        data.insert("path".to_owned(), path.to_json());
                        data.insert("content".to_owned(), content.to_json());
                        data.insert("chapter_title".to_owned(), ch.name.to_json());
                        data.insert("path_to_root".to_owned(), utils::fs::path_to_root(&ch.path).to_json());

                        // Render the handlebars template with the data
                        debug!("[*]: Render template");
                        let rendered = try!(handlebars.render("index", &data));

                        debug!("[*]: Create file {:?}", &book.get_dest().join(&ch.path).with_extension("html"));
                        // Write to file
                        let mut file =
                            try!(utils::fs::create_file(&book.get_dest().join(&ch.path).with_extension("html")));
                        info!("[*] Creating {:?} ✓", &book.get_dest().join(&ch.path).with_extension("html"));

                        try!(file.write_all(&rendered.into_bytes()));

                        // Create an index.html from the first element in SUMMARY.md
                        if index {
                            debug!("[*]: index.html");

                            let mut index_file = try!(File::create(book.get_dest().join("index.html")));
                            let mut content = String::new();
                            let _source = try!(File::open(book.get_dest().join(&ch.path.with_extension("html"))))
                                .read_to_string(&mut content);

                            // This could cause a problem when someone displays code containing <base href=...>
                            // on the front page, however this case should be very very rare...
                            content = content.lines()
                                .filter(|line| !line.contains("<base href="))
                                .collect::<Vec<&str>>()
                                .join("\n");

                            try!(index_file.write_all(content.as_bytes()));

                            info!("[*] Creating index.html from {:?} ✓",
                                  book.get_dest().join(&ch.path.with_extension("html")));
                            index = false;
                        }
                    }
                },
                _ => {},
            }
        }

        // Print version

        // Update the context with data for this file
        data.insert("path".to_owned(), "print.md".to_json());
        data.insert("content".to_owned(), print_content.to_json());
        data.insert("path_to_root".to_owned(), utils::fs::path_to_root(Path::new("print.md")).to_json());

        // Render the handlebars template with the data
        debug!("[*]: Render template");
        let rendered = try!(handlebars.render("index", &data));
        let mut file = try!(utils::fs::create_file(&book.get_dest().join("print").with_extension("html")));
        try!(file.write_all(&rendered.into_bytes()));
        info!("[*] Creating print.html ✓");

        // Copy static files (js, css, images, ...)

        debug!("[*] Copy static files");
        // JavaScript
        let mut js_file = if let Ok(f) = File::create(book.get_dest().join("book.js")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create book.js")));
        };
        try!(js_file.write_all(&theme.js));

        // Css
        let mut css_file = if let Ok(f) = File::create(book.get_dest().join("book.css")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create book.css")));
        };
        try!(css_file.write_all(&theme.css));

        // Favicon
        let mut favicon_file = if let Ok(f) = File::create(book.get_dest().join("favicon.png")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create favicon.png")));
        };
        try!(favicon_file.write_all(&theme.favicon));

        // JQuery local fallback
        let mut jquery = if let Ok(f) = File::create(book.get_dest().join("jquery.js")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create jquery.js")));
        };
        try!(jquery.write_all(&theme.jquery));

        // syntax highlighting
        let mut highlight_css = if let Ok(f) = File::create(book.get_dest().join("highlight.css")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create highlight.css")));
        };
        try!(highlight_css.write_all(&theme.highlight_css));

        let mut tomorrow_night_css = if let Ok(f) = File::create(book.get_dest().join("tomorrow-night.css")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create tomorrow-night.css")));
        };
        try!(tomorrow_night_css.write_all(&theme.tomorrow_night_css));

        let mut highlight_js = if let Ok(f) = File::create(book.get_dest().join("highlight.js")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create highlight.js")));
        };
        try!(highlight_js.write_all(&theme.highlight_js));

        // Font Awesome local fallback
        let mut font_awesome = if let Ok(f) = utils::fs::create_file(&book.get_dest()
            .join("_FontAwesome/css/font-awesome.css")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create font-awesome.css")));
        };
        try!(font_awesome.write_all(theme::FONT_AWESOME));
        let mut font_awesome = if let Ok(f) = utils::fs::create_file(&book.get_dest()
            .join("_FontAwesome/fonts/fontawesome-webfont.eot")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create fontawesome-webfont.eot")));
        };
        try!(font_awesome.write_all(theme::FONT_AWESOME_EOT));
        let mut font_awesome = if let Ok(f) = utils::fs::create_file(&book.get_dest()
            .join("_FontAwesome/fonts/fontawesome-webfont.svg")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create fontawesome-webfont.svg")));
        };
        try!(font_awesome.write_all(theme::FONT_AWESOME_SVG));
        let mut font_awesome = if let Ok(f) = utils::fs::create_file(&book.get_dest()
            .join("_FontAwesome/fonts/fontawesome-webfont.ttf")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create fontawesome-webfont.ttf")));
        };
        try!(font_awesome.write_all(theme::FONT_AWESOME_TTF));
        let mut font_awesome = if let Ok(f) = utils::fs::create_file(&book.get_dest()
            .join("_FontAwesome/fonts/fontawesome-webfont.woff")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create fontawesome-webfont.woff")));
        };
        try!(font_awesome.write_all(theme::FONT_AWESOME_WOFF));
        let mut font_awesome = if let Ok(f) = utils::fs::create_file(&book.get_dest()
            .join("_FontAwesome/fonts/fontawesome-webfont.woff2")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create fontawesome-webfont.woff2")));
        };
        try!(font_awesome.write_all(theme::FONT_AWESOME_WOFF2));
        let mut font_awesome = if let Ok(f) = utils::fs::create_file(&book.get_dest()
            .join("_FontAwesome/fonts/FontAwesome.ttf")) {
            f
        } else {
            return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not create FontAwesome.ttf")));
        };
        try!(font_awesome.write_all(theme::FONT_AWESOME_TTF));

        // Copy all remaining files
        try!(utils::fs::copy_files_except_ext(book.get_src(), book.get_dest(), true, &["md"]));

        Ok(())
    }
}

fn make_data(book: &MDBook) -> Result<serde_json::Map<String, serde_json::Value>, Box<Error>> {
    debug!("[fn]: make_data");

    let mut data = serde_json::Map::new();
    data.insert("language".to_owned(), "en".to_json());
    data.insert("title".to_owned(), book.get_title().to_json());
    data.insert("description".to_owned(), book.get_description().to_json());
    data.insert("favicon".to_owned(), "favicon.png".to_json());
    if let Some(livereload) = book.get_livereload() {
        data.insert("livereload".to_owned(), livereload.to_json());
    }

    let mut chapters = vec![];

    for item in book.iter() {
        // Create the data to inject in the template
        let mut chapter = BTreeMap::new();

        match *item {
            BookItem::Affix(ref ch) => {
                chapter.insert("name".to_owned(), ch.name.to_json());
                let path = ch.path.to_str().ok_or(io::Error::new(io::ErrorKind::Other,
                                                                 "Could not convert path to str"))?;
                chapter.insert("path".to_owned(), path.to_json());
            },
            BookItem::Chapter(ref s, ref ch) => {
                chapter.insert("section".to_owned(), s.to_json());
                chapter.insert("name".to_owned(), ch.name.to_json());
                let path = ch.path.to_str().ok_or(io::Error::new(io::ErrorKind::Other,
                                                                 "Could not convert path to str"))?;
                chapter.insert("path".to_owned(), path.to_json());
            },
            BookItem::Spacer => {
                chapter.insert("spacer".to_owned(), "_spacer_".to_json());
            },

        }

        chapters.push(chapter);
    }

    data.insert("chapters".to_owned(), chapters.to_json());

    debug!("[*]: JSON constructed");
    Ok(data)
}
<|endoftext|>


<commit_before><commit_msg>Fix(mapping): if the host name contains ".", convert to "_" for map lookup, because "." is significant in toml<commit_after><|endoftext|>


<commit_before><commit_msg>align things<commit_after><|endoftext|>


<commit_before><commit_msg>mark todos<commit_after><|endoftext|>


<commit_before>// De-duplication macro used in src/app.rs
macro_rules! get_help {
	($opt:ident) => {
		if let Some(h) = $opt.help {
	        format!("{}{}", h,
	            if let Some(ref pv) = $opt.possible_vals {
	                let mut pv_s = pv.iter().fold(String::with_capacity(50), |acc, name| acc + &format!(" {}",name)[..]);
	                pv_s.shrink_to_fit();
	                format!(" [values:{}]", &pv_s[..])
	            }else{"".to_owned()})
	    } else {
	        "    ".to_owned()
	    }
	};
}

// Thanks to bluss and flan3002 in #rust IRC
//
// Helps with rightward drift when iterating over something and matching each item.
macro_rules! for_match {
	($it:ident, $($p:pat => $($e:expr);+),*) => {
		for i in $it {
			match i {
			$(
			    $p => { $($e)+ }
			)*
			}
		}
	};
}

/// Convenience macro getting a typed value
#[macro_export]
macro_rules! value_t {
	($m:ident.value_of($v:expr), $t:ty) => {
		match $m.value_of($v) {
			Some(v) => {
				match v.parse::<$t>() {
					Ok(val) => Ok(val),
					Err(_)  => Err(format!("{} isn't a valid {}",v,stringify!($t))),
				}
			},
			None => Err(format!("Argument \"{}\" not found", $v))
		}
	};
	($m:ident.values_of($v:expr), $t:ty) => {
		match $m.values_of($v) {
			Some(ref v) => {
				let mut tmp = Vec::with_capacity(v.len());
				let mut err = None;
				for pv in v {
					match pv.parse::<$t>() {
						Ok(rv) => tmp.push(rv),
						Err(_) => {
							err = Some(format!("{} isn't a valid {}",pv,stringify!($t)));
							break
						}
					}
				}
				match err {
					Some(e) => Err(e),
					None => Ok(tmp)
				}
			},
			None => Err(format!("Argument \"{}\" not found", $v))
		}
	};
}

/// Convenience macro getting a typed value or exiting on failure
#[macro_export]
macro_rules! value_t_or_exit {
	($m:ident.value_of($v:expr), $t:ty) => {
		match $m.value_of($v) {
			Some(v) => {
				match v.parse::<$t>() {
					Ok(val) => val,
					Err(_)  => {
						println!("{} isn't a valid {}\n{}\nPlease re-run with --help for more information",v,stringify!($t), $m.usage());
						::std::process::exit(1);
					}
				}
			},
			None => {
				println!("Argument \"{}\" not found or is not valid\n{}\nPlease re-run with --help for more information",$v, $m.usage());
				::std::process::exit(1);
			}
		}
	};
	($m:ident.values_of($v:expr), $t:ty) => {
		match $m.values_of($v) {
			Some(ref v) => {
				let mut tmp = Vec::with_capacity(v.len());
				for pv in v {
					match pv.parse::<$t>() {
						Ok(rv) => tmp.push(rv),
						Err(_)  => {
							println!("{} isn't a valid {}\n{}\nPlease re-run with --help for more information",pv,stringify!($t), $m.usage());
							::std::process::exit(1);
						}
					}
				}
				tmp
			},
			None => {
				println!("Argument \"{}\" not found or is not valid\n{}\nPlease re-run with --help for more information",$v, $m.usage());
				::std::process::exit(1);
			}
		}
	};
}<commit_msg>docs(macros): add documentation covering value_t! and value_t_or_exit<commit_after>// De-duplication macro used in src/app.rs
macro_rules! get_help {
	($opt:ident) => {
		if let Some(h) = $opt.help {
	        format!("{}{}", h,
	            if let Some(ref pv) = $opt.possible_vals {
	                let mut pv_s = pv.iter().fold(String::with_capacity(50), |acc, name| acc + &format!(" {}",name)[..]);
	                pv_s.shrink_to_fit();
	                format!(" [values:{}]", &pv_s[..])
	            }else{"".to_owned()})
	    } else {
	        "    ".to_owned()
	    }
	};
}

// Thanks to bluss and flan3002 in #rust IRC
//
// Helps with rightward drift when iterating over something and matching each item.
macro_rules! for_match {
	($it:ident, $($p:pat => $($e:expr);+),*) => {
		for i in $it {
			match i {
			$(
			    $p => { $($e)+ }
			)*
			}
		}
	};
}

/// Convenience macro getting a typed value `T` where `T` implements `std::fmt::FrmStr`
/// This macro returns a `Result<T,String>` which allows you as the developer to decide
/// what you'd like to do on a failed parse. There are two types of errors, parse failures
/// and those where the argument wasn't present (such as a non-required argument).
///
/// You can use it to get a single value, or a `Vec<T>` with the `values_of()`
///
/// **NOTE:** Be cautious, as since this a macro invocation it's not exactly like
/// standard syntax.
///
///
/// # Example single value
///
/// ```no_run
/// # #[macro_use]
/// # extern crate clap;
/// # use clap::App;
/// # fn main() {
/// let matches = App::new("myapp")
///                   .arg_from_usage("[length] 'Set the length to use as a positive whole number, i.e. 20'")
///					  .get_matches();
/// let len = value_t!(matches.value_of("length"), u32).unwrap_or_else(|e|{println!("{}",e); std::process::exit(1)});
///
/// println!("{} + 2: {}", len, len + 2);
/// # }
/// ```
///
///
/// # Example multiple values
///
/// ```no_run
/// # #[macro_use]
/// # extern crate clap;
/// # use clap::App;
/// # fn main() {
/// let matches = App::new("myapp")
///                   .arg_from_usage("[seq]... 'A sequence of positive whole numbers, i.e. 20 30 45'")
///					  .get_matches();
/// for v in value_t!(matches.values_of("seq"), u32).unwrap_or_else(|e|{println!("{}",e); std::process::exit(1)}) {
/// 	println!("{} + 2: {}", v, v + 2);
///	}
/// # }
/// ```
#[macro_export]
macro_rules! value_t {
	($m:ident.value_of($v:expr), $t:ty) => {
		match $m.value_of($v) {
			Some(v) => {
				match v.parse::<$t>() {
					Ok(val) => Ok(val),
					Err(_)  => Err(format!("{} isn't a valid {}",v,stringify!($t))),
				}
			},
			None => Err(format!("Argument \"{}\" not found", $v))
		}
	};
	($m:ident.values_of($v:expr), $t:ty) => {
		match $m.values_of($v) {
			Some(ref v) => {
				let mut tmp = Vec::with_capacity(v.len());
				let mut err = None;
				for pv in v {
					match pv.parse::<$t>() {
						Ok(rv) => tmp.push(rv),
						Err(_) => {
							err = Some(format!("{} isn't a valid {}",pv,stringify!($t)));
							break
						}
					}
				}
				match err {
					Some(e) => Err(e),
					None => Ok(tmp)
				}
			},
			None => Err(format!("Argument \"{}\" not found", $v))
		}
	};
}

/// Convenience macro getting a typed value `T` where `T` implements `std::fmt::FrmStr`
/// This macro returns a `T` or `Vec<T>` or exits with a usage string upon failure. This
/// removes some of the boiler plate to handle failures from value_t! above.
///
/// You can use it to get a single value `T`, or a `Vec<T>` with the `values_of()`
///
/// **NOTE:** This should only be used on required arguments, as it can be confusing to the user
/// why they are getting error messages when it appears they're entering all required argumetns.
///
/// **NOTE:** Be cautious, as since this a macro invocation it's not exactly like
/// standard syntax.
///
///
/// # Example single value
///
/// ```no_run
/// # #[macro_use]
/// # extern crate clap;
/// # use clap::App;
/// # fn main() {
/// let matches = App::new("myapp")
///                   .arg_from_usage("[length] 'Set the length to use as a positive whole number, i.e. 20'")
///					  .get_matches();
/// let len = value_t_or_exit!(matches.value_of("length"), u32);
///
/// println!("{} + 2: {}", len, len + 2);
/// # }
/// ```
///
///
/// # Example multiple values
///
/// ```no_run
/// # #[macro_use]
/// # extern crate clap;
/// # use clap::App;
/// # fn main() {
/// let matches = App::new("myapp")
///                   .arg_from_usage("[seq]... 'A sequence of positive whole numbers, i.e. 20 30 45'")
///					  .get_matches();
/// for v in value_t_or_exit!(matches.values_of("seq"), u32) {
/// 	println!("{} + 2: {}", v, v + 2);
///	}
/// # }
/// ```
#[macro_export]
macro_rules! value_t_or_exit {
	($m:ident.value_of($v:expr), $t:ty) => {
		match $m.value_of($v) {
			Some(v) => {
				match v.parse::<$t>() {
					Ok(val) => val,
					Err(_)  => {
						println!("{} isn't a valid {}\n{}\nPlease re-run with --help for more information",v,stringify!($t), $m.usage());
						::std::process::exit(1);
					}
				}
			},
			None => {
				println!("Argument \"{}\" not found or is not valid\n{}\nPlease re-run with --help for more information",$v, $m.usage());
				::std::process::exit(1);
			}
		}
	};
	($m:ident.values_of($v:expr), $t:ty) => {
		match $m.values_of($v) {
			Some(ref v) => {
				let mut tmp = Vec::with_capacity(v.len());
				for pv in v {
					match pv.parse::<$t>() {
						Ok(rv) => tmp.push(rv),
						Err(_)  => {
							println!("{} isn't a valid {}\n{}\nPlease re-run with --help for more information",pv,stringify!($t), $m.usage());
							::std::process::exit(1);
						}
					}
				}
				tmp
			},
			None => {
				println!("Argument \"{}\" not found or is not valid\n{}\nPlease re-run with --help for more information",$v, $m.usage());
				::std::process::exit(1);
			}
		}
	};
}<|endoftext|>


<commit_before><commit_msg>add test for rust issue 94371<commit_after>#[repr(C)]
struct Demo(u64, bool, u64, u32, u64, u64, u64);

fn test() -> (Demo, Demo) {
    let mut x = Demo(1, true, 3, 4, 5, 6, 7);
    let mut y = Demo(10, false, 12, 13, 14, 15, 16);
    std::mem::swap(&mut x, &mut y);
    (x, y)
}

fn main() {
    drop(test());
}
<|endoftext|>


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

// xfail-test

// compile-flags:-Z extra-debug-info
// debugger:break zzz
// debugger:run
// debugger:finish
// debugger:print simple
// check:$1 = {x = 10, y = 20}

// debugger:print noDestructor
// check:$2 = {a = {x = 10, y = 20}, guard = -1}

// debugger:print withDestructor
// check:$3 = {a = {x = 10, y = 20}, guard = -1}

struct NoDestructor {
    x : i32,
    y : i64
}

struct WithDestructor {
    x : i32,
    y : i64
}

impl Drop for WithDestructor {
    fn finalize(&self) {}
}

struct NoDestructorGuarded
{
    a: NoDestructor,
    guard: i64
}

struct WithDestructorGuarded
{
    a: WithDestructor,
    guard: i64
}

// The compiler adds a 'destructed' boolean field to structs implementing Drop. This field is used
// at runtime to prevent finalize() to be executed more than once (see middle::trans::adt).
// This field must be incorporated by the debug info generation. Otherwise the debugger assumes a
// wrong size/layout for the struct.
fn main() {

    let simple = WithDestructor { x: 10, y: 20 };

    let noDestructor = NoDestructorGuarded {
        a: NoDestructor { x: 10, y: 20 },
        guard: -1
    };

    // If the destructor flag field is not incorporated into the debug info for 'WithDestructor'
    // then the debugger will have an invalid offset for the field 'guard' and thus should not be
    // able to read its value correctly.
    let withDestructor = WithDestructorGuarded {
        a: WithDestructor { x: 10, y: 20 },
        guard: -1
    };

    zzz();
}

fn zzz() {()}
<|endoftext|>