<commit_before><commit_msg>Add the API description<commit_after>
use BuildQuery;

// https://docs.gitlab.com/ce/api/projects.html

// Get a list of projects for which the authenticated user is a member.
// GET /projects
//
// Get a list of projects which the authenticated user can see.
// GET /projects/visible
//
// Get a list of projects which are owned by the authenticated user.
// GET /projects/owned
//
// Get a list of projects which are starred by the authenticated user.
// GET /projects/starred
//
// Get a list of all GitLab projects (admin only).
// GET /projects/all
//
// Get a specific project, identified by project `ID` or `NAMESPACE/PROJECT_NAME`, which is owned by the authenticated user. If using namespaced projects call make sure that the `NAMESPACE/PROJECT_NAME` is URL-encoded, eg. `/api/v3/projects/diaspora%2Fdiaspora` (where `/` is represented by `%2F`).
// GET /projects/:id
//
// Get the events for the specified project. Sorted from newest to oldest
// GET /projects/:id/events
//
// Creates a new project owned by the authenticated user.
// POST /projects
//
// Creates a new project owned by the specified user. Available only for admins.
// POST /projects/user/:user_id
//
// Updates an existing project
// PUT /projects/:id
//
// Forks a project into the user namespace of the authenticated user or the one provided.
// POST /projects/fork/:id
//
// Stars a given project. Returns status code `201` and the project on success and `304` if the project is already starred.
// POST /projects/:id/star
//
// Unstars a given project. Returns status code `200` and the project on success and `304` if the project is not starred.
// DELETE /projects/:id/star
//
// Archives the project if the user is either admin or the project owner of this project. This action is idempotent, thus archiving an already archived project will not change the project.
//
// Status code `201` with the project as body is given when successful, in case the user doesn't have the proper access rights, code `403` is returned. Status `404` is returned if the project doesn't exist, or is hidden to the user.
// POST /projects/:id/archive
//
//
// Unarchives the project if the user is either admin or the project owner of this project. This action is idempotent, thus unarchiving an non-archived project will not change the project.
//
// Status code `201` with the project as body is given when successful, in case the user doesn't have the proper access rights, code `403` is returned. Status `404` is returned if the project doesn't exist, or is hidden to the user.
// POST /projects/:id/unarchive
//
//
// Removes a project including all associated resources (issues, merge requests etc.)
// DELETE /projects/:id
//
//
// Uploads a file to the specified project to be used in an issue or merge request description, or a comment.
// POST /projects/:id/uploads
//
//
// Allow to share project with group.
// POST /projects/:id/share
//
//
// Get a list of project hooks.
// GET /projects/:id/hooks
//
//
// Get a specific hook for a project.
// GET /projects/:id/hooks/:hook_id
//
//
// Adds a hook to a specified project.
// POST /projects/:id/hooks
//
//
// Edits a hook for a specified project.
// PUT /projects/:id/hooks/:hook_id
//
//
// Removes a hook from a project. This is an idempotent method and can be called multiple times. Either the hook is available or not.
// DELETE /projects/:id/hooks/:hook_id
//
//
// Lists all branches of a project.
// GET /projects/:id/repository/branches
//
//
// A specific branch of a project.
// GET /projects/:id/repository/branches/:branch
//
//
// Protects a single branch of a project.
// PUT /projects/:id/repository/branches/:branch/protect
//
//
// Unprotects a single branch of a project.
// PUT /projects/:id/repository/branches/:branch/unprotect
//
//
// Create a forked from/to relation between existing projects.
// POST /projects/:id/fork/:forked_from_id
//
//
// Delete an existing forked from relationship
// DELETE /projects/:id/fork
//
//
// Search for projects by name which are accessible to the authenticated user.
// GET /projects/search/:query
<|endoftext|>


<commit_before><commit_msg>Add test for issue #4791<commit_after>// rustfmt-brace_style: SameLineWhere
// rustfmt-comment_width: 100
// rustfmt-edition: 2018
// rustfmt-fn_args_layout: Compressed
// rustfmt-hard_tabs: false
// rustfmt-match_block_trailing_comma: true
// rustfmt-max_width: 100
// rustfmt-merge_derives: false
// rustfmt-newline_style: Unix
// rustfmt-normalize_doc_attributes: true
// rustfmt-overflow_delimited_expr: true
// rustfmt-reorder_imports: false
// rustfmt-reorder_modules: true
// rustfmt-struct_field_align_threshold: 20
// rustfmt-tab_spaces: 4
// rustfmt-trailing_comma: Never
// rustfmt-use_small_heuristics: Max
// rustfmt-use_try_shorthand: true
// rustfmt-wrap_comments: true

/// Lorem ipsum dolor sit amet.
#[repr(C)]
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
pub struct BufferAttr {
    /* NOTE: Blah blah blah blah blah. */
    /// Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt
    /// ut labore et dolore magna aliqua. Morbi quis commodo odio aenean sed adipiscing. Nunc
    /// congue nisi vitae suscipit tellus mauris a. Consectetur adipiscing elit pellentesque
    /// habitant morbi tristique senectus.
    pub foo: u32,

    /// Elit eget gravida cum sociis natoque penatibus et magnis dis. Consequat semper viverra nam
    /// libero. Accumsan in nisl nisi scelerisque eu. Pellentesque id nibh tortor id aliquet. Sed
    /// velit dignissim sodales ut. Facilisis sed odio morbi quis commodo odio aenean sed. Et
    /// ultrices neque ornare aenean euismod elementum. Condimentum lacinia quis vel eros donec ac
    /// odio tempor.
    ///
    /// Lacinia at quis risus sed vulputate odio ut enim. Etiam erat velit scelerisque in dictum.
    /// Nibh tellus molestie nunc non blandit massa enim nec. Nascetur ridiculus mus mauris vitae.
    pub bar: u32,

    /// Mi proin sed libero enim sed faucibus turpis. Amet consectetur adipiscing elit duis
    /// tristique sollicitudin nibh sit amet. Congue quisque egestas diam in arcu cursus euismod
    /// quis viverra. Cum sociis natoque penatibus et magnis dis parturient montes. Enim sit amet
    /// venenatis urna cursus eget nunc scelerisque viverra. Cras semper auctor neque vitae tempus
    /// quam pellentesque. Tortor posuere ac ut consequat semper viverra nam libero justo. Vitae
    /// auctor eu augue ut lectus arcu bibendum at. Faucibus vitae aliquet nec ullamcorper sit amet
    /// risus nullam. Maecenas accumsan lacus vel facilisis volutpat. Arcu non odio euismod
    /// lacinia.
    ///
    /// [`FooBar::beep()`]: crate::foobar::FooBar::beep
    /// [`FooBar::boop()`]: crate::foobar::FooBar::boop
    /// [`foobar::BazBaq::BEEP_BOOP`]: crate::foobar::BazBaq::BEEP_BOOP
    pub baz: u32,

    /// Eu consequat ac felis donec et odio pellentesque diam. Ut eu sem integer vitae justo eget.
    /// Consequat ac felis donec et odio pellentesque diam volutpat.
    pub baq: u32,

    /// Amet consectetur adipiscing elit pellentesque habitant. Ut morbi tincidunt augue interdum
    /// velit euismod in pellentesque. Imperdiet sed euismod nisi porta lorem. Nec tincidunt
    /// praesent semper feugiat. Facilisis leo vel fringilla est. Egestas diam in arcu cursus
    /// euismod quis viverra. Sagittis eu volutpat odio facilisis mauris sit amet. Posuere morbi
    /// leo urna molestie at.
    ///
    /// Pretium aenean pharetra magna ac. Nisl condimentum id venenatis a condimentum vitae. Semper
    /// quis lectus nulla at volutpat diam ut venenatis tellus. Egestas tellus rutrum tellus
    /// pellentesque eu tincidunt tortor aliquam.
    pub foobar: u32
}
<|endoftext|>


<commit_before>// Copyright (c) 2016 The vulkano developers
// 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. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.

use std::error;
use std::fmt;
use std::mem;
use std::path::Path;
use std::ptr;

use shared_library;
use vk;

#[cfg(any(target_os = "macos", target_os = "ios"))]
#[link(name = "MoltenVK", kind = "framework")]
extern {
    fn vkGetInstanceProcAddr(instance: vk::Instance, pName: *const ::std::os::raw::c_char) -> vk::PFN_vkVoidFunction;
}

#[cfg(any(target_os = "macos", target_os = "ios"))]
fn load_static() -> Result<vk::Static, LoadingError> {
    vk::Static {
        GetInstanceProcAddr: vkGetInstanceProcAddr as fn(vk::Instance, *const ::std::os::raw::c_char) -> vk::PFN_vkVoidFunction,
    }
}

#[cfg(not(any(target_os = "macos", target_os = "ios")))]
fn load_static() -> Result<vk::Static, LoadingError> {
    lazy_static! {
        static ref VK_LIB: Result<shared_library::dynamic_library::DynamicLibrary, LoadingError> = {
            #[cfg(windows)] fn get_path() -> &'static Path { Path::new("vulkan-1.dll") }
            #[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))] fn get_path() -> &'static Path { Path::new("libvulkan.so.1") }
            #[cfg(target_os = "android")] fn get_path() -> &'static Path { Path::new("libvulkan.so") }
            let path = get_path();
            shared_library::dynamic_library::DynamicLibrary::open(Some(path))
                                        .map_err(|err| LoadingError::LibraryLoadFailure(err))
        };
    }

    match *VK_LIB {
        Ok(ref lib) => {
            let mut err = None;
            let result = vk::Static::load(|name| unsafe {
                let name = name.to_str().unwrap();
                match lib.symbol(name) {
                    Ok(s) => s,
                    Err(_) => {     // TODO: return error?
                        err = Some(LoadingError::MissingEntryPoint(name.to_owned()));
                        ptr::null()
                    }
                }
            });

            if let Some(err) = err {
                Err(err)
            } else {
                Ok(result)
            }
        },
        Err(ref err) => Err(err.clone()),
    }
}

lazy_static! {
    static ref VK_STATIC: Result<vk::Static, LoadingError> = load_static();

    static ref VK_ENTRY: Result<vk::EntryPoints, LoadingError> = {
        match *VK_STATIC {
            Ok(ref lib) => {
                // At this point we assume that if one of the functions fails to load, it is an
                // implementation bug and not a real-life situation that could be handled by
                // an error.
                Ok(vk::EntryPoints::load(|name| unsafe {
                    mem::transmute(lib.GetInstanceProcAddr(0, name.as_ptr()))
                }))
            },
            Err(ref err) => Err(err.clone()),
        }
    };
}

/// Returns the collection of static functions from the Vulkan loader, or an error if failed to
/// open the loader.
pub fn static_functions() -> Result<&'static vk::Static, LoadingError> {
    VK_STATIC.as_ref().map_err(|err| err.clone())
}

/// Returns the collection of Vulkan entry points from the Vulkan loader, or an error if failed to
/// open the loader.
pub fn entry_points() -> Result<&'static vk::EntryPoints, LoadingError> {
    VK_ENTRY.as_ref().map_err(|err| err.clone())
}

/// Error that can happen when loading the Vulkan loader.
#[derive(Debug, Clone)]
pub enum LoadingError {
    /// Failed to load the Vulkan shared library.
    LibraryLoadFailure(String),         // TODO: meh for error type, but this needs changes in shared_library

    /// One of the entry points required to be supported by the Vulkan implementation is missing.
    MissingEntryPoint(String),
}

impl error::Error for LoadingError {
    #[inline]
    fn description(&self) -> &str {
        match *self {
            LoadingError::LibraryLoadFailure(_) => {
                "failed to load the Vulkan shared library"
            },
            LoadingError::MissingEntryPoint(_) => {
                "one of the entry points required to be supported by the Vulkan implementation \
                 is missing"
            },
        }
    }

    /*#[inline]
    fn cause(&self) -> Option<&error::Error> {
        match *self {
            LoadingError::LibraryLoadFailure(ref err) => Some(err),
            _ => None
        }
    }*/
}

impl fmt::Display for LoadingError {
    #[inline]
    fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        write!(fmt, "{}", error::Error::description(self))
    }
}
<commit_msg>Fix compilation on mac<commit_after>// Copyright (c) 2016 The vulkano developers
// 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. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.

use std::error;
use std::fmt;
use std::mem;
use std::path::Path;
use std::ptr;

use shared_library;
use vk;

#[cfg(any(target_os = "macos", target_os = "ios"))]
#[link(name = "MoltenVK", kind = "framework")]
extern {
    fn vkGetInstanceProcAddr(instance: vk::Instance, pName: *const ::std::os::raw::c_char) -> vk::PFN_vkVoidFunction;
}

#[cfg(any(target_os = "macos", target_os = "ios"))]
fn load_static() -> Result<vk::Static, LoadingError> {
    extern "system" fn wrapper(instance: vk::Instance, pName: *const ::std::os::raw::c_char) -> vk::PFN_vkVoidFunction {
        unsafe {
            vkGetInstanceProcAddr(instance, pName)
        }
    }

    Ok(vk::Static {
        GetInstanceProcAddr: wrapper,
    })
}

#[cfg(not(any(target_os = "macos", target_os = "ios")))]
fn load_static() -> Result<vk::Static, LoadingError> {
    lazy_static! {
        static ref VK_LIB: Result<shared_library::dynamic_library::DynamicLibrary, LoadingError> = {
            #[cfg(windows)] fn get_path() -> &'static Path { Path::new("vulkan-1.dll") }
            #[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))] fn get_path() -> &'static Path { Path::new("libvulkan.so.1") }
            #[cfg(target_os = "android")] fn get_path() -> &'static Path { Path::new("libvulkan.so") }
            let path = get_path();
            shared_library::dynamic_library::DynamicLibrary::open(Some(path))
                                        .map_err(|err| LoadingError::LibraryLoadFailure(err))
        };
    }

    match *VK_LIB {
        Ok(ref lib) => {
            let mut err = None;
            let result = vk::Static::load(|name| unsafe {
                let name = name.to_str().unwrap();
                match lib.symbol(name) {
                    Ok(s) => s,
                    Err(_) => {     // TODO: return error?
                        err = Some(LoadingError::MissingEntryPoint(name.to_owned()));
                        ptr::null()
                    }
                }
            });

            if let Some(err) = err {
                Err(err)
            } else {
                Ok(result)
            }
        },
        Err(ref err) => Err(err.clone()),
    }
}

lazy_static! {
    static ref VK_STATIC: Result<vk::Static, LoadingError> = load_static();

    static ref VK_ENTRY: Result<vk::EntryPoints, LoadingError> = {
        match *VK_STATIC {
            Ok(ref lib) => {
                // At this point we assume that if one of the functions fails to load, it is an
                // implementation bug and not a real-life situation that could be handled by
                // an error.
                Ok(vk::EntryPoints::load(|name| unsafe {
                    mem::transmute(lib.GetInstanceProcAddr(0, name.as_ptr()))
                }))
            },
            Err(ref err) => Err(err.clone()),
        }
    };
}

/// Returns the collection of static functions from the Vulkan loader, or an error if failed to
/// open the loader.
pub fn static_functions() -> Result<&'static vk::Static, LoadingError> {
    VK_STATIC.as_ref().map_err(|err| err.clone())
}

/// Returns the collection of Vulkan entry points from the Vulkan loader, or an error if failed to
/// open the loader.
pub fn entry_points() -> Result<&'static vk::EntryPoints, LoadingError> {
    VK_ENTRY.as_ref().map_err(|err| err.clone())
}

/// Error that can happen when loading the Vulkan loader.
#[derive(Debug, Clone)]
pub enum LoadingError {
    /// Failed to load the Vulkan shared library.
    LibraryLoadFailure(String),         // TODO: meh for error type, but this needs changes in shared_library

    /// One of the entry points required to be supported by the Vulkan implementation is missing.
    MissingEntryPoint(String),
}

impl error::Error for LoadingError {
    #[inline]
    fn description(&self) -> &str {
        match *self {
            LoadingError::LibraryLoadFailure(_) => {
                "failed to load the Vulkan shared library"
            },
            LoadingError::MissingEntryPoint(_) => {
                "one of the entry points required to be supported by the Vulkan implementation \
                 is missing"
            },
        }
    }

    /*#[inline]
    fn cause(&self) -> Option<&error::Error> {
        match *self {
            LoadingError::LibraryLoadFailure(ref err) => Some(err),
            _ => None
        }
    }*/
}

impl fmt::Display for LoadingError {
    #[inline]
    fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        write!(fmt, "{}", error::Error::description(self))
    }
}
<|endoftext|>


<commit_before><commit_msg>Remove unneeded masquerade_as_nightly_cargo.<commit_after><|endoftext|>


<commit_before>struct Foo;
struct Bar;

#[deriving(Show)]
struct FooBar;

#[deriving(Show)]
struct BarFoo;

// The `Add<T, U>` trait needs two generic parameters:
// * T is the type of the RHS summand, and
// * U is the type of the sum
// This block implements the operation: Foo + Bar = FooBar
impl Add<Bar, FooBar> for Foo {
    fn add(self, _rhs: Bar) -> FooBar {
        println!("> Foo.add(&Bar) was called");

        FooBar
    }
}

// Addition can be implemented in a non-commutative way
// This block implements the operation: Bar + Foo = BarFoo
impl Add<Foo, BarFoo> for Bar {
    fn add(self, _rhs: Foo) -> BarFoo {
        println!("> Bar.add(&Foo) was called");

        BarFoo
    }
}

fn main() {
    println!("Foo + Bar = {}", Foo + Bar);
    println!("Bar + Foo = {}", Bar + Foo);
}
<commit_msg>Fix ops example according to latest nightly<commit_after>use std::ops::Add;

struct Foo;
struct Bar;

#[derive(Show)]
struct FooBar;

#[derive(Show)]
struct BarFoo;

// The `Add<T, U>` trait needs two generic parameters:
// * T is the type of the RHS summand, and
// * U is the type of the sum
// This block implements the operation: Foo + Bar = FooBar
impl Add<Bar> for Foo {
    type Output = FooBar;

    fn add(self, _rhs: Bar) -> FooBar {
        println!("> Foo.add(&Bar) was called");

        FooBar
    }
}

// Addition can be implemented in a non-commutative way
// This block implements the operation: Bar + Foo = BarFoo
impl Add<Foo> for Bar {
    type Output = BarFoo;

    fn add(self, _rhs: Foo) -> BarFoo {
        println!("> Bar.add(&Foo) was called");

        BarFoo
    }
}

fn main() {
    println!("Foo + Bar = {}", Foo + Bar);
    println!("Bar + Foo = {}", Bar + Foo);
}
<|endoftext|>


<commit_before><commit_msg>add IdFunctor to rustc_data_structures<commit_after>use rustc_index::vec::{Idx, IndexVec};
use std::mem;
use std::ptr;

pub trait IdFunctor {
    type Inner;

    fn map_id<F>(self, f: F) -> Self
    where
        F: FnMut(Self::Inner) -> Self::Inner;
}

impl<T> IdFunctor for Box<T> {
    type Inner = T;

    #[inline]
    fn map_id<F>(self, mut f: F) -> Self
    where
        F: FnMut(Self::Inner) -> Self::Inner,
    {
        let raw = Box::into_raw(self);
        unsafe {
            // SAFETY: The raw pointer points to a valid value of type `T`.
            let value = ptr::read(raw);
            // SAFETY: Convert's `Box<T>` to `Box<MaybeUninit<T>>` which is the
            // inverse of `Box::assume_init()` and should be safe.
            let mut raw: Box<mem::MaybeUninit<T>> = Box::from_raw(raw.cast());
            // SAFETY: Write the mapped value back into the `Box`.
            ptr::write(raw.as_mut_ptr(), f(value));
            // SAFETY: We just initialized `raw`.
            raw.assume_init()
        }
    }
}

impl<T> IdFunctor for Vec<T> {
    type Inner = T;

    #[inline]
    fn map_id<F>(mut self, mut f: F) -> Self
    where
        F: FnMut(Self::Inner) -> Self::Inner,
    {
        // FIXME: We don't really care about panics here and leak
        // far more than we should, but that should be fine for now.
        let len = self.len();
        unsafe {
            self.set_len(0);
            let start = self.as_mut_ptr();
            for i in 0..len {
                let p = start.add(i);
                ptr::write(p, f(ptr::read(p)));
            }
            self.set_len(len);
        }
        self
    }
}

impl<T> IdFunctor for Box<[T]> {
    type Inner = T;

    #[inline]
    fn map_id<F>(self, f: F) -> Self
    where
        F: FnMut(Self::Inner) -> Self::Inner,
    {
        Vec::from(self).map_id(f).into()
    }
}

impl<I: Idx, T> IdFunctor for IndexVec<I, T> {
    type Inner = T;

    #[inline]
    fn map_id<F>(self, f: F) -> Self
    where
        F: FnMut(Self::Inner) -> Self::Inner,
    {
        IndexVec::from_raw(self.raw.map_id(f))
    }
}
<|endoftext|>


<commit_before><commit_msg>Playing with internal changes<commit_after>struct Object1 {
    value: String,
    value2: i32,
}

impl Object1 {
    fn run(&self) {
        println!("hello world {}", self.value2);
    }
    fn internal_change(& mut self, new_number: i32) {
        self.value2 = new_number;
    }
}

fn main () {
    // let object = Object1{value: String::new("carlos"), value2: 1};
    let mut object = Object1{value: String::from("carlos"), value2: 1};
    object.value2 = 2;
    object.run();
    object.internal_change(3);
    object.run();
}
<|endoftext|>


<commit_before><commit_msg>add sleep to sending whispers<commit_after><|endoftext|>


<commit_before><commit_msg>Add file to section 2 of examples<commit_after>use std::mem;

// This function borrows a slice
fn analyze_slice(slice: &[i32]) {
    println!("first element: {}", slice[0]);
    println!("slice has {} elements", slice.len());
}

fn main() {
    // Fixed-sized array
    let xs: [i32; 4] = [1, 2, 3, 4];

    // All elements can be initialized to same value
    let ys: [i32; 500] = [0; 500];

    // Indexing starts at 0
    println!("first: {}", xs[0]);
    println!("second: {}", xs[1]);

    // Print length of array
    println!("array size: {}", xs.len());

    // Arrays are stack allocated
    println!("array occupies {} bytes", mem::size_of_val(&xs));

    // Arrays can automatically be borrowed as slices
    println!("borrow the whole array as a slice");
    analyze_slice(&xs);

    // Slices can point to a section of an array
    println!("borrow a section of the array as a slice");
    analyze_slice(&ys[1 .. 4]);
}
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #86398 - yerke:add-test-for-issue-54685, r=Mark-Simulacrum<commit_after>// min-llvm-version: 12.0
// compile-flags: -C opt-level=3
// run-pass

fn foo(_i: i32) -> i32 {
    1
}
fn bar(_i: i32) -> i32 {
    1
}

fn main() {
    let x: fn(i32) -> i32 = foo;
    let y: fn(i32) -> i32 = bar;

    let s1;
    if x == y {
        s1 = "same".to_string();
    } else {
        s1 = format!("{:?}, {:?}", x, y);
    }

    let s2;
    if x == y {
        s2 = "same".to_string();
    } else {
        s2 = format!("{:?}, {:?}", x, y);
    }

    assert_eq!(s1, s2);
}
<|endoftext|>


<commit_before>use std::io::Write;
use inflector::Inflector;
use botocore::{Operation, Service, Shape, ShapeType, Member};

use super::xml_payload_parser;
use super::{IoResult, FileWriter, GenerateProtocol, error_type_name, capitalize_first,
            generate_field_name};

pub struct QueryGenerator;

impl GenerateProtocol for QueryGenerator {
    fn generate_method_signatures(&self, writer: &mut FileWriter, service: &Service) -> IoResult {
        for (operation_name, operation) in service.operations.iter() {
            writeln!(writer,"
                {documentation}
                {method_signature};
                ",
                documentation = generate_documentation(operation),
                method_signature = generate_method_signature(operation_name, operation),
            )?
        }
        Ok(())
    }

    fn generate_method_impls(&self, writer: &mut FileWriter, service: &Service) -> IoResult {
        for (operation_name, operation) in service.operations.iter() {
            writeln!(writer,
                     "
                {documentation}
                {method_signature} {{
                    let mut request = SignedRequest::new(\"{http_method}\", \"{endpoint_prefix}\", self.region, \"{request_uri}\");
                    let mut params = Params::new();

                    params.put(\"Action\", \"{operation_name}\");
                    params.put(\"Version\", \"{api_version}\");
                    {serialize_input}
                    request.set_params(params);

                    request.sign(&try!(self.credentials_provider.credentials()));
                    let response = try!(self.dispatcher.dispatch(&request));
                    match response.status {{
                        StatusCode::Ok => {{
                            {parse_payload}
                            Ok(result)
                        }}
                        _ => {{
                            Err({error_type}::from_body(String::from_utf8_lossy(&response.body).as_ref()))
                        }}
                    }}
                }}
                ",
                     api_version = &service.metadata.api_version,
                     documentation = generate_documentation(operation),
                     error_type = error_type_name(operation_name),
                     http_method = &operation.http.method,
                     endpoint_prefix = &service.metadata.endpoint_prefix,
                     parse_payload =
                         xml_payload_parser::generate_response_parser(service, operation, false),
                     method_signature = generate_method_signature(operation_name, operation),
                     operation_name = &operation.name,
                     request_uri = &operation.http.request_uri,
                     serialize_input = generate_method_input_serialization(operation))?;
        }
        Ok(())
    }

    fn generate_prelude(&self, writer: &mut FileWriter, _service: &Service) -> IoResult {
        writeln!(writer,
                 "use std::str::FromStr;
            use xml::EventReader;
            use xml::reader::ParserConfig;
            use rusoto_core::param::{{Params, ServiceParams}};
            use rusoto_core::signature::SignedRequest;
            use xml::reader::XmlEvent;
            use rusoto_core::xmlutil::{{Next, Peek, XmlParseError, XmlResponse}};
            use rusoto_core::xmlutil::{{characters, end_element, start_element, skip_tree, peek_at_name}};
            use rusoto_core::xmlerror::*;

            enum DeserializerNext {{
                Close,
                Skip,
                Element(String),
        }}")
    }

    fn generate_struct_attributes(&self,
                                  _serialized: bool,
                                  deserialized: bool)
                                  -> String {
        xml_payload_parser::generate_struct_attributes(deserialized)
    }

    fn generate_serializer(&self, name: &str, shape: &Shape, service: &Service) -> Option<String> {
        if shape.is_primitive() {
            return None;
        }

        Some(format!("
            /// Serialize `{name}` contents to a `SignedRequest`.
            struct {name}Serializer;
            impl {name}Serializer {{
                {serializer_signature} {{
                    {serializer_body}
                }}
            }}
            ",
                     name = name,
                     serializer_signature = generate_serializer_signature(name, shape),
                     serializer_body = generate_serializer_body(service, shape)))
    }

    fn generate_deserializer(&self,
                             name: &str,
                             shape: &Shape,
                             service: &Service)
                             -> Option<String> {
        Some(xml_payload_parser::generate_deserializer(name, shape, service))
    }

    fn timestamp_type(&self) -> &'static str {
        "String"
    }
}

pub fn generate_method_input_serialization(operation: &Operation) -> String {
    if operation.input.is_some() {
        format!(
            "{input_type}Serializer::serialize(&mut params, \"\", &input);",
            input_type = operation.input.as_ref().unwrap().shape,
        )
    } else {
        String::new()
    }
}

fn generate_serializer_body(service: &Service, shape: &Shape) -> String {
    match shape.shape_type {
        ShapeType::List => generate_list_serializer(service, shape),
        ShapeType::Map => generate_map_serializer(service, shape),
        ShapeType::Structure => generate_struct_serializer(service, shape),
        _ => "".to_owned(),
    }
}

fn generate_serializer_signature(name: &str, shape: &Shape) -> String {
    if shape.shape_type == ShapeType::Structure && shape.members.as_ref().unwrap().is_empty() {
        format!("fn serialize(_params: &mut Params, name: &str, _obj: &{})",
                name)
    } else {
        format!("fn serialize(params: &mut Params, name: &str, obj: &{})",
                name)
    }
}

fn generate_list_serializer(service: &Service, shape: &Shape) -> String {
    let member_shape = service.shape_for_member(shape.member.as_ref().unwrap()).unwrap();
    let primitive = member_shape.is_primitive();
    let is_shape_flattened = match shape.flattened {
        None => false,
        Some(_) => true,
    };
    let mut parts = Vec::new();

    let lmf = list_member_format(service, is_shape_flattened);

    parts.push(format!("for (index, obj) in obj.iter().enumerate() {{
                    let key = format!(\"{list_member_format}\", name, index+1);",
                       list_member_format = lmf));

    if primitive {
        parts.push(format!("params.put(&key, {});",
                           serialize_primitive_expression(&member_shape.shape_type, "obj")));
    } else {
        parts.push(format!("{}Serializer::serialize(params, &key, obj);",
                           shape.member_type()));
    }

    parts.push("}".to_owned());
    parts.join("\n")
}

fn list_member_format(service: &Service, flattened: bool) -> String {
    match &service.metadata.protocol[..] {
        "ec2" => "{}.{}".to_owned(),
        "query" => {
            match flattened {
                true => "{}.{}".to_owned(),
                false => "{}.member.{}".to_owned(),
            }
        },
        _ => panic!("Unsupported protocol"),
    }
}

fn generate_map_serializer(service: &Service, shape: &Shape) -> String {
    let mut parts = Vec::new();

    // the key is always a string type
    parts.push(format!("for (index, (key, value)) in obj.iter().enumerate() {{
            let prefix = format!(\"{{}}.{{}}\", name, index+1);
            params.put(&format!(\"{{}}.{{}}\", prefix, \"{key_name}\"), &key);",
            key_name = key_name(service, shape),
        ));

    let value_shape = service.shape_for_value(shape.value.as_ref().unwrap()).unwrap();
    let primitive_value = value_shape.is_primitive();

    if primitive_value {
        parts.push(format!("params.put(&key, {});",
                           serialize_primitive_expression(&value_shape.shape_type, "value")));
    } else {
        parts.push(format!("{value_type}Serializer::serialize(
                    params,
                    &format!(\"{{}}.{{}}\", prefix, \"{value_name}\"),
                    value,
                );",
                           value_type = shape.value_type(),
                           value_name = value_name(service, shape)))
    }

    parts.push("}".to_owned());
    parts.join("\n")
}

fn key_name(service: &Service, shape: &Shape) -> String {
    let key_name = shape.key
        .as_ref()
        .expect("Key undefined")
        .location_name
        .as_ref()
        .map(String::as_ref)
        .unwrap_or_else(|| "key");
    capitalize_if_ec2(service, key_name)
}

fn value_name(service: &Service, shape: &Shape) -> String {
    let value_name = shape.value
        .as_ref()
        .expect("Value undefined")
        .location_name
        .as_ref()
        .map(String::as_ref)
        .unwrap_or_else(|| "value");
    capitalize_if_ec2(service, value_name)
}

fn member_location(service: &Service, member: &Member, default: &str) -> String {
    let member_location = member.location_name.clone().unwrap_or_else(|| default.to_owned());
    capitalize_if_ec2(service, &member_location)
}

fn capitalize_if_ec2(service: &Service, name: &str) -> String {
    match &service.metadata.protocol[..] {
        "ec2" => capitalize_first(name),
        _ => name.to_owned(),
    }
}

fn generate_struct_serializer(service: &Service, shape: &Shape) -> String {
    format!(
        "let mut prefix = name.to_string();
        if prefix != \"\" {{
            prefix.push_str(\".\");
        }}

        {struct_field_serializers}
        ",
        struct_field_serializers = generate_struct_field_serializers(service, shape),
    )
}

fn generate_struct_field_serializers(service: &Service, shape: &Shape) -> String {
    shape.members
        .as_ref()
        .unwrap()
        .iter()
        .map(|(member_name, member)| {
            let primitive = service.shape_for_member(member).unwrap().is_primitive();

            if shape.required(member_name) {
                if primitive {
                    required_primitive_field_serializer(service, member_name, member)
                } else {
                    required_complex_field_serializer(service, member_name, member)
                }
            } else if primitive {
                optional_primitive_field_serializer(service, member_name, member)
            } else {
                optional_complex_field_serializer(service, member_name, member)
            }
        })
        .collect::<Vec<String>>()
        .join("\n")
}

fn optional_primitive_field_serializer(service: &Service,
                                       member_name: &str,
                                       member: &Member)
                                       -> String {
    let member_shape = service.shape_for_member(member).unwrap();
    let expression = serialize_primitive_expression(&member_shape.shape_type, "field_value");

    format!("if let Some(ref field_value) = obj.{field_name} {{
                params.put(&format!(\"{{}}{{}}\", prefix, \"{tag_name}\"), {expression});
            }}",
            field_name = generate_field_name(member_name),
            expression = expression,
            tag_name = member_location(service, member, member_name))
}

fn required_primitive_field_serializer(service: &Service,
                                       member_name: &str,
                                       member: &Member)
                                       -> String {
    let member_shape = service.shape_for_member(member).unwrap();
    let expression = serialize_primitive_expression(&member_shape.shape_type,
                                                    &format!("obj.{}",
                                                             generate_field_name(member_name)));

    format!("params.put(&format!(\"{{}}{{}}\", prefix, \"{tag_name}\"), {expression});",
            expression = expression,
            tag_name = member_location(service, member, member_name))
}

fn serialize_primitive_expression(shape_type: &ShapeType, var_name: &str) -> String {
    match *shape_type {
        ShapeType::String | ShapeType::Timestamp => format!("&{}", var_name),
        ShapeType::Integer | ShapeType::Double | ShapeType::Long | ShapeType::Boolean => {
            format!("&{}.to_string()", var_name)
        }
        ShapeType::Blob => format!("::std::str::from_utf8(&{}).unwrap()", var_name),
        shape_type => panic!("Unknown primitive shape type: {:?}", shape_type),
    }
}

fn required_complex_field_serializer(service: &Service,
                                     member_name: &str,
                                     member: &Member)
                                     -> String {
    format!("{member_shape}Serializer::serialize(
                params,
                &format!(\"{{}}{{}}\", prefix, \"{tag_name}\"),
                &obj.{field_name},
            );",
            field_name = generate_field_name(member_name),
            member_shape = member.shape,
            tag_name = member_location(service, member, member_name))
}

fn optional_complex_field_serializer(service: &Service,
                                     member_name: &str,
                                     member: &Member)
                                     -> String {
    format!("if let Some(ref field_value) = obj.{field_name} {{
                {member_shape_name}Serializer::serialize(
                    params,
                    &format!(\"{{}}{{}}\", prefix, \"{tag_name}\"),
                    field_value,
                );
            }}",
            field_name = generate_field_name(member_name),
            member_shape_name = member.shape,
            tag_name = member_location(service, member, member_name))
}

fn generate_documentation(operation: &Operation) -> String {
    match operation.documentation {
        Some(ref docs) => {
            format!("#[doc=\"{}\"]",
                    docs.replace("\\", "\\\\").replace("\"", "\\\""))
        }
        None => "".to_owned(),
    }
}

fn generate_method_signature(operation_name: &str, operation: &Operation) -> String {
    if operation.input.is_some() {
        format!(
            "fn {operation_name}(&self, input: &{input_type}) -> Result<{output_type}, {error_type}>",
            input_type = operation.input.as_ref().unwrap().shape,
            operation_name = operation.name.to_snake_case(),
            output_type = &operation.output_shape_or("()"),
            error_type = error_type_name(operation_name),
        )
    } else {
        format!(
            "fn {operation_name}(&self) -> Result<{output_type}, {error_type}>",
            operation_name = operation.name.to_snake_case(),
            output_type = &operation.output_shape_or("()"),
            error_type = error_type_name(operation_name),
        )
    }
}
<commit_msg>Use shape defined flatness for query codegen.<commit_after>use std::io::Write;
use inflector::Inflector;
use botocore::{Operation, Service, Shape, ShapeType, Member};

use super::xml_payload_parser;
use super::{IoResult, FileWriter, GenerateProtocol, error_type_name, capitalize_first,
            generate_field_name};

pub struct QueryGenerator;

impl GenerateProtocol for QueryGenerator {
    fn generate_method_signatures(&self, writer: &mut FileWriter, service: &Service) -> IoResult {
        for (operation_name, operation) in service.operations.iter() {
            writeln!(writer,"
                {documentation}
                {method_signature};
                ",
                documentation = generate_documentation(operation),
                method_signature = generate_method_signature(operation_name, operation),
            )?
        }
        Ok(())
    }

    fn generate_method_impls(&self, writer: &mut FileWriter, service: &Service) -> IoResult {
        for (operation_name, operation) in service.operations.iter() {
            writeln!(writer,
                     "
                {documentation}
                {method_signature} {{
                    let mut request = SignedRequest::new(\"{http_method}\", \"{endpoint_prefix}\", self.region, \"{request_uri}\");
                    let mut params = Params::new();

                    params.put(\"Action\", \"{operation_name}\");
                    params.put(\"Version\", \"{api_version}\");
                    {serialize_input}
                    request.set_params(params);

                    request.sign(&try!(self.credentials_provider.credentials()));
                    let response = try!(self.dispatcher.dispatch(&request));
                    match response.status {{
                        StatusCode::Ok => {{
                            {parse_payload}
                            Ok(result)
                        }}
                        _ => {{
                            Err({error_type}::from_body(String::from_utf8_lossy(&response.body).as_ref()))
                        }}
                    }}
                }}
                ",
                     api_version = &service.metadata.api_version,
                     documentation = generate_documentation(operation),
                     error_type = error_type_name(operation_name),
                     http_method = &operation.http.method,
                     endpoint_prefix = &service.metadata.endpoint_prefix,
                     parse_payload =
                         xml_payload_parser::generate_response_parser(service, operation, false),
                     method_signature = generate_method_signature(operation_name, operation),
                     operation_name = &operation.name,
                     request_uri = &operation.http.request_uri,
                     serialize_input = generate_method_input_serialization(operation))?;
        }
        Ok(())
    }

    fn generate_prelude(&self, writer: &mut FileWriter, _service: &Service) -> IoResult {
        writeln!(writer,
                 "use std::str::FromStr;
            use xml::EventReader;
            use xml::reader::ParserConfig;
            use rusoto_core::param::{{Params, ServiceParams}};
            use rusoto_core::signature::SignedRequest;
            use xml::reader::XmlEvent;
            use rusoto_core::xmlutil::{{Next, Peek, XmlParseError, XmlResponse}};
            use rusoto_core::xmlutil::{{characters, end_element, start_element, skip_tree, peek_at_name}};
            use rusoto_core::xmlerror::*;

            enum DeserializerNext {{
                Close,
                Skip,
                Element(String),
        }}")
    }

    fn generate_struct_attributes(&self,
                                  _serialized: bool,
                                  deserialized: bool)
                                  -> String {
        xml_payload_parser::generate_struct_attributes(deserialized)
    }

    fn generate_serializer(&self, name: &str, shape: &Shape, service: &Service) -> Option<String> {
        if shape.is_primitive() {
            return None;
        }

        Some(format!("
            /// Serialize `{name}` contents to a `SignedRequest`.
            struct {name}Serializer;
            impl {name}Serializer {{
                {serializer_signature} {{
                    {serializer_body}
                }}
            }}
            ",
                     name = name,
                     serializer_signature = generate_serializer_signature(name, shape),
                     serializer_body = generate_serializer_body(service, shape)))
    }

    fn generate_deserializer(&self,
                             name: &str,
                             shape: &Shape,
                             service: &Service)
                             -> Option<String> {
        Some(xml_payload_parser::generate_deserializer(name, shape, service))
    }

    fn timestamp_type(&self) -> &'static str {
        "String"
    }
}

pub fn generate_method_input_serialization(operation: &Operation) -> String {
    if operation.input.is_some() {
        format!(
            "{input_type}Serializer::serialize(&mut params, \"\", &input);",
            input_type = operation.input.as_ref().unwrap().shape,
        )
    } else {
        String::new()
    }
}

fn generate_serializer_body(service: &Service, shape: &Shape) -> String {
    match shape.shape_type {
        ShapeType::List => generate_list_serializer(service, shape),
        ShapeType::Map => generate_map_serializer(service, shape),
        ShapeType::Structure => generate_struct_serializer(service, shape),
        _ => "".to_owned(),
    }
}

fn generate_serializer_signature(name: &str, shape: &Shape) -> String {
    if shape.shape_type == ShapeType::Structure && shape.members.as_ref().unwrap().is_empty() {
        format!("fn serialize(_params: &mut Params, name: &str, _obj: &{})",
                name)
    } else {
        format!("fn serialize(params: &mut Params, name: &str, obj: &{})",
                name)
    }
}

fn generate_list_serializer(service: &Service, shape: &Shape) -> String {
    let member_shape = service.shape_for_member(shape.member.as_ref().unwrap()).unwrap();
    let primitive = member_shape.is_primitive();
    let is_shape_flattened = match shape.flattened {
        None => false,
        Some(shape_defined_flatness) => shape_defined_flatness,
    };
    let mut parts = Vec::new();

    let lmf = list_member_format(service, is_shape_flattened);

    parts.push(format!("for (index, obj) in obj.iter().enumerate() {{
                    let key = format!(\"{list_member_format}\", name, index+1);",
                       list_member_format = lmf));

    if primitive {
        parts.push(format!("params.put(&key, {});",
                           serialize_primitive_expression(&member_shape.shape_type, "obj")));
    } else {
        parts.push(format!("{}Serializer::serialize(params, &key, obj);",
                           shape.member_type()));
    }

    parts.push("}".to_owned());
    parts.join("\n")
}

fn list_member_format(service: &Service, flattened: bool) -> String {
    match &service.metadata.protocol[..] {
        "ec2" => "{}.{}".to_owned(),
        "query" => {
            match flattened {
                true => "{}.{}".to_owned(),
                false => "{}.member.{}".to_owned(),
            }
        },
        _ => panic!("Unsupported protocol"),
    }
}

fn generate_map_serializer(service: &Service, shape: &Shape) -> String {
    let mut parts = Vec::new();

    // the key is always a string type
    parts.push(format!("for (index, (key, value)) in obj.iter().enumerate() {{
            let prefix = format!(\"{{}}.{{}}\", name, index+1);
            params.put(&format!(\"{{}}.{{}}\", prefix, \"{key_name}\"), &key);",
            key_name = key_name(service, shape),
        ));

    let value_shape = service.shape_for_value(shape.value.as_ref().unwrap()).unwrap();
    let primitive_value = value_shape.is_primitive();

    if primitive_value {
        parts.push(format!("params.put(&key, {});",
                           serialize_primitive_expression(&value_shape.shape_type, "value")));
    } else {
        parts.push(format!("{value_type}Serializer::serialize(
                    params,
                    &format!(\"{{}}.{{}}\", prefix, \"{value_name}\"),
                    value,
                );",
                           value_type = shape.value_type(),
                           value_name = value_name(service, shape)))
    }

    parts.push("}".to_owned());
    parts.join("\n")
}

fn key_name(service: &Service, shape: &Shape) -> String {
    let key_name = shape.key
        .as_ref()
        .expect("Key undefined")
        .location_name
        .as_ref()
        .map(String::as_ref)
        .unwrap_or_else(|| "key");
    capitalize_if_ec2(service, key_name)
}

fn value_name(service: &Service, shape: &Shape) -> String {
    let value_name = shape.value
        .as_ref()
        .expect("Value undefined")
        .location_name
        .as_ref()
        .map(String::as_ref)
        .unwrap_or_else(|| "value");
    capitalize_if_ec2(service, value_name)
}

fn member_location(service: &Service, member: &Member, default: &str) -> String {
    let member_location = member.location_name.clone().unwrap_or_else(|| default.to_owned());
    capitalize_if_ec2(service, &member_location)
}

fn capitalize_if_ec2(service: &Service, name: &str) -> String {
    match &service.metadata.protocol[..] {
        "ec2" => capitalize_first(name),
        _ => name.to_owned(),
    }
}

fn generate_struct_serializer(service: &Service, shape: &Shape) -> String {
    format!(
        "let mut prefix = name.to_string();
        if prefix != \"\" {{
            prefix.push_str(\".\");
        }}

        {struct_field_serializers}
        ",
        struct_field_serializers = generate_struct_field_serializers(service, shape),
    )
}

fn generate_struct_field_serializers(service: &Service, shape: &Shape) -> String {
    shape.members
        .as_ref()
        .unwrap()
        .iter()
        .map(|(member_name, member)| {
            let primitive = service.shape_for_member(member).unwrap().is_primitive();

            if shape.required(member_name) {
                if primitive {
                    required_primitive_field_serializer(service, member_name, member)
                } else {
                    required_complex_field_serializer(service, member_name, member)
                }
            } else if primitive {
                optional_primitive_field_serializer(service, member_name, member)
            } else {
                optional_complex_field_serializer(service, member_name, member)
            }
        })
        .collect::<Vec<String>>()
        .join("\n")
}

fn optional_primitive_field_serializer(service: &Service,
                                       member_name: &str,
                                       member: &Member)
                                       -> String {
    let member_shape = service.shape_for_member(member).unwrap();
    let expression = serialize_primitive_expression(&member_shape.shape_type, "field_value");

    format!("if let Some(ref field_value) = obj.{field_name} {{
                params.put(&format!(\"{{}}{{}}\", prefix, \"{tag_name}\"), {expression});
            }}",
            field_name = generate_field_name(member_name),
            expression = expression,
            tag_name = member_location(service, member, member_name))
}

fn required_primitive_field_serializer(service: &Service,
                                       member_name: &str,
                                       member: &Member)
                                       -> String {
    let member_shape = service.shape_for_member(member).unwrap();
    let expression = serialize_primitive_expression(&member_shape.shape_type,
                                                    &format!("obj.{}",
                                                             generate_field_name(member_name)));

    format!("params.put(&format!(\"{{}}{{}}\", prefix, \"{tag_name}\"), {expression});",
            expression = expression,
            tag_name = member_location(service, member, member_name))
}

fn serialize_primitive_expression(shape_type: &ShapeType, var_name: &str) -> String {
    match *shape_type {
        ShapeType::String | ShapeType::Timestamp => format!("&{}", var_name),
        ShapeType::Integer | ShapeType::Double | ShapeType::Long | ShapeType::Boolean => {
            format!("&{}.to_string()", var_name)
        }
        ShapeType::Blob => format!("::std::str::from_utf8(&{}).unwrap()", var_name),
        shape_type => panic!("Unknown primitive shape type: {:?}", shape_type),
    }
}

fn required_complex_field_serializer(service: &Service,
                                     member_name: &str,
                                     member: &Member)
                                     -> String {
    format!("{member_shape}Serializer::serialize(
                params,
                &format!(\"{{}}{{}}\", prefix, \"{tag_name}\"),
                &obj.{field_name},
            );",
            field_name = generate_field_name(member_name),
            member_shape = member.shape,
            tag_name = member_location(service, member, member_name))
}

fn optional_complex_field_serializer(service: &Service,
                                     member_name: &str,
                                     member: &Member)
                                     -> String {
    format!("if let Some(ref field_value) = obj.{field_name} {{
                {member_shape_name}Serializer::serialize(
                    params,
                    &format!(\"{{}}{{}}\", prefix, \"{tag_name}\"),
                    field_value,
                );
            }}",
            field_name = generate_field_name(member_name),
            member_shape_name = member.shape,
            tag_name = member_location(service, member, member_name))
}

fn generate_documentation(operation: &Operation) -> String {
    match operation.documentation {
        Some(ref docs) => {
            format!("#[doc=\"{}\"]",
                    docs.replace("\\", "\\\\").replace("\"", "\\\""))
        }
        None => "".to_owned(),
    }
}

fn generate_method_signature(operation_name: &str, operation: &Operation) -> String {
    if operation.input.is_some() {
        format!(
            "fn {operation_name}(&self, input: &{input_type}) -> Result<{output_type}, {error_type}>",
            input_type = operation.input.as_ref().unwrap().shape,
            operation_name = operation.name.to_snake_case(),
            output_type = &operation.output_shape_or("()"),
            error_type = error_type_name(operation_name),
        )
    } else {
        format!(
            "fn {operation_name}(&self) -> Result<{output_type}, {error_type}>",
            operation_name = operation.name.to_snake_case(),
            output_type = &operation.output_shape_or("()"),
            error_type = error_type_name(operation_name),
        )
    }
}
<|endoftext|>


<commit_before>fn main(vec[str] args) {
  rustc::driver::rustc::main(args);
}<commit_msg>fuzzer: Begin writing main<commit_after>import std::fs;
import std::getopts;
import std::getopts::optopt;
import std::getopts::opt_present;
import std::getopts::opt_str;
import std::io;
import std::vec;

import rustc::front::ast;

type src_gen = iter() -> str;

iter dir_src_gen(str dir) -> str {
}

fn usage(str binary) {
    io::stdout().write_line("usage");
}

type session = rec(str srcdir);

fn make_session(vec[str] args) -> session {
    // Directory of rust source files to use as input
    auto opt_src = "src";

    auto binary = vec::shift[str](args);
    auto opts  = [optopt(opt_src)];
    auto match;
    alt (getopts::getopts(args, opts)) {
        case (getopts::failure(?f)) {
            log_err #fmt("error: %s", getopts::fail_str(f));
            fail;
        }
        case (getopts::success(?m)) {
            match = m;
        }
    };

    if (!opt_present(match, opt_src)) {
        usage(binary);
        fail;
    }

    auto srcdir = opt_str(match, opt_src);

    ret rec(srcdir = srcdir);
}

fn log_session(session sess) {
    log #fmt("srcdir: %s", sess.srcdir);
}

fn run_session(session sess) {
}

fn main(vec[str] args) {
    auto sess = make_session(args);
    log_session(sess);
    run_session(sess);
}

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

//! A module for working with borrowed data.
//!
//! # The `BorrowFrom` traits
//!
//! In general, there may be several ways to "borrow" a piece of data.  The
//! typical ways of borrowing a type `T` are `&T` (a shared borrow) and `&mut T`
//! (a mutable borrow). But types like `Vec<T>` provide additional kinds of
//! borrows: the borrowed slices `&[T]` and `&mut [T]`.
//!
//! When writing generic code, it is often desirable to abstract over all ways
//! of borrowing data from a given type. That is the role of the `BorrowFrom`
//! trait: if `T: BorrowFrom<U>`, then `&T` can be borrowed from `&U`.  A given
//! type can be borrowed as multiple different types. In particular, `Vec<T>:
//! BorrowFrom<Vec<T>>` and `[T]: BorrowFrom<Vec<T>>`.
//!
//! # The `ToOwned` trait
//!
//! Some types make it possible to go from borrowed to owned, usually by
//! implementing the `Clone` trait. But `Clone` works only for going from `&T`
//! to `T`. The `ToOwned` trait generalizes `Clone` to construct owned data
//! from any borrow of a given type.
//!
//! # The `Cow` (clone-on-write) type
//!
//! The type `Cow` is a smart pointer providing clone-on-write functionality: it
//! can enclose and provide immutable access to borrowed data, and clone the
//! data lazily when mutation or ownership is required. The type is designed to
//! work with general borrowed data via the `BorrowFrom` trait.
//!
//! `Cow` implements both `Deref` and `DerefMut`, which means that you can call
//! methods directly on the data it encloses. The first time a mutable reference
//! is required, the data will be cloned (via `to_owned`) if it is not
//! already owned.

#![unstable = "recently added as part of collections reform"]

use clone::Clone;
use kinds::Sized;
use ops::Deref;
use self::Cow::*;

/// A trait for borrowing data.
pub trait BorrowFrom<Sized? Owned> for Sized? {
    /// Immutably borrow from an owned value.
    fn borrow_from(owned: &Owned) -> &Self;
}

/// A trait for mutably borrowing data.
pub trait BorrowFromMut<Sized? Owned> for Sized? : BorrowFrom<Owned> {
    /// Mutably borrow from an owned value.
    fn borrow_from_mut(owned: &mut Owned) -> &mut Self;
}

impl<Sized? T> BorrowFrom<T> for T {
    fn borrow_from(owned: &T) -> &T { owned }
}

impl<Sized? T> BorrowFromMut<T> for T {
    fn borrow_from_mut(owned: &mut T) -> &mut T { owned }
}

impl BorrowFrom<&'static str> for str {
    fn borrow_from<'a>(owned: &'a &'static str) -> &'a str { &**owned }
}

/// A generalization of Clone to borrowed data.
pub trait ToOwned<Owned> for Sized?: BorrowFrom<Owned> {
    /// Create owned data from borrowed data, usually by copying.
    fn to_owned(&self) -> Owned;
}

impl<T> ToOwned<T> for T where T: Clone {
    fn to_owned(&self) -> T { self.clone() }
}

/// A clone-on-write smart pointer.
pub enum Cow<'a, T, B: 'a> where B: ToOwned<T> {
    /// Borrowed data.
    Borrowed(&'a B),

    /// Owned data.
    Owned(T)
}

impl<'a, T, B> Cow<'a, T, B> where B: ToOwned<T> {
    /// Acquire a mutable reference to the owned form of the data.
    ///
    /// Copies the data if it is not already owned.
    pub fn to_mut(&mut self) -> &mut T {
        match *self {
            Borrowed(borrowed) => {
                *self = Owned(borrowed.to_owned());
                self.to_mut()
            }
            Owned(ref mut owned) => owned
        }
    }

    /// Extract the owned data.
    ///
    /// Copies the data if it is not already owned.
    pub fn into_owned(self) -> T {
        match self {
            Borrowed(borrowed) => borrowed.to_owned(),
            Owned(owned) => owned
        }
    }
}

impl<'a, T, B> Deref<B> for Cow<'a, T, B> where B: ToOwned<T>  {
    fn deref(&self) -> &B {
        match *self {
            Borrowed(borrowed) => borrowed,
            Owned(ref owned) => BorrowFrom::borrow_from(owned)
        }
    }
}
<commit_msg>auto merge of #19146 : gereeter/rust/reference-borrow, r=aturon<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! A module for working with borrowed data.
//!
//! # The `BorrowFrom` traits
//!
//! In general, there may be several ways to "borrow" a piece of data.  The
//! typical ways of borrowing a type `T` are `&T` (a shared borrow) and `&mut T`
//! (a mutable borrow). But types like `Vec<T>` provide additional kinds of
//! borrows: the borrowed slices `&[T]` and `&mut [T]`.
//!
//! When writing generic code, it is often desirable to abstract over all ways
//! of borrowing data from a given type. That is the role of the `BorrowFrom`
//! trait: if `T: BorrowFrom<U>`, then `&T` can be borrowed from `&U`.  A given
//! type can be borrowed as multiple different types. In particular, `Vec<T>:
//! BorrowFrom<Vec<T>>` and `[T]: BorrowFrom<Vec<T>>`.
//!
//! # The `ToOwned` trait
//!
//! Some types make it possible to go from borrowed to owned, usually by
//! implementing the `Clone` trait. But `Clone` works only for going from `&T`
//! to `T`. The `ToOwned` trait generalizes `Clone` to construct owned data
//! from any borrow of a given type.
//!
//! # The `Cow` (clone-on-write) type
//!
//! The type `Cow` is a smart pointer providing clone-on-write functionality: it
//! can enclose and provide immutable access to borrowed data, and clone the
//! data lazily when mutation or ownership is required. The type is designed to
//! work with general borrowed data via the `BorrowFrom` trait.
//!
//! `Cow` implements both `Deref` and `DerefMut`, which means that you can call
//! methods directly on the data it encloses. The first time a mutable reference
//! is required, the data will be cloned (via `to_owned`) if it is not
//! already owned.

#![unstable = "recently added as part of collections reform"]

use clone::Clone;
use kinds::Sized;
use ops::Deref;
use self::Cow::*;

/// A trait for borrowing data.
pub trait BorrowFrom<Sized? Owned> for Sized? {
    /// Immutably borrow from an owned value.
    fn borrow_from(owned: &Owned) -> &Self;
}

/// A trait for mutably borrowing data.
pub trait BorrowFromMut<Sized? Owned> for Sized? : BorrowFrom<Owned> {
    /// Mutably borrow from an owned value.
    fn borrow_from_mut(owned: &mut Owned) -> &mut Self;
}

impl<Sized? T> BorrowFrom<T> for T {
    fn borrow_from(owned: &T) -> &T { owned }
}

impl<Sized? T> BorrowFromMut<T> for T {
    fn borrow_from_mut(owned: &mut T) -> &mut T { owned }
}

impl<'a, Sized? T> BorrowFrom<&'a T> for T {
    fn borrow_from<'b>(owned: &'b &'a T) -> &'b T { &**owned }
}

impl<'a, Sized? T> BorrowFrom<&'a mut T> for T {
    fn borrow_from<'b>(owned: &'b &'a mut T) -> &'b T { &**owned }
}

impl<'a, Sized? T> BorrowFromMut<&'a mut T> for T {
    fn borrow_from_mut<'b>(owned: &'b mut &'a mut T) -> &'b mut T { &mut **owned }
}

/// A generalization of Clone to borrowed data.
pub trait ToOwned<Owned> for Sized?: BorrowFrom<Owned> {
    /// Create owned data from borrowed data, usually by copying.
    fn to_owned(&self) -> Owned;
}

impl<T> ToOwned<T> for T where T: Clone {
    fn to_owned(&self) -> T { self.clone() }
}

/// A clone-on-write smart pointer.
pub enum Cow<'a, T, B: 'a> where B: ToOwned<T> {
    /// Borrowed data.
    Borrowed(&'a B),

    /// Owned data.
    Owned(T)
}

impl<'a, T, B> Cow<'a, T, B> where B: ToOwned<T> {
    /// Acquire a mutable reference to the owned form of the data.
    ///
    /// Copies the data if it is not already owned.
    pub fn to_mut(&mut self) -> &mut T {
        match *self {
            Borrowed(borrowed) => {
                *self = Owned(borrowed.to_owned());
                self.to_mut()
            }
            Owned(ref mut owned) => owned
        }
    }

    /// Extract the owned data.
    ///
    /// Copies the data if it is not already owned.
    pub fn into_owned(self) -> T {
        match self {
            Borrowed(borrowed) => borrowed.to_owned(),
            Owned(owned) => owned
        }
    }
}

impl<'a, T, B> Deref<B> for Cow<'a, T, B> where B: ToOwned<T>  {
    fn deref(&self) -> &B {
        match *self {
            Borrowed(borrowed) => borrowed,
            Owned(ref owned) => BorrowFrom::borrow_from(owned)
        }
    }
}
<|endoftext|>


<commit_before>#[doc = "A type representing either success or failure"];

import either::either;

#[doc = "The result type"]
enum result<T, U> {
    #[doc = "Contains the successful result value"]
    ok(T),
    #[doc = "Contains the error value"]
    err(U)
}

#[doc = "
Get the value out of a successful result

# Failure

If the result is an error
"]
pure fn get<T: copy, U>(res: result<T, U>) -> T {
    alt res {
      ok(t) { t }
      err(the_err) {
        // FIXME: have a run-fail test for this
        unchecked{ fail #fmt("get called on error result: %?", the_err); }
      }
    }
}

#[doc = "
Get the value out of an error result

# Failure

If the result is not an error
"]
pure fn get_err<T, U: copy>(res: result<T, U>) -> U {
    alt res {
      err(u) { u }
      ok(_) {
        fail "get_error called on ok result";
      }
    }
}

#[doc = "Returns true if the result is `ok`"]
pure fn success<T, U>(res: result<T, U>) -> bool {
    alt res {
      ok(_) { true }
      err(_) { false }
    }
}

#[doc = "Returns true if the result is `error`"]
pure fn failure<T, U>(res: result<T, U>) -> bool {
    !success(res)
}

#[doc = "
Convert to the `either` type

`ok` result variants are converted to `either::right` variants, `err`
result variants are converted to `either::left`.
"]
pure fn to_either<T: copy, U: copy>(res: result<U, T>) -> either<T, U> {
    alt res {
      ok(res) { either::right(res) }
      err(fail_) { either::left(fail_) }
    }
}

#[doc = "
Call a function based on a previous result

If `res` is `ok` then the value is extracted and passed to `op` whereupon
`op`s result is returned. if `res` is `err` then it is immediately returned.
This function can be used to compose the results of two functions.

Example:

    let res = chain(read_file(file)) { |buf|
        ok(parse_buf(buf))
    }
"]
fn chain<T, U: copy, V: copy>(res: result<T, V>, op: fn(T) -> result<U, V>)
    -> result<U, V> {
    alt res {
      ok(t) { op(t) }
      err(e) { err(e) }
    }
}

#[doc = "
Call a function based on a previous result

If `res` is `err` then the value is extracted and passed to `op`
whereupon `op`s result is returned. if `res` is `ok` then it is
immediately returned.  This function can be used to pass through a
successful result while handling an error.
"]
fn chain_err<T: copy, U: copy, V: copy>(
    res: result<T, V>,
    op: fn(V) -> result<T, U>)
    -> result<T, U> {
    alt res {
      ok(t) { ok(t) }
      err(v) { op(v) }
    }
}

impl extensions<T:copy, E:copy> for result<T,E> {
    fn chain<U:copy>(op: fn(T) -> result<U,E>) -> result<U,E> {
        chain(self, op)
    }

    fn chain_err<F:copy>(op: fn(E) -> result<T,F>) -> result<T,F> {
        chain_err(self, op)
    }
}

#[doc = "
Maps each element in the vector `ts` using the operation `op`.  Should an
error occur, no further mappings are performed and the error is returned.
Should no error occur, a vector containing the result of each map is
returned.

Here is an example which increments every integer in a vector,
checking for overflow:

    fn inc_conditionally(x: uint) -> result<uint,str> {
        if x == uint::max_value { ret err(\"overflow\"); }
        else { ret ok(x+1u); }
    }
    map([1u, 2u, 3u], inc_conditionally).chain {|incd|
        assert incd == [2u, 3u, 4u];
    }
"]
fn map<T,U:copy,V:copy>(ts: [T], op: fn(T) -> result<V,U>) -> result<[V],U> {
    let mut vs: [V] = [];
    vec::reserve(vs, vec::len(ts));
    for vec::each(ts) {|t|
        alt op(t) {
          ok(v) { vs += [v]; }
          err(u) { ret err(u); }
        }
    }
    ret ok(vs);
}

#[doc = "Same as map, but it operates over two parallel vectors.

A precondition is used here to ensure that the vectors are the same
length.  While we do not often use preconditions in the standard
library, a precondition is used here because result::t is generally
used in 'careful' code contexts where it is both appropriate and easy
to accommodate an error like the vectors being of different lengths."]
fn map2<S,T,U:copy,V:copy>(ss: [S], ts: [T], op: fn(S,T) -> result<V,U>)
    : vec::same_length(ss, ts) -> result<[V],U> {

    let n = vec::len(ts);
    let mut vs = [];
    vec::reserve(vs, n);
    let mut i = 0u;
    while i < n {
        alt op(ss[i],ts[i]) {
          ok(v) { vs += [v]; }
          err(u) { ret err(u); }
        }
        i += 1u;
    }
    ret ok(vs);
}

#[doc = "
Applies op to the pairwise elements from `ss` and `ts`, aborting on
error.  This could be implemented using `map2()` but it is more efficient
on its own as no result vector is built.
"]
fn iter2<S,T,U:copy>(ss: [S], ts: [T],
                     op: fn(S,T) -> result<(),U>)
    : vec::same_length(ss, ts)
    -> result<(),U> {

    let n = vec::len(ts);
    let mut i = 0u;
    while i < n {
        alt op(ss[i],ts[i]) {
          ok(()) { }
          err(u) { ret err(u); }
        }
        i += 1u;
    }
    ret ok(());
}

#[cfg(test)]
mod tests {
    fn op1() -> result::result<int, str> { result::ok(666) }

    fn op2(&&i: int) -> result::result<uint, str> {
        result::ok(i as uint + 1u)
    }

    fn op3() -> result::result<int, str> { result::err("sadface") }

    #[test]
    fn chain_success() {
        assert get(chain(op1(), op2)) == 667u;
    }

    #[test]
    fn chain_failure() {
        assert get_err(chain(op3(), op2)) == "sadface";
    }
}
<commit_msg>std: Flesh out result::extensions.<commit_after>#[doc = "A type representing either success or failure"];

import either::either;

#[doc = "The result type"]
enum result<T, U> {
    #[doc = "Contains the successful result value"]
    ok(T),
    #[doc = "Contains the error value"]
    err(U)
}

#[doc = "
Get the value out of a successful result

# Failure

If the result is an error
"]
pure fn get<T: copy, U>(res: result<T, U>) -> T {
    alt res {
      ok(t) { t }
      err(the_err) {
        // FIXME: have a run-fail test for this
        unchecked{ fail #fmt("get called on error result: %?", the_err); }
      }
    }
}

#[doc = "
Get the value out of an error result

# Failure

If the result is not an error
"]
pure fn get_err<T, U: copy>(res: result<T, U>) -> U {
    alt res {
      err(u) { u }
      ok(_) {
        fail "get_error called on ok result";
      }
    }
}

#[doc = "Returns true if the result is `ok`"]
pure fn success<T, U>(res: result<T, U>) -> bool {
    alt res {
      ok(_) { true }
      err(_) { false }
    }
}

#[doc = "Returns true if the result is `error`"]
pure fn failure<T, U>(res: result<T, U>) -> bool {
    !success(res)
}

#[doc = "
Convert to the `either` type

`ok` result variants are converted to `either::right` variants, `err`
result variants are converted to `either::left`.
"]
pure fn to_either<T: copy, U: copy>(res: result<U, T>) -> either<T, U> {
    alt res {
      ok(res) { either::right(res) }
      err(fail_) { either::left(fail_) }
    }
}

#[doc = "
Call a function based on a previous result

If `res` is `ok` then the value is extracted and passed to `op` whereupon
`op`s result is returned. if `res` is `err` then it is immediately returned.
This function can be used to compose the results of two functions.

Example:

    let res = chain(read_file(file)) { |buf|
        ok(parse_buf(buf))
    }
"]
fn chain<T, U: copy, V: copy>(res: result<T, V>, op: fn(T) -> result<U, V>)
    -> result<U, V> {
    alt res {
      ok(t) { op(t) }
      err(e) { err(e) }
    }
}

#[doc = "
Call a function based on a previous result

If `res` is `err` then the value is extracted and passed to `op`
whereupon `op`s result is returned. if `res` is `ok` then it is
immediately returned.  This function can be used to pass through a
successful result while handling an error.
"]
fn chain_err<T: copy, U: copy, V: copy>(
    res: result<T, V>,
    op: fn(V) -> result<T, U>)
    -> result<T, U> {
    alt res {
      ok(t) { ok(t) }
      err(v) { op(v) }
    }
}

impl extensions<T:copy, E:copy> for result<T,E> {
    fn get() -> T { get(self) }

    fn get_err() -> E { get_err(self) }

    fn success() -> bool { success(self) }

    fn failure() -> bool { failure(self) }

    fn chain<U:copy>(op: fn(T) -> result<U,E>) -> result<U,E> {
        chain(self, op)
    }

    fn chain_err<F:copy>(op: fn(E) -> result<T,F>) -> result<T,F> {
        chain_err(self, op)
    }
}

#[doc = "
Maps each element in the vector `ts` using the operation `op`.  Should an
error occur, no further mappings are performed and the error is returned.
Should no error occur, a vector containing the result of each map is
returned.

Here is an example which increments every integer in a vector,
checking for overflow:

    fn inc_conditionally(x: uint) -> result<uint,str> {
        if x == uint::max_value { ret err(\"overflow\"); }
        else { ret ok(x+1u); }
    }
    map([1u, 2u, 3u], inc_conditionally).chain {|incd|
        assert incd == [2u, 3u, 4u];
    }
"]
fn map<T,U:copy,V:copy>(ts: [T], op: fn(T) -> result<V,U>) -> result<[V],U> {
    let mut vs: [V] = [];
    vec::reserve(vs, vec::len(ts));
    for vec::each(ts) {|t|
        alt op(t) {
          ok(v) { vs += [v]; }
          err(u) { ret err(u); }
        }
    }
    ret ok(vs);
}

#[doc = "Same as map, but it operates over two parallel vectors.

A precondition is used here to ensure that the vectors are the same
length.  While we do not often use preconditions in the standard
library, a precondition is used here because result::t is generally
used in 'careful' code contexts where it is both appropriate and easy
to accommodate an error like the vectors being of different lengths."]
fn map2<S,T,U:copy,V:copy>(ss: [S], ts: [T], op: fn(S,T) -> result<V,U>)
    : vec::same_length(ss, ts) -> result<[V],U> {

    let n = vec::len(ts);
    let mut vs = [];
    vec::reserve(vs, n);
    let mut i = 0u;
    while i < n {
        alt op(ss[i],ts[i]) {
          ok(v) { vs += [v]; }
          err(u) { ret err(u); }
        }
        i += 1u;
    }
    ret ok(vs);
}

#[doc = "
Applies op to the pairwise elements from `ss` and `ts`, aborting on
error.  This could be implemented using `map2()` but it is more efficient
on its own as no result vector is built.
"]
fn iter2<S,T,U:copy>(ss: [S], ts: [T],
                     op: fn(S,T) -> result<(),U>)
    : vec::same_length(ss, ts)
    -> result<(),U> {

    let n = vec::len(ts);
    let mut i = 0u;
    while i < n {
        alt op(ss[i],ts[i]) {
          ok(()) { }
          err(u) { ret err(u); }
        }
        i += 1u;
    }
    ret ok(());
}

#[cfg(test)]
mod tests {
    fn op1() -> result::result<int, str> { result::ok(666) }

    fn op2(&&i: int) -> result::result<uint, str> {
        result::ok(i as uint + 1u)
    }

    fn op3() -> result::result<int, str> { result::err("sadface") }

    #[test]
    fn chain_success() {
        assert get(chain(op1(), op2)) == 667u;
    }

    #[test]
    fn chain_failure() {
        assert get_err(chain(op3(), op2)) == "sadface";
    }
}
<|endoftext|>


<commit_before>/*!
 * A key,value store that works on anything.
 *
 * This works using a binary search tree. In the first version, it's a
 * very naive algorithm, but it will probably be updated to be a
 * red-black tree or something else.
 */
#[forbid(deprecated_mode)];

use core::cmp::{Eq, Ord};
use core::option::{Some, None};
use Option = core::Option;

pub type TreeMap<K, V> = @mut TreeEdge<K, V>;

type TreeEdge<K, V> = Option<@TreeNode<K, V>>;

enum TreeNode<K, V> = {
    key: K,
    mut value: V,
    mut left: TreeEdge<K, V>,
    mut right: TreeEdge<K, V>
};

/// Create a treemap
pub fn TreeMap<K, V>() -> TreeMap<K, V> { @mut None }

/// Insert a value into the map
pub fn insert<K: Copy Eq Ord, V: Copy>(m: &mut TreeEdge<K, V>, k: K, v: V) {
    match copy *m {
      None => {
        *m = Some(@TreeNode({key: k,
                              mut value: v,
                              mut left: None,
                              mut right: None}));
        return;
      }
      Some(node) => {
        if k == node.key {
            node.value = v;
        } else if k < node.key {
            insert(&mut node.left, k, v);
        } else {
            insert(&mut node.right, k, v);
        }
      }
    };
}

/// Find a value based on the key
pub fn find<K: Copy Eq Ord, V: Copy>(m: &const TreeEdge<K, V>, k: K)
                              -> Option<V> {
    match copy *m {
      None => None,

      // FIXME (#2808): was that an optimization?
      Some(node) => {
        if k == node.key {
            Some(node.value)
        } else if k < node.key {
            find(&const node.left, k)
        } else {
            find(&const node.right, k)
        }
      }
    }
}

/// Visit all pairs in the map in order.
pub fn traverse<K, V: Copy>(m: &const TreeEdge<K, V>, f: fn((&K), (&V))) {
    match copy *m {
      None => (),
      Some(node) => {
        traverse(&const node.left, f);
        // copy of value is req'd as f() requires an immutable ptr
        f(&node.key, &copy node.value);
        traverse(&const node.right, f);
      }
    }
}

#[cfg(test)]
mod tests {
    #[legacy_exports];

    #[test]
    fn init_treemap() { let _m = TreeMap::<int, int>(); }

    #[test]
    fn insert_one() { let m = TreeMap(); insert(m, 1, 2); }

    #[test]
    fn insert_two() { let m = TreeMap(); insert(m, 1, 2); insert(m, 3, 4); }

    #[test]
    fn insert_find() {
        let m = TreeMap();
        insert(m, 1, 2);
        assert (find(m, 1) == Some(2));
    }

    #[test]
    fn find_empty() {
        let m = TreeMap::<int, int>(); assert (find(m, 1) == None);
    }

    #[test]
    fn find_not_found() {
        let m = TreeMap();
        insert(m, 1, 2);
        assert (find(m, 2) == None);
    }

    #[test]
    fn traverse_in_order() {
        let m = TreeMap();
        insert(m, 3, ());
        insert(m, 0, ());
        insert(m, 4, ());
        insert(m, 2, ());
        insert(m, 1, ());

        let n = @mut 0;
        fn t(n: @mut int, k: int, _v: ()) {
            assert (*n == k); *n += 1;
        }
        traverse(m, |x,y| t(n, *x, *y));
    }

    #[test]
    fn u8_map() {
        let m = TreeMap();

        let k1 = str::to_bytes(~"foo");
        let k2 = str::to_bytes(~"bar");

        insert(m, k1, ~"foo");
        insert(m, k2, ~"bar");

        assert (find(m, k2) == Some(~"bar"));
        assert (find(m, k1) == Some(~"foo"));
    }
}
<commit_msg>std::treemap - changing types to reflect constraints, adding equality check (space expensive)<commit_after>/*!
 * A key,value store that works on anything.
 *
 * This works using a binary search tree. In the first version, it's a
 * very naive algorithm, but it will probably be updated to be a
 * red-black tree or something else.
 */
#[forbid(deprecated_mode)];

use core::cmp::{Eq, Ord};
use core::option::{Some, None};
use Option = core::Option;

pub type TreeMap<K: Copy Eq Ord, V: Copy> = @mut TreeEdge<K, V>;

type TreeEdge<K: Copy Eq Ord, V: Copy> = Option<@TreeNode<K, V>>;

struct TreeNode<K: Copy Eq Ord, V: Copy> {
    key: K,
    mut value: V,
    mut left: TreeEdge<K, V>,
    mut right: TreeEdge<K, V>
}

/// Create a treemap
pub fn TreeMap<K: Copy Eq Ord, V: Copy>() -> TreeMap<K, V> { @mut None }

/// Insert a value into the map
pub fn insert<K: Copy Eq Ord, V: Copy>(m: &mut TreeEdge<K, V>, k: K, v: V) {
    match copy *m {
      None => {
        *m = Some(@TreeNode {key: k,
                             mut value: v,
                             mut left: None,
                             mut right: None});
        return;
      }
      Some(node) => {
        if k == node.key {
            node.value = v;
        } else if k < node.key {
            insert(&mut node.left, k, v);
        } else {
            insert(&mut node.right, k, v);
        }
      }
    };
}

/// Find a value based on the key
pub fn find<K: Copy Eq Ord, V: Copy>(m: &const TreeEdge<K, V>, k: K)
                              -> Option<V> {
    match copy *m {
      None => None,

      // FIXME (#2808): was that an optimization?
      Some(node) => {
        if k == node.key {
            Some(node.value)
        } else if k < node.key {
            find(&const node.left, k)
        } else {
            find(&const node.right, k)
        }
      }
    }
}

/// Visit all pairs in the map in order.
pub fn traverse<K: Copy Eq Ord, V: Copy>(m: &const TreeEdge<K, V>,
                                         f: fn((&K), (&V))) {
    match copy *m {
      None => (),
      Some(node) => {
        traverse(&const node.left, f);
        // copy of value is req'd as f() requires an immutable ptr
        f(&node.key, &copy node.value);
        traverse(&const node.right, f);
      }
    }
}

/// Compare two treemaps and return true iff
/// they contain same keys and values
pub fn equals<K: Copy Eq Ord, V: Copy Eq>(t1: &const TreeEdge<K, V>,
                                          t2: &const TreeEdge<K, V>)
                                        -> bool {
    let mut v1 = ~[];
    let mut v2 = ~[];
    traverse(t1, |k,v| { v1.push((copy *k, copy *v)) });
    traverse(t2, |k,v| { v2.push((copy *k, copy *v)) });
    return v1 == v2;
}

#[cfg(test)]
mod tests {
    #[legacy_exports];

    #[test]
    fn init_treemap() { let _m = TreeMap::<int, int>(); }

    #[test]
    fn insert_one() { let m = TreeMap(); insert(m, 1, 2); }

    #[test]
    fn insert_two() { let m = TreeMap(); insert(m, 1, 2); insert(m, 3, 4); }

    #[test]
    fn insert_find() {
        let m = TreeMap();
        insert(m, 1, 2);
        assert (find(m, 1) == Some(2));
    }

    #[test]
    fn find_empty() {
        let m = TreeMap::<int, int>(); assert (find(m, 1) == None);
    }

    #[test]
    fn find_not_found() {
        let m = TreeMap();
        insert(m, 1, 2);
        assert (find(m, 2) == None);
    }

    #[test]
    fn traverse_in_order() {
        let m = TreeMap();
        insert(m, 3, ());
        insert(m, 0, ());
        insert(m, 4, ());
        insert(m, 2, ());
        insert(m, 1, ());

        let n = @mut 0;
        fn t(n: @mut int, k: int, _v: ()) {
            assert (*n == k); *n += 1;
        }
        traverse(m, |x,y| t(n, *x, *y));
    }

    #[test]
    fn equality() {
        let m1 = TreeMap();
        insert(m1, 3, ());
        insert(m1, 0, ());
        insert(m1, 4, ());
        insert(m1, 2, ());
        insert(m1, 1, ());
        let m2 = TreeMap();
        insert(m2, 2, ());
        insert(m2, 1, ());
        insert(m2, 3, ());
        insert(m2, 0, ());
        insert(m2, 4, ());

        assert equals(m1, m2);

        let m3 = TreeMap();
        assert !equals(m1,m3);

    }

    #[test]
    fn u8_map() {
        let m = TreeMap();

        let k1 = str::to_bytes(~"foo");
        let k2 = str::to_bytes(~"bar");

        insert(m, k1, ~"foo");
        insert(m, k2, ~"bar");

        assert (find(m, k2) == Some(~"bar"));
        assert (find(m, k1) == Some(~"foo"));
    }
}
<|endoftext|>


<commit_before>extern crate http;
extern crate floor;

use floor::{ Floor, Request };
use http::server::{ ResponseWriter };

fn main() {

    let mut server = Floor::new();

    // we would love to use a closure for the handler but it seems to be hard
    // to achieve with the current version of rust.

    fn user_handler (request: Request, response: &mut ResponseWriter) {

        let text = String::new()
                    .append("This is user: ")
                    .append(request.params.get(&"userid".to_string()).as_slice());

        response.write(text.as_bytes());
    };

    fn bar_handler (request: Request, response: &mut ResponseWriter) {
        response.write("This is the /bar handler".as_bytes());
    };

    fn simple_wildcard (request: Request, response: &mut ResponseWriter) {
        response.write("This matches /some/crazy/route but not /some/super/crazy/route".as_bytes());
    };

    fn double_wildcard (request: Request, response: &mut ResponseWriter) {
        response.write("This matches /a/crazy/route and also /a/super/crazy/route".as_bytes());
    };

    // go to http://localhost:6767/user/4711 to see this route in action
    server.get("/user/:userid", user_handler);

    // go to http://localhost:6767/bar to see this route in action
    server.get("/bar", bar_handler);

    // go to http://localhost:6767/some/crazy/route to see this route in action
    server.get("/some/*/route", simple_wildcard);

    // go to http://localhost:6767/some/nice/route or http://localhost:6767/some/super/nice/route to see this route in action
    server.get("/a/**/route", double_wildcard);

    server.listen(6767);
}<commit_msg>Update example.rs<commit_after>extern crate http;
extern crate floor;

use floor::{ Floor, Request };
use http::server::{ ResponseWriter };

fn main() {

    let mut server = Floor::new();

    // we would love to use a closure for the handler but it seems to be hard
    // to achieve with the current version of rust.

    fn user_handler (request: Request, response: &mut ResponseWriter) {

        let text = String::new()
                    .append("This is user: ")
                    .append(request.params.get(&"userid".to_string()).as_slice());

        response.write(text.as_bytes());
    };

    fn bar_handler (request: Request, response: &mut ResponseWriter) {
        response.write("This is the /bar handler".as_bytes());
    };

    fn simple_wildcard (request: Request, response: &mut ResponseWriter) {
        response.write("This matches /some/crazy/route but not /some/super/crazy/route".as_bytes());
    };

    fn double_wildcard (request: Request, response: &mut ResponseWriter) {
        response.write("This matches /a/crazy/route and also /a/super/crazy/route".as_bytes());
    };

    // go to http://localhost:6767/user/4711 to see this route in action
    server.get("/user/:userid", user_handler);

    // go to http://localhost:6767/bar to see this route in action
    server.get("/bar", bar_handler);

    // go to http://localhost:6767/some/crazy/route to see this route in action
    server.get("/some/*/route", simple_wildcard);

    // go to http://localhost:6767/a/nice/route or http://localhost:6767/a/super/nice/route to see this route in action
    server.get("/a/**/route", double_wildcard);

    server.listen(6767);
}
<|endoftext|>


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


<commit_before><commit_msg>Added a subdirectory with a file to test whether tidy command ignores files in subdirectories<commit_after><|endoftext|>


<commit_before><commit_msg>Add problem #67<commit_after>use common::problem::{ Problem };

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

fn solve() -> ~str {
    let result = io::file_reader(&Path("files/triangle.txt")).map(|file| {
        let mut triangle = ~[];
        for file.each_line |line| {
            let mut nums = ~[];
            for str::each_word(line) |word| {
                nums.push(uint::from_str(word).get())
            }
            triangle.push(nums);
        }
        triangle
    }).map(|triangle| {
        let init = triangle.init();
        let last = triangle.last();
        (do init.foldr(vec::from_slice(*last)) |elm, prev| {
            do vec::from_fn(elm.len()) |i| {
                elm[i] + uint::max(prev[i], prev[i + 1])
            }
        })[0]
    });

    match result {
        Err(msg) => fail!(msg),
        Ok(value) => return value.to_str()
    }
}

<|endoftext|>


<commit_before><commit_msg>rust variable binding<commit_after>fn main() {
    let an_integer = 1u32;
    // because name starts with "_", no warning that variable is unused
    let _unused_variable = an_integer;

    let mut mutable = 1;
    mutable += 1;
    println!("{}", mutable);

    let a_binding;
    {
        let x = 2;
        a_binding = x * x;
    }
    println!("a binding: {}", a_binding);

    let another_binding: i32;
    // error: use of possibly uninitialized variable: `another_binding` [E0381]
    // println!("another binding: {}", another_binding);
}
<|endoftext|>


<commit_before><commit_msg>[katas] new problem solved<commit_after>// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
//   pub val: i32,
//   pub left: Option<Rc<RefCell<TreeNode>>>,
//   pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
//   #[inline]
//   pub fn new(val: i32) -> Self {
//     TreeNode {
//       val,
//       left: None,
//       right: None
//     }
//   }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
    pub fn invert_tree(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
        if (root.is_none()) { return None; } // if root is empty ([])

        let unwrapped = root.unwrap();
        let node = unwrapped.borrow();

        Some(Rc::new(RefCell::new(TreeNode {
            val: node.val,
            left: node.right.as_ref().and_then(|right_root| Self::invert_tree(Some(right_root.clone()))),
            right: node.left.as_ref().and_then(|left_root| Self::invert_tree(Some(left_root.clone())))
        })))
    }
}
<|endoftext|>


<commit_before><commit_msg>test: add a basic test for the vectorcall calling convention<commit_after>// Copyright 2016 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.

#![feature(abi_vectorcall)]

trait A {
    extern "vectorcall" fn test1(i: i32);
}

struct S;

impl A for S {
    extern "vectorcall" fn test1(i: i32) {
        assert_eq!(i, 1);
    }
}

extern "vectorcall" fn test2(i: i32) {
    assert_eq!(i, 2);
}

fn main() {
    <S as A>::test1(1);
    test2(2);
}
<|endoftext|>


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

#![feature(slicing_syntax, box_syntax)]
#![feature(collections)]
#![feature(core)]
#![feature(io)]
#![feature(os)]
#![feature(path)]
#![feature(rustdoc)]

extern crate rustdoc;

use std::os;
use subcommand::Subcommand;
use term::Term;

macro_rules! try (
    ($expr:expr) => ({
        use error;
        match $expr {
            Ok(val) => val,
            Err(err) => return Err(error::FromError::from_err(err))
        }
    })
);

mod term;
mod error;
mod book;

mod subcommand;
mod help;
mod build;
mod serve;
mod test;

mod css;
mod javascript;

#[cfg(not(test))] // thanks #12327
fn main() {
    let mut term = Term::new();
    let cmd = os::args();

    if cmd.len() < 1 {
        help::usage()
    } else {
        match subcommand::parse_name(&cmd[1][]) {
            Some(mut subcmd) => {
                match subcmd.parse_args(cmd.tail()) {
                    Ok(_) => {
                        match subcmd.execute(&mut term) {
                            Ok(_) => (),
                            Err(err) => {
                                term.err(&format!("error: {}", err.description())[]);
                                err.detail().map(|detail| {
                                    term.err(&format!("detail: {}", detail)[]);
                                });
                            }
                        }
                    }
                    Err(err) => {
                        println!("{}", err.description());
                        println!("");
                        subcmd.usage();
                    }
                }
            }
            None => {
                println!("Unrecognized command '{}'.", cmd[1]);
                println!("");
                help::usage();
            }
        }
    }
}
<commit_msg>Don't panic if there's no command line arguments<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![feature(slicing_syntax, box_syntax)]
#![feature(collections)]
#![feature(core)]
#![feature(io)]
#![feature(os)]
#![feature(path)]
#![feature(rustdoc)]

extern crate rustdoc;

use std::os;
use subcommand::Subcommand;
use term::Term;

macro_rules! try (
    ($expr:expr) => ({
        use error;
        match $expr {
            Ok(val) => val,
            Err(err) => return Err(error::FromError::from_err(err))
        }
    })
);

mod term;
mod error;
mod book;

mod subcommand;
mod help;
mod build;
mod serve;
mod test;

mod css;
mod javascript;

#[cfg(not(test))] // thanks #12327
fn main() {
    let mut term = Term::new();
    let cmd = os::args();

    if cmd.len() <= 1 {
        help::usage()
    } else {
        match subcommand::parse_name(&cmd[1][]) {
            Some(mut subcmd) => {
                match subcmd.parse_args(cmd.tail()) {
                    Ok(_) => {
                        match subcmd.execute(&mut term) {
                            Ok(_) => (),
                            Err(err) => {
                                term.err(&format!("error: {}", err.description())[]);
                                err.detail().map(|detail| {
                                    term.err(&format!("detail: {}", detail)[]);
                                });
                            }
                        }
                    }
                    Err(err) => {
                        println!("{}", err.description());
                        println!("");
                        subcmd.usage();
                    }
                }
            }
            None => {
                println!("Unrecognized command '{}'.", cmd[1]);
                println!("");
                help::usage();
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>My bad, forgot to track file<commit_after>use mapgen::*;
use core::{Vec2, Block};

/// A chunk grid, i.e. a grid of chunk size cotaining Block
type ChunkGrid = [[&Block; CHUNK_SIZE]; CHUNK_SIZE];
/// A cache of the relevant chunks
///
/// The ordering of the chunks are as follows.
/// 1---2
/// |   |
/// 3---4
struct cache {
  /// The offset of the cache, i.e. the place where you find chunk1
  offset: Vec2<i64>,
  chunk1: ChunkGrid,
  chunk2: ChunkGrid,
  chunk3: ChunkGrid,
  chunk4: ChunkGrid,
}
// NOTE: When moving chunks around remember to use mem::replace

impl cache {
  fn update(&mut self, new_offset: Vec2<i64>, mapgen: T)
            where T: TileMap {
    // TODO: Optimize this by using parts of the old cache which just should be
    //       moved.
    for (y, &mut row) in chunk1.into_iter().enumerate() {
      for (x, &mut block_ptr) in chunk1.into_iter().enumerate() {
        *block_ptr = &mapgen.get_tile(new_offset);
      }
    }
    for (y, &mut row) in chunk2.into_iter().enumerate() {
      for (x, &mut block_ptr) in chunk2.into_iter().enumerate() {
        *block_ptr = &mapgen.get_tile(new_offset
                                      + Vec2(CHUNK_SIZE, 0));
      }
    }
    for (y, &mut row) in chunk3.into_iter().enumerate() {
      for (x, &mut block_ptr) in chunk3.into_iter().enumerate() {
        *block_ptr = &mapgen.get_tile(new_offset
                                      + Vec2(0, CHUNK_SIZE));
      }
    }
    for (y, &mut row) in chunk4.into_iter().enumerate() {
      for (x, &mut block_ptr) in chunk4.into_iter().enumerate() {
        *block_ptr = &mapgen.get_tile(new_offset
                                      + Vec2(CHUNK_SIZE, CHUNK_SIZE));
      }
    }
    self.offset = new_offset;
  }

  fn get_block(&self) -> Block {
    unimplemented!();
  }
}
<|endoftext|>


<commit_before><commit_msg>Fix previously ignored test<commit_after><|endoftext|>


<commit_before><commit_msg>add build.rs script<commit_after>// build.rs
extern crate libc;

use std::io::Command;
use std::io::process::StdioContainer;
use libc::consts::os::posix88::STDERR_FILENO;

fn main() {
    // note that there are a number of downsides to this approach, the comments
    // below detail how to improve the portability of these commands.
    Command::new("/usr/bin/env")
        .args(&["mkbindings.py", "--prefix", "./src", "bindings.json", "build"])
        .stdout(StdioContainer::InheritFd(STDERR_FILENO))
        .status().unwrap();
}
<|endoftext|>


<commit_before><commit_msg>Add test for issue 74083<commit_after>use std::ops::Deref;

pub struct Foo;

impl Foo {
    pub fn foo(&mut self) {}
}

// @has issue_74083/struct.Bar.html
// !@has - '//div[@class="sidebar-links"]/a[@href="#method.foo"]' 'foo'
pub struct Bar {
    foo: Foo,
}

impl Deref for Bar {
    type Target = Foo;

    fn deref(&self) -> &Foo {
        &self.foo
    }
}
<|endoftext|>