<commit_before>use quote::{ToTokens, Tokens};
use syn::punctuated::Punctuated;
use syn::synom::Synom;
use syn::{Field, FieldValue, Ident, Meta};

mod metadata;
mod request;
mod response;

use self::metadata::Metadata;
use self::request::Request;
use self::response::Response;

pub fn strip_serde_attrs(field: &Field) -> Field {
    let mut field = field.clone();

    field.attrs = field.attrs.into_iter().filter(|attr| {
        let meta = attr.interpret_meta()
            .expect("ruma_api! could not parse field attributes");

        let meta_list = match meta {
            Meta::List(meta_list) => meta_list,
            _ => panic!("expected Meta::List"),
        };

        if meta_list.ident.as_ref() != "serde" {
            return true;
        }

        false
    }).collect();

    field
}

pub struct Api {
    metadata: Metadata,
    request: Request,
    response: Response,
}

impl From<RawApi> for Api {
    fn from(raw_api: RawApi) -> Self {
        Api {
            metadata: raw_api.metadata.into(),
            request: raw_api.request.into(),
            response: raw_api.response.into(),
        }
    }
}

impl ToTokens for Api {
    fn to_tokens(&self, tokens: &mut Tokens) {
        let description = &self.metadata.description;
        let method = Ident::from(self.metadata.method.as_ref());
        let name = &self.metadata.name;
        let path = &self.metadata.path;
        let rate_limited = &self.metadata.rate_limited;
        let requires_authentication = &self.metadata.requires_authentication;

        let request = &self.request;
        let request_types = quote! { #request };
        let response = &self.response;
        let response_types = quote! { #response };

        let set_request_path = if self.request.has_path_fields() {
            let path_str = path.as_str();

            assert!(path_str.starts_with('/'), "path needs to start with '/'");
            assert!(
                path_str.chars().filter(|c| *c == ':').count() == self.request.path_field_count(),
                "number of declared path parameters needs to match amount of placeholders in path"
            );

            let request_path_init_fields = self.request.request_path_init_fields();

            let mut tokens = quote! {
                let request_path = RequestPath {
                    #request_path_init_fields
                };

                // This `unwrap()` can only fail when the url is a
                // cannot-be-base url like `mailto:` or `data:`, which is not
                // the case for our placeholder url.
                let mut path_segments = url.path_segments_mut().unwrap();
            };

            for segment in path_str[1..].split('/') {
                tokens.append_all(quote! {
                    path_segments.push
                });

                if segment.starts_with(':') {
                    let path_var = &segment[1..];
                    let path_var_ident = Ident::from(path_var);

                    tokens.append_all(quote! {
                        (&request_path.#path_var_ident.to_string());
                    });
                } else {
                    tokens.append_all(quote! {
                        (#segment);
                    });
                }
            }

            tokens
        } else {
            quote! {
                url.set_path(metadata.path);
            }
        };

        let set_request_query = if self.request.has_query_fields() {
            let request_query_init_fields = self.request.request_query_init_fields();

            quote! {
                let request_query = RequestQuery {
                    #request_query_init_fields
                };

                url.set_query(Some(&::serde_urlencoded::to_string(request_query)?));
            }
        } else {
            Tokens::new()
        };

        let add_headers_to_request = if self.request.has_header_fields() {
            let mut header_tokens = quote! {
                let headers = http_request.headers_mut();
            };

            header_tokens.append_all(self.request.add_headers_to_request());

            header_tokens
        } else {
            Tokens::new()
        };

        let add_body_to_request = if let Some(field) = self.request.newtype_body_field() {
            let field_name = field.ident.expect("expected field to have an identifier");

            quote! {
                let request_body = RequestBody(request.#field_name);

                http_request.set_body(::serde_json::to_vec(&request_body)?);
            }
        } else if self.request.has_body_fields() {
            let request_body_init_fields = self.request.request_body_init_fields();

            quote! {
                let request_body = RequestBody {
                    #request_body_init_fields
                };

                http_request.set_body(::serde_json::to_vec(&request_body)?);
            }
        } else {
            Tokens::new()
        };

        let deserialize_response_body = if let Some(field) = self.response.newtype_body_field() {
            let field_type = &field.ty;

            quote! {
                let future_response = http_response.body()
                    .fold::<_, _, Result<_, ::std::io::Error>>(Vec::new(), |mut bytes, chunk| {
                        bytes.write_all(&chunk)?;

                        Ok(bytes)
                    })
                    .map_err(::ruma_api::Error::from)
                    .and_then(|bytes| {
                        ::serde_json::from_slice::<#field_type>(bytes.as_slice())
                            .map_err(::ruma_api::Error::from)
                    })
            }
        } else if self.response.has_body_fields() {
            quote! {
                let future_response = http_response.body()
                    .fold::<_, _, Result<_, ::std::io::Error>>(Vec::new(), |mut bytes, chunk| {
                        bytes.write_all(&chunk)?;

                        Ok(bytes)
                    })
                    .map_err(::ruma_api::Error::from)
                    .and_then(|bytes| {
                        ::serde_json::from_slice::<ResponseBody>(bytes.as_slice())
                            .map_err(::ruma_api::Error::from)
                    })
            }
        } else {
            quote! {
                let future_response = ::futures::future::ok(())
            }
        };

        let extract_headers = if self.response.has_header_fields() {
            quote! {
                let mut headers = http_response.headers().clone();
            }
        } else {
            Tokens::new()
        };

        let response_init_fields = if self.response.has_fields() {
            self.response.init_fields()
        } else {
            Tokens::new()
        };

        tokens.append_all(quote! {
            #[allow(unused_imports)]
            use std::io::Write as _Write;

            #[allow(unused_imports)]
            use ::futures::{Future as _Future, Stream as _Stream};
            use ::ruma_api::Endpoint as _RumaApiEndpoint;

            /// The API endpoint.
            #[derive(Debug)]
            pub struct Endpoint;

            #request_types

            impl<T> ::std::convert::TryFrom<Request> for ::http::Request<T> {
                type Error = ::ruma_api::Error;

                #[allow(unused_mut, unused_variables)]
                fn try_from(request: Request) -> Result<Self, Self::Error> {
                    let metadata = Endpoint::METADATA;

                    // Use dummy homeserver url which has to be overwritten in
                    // the calling code. Previously (with http::Uri) this was
                    // not required, but Url::parse only accepts absolute urls.
                    let mut url = ::url::Url::parse("http://invalid-host-please-change/").unwrap();

                    { #set_request_path }
                    { #set_request_query }

                    let mut http_request = ::http::Request::new(
                        ::http::Method::#method,
                        // Every valid URL is a valid URI
                        url.into_string().parse().unwrap(),
                    );

                    { #add_headers_to_request }

                    { #add_body_to_request }

                    Ok(http_request)
                }
            }

            #response_types

            impl<T> ::futures::future::FutureFrom<::http::Response<T>> for Response {
                type Future = Box<_Future<Item = Self, Error = Self::Error>>;
                type Error = ::ruma_api::Error;

                #[allow(unused_variables)]
                fn future_from(http_response: ::http::Response<T>)
                -> Box<_Future<Item = Self, Error = Self::Error>> {
                    #extract_headers

                    #deserialize_response_body
                    .and_then(move |response_body| {
                        let response = Response {
                            #response_init_fields
                        };

                        Ok(response)
                    });

                    Box::new(future_response)
                }
            }

            impl ::ruma_api::Endpoint for Endpoint {
                type Request = Request;
                type Response = Response;

                const METADATA: ::ruma_api::Metadata = ::ruma_api::Metadata {
                    description: #description,
                    method: ::http::Method::#method,
                    name: #name,
                    path: #path,
                    rate_limited: #rate_limited,
                    requires_authentication: #requires_authentication,
                };
            }
        });
    }
}

type ParseMetadata = Punctuated<FieldValue, Token![,]>;
type ParseFields = Punctuated<Field, Token![,]>;

pub struct RawApi {
    pub metadata: Vec<FieldValue>,
    pub request: Vec<Field>,
    pub response: Vec<Field>,
}

impl Synom for RawApi {
    named!(parse -> Self, do_parse!(
        custom_keyword!(metadata) >>
        metadata: braces!(ParseMetadata::parse_terminated) >>
        custom_keyword!(request) >>
        request: braces!(call!(ParseFields::parse_terminated_with, Field::parse_named)) >>
        custom_keyword!(response) >>
        response: braces!(call!(ParseFields::parse_terminated_with, Field::parse_named)) >>
        (RawApi {
            metadata: metadata.1.into_iter().collect(),
            request: request.1.into_iter().collect(),
            response: response.1.into_iter().collect(),
        })
    ));
}
<commit_msg>Use Vec<u8> for request and response bodies. Use http's API for creating requests and responses.<commit_after>use quote::{ToTokens, Tokens};
use syn::punctuated::Punctuated;
use syn::synom::Synom;
use syn::{Field, FieldValue, Ident, Meta};

mod metadata;
mod request;
mod response;

use self::metadata::Metadata;
use self::request::Request;
use self::response::Response;

pub fn strip_serde_attrs(field: &Field) -> Field {
    let mut field = field.clone();

    field.attrs = field.attrs.into_iter().filter(|attr| {
        let meta = attr.interpret_meta()
            .expect("ruma_api! could not parse field attributes");

        let meta_list = match meta {
            Meta::List(meta_list) => meta_list,
            _ => panic!("expected Meta::List"),
        };

        if meta_list.ident.as_ref() != "serde" {
            return true;
        }

        false
    }).collect();

    field
}

pub struct Api {
    metadata: Metadata,
    request: Request,
    response: Response,
}

impl From<RawApi> for Api {
    fn from(raw_api: RawApi) -> Self {
        Api {
            metadata: raw_api.metadata.into(),
            request: raw_api.request.into(),
            response: raw_api.response.into(),
        }
    }
}

impl ToTokens for Api {
    fn to_tokens(&self, tokens: &mut Tokens) {
        let description = &self.metadata.description;
        let method = Ident::from(self.metadata.method.as_ref());
        let name = &self.metadata.name;
        let path = &self.metadata.path;
        let rate_limited = &self.metadata.rate_limited;
        let requires_authentication = &self.metadata.requires_authentication;

        let request = &self.request;
        let request_types = quote! { #request };
        let response = &self.response;
        let response_types = quote! { #response };

        let set_request_path = if self.request.has_path_fields() {
            let path_str = path.as_str();

            assert!(path_str.starts_with('/'), "path needs to start with '/'");
            assert!(
                path_str.chars().filter(|c| *c == ':').count() == self.request.path_field_count(),
                "number of declared path parameters needs to match amount of placeholders in path"
            );

            let request_path_init_fields = self.request.request_path_init_fields();

            let mut tokens = quote! {
                let request_path = RequestPath {
                    #request_path_init_fields
                };

                // This `unwrap()` can only fail when the url is a
                // cannot-be-base url like `mailto:` or `data:`, which is not
                // the case for our placeholder url.
                let mut path_segments = url.path_segments_mut().unwrap();
            };

            for segment in path_str[1..].split('/') {
                tokens.append_all(quote! {
                    path_segments.push
                });

                if segment.starts_with(':') {
                    let path_var = &segment[1..];
                    let path_var_ident = Ident::from(path_var);

                    tokens.append_all(quote! {
                        (&request_path.#path_var_ident.to_string());
                    });
                } else {
                    tokens.append_all(quote! {
                        (#segment);
                    });
                }
            }

            tokens
        } else {
            quote! {
                url.set_path(metadata.path);
            }
        };

        let set_request_query = if self.request.has_query_fields() {
            let request_query_init_fields = self.request.request_query_init_fields();

            quote! {
                let request_query = RequestQuery {
                    #request_query_init_fields
                };

                url.set_query(Some(&::serde_urlencoded::to_string(request_query)?));
            }
        } else {
            Tokens::new()
        };

        let add_headers_to_request = if self.request.has_header_fields() {
            let mut header_tokens = quote! {
                let headers = http_request.headers_mut();
            };

            header_tokens.append_all(self.request.add_headers_to_request());

            header_tokens
        } else {
            Tokens::new()
        };

        let create_http_request = if let Some(field) = self.request.newtype_body_field() {
            let field_name = field.ident.expect("expected field to have an identifier");

            quote! {
                let request_body = RequestBody(request.#field_name);

                let mut http_request = ::http::Request::new(::serde_json::to_vec(&request_body)?);
            }
        } else if self.request.has_body_fields() {
            let request_body_init_fields = self.request.request_body_init_fields();

            quote! {
                let request_body = RequestBody {
                    #request_body_init_fields
                };

                let mut http_request = ::http::Request::new(::serde_json::to_vec(&request_body)?);
            }
        } else {
            quote! {
                let mut http_request = ::http::Request::new(());
            }
        };

        let deserialize_response_body = if let Some(field) = self.response.newtype_body_field() {
            let field_type = &field.ty;

            quote! {
                let future_response = http_response.body()
                    .fold::<_, _, Result<_, ::std::io::Error>>(Vec::new(), |mut bytes, chunk| {
                        bytes.write_all(&chunk)?;

                        Ok(bytes)
                    })
                    .map_err(::ruma_api::Error::from)
                    .and_then(|bytes| {
                        ::serde_json::from_slice::<#field_type>(bytes.as_slice())
                            .map_err(::ruma_api::Error::from)
                    })
            }
        } else if self.response.has_body_fields() {
            quote! {
                let future_response = http_response.body()
                    .fold::<_, _, Result<_, ::std::io::Error>>(Vec::new(), |mut bytes, chunk| {
                        bytes.write_all(&chunk)?;

                        Ok(bytes)
                    })
                    .map_err(::ruma_api::Error::from)
                    .and_then(|bytes| {
                        ::serde_json::from_slice::<ResponseBody>(bytes.as_slice())
                            .map_err(::ruma_api::Error::from)
                    })
            }
        } else {
            quote! {
                let future_response = ::futures::future::ok(())
            }
        };

        let extract_headers = if self.response.has_header_fields() {
            quote! {
                let mut headers = http_response.headers().clone();
            }
        } else {
            Tokens::new()
        };

        let response_init_fields = if self.response.has_fields() {
            self.response.init_fields()
        } else {
            Tokens::new()
        };

        tokens.append_all(quote! {
            #[allow(unused_imports)]
            use std::io::Write as _Write;

            #[allow(unused_imports)]
            use ::futures::{Future as _Future, Stream as _Stream};
            use ::ruma_api::Endpoint as _RumaApiEndpoint;

            /// The API endpoint.
            #[derive(Debug)]
            pub struct Endpoint;

            #request_types

            impl ::std::convert::TryFrom<Request> for ::http::Request<Vec<u8>> {
                type Error = ::ruma_api::Error;

                #[allow(unused_mut, unused_variables)]
                fn try_from(request: Request) -> Result<Self, Self::Error> {
                    let metadata = Endpoint::METADATA;

                    // Use dummy homeserver url which has to be overwritten in
                    // the calling code. Previously (with http::Uri) this was
                    // not required, but Url::parse only accepts absolute urls.
                    let mut url = ::url::Url::parse("http://invalid-host-please-change/").unwrap();

                    { #set_request_path }
                    { #set_request_query }

                    #create_http_request

                    *http_request.method_mut() = ::http::Method::#method;
                    *http_request.uri_mut() = url.into_string().parse().unwrap();

                    { #add_headers_to_request }

                    Ok(http_request)
                }
            }

            #response_types

            impl ::futures::future::FutureFrom<::http::Response<Vec<u8>>> for Response {
                type Future = Box<_Future<Item = Self, Error = Self::Error>>;
                type Error = ::ruma_api::Error;

                #[allow(unused_variables)]
                fn future_from(http_response: ::http::Response<Vec<u8>>)
                -> Box<_Future<Item = Self, Error = Self::Error>> {
                    #extract_headers

                    #deserialize_response_body
                    .and_then(move |response_body| {
                        let response = Response {
                            #response_init_fields
                        };

                        Ok(response)
                    });

                    Box::new(future_response)
                }
            }

            impl ::ruma_api::Endpoint<Vec<u8>, Vec<u8>> for Endpoint {
                type Request = Request;
                type Response = Response;

                const METADATA: ::ruma_api::Metadata = ::ruma_api::Metadata {
                    description: #description,
                    method: ::http::Method::#method,
                    name: #name,
                    path: #path,
                    rate_limited: #rate_limited,
                    requires_authentication: #requires_authentication,
                };
            }
        });
    }
}

type ParseMetadata = Punctuated<FieldValue, Token![,]>;
type ParseFields = Punctuated<Field, Token![,]>;

pub struct RawApi {
    pub metadata: Vec<FieldValue>,
    pub request: Vec<Field>,
    pub response: Vec<Field>,
}

impl Synom for RawApi {
    named!(parse -> Self, do_parse!(
        custom_keyword!(metadata) >>
        metadata: braces!(ParseMetadata::parse_terminated) >>
        custom_keyword!(request) >>
        request: braces!(call!(ParseFields::parse_terminated_with, Field::parse_named)) >>
        custom_keyword!(response) >>
        response: braces!(call!(ParseFields::parse_terminated_with, Field::parse_named)) >>
        (RawApi {
            metadata: metadata.1.into_iter().collect(),
            request: request.1.into_iter().collect(),
            response: response.1.into_iter().collect(),
        })
    ));
}
<|endoftext|>


<commit_before><commit_msg>add codegen test<commit_after>// Copyright 2017 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.

// compile-flags: -O
#![crate_type="lib"]
#![feature(maybe_uninit)]

use std::mem::MaybeUninit;

// Boxing a `MaybeUninit` value should not copy junk from the stack
#[no_mangle]
pub fn box_uninitialized() -> Box<MaybeUninit<usize>> {
    // CHECK-LABEL: @box_uninitialized
    // CHECK-NOT: store
    Box::new(MaybeUninit::uninitialized())
}
<|endoftext|>


<commit_before><commit_msg>Add a test written by jdm that tests repeated vector self appending.<commit_after>// xfail-stage0

fn main()
{
    // Make sure we properly handle repeated self-appends.
    let vec[int] a = [0];
    auto i = 20;
    while (i > 0) {
        a += a;
        i -= 1;
    }
}
<|endoftext|>


<commit_before><commit_msg>Remove duplicated documentation<commit_after><|endoftext|>


<commit_before><commit_msg>auto merge of #529 : eschweic/servo/master, r=pcwalton<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// Implements a Quadtree data structure to keep track of which tiles have
// been rasterized and which have not.

use geom::point::Point2D;
use geom::size::Size2D;
use geom::rect::Rect;

priv enum Quadtype {
    Empty,
    Base,
    Branch,
}

priv enum Quadrant {
    TL = 0,
    TR = 1,
    BL = 2,
    BR = 3,
}

pub struct Quadtree {
    quadtype: Quadtype,
    rect: Rect<uint>,
    quadrants: [Option<~Quadtree>, ..4],
}

impl Quadtree {
    pub fn new(x: uint, y: uint, width: uint, height: uint) -> Quadtree {
        Quadtree {
            quadtype: Empty,
            rect: Rect {
                origin: Point2D(x, y),
                size: Size2D(width, height),
            },

            quadrants: [None, None, None, None],
        }
    }

    /// Determine which child contains a given point
    priv fn get_quadrant(&self, x: uint, y: uint) -> Quadrant {
        let self_width = self.rect.size.width;
        let self_height = self.rect.size.height;
        let self_x = self.rect.origin.x;
        let self_y = self.rect.origin.y;
        match (self_width, self_height) {
            (1, _) => {
                if y < self_y + self_height / 2 {
                    TL
                } else {
                    BR
                }
            }
            (_, 1) => {
                if x < self_x + self_width / 2 {
                    TL
                } else {
                    BR
                }
            }
            _ => {
                if x < self_x + self_width / 2 {
                    if y < self_y + self_height / 2 {
                        TL
                    } else {
                        BL
                    }
                } else if y < self_y + self_height / 2 {
                    TR
                } else {
                    BR
                }
            }
        }
    }

    /// Change a point from Empty to Base
    pub fn add_region(&mut self, x: uint, y: uint) {
        let self_x = self.rect.origin.x;
        let self_y = self.rect.origin.y;
        let self_width = self.rect.size.width;
        let self_height = self.rect.size.height;

        debug!("Quadtree: adding: (%?, %?) w:%?, h:%?", self_x, self_y, self_width, self_height);

        if x >= self_x + self_width || x < self_x
            || y >= self_y + self_height || y < self_y {
            return; // Out of bounds
        }
        match self.quadtype {
            Base => return,
            Empty => {
                if self_width == 1 && self_height == 1 {
                    self.quadtype = Base;
                    return;
                }
                self.quadtype = Branch;

                // Initialize children
                self.quadrants[TL as int] = Some(~Quadtree::new(self_x,
                                                                self_y,
                                                                (self_width / 2).max(&1),
                                                                (self_height / 2).max(&1)));
                if self_width > 1 && self_height > 1 {
                    self.quadrants[TR as int] = Some(~Quadtree::new(self_x + self_width / 2,
                                                                    self_y,
                                                                    self_width - self_width / 2,
                                                                    self_height / 2));
                    self.quadrants[BL as int] = Some(~Quadtree::new(self_x,
                                                                    self_y + self_height / 2,
                                                                    self_width / 2,
                                                                    self_height - self_height / 2));
                }
                self.quadrants[BR as int] = Some(~Quadtree::new(self_x + self_width / 2,
                                                                self_y + self_height / 2,
                                                                self_width - self_width / 2,
                                                                self_height - self_height / 2));
            }
            Branch => {} // Fall through
        }

        // If we've made it this far, we know we are a branch and therefore have children
        let index = self.get_quadrant(x, y) as int;

        match self.quadrants[index] {
            None => fail!("Quadtree: child query failure"),
            Some(ref mut region) => {
                // Recurse if necessary
                match region.quadtype {
                    Empty | Branch => {
                        region.add_region(x, y);
                    }
                    Base => {} // nothing to do
                }
            }
        }

        // FIXME: ideally we could make the assignments in the match,
        // but borrowed pointers prevent that. So here's a flag instead.
        let mut base_flag = 0;

        // If all children are Bases, convert self to Base
        match (&self.quadrants, self_width, self_height) {
            (&[Some(ref tl_q), _, _, Some(ref br_q)], 1, _) |
            (&[Some(ref tl_q), _, _, Some(ref br_q)], _, 1) => {
                match(tl_q.quadtype, br_q.quadtype) {
                    (Base, Base) => {
                        base_flag = 1;
                    }
                    _ => {} // nothing to do
                }
            }
            (&[Some(ref tl_q), Some(ref tr_q), Some(ref bl_q), Some(ref br_q)], _, _) => {
                    match (tl_q.quadtype, tr_q.quadtype, bl_q.quadtype, br_q.quadtype) {
                        (Base, Base, Base, Base) => {
                            base_flag = 2;
                        }
                        _ => {} // nothing to do
                    }
            }
            _ => {} // nothing to do
        }

        match base_flag {
            0 => {}
            1 => {
                self.quadtype = Base;
                self.quadrants[TL as int] = None;
                self.quadrants[BR as int] = None;
            }
            2 => {
                self.quadtype = Base;
                self.quadrants[TL as int] = None;
                self.quadrants[TR as int] = None;
                self.quadrants[BL as int] = None;
                self.quadrants[BR as int] = None;
            }
            _ => fail!("Quadtree: Unknown flag type"),
        }
    }

    /// Check if a point is a Base or Empty.
    pub fn check_region(&self, x: uint, y: uint) -> bool {
        let self_x = self.rect.origin.x;
        let self_y = self.rect.origin.y;
        let self_width = self.rect.size.width;
        let self_height = self.rect.size.height;

        if x >= self_x + self_width || x < self_x
            || y >= self_y + self_height || y < self_y {
            return false; // out of bounds
        }

        match self.quadtype {
            Empty => false,
            Base => true,
            Branch => {
                let index = self.get_quadrant(x,y) as int;
                match self.quadrants[index] {
                    None => fail!("Quadtree: child query failed"),
                    Some(ref region) => region.check_region(x, y)
                }
            }
        }
    }

}

#[test]
fn test_add_region() {
    let mut t = Quadtree::new(50, 50, 3, 4);
    assert!(!t.check_region(50, 50));
    t.add_region(50, 50);
    assert!(t.check_region(50, 50));
    assert!(!t.check_region(51, 50));
    assert!(!t.check_region(50, 51));
    t.add_region(53, 50);
    assert!(!t.check_region(53, 50));

}<|endoftext|>


<commit_before><commit_msg>Cubes - resize support<commit_after><|endoftext|>


<commit_before><commit_msg>disallow range for now<commit_after><|endoftext|>


<commit_before><commit_msg>Remove superfluous debug println.<commit_after><|endoftext|>


<commit_before><commit_msg>add option for sprites onto tiles<commit_after><|endoftext|>


<commit_before><commit_msg>Implement LED brightness regs<commit_after><|endoftext|>


<commit_before><commit_msg>Use Ar1 alias in Map impls<commit_after><|endoftext|>


<commit_before><commit_msg>Implement sound disable reg and wave mem lockout<commit_after><|endoftext|>


<commit_before>use ansi_term::Style;
use ansi_term::Style::Plain;
use ansi_term::Colour::{Red, Green, Yellow, Blue, Cyan, Purple, Fixed};

use std::default::Default;

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Colours {
    pub filetypes:  FileTypes,
    pub perms:      Permissions,
    pub size:       Size,
    pub users:      Users,
    pub links:      Links,
    pub git:        Git,

    pub punctuation:  Style,
    pub date:         Style,
    pub inode:        Style,
    pub blocks:       Style,
    pub header:       Style,

    pub symlink_path:     Style,
    pub broken_arrow:     Style,
    pub broken_filename:  Style,
}

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct FileTypes {
    pub normal: Style,
    pub directory: Style,
    pub symlink: Style,
    pub special: Style,
    pub executable: Style,
    pub image: Style,
    pub video: Style,
    pub music: Style,
    pub lossless: Style,
    pub crypto: Style,
    pub document: Style,
    pub compressed: Style,
    pub temp: Style,
    pub immediate: Style,
    pub compiled: Style,
}

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Permissions {
    pub user_read:          Style,
    pub user_write:         Style,
    pub user_execute_file:  Style,
    pub user_execute_other: Style,

    pub group_read:    Style,
    pub group_write:   Style,
    pub group_execute: Style,

    pub other_read:    Style,
    pub other_write:   Style,
    pub other_execute: Style,

    pub attribute:  Style,
}

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Size {
    pub numbers: Style,
    pub unit: Style,
}

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Users {
    pub user_you: Style,
    pub user_someone_else: Style,
    pub group_yours: Style,
    pub group_not_yours: Style,
}

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Links {
    pub normal: Style,
    pub multi_link_file: Style,
}

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Git {
    pub new: Style,
    pub modified: Style,
    pub deleted: Style,
    pub renamed: Style,
    pub typechange: Style,
}

impl Colours {
    pub fn plain() -> Colours {
        Colours::default()
    }

    pub fn colourful() -> Colours {
        Colours {
            filetypes: FileTypes {
                normal:      Plain,
                directory:   Blue.bold(),
                symlink:     Cyan.normal(),
                special:     Yellow.normal(),
                executable:  Green.bold(),
                image:       Fixed(133).normal(),
                video:       Fixed(135).normal(),
                music:       Fixed(92).normal(),
                lossless:    Fixed(93).normal(),
                crypto:      Fixed(109).normal(),
                document:    Fixed(105).normal(),
                compressed:  Red.normal(),
                temp:        Fixed(244).normal(),
                immediate:   Yellow.bold().underline(),
                compiled:    Fixed(137).normal(),
            },

            perms: Permissions {
                user_read:           Yellow.bold(),
                user_write:          Red.bold(),
                user_execute_file:   Green.bold().underline(),
                user_execute_other:  Green.bold(),
                group_read:          Yellow.normal(),
                group_write:         Red.normal(),
                group_execute:       Green.normal(),
                other_read:          Yellow.normal(),
                other_write:         Red.normal(),
                other_execute:       Green.normal(),
                attribute:           Plain,
            },

            size: Size {
                numbers:  Green.bold(),
                unit:     Green.normal(),
            },

            users: Users {
                user_you:           Yellow.bold(),
                user_someone_else:  Plain,
                group_yours:        Yellow.bold(),
                group_not_yours:    Plain,
            },

            links: Links {
                normal:          Red.bold(),
                multi_link_file: Red.on(Yellow),
            },

            git: Git {
                new:         Green.normal(),
                modified:    Blue.normal(),
                deleted:     Red.normal(),
                renamed:     Yellow.normal(),
                typechange:  Purple.normal(),
            },

            punctuation:  Fixed(244).normal(),
            date:         Blue.normal(),
            inode:        Purple.normal(),
            blocks:       Cyan.normal(),
            header:       Plain.underline(),

            symlink_path:     Cyan.normal(),
            broken_arrow:     Red.normal(),
            broken_filename:  Red.underline()
        }
    }
}
<commit_msg>Use new ansi-term<commit_after>use ansi_term::Style;
use ansi_term::Colour::{Red, Green, Yellow, Blue, Cyan, Purple, Fixed};

use std::default::Default;

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Colours {
    pub filetypes:  FileTypes,
    pub perms:      Permissions,
    pub size:       Size,
    pub users:      Users,
    pub links:      Links,
    pub git:        Git,

    pub punctuation:  Style,
    pub date:         Style,
    pub inode:        Style,
    pub blocks:       Style,
    pub header:       Style,

    pub symlink_path:     Style,
    pub broken_arrow:     Style,
    pub broken_filename:  Style,
}

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct FileTypes {
    pub normal: Style,
    pub directory: Style,
    pub symlink: Style,
    pub special: Style,
    pub executable: Style,
    pub image: Style,
    pub video: Style,
    pub music: Style,
    pub lossless: Style,
    pub crypto: Style,
    pub document: Style,
    pub compressed: Style,
    pub temp: Style,
    pub immediate: Style,
    pub compiled: Style,
}

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Permissions {
    pub user_read:          Style,
    pub user_write:         Style,
    pub user_execute_file:  Style,
    pub user_execute_other: Style,

    pub group_read:    Style,
    pub group_write:   Style,
    pub group_execute: Style,

    pub other_read:    Style,
    pub other_write:   Style,
    pub other_execute: Style,

    pub attribute:  Style,
}

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Size {
    pub numbers: Style,
    pub unit: Style,
}

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Users {
    pub user_you: Style,
    pub user_someone_else: Style,
    pub group_yours: Style,
    pub group_not_yours: Style,
}

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Links {
    pub normal: Style,
    pub multi_link_file: Style,
}

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Git {
    pub new: Style,
    pub modified: Style,
    pub deleted: Style,
    pub renamed: Style,
    pub typechange: Style,
}

impl Colours {
    pub fn plain() -> Colours {
        Colours::default()
    }

    pub fn colourful() -> Colours {
        Colours {
            filetypes: FileTypes {
                normal:      Style::default(),
                directory:   Blue.bold(),
                symlink:     Cyan.normal(),
                special:     Yellow.normal(),
                executable:  Green.bold(),
                image:       Fixed(133).normal(),
                video:       Fixed(135).normal(),
                music:       Fixed(92).normal(),
                lossless:    Fixed(93).normal(),
                crypto:      Fixed(109).normal(),
                document:    Fixed(105).normal(),
                compressed:  Red.normal(),
                temp:        Fixed(244).normal(),
                immediate:   Yellow.bold().underline(),
                compiled:    Fixed(137).normal(),
            },

            perms: Permissions {
                user_read:           Yellow.bold(),
                user_write:          Red.bold(),
                user_execute_file:   Green.bold().underline(),
                user_execute_other:  Green.bold(),
                group_read:          Yellow.normal(),
                group_write:         Red.normal(),
                group_execute:       Green.normal(),
                other_read:          Yellow.normal(),
                other_write:         Red.normal(),
                other_execute:       Green.normal(),
                attribute:           Style::default(),
            },

            size: Size {
                numbers:  Green.bold(),
                unit:     Green.normal(),
            },

            users: Users {
                user_you:           Yellow.bold(),
                user_someone_else:  Style::default(),
                group_yours:        Yellow.bold(),
                group_not_yours:    Style::default(),
            },

            links: Links {
                normal:          Red.bold(),
                multi_link_file: Red.on(Yellow),
            },

            git: Git {
                new:         Green.normal(),
                modified:    Blue.normal(),
                deleted:     Red.normal(),
                renamed:     Yellow.normal(),
                typechange:  Purple.normal(),
            },

            punctuation:  Fixed(244).normal(),
            date:         Blue.normal(),
            inode:        Purple.normal(),
            blocks:       Cyan.normal(),
            header:       Style::default().underline(),

            symlink_path:     Cyan.normal(),
            broken_arrow:     Red.normal(),
            broken_filename:  Red.underline()
        }
    }
}
<|endoftext|>


<commit_before>//! Yet more cli test cases. These are testing that the output
//! is exactly as expected.

extern crate multirust_dist;
extern crate multirust_mock;

use multirust_mock::clitools::{self, Config, Scenario,
                               expect_ok, expect_ok_ex,
                               expect_err_ex,
                               this_host_triple};
use std::env;

fn setup(f: &Fn(&Config)) {
    clitools::setup(Scenario::SimpleV2, f);
}

#[test]
fn update() {
    setup(&|config| {
        expect_ok_ex(config, &["multirust", "update", "nightly"],
r"
nightly revision:

1.3.0 (hash-n-2)
1.3.0 (hash-n-2)

",
r"info: installing toolchain 'nightly'
info: downloading toolchain manifest
info: downloading component 'rust-std'
info: downloading component 'rustc'
info: downloading component 'cargo'
info: downloading component 'rust-docs'
info: installing component 'rust-std'
info: installing component 'rustc'
info: installing component 'cargo'
info: installing component 'rust-docs'
info: toolchain 'nightly' installed
");
    });
}

#[test]
fn update_again() {
    setup(&|config| {
        expect_ok(config, &["multirust", "update", "nightly"]);
        expect_ok_ex(config, &["multirust", "update", "nightly"],
r"
nightly revision:

1.3.0 (hash-n-2)
1.3.0 (hash-n-2)

",
r"info: updating existing install for 'nightly'
info: downloading toolchain manifest
info: toolchain is already up to date
");
    });
}

#[test]
fn default() {
    setup(&|config| {
        expect_ok_ex(config, &["multirust", "update", "nightly"],
r"
nightly revision:

1.3.0 (hash-n-2)
1.3.0 (hash-n-2)

",
r"info: installing toolchain 'nightly'
info: downloading toolchain manifest
info: downloading component 'rust-std'
info: downloading component 'rustc'
info: downloading component 'cargo'
info: downloading component 'rust-docs'
info: installing component 'rust-std'
info: installing component 'rustc'
info: installing component 'cargo'
info: installing component 'rust-docs'
info: toolchain 'nightly' installed
");
    });
}

#[test]
fn override_again() {
    setup(&|config| {
        let cwd = env::current_dir().unwrap();
        expect_ok(config, &["multirust", "override", "nightly"]);
        expect_ok_ex(config, &["multirust", "override", "nightly"],
r"
nightly revision:

1.3.0 (hash-n-2)
1.3.0 (hash-n-2)

",
&format!(
r"info: using existing install for 'nightly'
info: override toolchain for '{}' set to 'nightly'
", cwd.display()));
    });
}

#[test]
fn remove_override() {
    setup(&|config| {
        let cwd = env::current_dir().unwrap();
        expect_ok(config, &["multirust", "override", "nightly"]);
        expect_ok_ex(config, &["multirust", "remove-override"],
r"",
&format!(r"info: override toolchain for '{}' removed
", cwd.display()));
    });
}

#[test]
fn remove_override_none() {
    setup(&|config| {
        let cwd = env::current_dir().unwrap();
        expect_ok_ex(config, &["multirust", "remove-override"],
r"",
&format!(r"info: no override toolchain for '{}'
", cwd.display()));
    });
}

#[test]
fn update_no_manifest() {
    setup(&|config| {
        expect_err_ex(config, &["multirust", "update", "nightly-2016-01-01"],
r"",
r"info: installing toolchain 'nightly-2016-01-01'
info: downloading toolchain manifest
error: no release found for 'nightly-2016-01-01'
");
    });
}

#[test]
fn delete_data() {
    setup(&|config| {
        expect_ok(config, &["multirust", "default", "nightly"]);
        assert!(config.homedir.path().exists());
        expect_ok_ex(config, &["multirust", "delete-data", "-y"],
r"",
&format!(
r"info: deleted directory '{}'
", config.homedir.path().display()));
    });
}

// Issue #111
// multirust update nightly-2016-03-1
#[test]
fn update_invalid_toolchain() {
   setup(&|config| {
        expect_err_ex(config, &["multirust", "update", "nightly-2016-03-1"],
r"",
r"error: toolchain 'nightly-2016-03-1' is not installed
");
   });
 }

#[test]
fn default_invalid_toolchain() {
   setup(&|config| {
        expect_err_ex(config, &["multirust", "default", "nightly-2016-03-1"],
r"",
r"error: toolchain 'nightly-2016-03-1' is not installed
");
   });
}

#[test]
fn list_targets() {
    setup(&|config| {
        let trip = this_host_triple();
        let mut sorted = vec![format!("{} (default)", &*trip),
                              format!("{} (installed)", clitools::CROSS_ARCH1),
                              clitools::CROSS_ARCH2.to_string()];
        sorted.sort();

        let expected = format!("{}\n{}\n{}\n", sorted[0], sorted[1], sorted[2]);

        expect_ok(config, &["multirust", "update", "nightly"]);
        expect_ok(config, &["multirust", "add-target", "nightly",
                            clitools::CROSS_ARCH1]);
        expect_ok_ex(config, &["multirust", "list-targets", "nightly"],
&expected,
r"");
    });
}
<commit_msg>Fix the test for 'default'<commit_after>//! Yet more cli test cases. These are testing that the output
//! is exactly as expected.

extern crate multirust_dist;
extern crate multirust_mock;

use multirust_mock::clitools::{self, Config, Scenario,
                               expect_ok, expect_ok_ex,
                               expect_err_ex,
                               this_host_triple};
use std::env;

fn setup(f: &Fn(&Config)) {
    clitools::setup(Scenario::SimpleV2, f);
}

#[test]
fn update() {
    setup(&|config| {
        expect_ok_ex(config, &["multirust", "update", "nightly"],
r"
nightly revision:

1.3.0 (hash-n-2)
1.3.0 (hash-n-2)

",
r"info: installing toolchain 'nightly'
info: downloading toolchain manifest
info: downloading component 'rust-std'
info: downloading component 'rustc'
info: downloading component 'cargo'
info: downloading component 'rust-docs'
info: installing component 'rust-std'
info: installing component 'rustc'
info: installing component 'cargo'
info: installing component 'rust-docs'
info: toolchain 'nightly' installed
");
    });
}

#[test]
fn update_again() {
    setup(&|config| {
        expect_ok(config, &["multirust", "update", "nightly"]);
        expect_ok_ex(config, &["multirust", "update", "nightly"],
r"
nightly revision:

1.3.0 (hash-n-2)
1.3.0 (hash-n-2)

",
r"info: updating existing install for 'nightly'
info: downloading toolchain manifest
info: toolchain is already up to date
");
    });
}

#[test]
fn default() {
    setup(&|config| {
        expect_ok_ex(config, &["multirust", "default", "nightly"],
r"
nightly revision:

1.3.0 (hash-n-2)
1.3.0 (hash-n-2)

",
r"info: installing toolchain 'nightly'
info: downloading toolchain manifest
info: downloading component 'rust-std'
info: downloading component 'rustc'
info: downloading component 'cargo'
info: downloading component 'rust-docs'
info: installing component 'rust-std'
info: installing component 'rustc'
info: installing component 'cargo'
info: installing component 'rust-docs'
info: toolchain 'nightly' installed
info: default toolchain set to 'nightly'
");
    });
}

#[test]
fn override_again() {
    setup(&|config| {
        let cwd = env::current_dir().unwrap();
        expect_ok(config, &["multirust", "override", "nightly"]);
        expect_ok_ex(config, &["multirust", "override", "nightly"],
r"
nightly revision:

1.3.0 (hash-n-2)
1.3.0 (hash-n-2)

",
&format!(
r"info: using existing install for 'nightly'
info: override toolchain for '{}' set to 'nightly'
", cwd.display()));
    });
}

#[test]
fn remove_override() {
    setup(&|config| {
        let cwd = env::current_dir().unwrap();
        expect_ok(config, &["multirust", "override", "nightly"]);
        expect_ok_ex(config, &["multirust", "remove-override"],
r"",
&format!(r"info: override toolchain for '{}' removed
", cwd.display()));
    });
}

#[test]
fn remove_override_none() {
    setup(&|config| {
        let cwd = env::current_dir().unwrap();
        expect_ok_ex(config, &["multirust", "remove-override"],
r"",
&format!(r"info: no override toolchain for '{}'
", cwd.display()));
    });
}

#[test]
fn update_no_manifest() {
    setup(&|config| {
        expect_err_ex(config, &["multirust", "update", "nightly-2016-01-01"],
r"",
r"info: installing toolchain 'nightly-2016-01-01'
info: downloading toolchain manifest
error: no release found for 'nightly-2016-01-01'
");
    });
}

#[test]
fn delete_data() {
    setup(&|config| {
        expect_ok(config, &["multirust", "default", "nightly"]);
        assert!(config.homedir.path().exists());
        expect_ok_ex(config, &["multirust", "delete-data", "-y"],
r"",
&format!(
r"info: deleted directory '{}'
", config.homedir.path().display()));
    });
}

// Issue #111
// multirust update nightly-2016-03-1
#[test]
fn update_invalid_toolchain() {
   setup(&|config| {
        expect_err_ex(config, &["multirust", "update", "nightly-2016-03-1"],
r"",
r"error: toolchain 'nightly-2016-03-1' is not installed
");
   });
 }

#[test]
fn default_invalid_toolchain() {
   setup(&|config| {
        expect_err_ex(config, &["multirust", "default", "nightly-2016-03-1"],
r"",
r"error: toolchain 'nightly-2016-03-1' is not installed
");
   });
}

#[test]
fn list_targets() {
    setup(&|config| {
        let trip = this_host_triple();
        let mut sorted = vec![format!("{} (default)", &*trip),
                              format!("{} (installed)", clitools::CROSS_ARCH1),
                              clitools::CROSS_ARCH2.to_string()];
        sorted.sort();

        let expected = format!("{}\n{}\n{}\n", sorted[0], sorted[1], sorted[2]);

        expect_ok(config, &["multirust", "update", "nightly"]);
        expect_ok(config, &["multirust", "add-target", "nightly",
                            clitools::CROSS_ARCH1]);
        expect_ok_ex(config, &["multirust", "list-targets", "nightly"],
&expected,
r"");
    });
}
<|endoftext|>


<commit_before><commit_msg>Derive Debug trait for PacketSet in define_packet_set macro<commit_after><|endoftext|>


<commit_before><commit_msg>Use resiter::IterInnerOkOrElse instead of libimagerror version<commit_after><|endoftext|>


<commit_before><commit_msg>Completed Implementation of Cat<commit_after><|endoftext|>


<commit_before><commit_msg>fixed comment at top of tut-03<commit_after><|endoftext|>


<commit_before><commit_msg>add tests for invalid UTF-16 on Windows<commit_after>//! These Windows-only tests are ported from the Unix-only tests in
//! tests/utf16.rs. The tests that use StrictUtf8 mode are omitted here,
//! because that's a Unix-only feature.

#![cfg(windows)]

use clap::{App, Arg};
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;

// Take a slice of ASCII bytes, convert them to UTF-16, and then append a
// dangling surrogate character to make the result invalid UTF-16.
fn bad_osstring(ascii: &[u8]) -> OsString {
    let mut wide_chars: Vec<u16> = ascii.iter().map(|&c| c as u16).collect();
    // UTF-16 surrogate characters are only valid in pairs.
    let surrogate_char: u16 = 0xDC00;
    wide_chars.push(surrogate_char);
    let os = OsString::from_wide(&wide_chars);
    assert!(os.to_str().is_none(), "invalid Unicode");
    os
}

#[test]
fn invalid_utf16_lossy_positional() {
    let r = App::new("bad_utf16")
        .arg(Arg::from("<arg> 'some arg'"))
        .try_get_matches_from(vec![OsString::from(""), bad_osstring(b"")]);
    assert!(r.is_ok());
    let m = r.unwrap();
    assert!(m.is_present("arg"));
    assert_eq!(&*m.value_of_lossy("arg").unwrap(), "\u{FFFD}");
}

#[test]
fn invalid_utf16_lossy_option_short_space() {
    let r = App::new("bad_utf16")
        .arg(Arg::from("-a, --arg <arg> 'some arg'"))
        .try_get_matches_from(vec![
            OsString::from(""),
            OsString::from("-a"),
            bad_osstring(b""),
        ]);
    assert!(r.is_ok());
    let m = r.unwrap();
    assert!(m.is_present("arg"));
    assert_eq!(&*m.value_of_lossy("arg").unwrap(), "\u{FFFD}");
}

#[test]
fn invalid_utf16_lossy_option_short_equals() {
    let r = App::new("bad_utf16")
        .arg(Arg::from("-a, --arg <arg> 'some arg'"))
        .try_get_matches_from(vec![OsString::from(""), bad_osstring(b"-a=")]);
    assert!(r.is_ok());
    let m = r.unwrap();
    assert!(m.is_present("arg"));
    assert_eq!(&*m.value_of_lossy("arg").unwrap(), "\u{FFFD}");
}

#[test]
fn invalid_utf16_lossy_option_short_no_space() {
    let r = App::new("bad_utf16")
        .arg(Arg::from("-a, --arg <arg> 'some arg'"))
        .try_get_matches_from(vec![OsString::from(""), bad_osstring(b"-a")]);
    assert!(r.is_ok());
    let m = r.unwrap();
    assert!(m.is_present("arg"));
    assert_eq!(&*m.value_of_lossy("arg").unwrap(), "\u{FFFD}");
}

#[test]
fn invalid_utf16_lossy_option_long_space() {
    let r = App::new("bad_utf16")
        .arg(Arg::from("-a, --arg <arg> 'some arg'"))
        .try_get_matches_from(vec![
            OsString::from(""),
            OsString::from("--arg"),
            bad_osstring(b""),
        ]);
    assert!(r.is_ok());
    let m = r.unwrap();
    assert!(m.is_present("arg"));
    assert_eq!(&*m.value_of_lossy("arg").unwrap(), "\u{FFFD}");
}

#[test]
fn invalid_utf16_lossy_option_long_equals() {
    let r = App::new("bad_utf16")
        .arg(Arg::from("-a, --arg <arg> 'some arg'"))
        .try_get_matches_from(vec![OsString::from(""), bad_osstring(b"--arg=")]);
    assert!(r.is_ok());
    let m = r.unwrap();
    assert!(m.is_present("arg"));
    assert_eq!(&*m.value_of_lossy("arg").unwrap(), "\u{FFFD}");
}

#[test]
fn invalid_utf16_positional() {
    let r = App::new("bad_utf16")
        .arg(Arg::from("<arg> 'some arg'"))
        .try_get_matches_from(vec![OsString::from(""), bad_osstring(b"")]);
    assert!(r.is_ok());
    let m = r.unwrap();
    assert!(m.is_present("arg"));
    assert_eq!(&*m.value_of_os("arg").unwrap(), &*bad_osstring(b""));
}

#[test]
fn invalid_utf16_option_short_space() {
    let r = App::new("bad_utf16")
        .arg(Arg::from("-a, --arg <arg> 'some arg'"))
        .try_get_matches_from(vec![
            OsString::from(""),
            OsString::from("-a"),
            bad_osstring(b""),
        ]);
    assert!(r.is_ok());
    let m = r.unwrap();
    assert!(m.is_present("arg"));
    assert_eq!(&*m.value_of_os("arg").unwrap(), &*bad_osstring(b""));
}

#[test]
fn invalid_utf16_option_short_equals() {
    let r = App::new("bad_utf16")
        .arg(Arg::from("-a, --arg <arg> 'some arg'"))
        .try_get_matches_from(vec![OsString::from(""), bad_osstring(b"-a=")]);
    assert!(r.is_ok());
    let m = r.unwrap();
    assert!(m.is_present("arg"));
    assert_eq!(&*m.value_of_os("arg").unwrap(), &*bad_osstring(b""));
}

#[test]
fn invalid_utf16_option_short_no_space() {
    let r = App::new("bad_utf16")
        .arg(Arg::from("-a, --arg <arg> 'some arg'"))
        .try_get_matches_from(vec![OsString::from(""), bad_osstring(b"-a")]);
    assert!(r.is_ok());
    let m = r.unwrap();
    assert!(m.is_present("arg"));
    assert_eq!(&*m.value_of_os("arg").unwrap(), &*bad_osstring(b""));
}

#[test]
fn invalid_utf16_option_long_space() {
    let r = App::new("bad_utf16")
        .arg(Arg::from("-a, --arg <arg> 'some arg'"))
        .try_get_matches_from(vec![
            OsString::from(""),
            OsString::from("--arg"),
            bad_osstring(b""),
        ]);
    assert!(r.is_ok());
    let m = r.unwrap();
    assert!(m.is_present("arg"));
    assert_eq!(&*m.value_of_os("arg").unwrap(), &*bad_osstring(b""));
}

#[test]
fn invalid_utf16_option_long_equals() {
    let r = App::new("bad_utf16")
        .arg(Arg::from("-a, --arg <arg> 'some arg'"))
        .try_get_matches_from(vec![OsString::from(""), bad_osstring(b"--arg=")]);
    assert!(r.is_ok());
    let m = r.unwrap();
    assert!(m.is_present("arg"));
    assert_eq!(&*m.value_of_os("arg").unwrap(), &*bad_osstring(b""));
}
<|endoftext|>


<commit_before><commit_msg>Manage notification error correctly<commit_after><|endoftext|>


<commit_before><commit_msg>Add ID reporting in imag-tag<commit_after><|endoftext|>


<commit_before><commit_msg>updated build.rs to use 'git describe --all'<commit_after><|endoftext|>


<commit_before><commit_msg>Add Session::new function.<commit_after><|endoftext|>


<commit_before><commit_msg>Update pattern.rs<commit_after><|endoftext|>


<commit_before><commit_msg>adds state commit in updates kicks<commit_after><|endoftext|>


<commit_before>// Extracting metadata from crate files

import driver::session;
import syntax::{ast, ast_util};
import lib::llvm::{False, llvm, mk_object_file, mk_section_iter};
import front::attr;
import middle::resolve;
import syntax::visit;
import syntax::codemap::span;
import back::x86;
import util::{common, filesearch};
import std::{vec, str, fs, io, option};
import std::option::{none, some};
import std::map::{hashmap, new_int_hash};
import syntax::print::pprust;
import common::*;

export read_crates;
export list_file_metadata;

// Traverses an AST, reading all the information about use'd crates and native
// libraries necessary for later resolving, typechecking, linking, etc.
fn read_crates(sess: session::session, crate: ast::crate) {
    let e =
        @{sess: sess,
          crate_cache: @std::map::new_str_hash::<int>(),
          mutable next_crate_num: 1};
    let v =
        visit::mk_simple_visitor(@{visit_view_item:
                                       bind visit_view_item(e, _),
                                   visit_item: bind visit_item(e, _)
                                      with *visit::default_simple_visitor()});
    visit::visit_crate(crate, (), v);
}

type env =
    @{sess: session::session,
      crate_cache: @hashmap<str, int>,
      mutable next_crate_num: ast::crate_num};

fn visit_view_item(e: env, i: @ast::view_item) {
    alt i.node {
      ast::view_item_use(ident, meta_items, id) {
        let cnum = resolve_crate(e, ident, meta_items, i.span);
        cstore::add_use_stmt_cnum(e.sess.get_cstore(), id, cnum);
      }
      _ { }
    }
}

fn visit_item(e: env, i: @ast::item) {
    alt i.node {
      ast::item_native_mod(m) {
        if m.abi != ast::native_abi_rust && m.abi != ast::native_abi_cdecl &&
                m.abi != ast::native_abi_c_stack_cdecl &&
                m.abi != ast::native_abi_c_stack_stdcall {
            ret;
        }
        let cstore = e.sess.get_cstore();
        if !cstore::add_used_library(cstore, m.native_name) { ret; }
        for a: ast::attribute in
            attr::find_attrs_by_name(i.attrs, "link_args") {

            alt attr::get_meta_item_value_str(attr::attr_meta(a)) {
              some(linkarg) { cstore::add_used_link_args(cstore, linkarg); }
              none. {/* fallthrough */ }
            }
        }
      }
      _ { }
    }
}

// A diagnostic function for dumping crate metadata to an output stream
fn list_file_metadata(path: str, out: io::writer) {
    alt get_metadata_section(path) {
      option::some(bytes) { decoder::list_crate_metadata(bytes, out); }
      option::none. {
        out.write_str("Could not find metadata in " + path + ".\n");
      }
    }
}

fn metadata_matches(crate_data: @[u8], metas: [@ast::meta_item]) -> bool {
    let attrs = decoder::get_crate_attributes(crate_data);
    let linkage_metas = attr::find_linkage_metas(attrs);

    log #fmt["matching %u metadata requirements against %u items",
             vec::len(metas), vec::len(linkage_metas)];

    log #fmt("crate metadata:");
    for have: @ast::meta_item in linkage_metas {
        log #fmt("  %s", pprust::meta_item_to_str(*have));
    }

    for needed: @ast::meta_item in metas {
        log #fmt["looking for %s", pprust::meta_item_to_str(*needed)];
        if !attr::contains(linkage_metas, needed) {
            log #fmt["missing %s", pprust::meta_item_to_str(*needed)];
            ret false;
        }
    }
    ret true;
}

fn default_native_lib_naming(sess: session::session, static: bool) ->
   {prefix: str, suffix: str} {
    if static { ret {prefix: "lib", suffix: ".rlib"}; }
    alt sess.get_targ_cfg().os {
      session::os_win32. { ret {prefix: "", suffix: ".dll"}; }
      session::os_macos. { ret {prefix: "lib", suffix: ".dylib"}; }
      session::os_linux. { ret {prefix: "lib", suffix: ".so"}; }
    }
}

fn find_library_crate(sess: session::session, ident: ast::ident,
                      metas: [@ast::meta_item])
   -> option::t<{ident: str, data: @[u8]}> {

    attr::require_unique_names(sess, metas);

    let crate_name =
        {
            let name_items = attr::find_meta_items_by_name(metas, "name");
            alt vec::last(name_items) {
              some(i) {
                alt attr::get_meta_item_value_str(i) {
                  some(n) { n }
                  // FIXME: Probably want a warning here since the user
                  // is using the wrong type of meta item
                  _ { ident }
                }
              }
              none. { ident }
            }
        };

    let nn = default_native_lib_naming(sess, sess.get_opts().static);
    let x =
        find_library_crate_aux(nn, crate_name, metas,
                               sess.filesearch());
    if x != none || sess.get_opts().static { ret x; }
    let nn2 = default_native_lib_naming(sess, true);
    ret find_library_crate_aux(nn2, crate_name, metas,
                               sess.filesearch());
}

fn find_library_crate_aux(nn: {prefix: str, suffix: str}, crate_name: str,
                          metas: [@ast::meta_item],
                          filesearch: filesearch::filesearch) ->
   option::t<{ident: str, data: @[u8]}> {
    let prefix: str = nn.prefix + crate_name;
    let suffix: str = nn.suffix;

    ret filesearch::search(filesearch, { |path|
        log #fmt("inspecting file %s", path);
        let f: str = fs::basename(path);
        if !(str::starts_with(f, prefix) && str::ends_with(f, suffix)) {
            log #fmt["skipping %s, doesn't look like %s*%s", path, prefix,
                     suffix];
            option::none
        } else {
            log #fmt("%s is a candidate", path);
            alt get_metadata_section(path) {
              option::some(cvec) {
                if !metadata_matches(cvec, metas) {
                    log #fmt["skipping %s, metadata doesn't match", path];
                    option::none
                } else {
                    log #fmt["found %s with matching metadata", path];
                    option::some({ident: path, data: cvec})
                }
              }
              _ {
                log #fmt("could not load metadata for %s", path);
                option::none
              }
            }
        }
    });
}

fn get_metadata_section(filename: str) -> option::t<@[u8]> unsafe {
    let mb = str::as_buf(filename, {|buf|
        llvm::LLVMRustCreateMemoryBufferWithContentsOfFile(buf)
                                   });
    if mb as int == 0 { ret option::none::<@[u8]>; }
    let of = mk_object_file(mb);
    let si = mk_section_iter(of.llof);
    while llvm::LLVMIsSectionIteratorAtEnd(of.llof, si.llsi) == False {
        let name_buf = llvm::LLVMGetSectionName(si.llsi);
        let name = str::str_from_cstr(name_buf);
        if str::eq(name, x86::get_meta_sect_name()) {
            let cbuf = llvm::LLVMGetSectionContents(si.llsi);
            let csz = llvm::LLVMGetSectionSize(si.llsi);
            let cvbuf: *u8 = std::unsafe::reinterpret_cast(cbuf);
            ret option::some::<@[u8]>(@vec::unsafe::from_buf(cvbuf, csz));
        }
        llvm::LLVMMoveToNextSection(si.llsi);
    }
    ret option::none::<@[u8]>;
}

fn load_library_crate(sess: session::session, span: span, ident: ast::ident,
                      metas: [@ast::meta_item])
   -> {ident: str, data: @[u8]} {

    alt find_library_crate(sess, ident, metas) {
      some(t) { ret t; }
      none. {
        sess.span_fatal(span, #fmt["can't find crate for '%s'", ident]);
      }
    }
}

fn resolve_crate(e: env, ident: ast::ident, metas: [@ast::meta_item],
                 span: span) -> ast::crate_num {
    if !e.crate_cache.contains_key(ident) {
        let cinfo =
            load_library_crate(e.sess, span, ident, metas);

        let cfilename = cinfo.ident;
        let cdata = cinfo.data;

        // Claim this crate number and cache it
        let cnum = e.next_crate_num;
        e.crate_cache.insert(ident, cnum);
        e.next_crate_num += 1;

        // Now resolve the crates referenced by this crate
        let cnum_map = resolve_crate_deps(e, cdata);

        let cmeta = {name: ident, data: cdata, cnum_map: cnum_map};

        let cstore = e.sess.get_cstore();
        cstore::set_crate_data(cstore, cnum, cmeta);
        cstore::add_used_crate_file(cstore, cfilename);
        ret cnum;
    } else { ret e.crate_cache.get(ident); }
}

// Go through the crate metadata and load any crates that it references
fn resolve_crate_deps(e: env, cdata: @[u8]) -> cstore::cnum_map {
    log "resolving deps of external crate";
    // The map from crate numbers in the crate we're resolving to local crate
    // numbers
    let cnum_map = new_int_hash::<ast::crate_num>();
    for dep: decoder::crate_dep in decoder::get_crate_deps(cdata) {
        let extrn_cnum = dep.cnum;
        let cname = dep.ident;
        log #fmt["resolving dep %s", cname];
        if e.crate_cache.contains_key(cname) {
            log "already have it";
            // We've already seen this crate
            let local_cnum = e.crate_cache.get(cname);
            cnum_map.insert(extrn_cnum, local_cnum);
        } else {
            log "need to load it";
            // This is a new one so we've got to load it
            // FIXME: Need better error reporting than just a bogus span
            let fake_span = ast_util::dummy_sp();
            let local_cnum = resolve_crate(e, cname, [], fake_span);
            cnum_map.insert(extrn_cnum, local_cnum);
        }
    }
    ret cnum_map;
}

// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<commit_msg>rustc: Find crates by matching the name metadata<commit_after>// Extracting metadata from crate files

import driver::session;
import syntax::{ast, ast_util};
import lib::llvm::{False, llvm, mk_object_file, mk_section_iter};
import front::attr;
import middle::resolve;
import syntax::visit;
import syntax::codemap::span;
import back::x86;
import util::{common, filesearch};
import std::{vec, str, fs, io, option};
import std::option::{none, some};
import std::map::{hashmap, new_int_hash};
import syntax::print::pprust;
import common::*;

export read_crates;
export list_file_metadata;

// Traverses an AST, reading all the information about use'd crates and native
// libraries necessary for later resolving, typechecking, linking, etc.
fn read_crates(sess: session::session, crate: ast::crate) {
    let e =
        @{sess: sess,
          crate_cache: @std::map::new_str_hash::<int>(),
          mutable next_crate_num: 1};
    let v =
        visit::mk_simple_visitor(@{visit_view_item:
                                       bind visit_view_item(e, _),
                                   visit_item: bind visit_item(e, _)
                                      with *visit::default_simple_visitor()});
    visit::visit_crate(crate, (), v);
}

type env =
    @{sess: session::session,
      crate_cache: @hashmap<str, int>,
      mutable next_crate_num: ast::crate_num};

fn visit_view_item(e: env, i: @ast::view_item) {
    alt i.node {
      ast::view_item_use(ident, meta_items, id) {
        let cnum = resolve_crate(e, ident, meta_items, i.span);
        cstore::add_use_stmt_cnum(e.sess.get_cstore(), id, cnum);
      }
      _ { }
    }
}

fn visit_item(e: env, i: @ast::item) {
    alt i.node {
      ast::item_native_mod(m) {
        if m.abi != ast::native_abi_rust && m.abi != ast::native_abi_cdecl &&
                m.abi != ast::native_abi_c_stack_cdecl &&
                m.abi != ast::native_abi_c_stack_stdcall {
            ret;
        }
        let cstore = e.sess.get_cstore();
        if !cstore::add_used_library(cstore, m.native_name) { ret; }
        for a: ast::attribute in
            attr::find_attrs_by_name(i.attrs, "link_args") {

            alt attr::get_meta_item_value_str(attr::attr_meta(a)) {
              some(linkarg) { cstore::add_used_link_args(cstore, linkarg); }
              none. {/* fallthrough */ }
            }
        }
      }
      _ { }
    }
}

// A diagnostic function for dumping crate metadata to an output stream
fn list_file_metadata(path: str, out: io::writer) {
    alt get_metadata_section(path) {
      option::some(bytes) { decoder::list_crate_metadata(bytes, out); }
      option::none. {
        out.write_str("Could not find metadata in " + path + ".\n");
      }
    }
}

fn metadata_matches(crate_data: @[u8], metas: [@ast::meta_item]) -> bool {
    let attrs = decoder::get_crate_attributes(crate_data);
    let linkage_metas = attr::find_linkage_metas(attrs);

    log #fmt["matching %u metadata requirements against %u items",
             vec::len(metas), vec::len(linkage_metas)];

    log #fmt("crate metadata:");
    for have: @ast::meta_item in linkage_metas {
        log #fmt("  %s", pprust::meta_item_to_str(*have));
    }

    for needed: @ast::meta_item in metas {
        log #fmt["looking for %s", pprust::meta_item_to_str(*needed)];
        if !attr::contains(linkage_metas, needed) {
            log #fmt["missing %s", pprust::meta_item_to_str(*needed)];
            ret false;
        }
    }
    ret true;
}

fn default_native_lib_naming(sess: session::session, static: bool) ->
   {prefix: str, suffix: str} {
    if static { ret {prefix: "lib", suffix: ".rlib"}; }
    alt sess.get_targ_cfg().os {
      session::os_win32. { ret {prefix: "", suffix: ".dll"}; }
      session::os_macos. { ret {prefix: "lib", suffix: ".dylib"}; }
      session::os_linux. { ret {prefix: "lib", suffix: ".so"}; }
    }
}

fn find_library_crate(sess: session::session, ident: ast::ident,
                      metas: [@ast::meta_item])
   -> option::t<{ident: str, data: @[u8]}> {

    attr::require_unique_names(sess, metas);

    // Metadata "name" will be used to find the crate. Use `ident'
    // as "name" if the attribute is not explicitly specified
    if !attr::contains_name(metas, "name") {
      metas += [attr::mk_name_value_item_str("name", ident)];
    }
    let nn = default_native_lib_naming(sess, sess.get_opts().static);
    let x =
        find_library_crate_aux(nn, metas, sess.filesearch());
    if x != none || sess.get_opts().static { ret x; }
    let nn2 = default_native_lib_naming(sess, true);
    ret find_library_crate_aux(nn2, metas, sess.filesearch());
}

fn find_library_crate_aux(nn: {prefix: str, suffix: str},
                          metas: [@ast::meta_item],
                          filesearch: filesearch::filesearch) ->
   option::t<{ident: str, data: @[u8]}> {
    let prefix: str = nn.prefix;
    let suffix: str = nn.suffix;

    ret filesearch::search(filesearch, { |path|
        log #fmt("inspecting file %s", path);
        let f: str = fs::basename(path);
        if !(str::starts_with(f, prefix) && str::ends_with(f, suffix)) {
            log #fmt["skipping %s, doesn't look like %s*%s", path, prefix,
                     suffix];
            option::none
        } else {
            log #fmt("%s is a candidate", path);
            alt get_metadata_section(path) {
              option::some(cvec) {
                if !metadata_matches(cvec, metas) {
                    log #fmt["skipping %s, metadata doesn't match", path];
                    option::none
                } else {
                    log #fmt["found %s with matching metadata", path];
                    option::some({ident: path, data: cvec})
                }
              }
              _ {
                log #fmt("could not load metadata for %s", path);
                option::none
              }
            }
        }
    });
}

fn get_metadata_section(filename: str) -> option::t<@[u8]> unsafe {
    let mb = str::as_buf(filename, {|buf|
        llvm::LLVMRustCreateMemoryBufferWithContentsOfFile(buf)
                                   });
    if mb as int == 0 { ret option::none::<@[u8]>; }
    let of = mk_object_file(mb);
    let si = mk_section_iter(of.llof);
    while llvm::LLVMIsSectionIteratorAtEnd(of.llof, si.llsi) == False {
        let name_buf = llvm::LLVMGetSectionName(si.llsi);
        let name = str::str_from_cstr(name_buf);
        if str::eq(name, x86::get_meta_sect_name()) {
            let cbuf = llvm::LLVMGetSectionContents(si.llsi);
            let csz = llvm::LLVMGetSectionSize(si.llsi);
            let cvbuf: *u8 = std::unsafe::reinterpret_cast(cbuf);
            ret option::some::<@[u8]>(@vec::unsafe::from_buf(cvbuf, csz));
        }
        llvm::LLVMMoveToNextSection(si.llsi);
    }
    ret option::none::<@[u8]>;
}

fn load_library_crate(sess: session::session, span: span, ident: ast::ident,
                      metas: [@ast::meta_item])
   -> {ident: str, data: @[u8]} {

    alt find_library_crate(sess, ident, metas) {
      some(t) { ret t; }
      none. {
        sess.span_fatal(span, #fmt["can't find crate for '%s'", ident]);
      }
    }
}

fn resolve_crate(e: env, ident: ast::ident, metas: [@ast::meta_item],
                 span: span) -> ast::crate_num {
    if !e.crate_cache.contains_key(ident) {
        let cinfo =
            load_library_crate(e.sess, span, ident, metas);

        let cfilename = cinfo.ident;
        let cdata = cinfo.data;

        // Claim this crate number and cache it
        let cnum = e.next_crate_num;
        e.crate_cache.insert(ident, cnum);
        e.next_crate_num += 1;

        // Now resolve the crates referenced by this crate
        let cnum_map = resolve_crate_deps(e, cdata);

        let cmeta = {name: ident, data: cdata, cnum_map: cnum_map};

        let cstore = e.sess.get_cstore();
        cstore::set_crate_data(cstore, cnum, cmeta);
        cstore::add_used_crate_file(cstore, cfilename);
        ret cnum;
    } else { ret e.crate_cache.get(ident); }
}

// Go through the crate metadata and load any crates that it references
fn resolve_crate_deps(e: env, cdata: @[u8]) -> cstore::cnum_map {
    log "resolving deps of external crate";
    // The map from crate numbers in the crate we're resolving to local crate
    // numbers
    let cnum_map = new_int_hash::<ast::crate_num>();
    for dep: decoder::crate_dep in decoder::get_crate_deps(cdata) {
        let extrn_cnum = dep.cnum;
        let cname = dep.ident;
        log #fmt["resolving dep %s", cname];
        if e.crate_cache.contains_key(cname) {
            log "already have it";
            // We've already seen this crate
            let local_cnum = e.crate_cache.get(cname);
            cnum_map.insert(extrn_cnum, local_cnum);
        } else {
            log "need to load it";
            // This is a new one so we've got to load it
            // FIXME: Need better error reporting than just a bogus span
            let fake_span = ast_util::dummy_sp();
            let local_cnum = resolve_crate(e, cname, [], fake_span);
            cnum_map.insert(extrn_cnum, local_cnum);
        }
    }
    ret cnum_map;
}

// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<|endoftext|>


<commit_before><commit_msg>issue/28: first test<commit_after><|endoftext|>


<commit_before><commit_msg>Cancellations.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix spacing<commit_after><|endoftext|>


<commit_before><commit_msg>Create main.rs<commit_after>use std::io;
use std::fs::{self, DirEntry};
use std::path::Path;

fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry) -> io::Result<()> ) -> io::Result<()> {
    if dir.is_dir() {
        for entry in fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                visit_dirs(&path, cb)?;
            } else {
                cb(&entry)?;
            }
        }
    }
    Ok(())
}

fn visit_files(cb: &DirEntry) -> io::Result<()> {
	println!("{:?}",cb.path()); //file_name());
	Ok(())
}

fn main() {
    let path = Path::new(".");
    visit_dirs(path, &visit_files);
}
<|endoftext|>


<commit_before><commit_msg>Fixed main.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Setup command arguments with getopts<commit_after>extern crate getopts;
use getopts::Options;
use std::env;

fn print_usage(opts: Options) {
    let brief = format!("Usage: listbotto DIR [options]");
    print!("{}", opts.usage(&brief));
}

fn main() {
    let args: Vec<String> = env::args().collect();

    let mut opts = Options::new();
    opts.optflag("h", "help", "print this help menu");
    let matches = match opts.parse(&args[1..]) {
        Ok(m) => { m }
        Err(f) => { panic!(f.to_string()) }
    };

    if matches.opt_present("h") {
        print_usage(opts);
        return;
    }

    print_usage(opts);
    return;
}

<|endoftext|>


<commit_before><commit_msg>Implements resolve_uri to also open Files<commit_after><|endoftext|>


<commit_before><commit_msg>Formatting<commit_after><|endoftext|>


<commit_before><commit_msg>Update main.rs<commit_after><|endoftext|>


<commit_before><commit_msg>add convolution to build<commit_after>pub mod convolution;
pub use self::convolution::*;
<|endoftext|>


<commit_before><commit_msg>grab item population for terrain map<commit_after><|endoftext|>


<commit_before><commit_msg>Improve textbox/cursor logic with return, backspace, left_key<commit_after><|endoftext|>


<commit_before><commit_msg>Add a few encoding tests<commit_after>extern crate opus;

#[test]
fn version_ascii() {
	println!("Opus version: {}", opus::version());
}

// 48000Hz * 1 channel * 20 ms / 1000
const MONO_20MS: usize = 48000 * 1 * 20 / 1000;

#[test]
fn encode_mono() {
	let mut encoder = opus::Encoder::new(48000, opus::Channels::Mono, opus::CodingMode::Audio).unwrap();

	let mut output = [0; 256];
	let len = encoder.encode(&[0_i16; MONO_20MS], &mut output).unwrap();
	assert_eq!(&output[..len], &[244, 255, 254]);

	let len = encoder.encode(&[0_i16; MONO_20MS], &mut output).unwrap();
	assert_eq!(&output[..len], &[244, 255, 254]);

	let len = encoder.encode(&[1_i16; MONO_20MS], &mut output).unwrap();
	assert!(len > 190 && len < 220);

	let len = encoder.encode(&[0_i16; MONO_20MS], &mut output).unwrap();
	assert!(len > 170 && len < 190);
}

#[test]
fn encode_stereo() {
	let mut encoder = opus::Encoder::new(48000, opus::Channels::Stereo, opus::CodingMode::Audio).unwrap();

	let mut output = [0; 512];
	let len = encoder.encode(&[0_i16; 2 * MONO_20MS], &mut output).unwrap();
	assert_eq!(&output[..len], &[249, 255, 254, 255, 254]);

	let len = encoder.encode(&[0_i16; 2 * MONO_20MS], &mut output).unwrap();
	assert_eq!(&output[..len], &[249, 255, 254, 255, 254]);

	let len = encoder.encode(&[17_i16; 2 * MONO_20MS], &mut output).unwrap();
	assert!(len > 240);

	let len = encoder.encode(&[0_i16; 2 * MONO_20MS], &mut output).unwrap();
	assert!(len > 240);

	// Very small buffer should still succeed
	let len = encoder.encode(&[95_i16; 2 * MONO_20MS], &mut [0; 20]).unwrap();
	assert!(len < 20);
}

#[test]
fn encode_bad_rate() {
	match opus::Encoder::new(48001, opus::Channels::Mono, opus::CodingMode::Audio) {
		Ok(_) => panic!("Encoder::new did not return BadArg"),
		Err(err) => assert_eq!(err.code(), opus::ErrorCode::BadArg),
	}
}

#[test]
fn encode_bad_buffer() {
	let mut encoder = opus::Encoder::new(48000, opus::Channels::Stereo, opus::CodingMode::Audio).unwrap();
	match encoder.encode(&[1_i16; 2 * MONO_20MS], &mut [0; 0]) {
		Ok(_) => panic!("encode with 0-length buffer did not return BadArg"),
		Err(err) => assert_eq!(err.code(), opus::ErrorCode::BadArg),
	}
}
<|endoftext|>


<commit_before><commit_msg>Remove `to_u32` method from `Kind`<commit_after><|endoftext|>


<commit_before><commit_msg>output songs in extended m3u format<commit_after><|endoftext|>


<commit_before>extern crate rusoto_codegen;

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

use rusoto_codegen::{Service, generate};

/*
gamelift/2015-10-01/service-2.json:    "protocol":"json"
support/2013-04-15/service-2.json:    "protocol":"json"
*/

// expand to use cfg!() so codegen only gets run for services
// in the feautres list
macro_rules! services {
    ( $( [$name:expr, $date:expr] ),* ) => {
        {
            let mut services = Vec::new();
            $(
                if cfg!(feature = $name) {
                    services.push(Service::new($name, $date));
                }
            )*
            services
        }
    }
}

fn main() {
    let out_dir = env::var_os("OUT_DIR").expect("OUT_DIR not specified");
    let out_path = Path::new(&out_dir);

    let services = services! {
        ["acm", "2015-12-08"],
        ["cloudhsm", "2014-05-30"],
        ["cloudtrail", "2013-11-01"],
        ["codecommit", "2015-04-13"],
        ["codedeploy", "2014-10-06"],
        ["codepipeline", "2015-07-09"],
        ["cognito-identity", "2014-06-30"],
        ["config", "2014-11-12"],
        ["datapipeline", "2012-10-29"],
        ["devicefarm", "2015-06-23"],
        ["directconnect", "2012-10-25"],
        ["ds", "2015-04-16"],
        ["dynamodb", "2012-08-10"],
        ["dynamodbstreams", "2012-08-10"],
        ["ec2", "2015-10-01"],
        ["ecr", "2015-09-21"],
        ["ecs", "2014-11-13"],
        ["elastictranscoder", "2012-09-25"],
        ["emr", "2009-03-31"],
        ["events", "2014-02-03"],
        ["firehose", "2015-08-04"],
        ["inspector", "2016-02-16"],
        ["kinesis", "2013-12-02"],
        ["kms", "2014-11-01"],
        ["logs", "2014-03-28"],
        ["machinelearning", "2014-12-12"],
        ["marketplacecommerceanalytics", "2015-07-01"],
        ["opsworks", "2013-02-18"],
        ["route53domains", "2014-05-15"],
        ["sqs", "2012-11-05"],
        ["ssm", "2014-11-06"],
        ["storagegateway", "2013-06-30"],
        ["swf", "2012-01-25"],
        ["waf", "2015-08-24"],
        ["workspaces", "2015-04-08"]
    };

    for service in services {
        generate(service, out_path);
    }

    println!("cargo:rerun-if-changed=codegen");
}
<commit_msg>fix typo<commit_after>extern crate rusoto_codegen;

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

use rusoto_codegen::{Service, generate};

/*
gamelift/2015-10-01/service-2.json:    "protocol":"json"
support/2013-04-15/service-2.json:    "protocol":"json"
*/

// expand to use cfg!() so codegen only gets run for services
// in the features list
macro_rules! services {
    ( $( [$name:expr, $date:expr] ),* ) => {
        {
            let mut services = Vec::new();
            $(
                if cfg!(feature = $name) {
                    services.push(Service::new($name, $date));
                }
            )*
            services
        }
    }
}

fn main() {
    let out_dir = env::var_os("OUT_DIR").expect("OUT_DIR not specified");
    let out_path = Path::new(&out_dir);

    let services = services! {
        ["acm", "2015-12-08"],
        ["cloudhsm", "2014-05-30"],
        ["cloudtrail", "2013-11-01"],
        ["codecommit", "2015-04-13"],
        ["codedeploy", "2014-10-06"],
        ["codepipeline", "2015-07-09"],
        ["cognito-identity", "2014-06-30"],
        ["config", "2014-11-12"],
        ["datapipeline", "2012-10-29"],
        ["devicefarm", "2015-06-23"],
        ["directconnect", "2012-10-25"],
        ["ds", "2015-04-16"],
        ["dynamodb", "2012-08-10"],
        ["dynamodbstreams", "2012-08-10"],
        ["ec2", "2015-10-01"],
        ["ecr", "2015-09-21"],
        ["ecs", "2014-11-13"],
        ["elastictranscoder", "2012-09-25"],
        ["emr", "2009-03-31"],
        ["events", "2014-02-03"],
        ["firehose", "2015-08-04"],
        ["inspector", "2016-02-16"],
        ["kinesis", "2013-12-02"],
        ["kms", "2014-11-01"],
        ["logs", "2014-03-28"],
        ["machinelearning", "2014-12-12"],
        ["marketplacecommerceanalytics", "2015-07-01"],
        ["opsworks", "2013-02-18"],
        ["route53domains", "2014-05-15"],
        ["sqs", "2012-11-05"],
        ["ssm", "2014-11-06"],
        ["storagegateway", "2013-06-30"],
        ["swf", "2012-01-25"],
        ["waf", "2015-08-24"],
        ["workspaces", "2015-04-08"]
    };

    for service in services {
        generate(service, out_path);
    }

    println!("cargo:rerun-if-changed=codegen");
}
<|endoftext|>


<commit_before><commit_msg>add example task_worker<commit_after>mod async_helpers;

use futures::FutureExt;
use std::io::Write;
use std::{error::Error, time::Duration};
use zeromq::{Socket, SocketRecv, SocketSend};

#[async_helpers::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Socket to receive messages on
    let mut receiver = zeromq::PullSocket::new();
    receiver.connect("tcp://127.0.0.1:5557").await?;

    // Socket to send messages to
    let mut sender = zeromq::PushSocket::new();
    sender.connect("tcp://127.0.0.1:5558").await?;

    // Socket for control input
    let mut controller = zeromq::SubSocket::new();
    controller.connect("tcp://127.0.0.1:5559").await?;
    controller.subscribe("").await?;

    // Process messages from receiver and controller
    loop {
        futures::select! {
            message = receiver.recv().fuse() => {
                // Process task
                let message = message.unwrap();
                let workload = String::from_utf8(message.get(0).unwrap().to_vec())?
                    .parse()
                    .expect("Couldn't parse u64 from data");

                // Do the work
                async_helpers::sleep(Duration::from_millis(workload)).await;

                // Send results to sink
                sender.send(message).await?;

                // Simple progress indicator for the viewer
                print!(".");
                std::io::stdout().flush()?;
            },
            // Any waiting controller command acts as 'KILL'
            _kill = controller.recv().fuse() => {
                break
            }
        };
    }

    println!("Done");
    receiver.close().await;
    sender.close().await;
    controller.close().await;
    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>Enrich error types<commit_after><|endoftext|>


<commit_before><commit_msg>Remove unnecessary clone().to_string() calls<commit_after><|endoftext|>