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

// ignore-android: FIXME(#10381)

// compile-flags:-g1

// Make sure functions have proper names
// debugger:info functions
// check:static void limited-debuginfo::main();
// check:static void limited-debuginfo::some_function();
// check:static void limited-debuginfo::some_other_function();
// check:static void limited-debuginfo::zzz();

// debugger:rbreak zzz
// debugger:run

// Make sure there is no information about locals
// debugger:finish
// debugger:info locals
// check:No locals.
// debugger:continue

#[allow(unused_variable)];

struct Struct {
    a: i64,
    b: i32
}

fn main() {
    some_function(101, 202);
}

fn zzz() {()}

fn some_function(a: int, b: int) {
    let some_variable = Struct { a: 11, b: 22 };
    let some_other_variable = 23;
    zzz();
}

fn some_other_function(a: int, b: int) -> bool { true }<commit_msg>auto merge of #12839 : alexcrichton/rust/fix-snap, r=huonw<commit_after>// Copyright 2013-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.

// ignore-android: FIXME(#10381)

// compile-flags:-g1

// Make sure functions have proper names
// debugger:info functions
// check:static void [...]main();
// check:static void [...]some_function();
// check:static void [...]some_other_function();
// check:static void [...]zzz();

// debugger:rbreak zzz
// debugger:run

// Make sure there is no information about locals
// debugger:finish
// debugger:info locals
// check:No locals.
// debugger:continue

#[allow(unused_variable)];

struct Struct {
    a: i64,
    b: i32
}

fn main() {
    some_function(101, 202);
}

fn zzz() {()}

fn some_function(a: int, b: int) {
    let some_variable = Struct { a: 11, b: 22 };
    let some_other_variable = 23;
    zzz();
}

fn some_other_function(a: int, b: int) -> bool { true }
<|endoftext|>


<commit_before><commit_msg>Introduce a testcase for conditional compilation via attributes<commit_after>// xfail-stage0
// xfail-stage1
// xfail-stage2

// Since the bogus configuration isn't defined main will just be
// parsed, but nothing further will be done with it
#[cfg(bogus)]
fn main() { fail }

fn main() {}<|endoftext|>


<commit_before><commit_msg>Added "nested_clipping" example<commit_after>extern crate graphics;
extern crate gfx_graphics;
extern crate piston;
extern crate glutin_window;
extern crate gfx;
extern crate gfx_device_gl;

use glutin_window::{GlutinWindow, OpenGL};
use gfx::traits::*;
use gfx::memory::Typed;
use gfx::format::{DepthStencil, Formatted, Srgba8};
use piston::window::{OpenGLWindow, Window, WindowSettings};
use piston::input::{AfterRenderEvent, RenderEvent, PressEvent};
use piston::event_loop::{Events, EventSettings, EventLoop};
use gfx_graphics::Gfx2d;
use graphics::draw_state::*;

fn main() {
    let opengl = OpenGL::V3_2;
    let (w, h) = (640, 480);
    let samples = 4;
    let mut window: GlutinWindow = WindowSettings::new("gfx_graphics: nested_clipping", [w, h])
        .exit_on_esc(true)
        .graphics_api(opengl)
        .samples(samples)
        .build()
        .unwrap();

    let (mut device, mut factory) = gfx_device_gl::create(|s|
        window.get_proc_address(s) as *const std::os::raw::c_void);

    // Create the main color/depth targets.
    let draw_size = window.draw_size();
    let aa = samples as gfx::texture::NumSamples;
    let dim = (draw_size.width as u16, draw_size.height as u16, 1, aa.into());
    let color_format = <Srgba8 as Formatted>::get_format();
    let depth_format = <DepthStencil as Formatted>::get_format();
    let (output_color, output_stencil) =
        gfx_device_gl::create_main_targets_raw(dim,
                                               color_format.0,
                                               depth_format.0);
    let output_color = Typed::new(output_color);
    let output_stencil = Typed::new(output_stencil);

    let mut encoder = factory.create_command_buffer().into();
    let mut g2d = Gfx2d::new(opengl, &mut factory);
    let mut events = Events::new(EventSettings::new().lazy(true));

    let increment = DrawState::new_increment();
    let inside_level1 = DrawState {
        blend: Some(Blend::Alpha),
        stencil: Some(Stencil::Inside(1)),
        scissor: None,
    };
    let inside_level2 = DrawState {
        blend: Some(Blend::Alpha),
        stencil: Some(Stencil::Inside(2)),
        scissor: None,
    };
    let inside_level3 = DrawState {
        blend: Some(Blend::Alpha),
        stencil: Some(Stencil::Inside(3)),
        scissor: None,
    };
    let mut clip = true;
    while let Some(e) = events.next(&mut window) {
        if let Some(args) = e.render_args() {
            use graphics::*;

            g2d.draw(&mut encoder, &output_color, &output_stencil, args.viewport(), |c, g| {
                clear([0.8, 0.8, 0.8, 1.0], g);

                if clip {
                    Rectangle::new([1.0; 4])
                        .draw([10.0, 10.0, 200.0, 200.0],
                        &increment, c.transform, g);
                    Rectangle::new([1.0, 0.0, 0.0, 1.0])
                        .draw([10.0, 10.0, 200.0, 200.0],
                        &inside_level1, c.transform, g);

                    Rectangle::new([1.0; 4])
                        .draw([100.0, 100.0, 200.0, 200.0],
                        &increment, c.transform, g);
                    Rectangle::new([0.0, 0.0, 1.0, 1.0])
                        .draw([100.0, 100.0, 200.0, 200.0],
                        &inside_level2, c.transform, g);

                    Rectangle::new([1.0; 4])
                        .draw([100.0, 100.0, 200.0, 200.0],
                        &increment, c.transform, g);
                    Rectangle::new([0.0, 1.0, 0.0, 1.0])
                        .draw([50.0, 50.0, 200.0, 100.0],
                        &inside_level3, c.transform, g);
                } else {
                    Rectangle::new([1.0, 0.0, 0.0, 1.0])
                        .draw([10.0, 10.0, 200.0, 200.0],
                        &c.draw_state, c.transform, g);

                    Rectangle::new([0.0, 0.0, 1.0, 1.0])
                        .draw([100.0, 100.0, 200.0, 200.0],
                        &c.draw_state, c.transform, g);

                    Rectangle::new([0.0, 1.0, 0.0, 1.0])
                        .draw([50.0, 50.0, 200.0, 100.0],
                        &c.draw_state, c.transform, g);
                }
            });

            encoder.flush(&mut device);
        }
        if let Some(_) = e.after_render_args() {
            device.cleanup();
        }
        if e.press_args().is_some() {
            clip = !clip;
        }
    }
}
<|endoftext|>


<commit_before>use libc::{c_void, c_int, c_char};
use core::result::{Result, Err, Ok};

pub enum SurfaceFlag {
    SWSurface = 0x00000000,
    HWSurface = 0x00000001,
    AsyncBlit = 0x00000004,
}

pub enum VideoModeFlag {
    AnyFormat = 0x10000000,
    HWPalette = 0x20000000,
    DoubleBuf = 0x40000000,
    Fullscreen = 0x80000000,
    OpenGL = 0x00000002,
    OpenGLBlit = 0x0000000A,
    Resizable  = 0x00000010,
    NoFrame = 0x00000020,
}

pub struct Surface {

    priv raw_surface: *ll::video::SDL_Surface,

    drop {
        ll::video::SDL_FreeSurface(self.raw_surface)
    }
}

impl Surface {

    fn display_format() -> Result<~Surface, ~str> {
        let raw_surface = ll::video::SDL_DisplayFormat(self.raw_surface);
        if raw_surface == ptr::null() {
            Err(sdl::get_error())
        } else {
            Ok(~Surface{ raw_surface: raw_surface })
        }
    }

    fn flip() -> bool {
        ll::video::SDL_Flip(self.raw_surface) == 0 as c_int
    }

    fn lock() -> bool {
        return ll::video::SDL_LockSurface(self.raw_surface) == 0 as c_int;
    }

    fn unlock() -> bool {
        return ll::video::SDL_UnlockSurface(self.raw_surface) == 0 as c_int;
    }

    fn blit_surface_rect(src: &Surface, srcrect: &util::Rect, dstrect: &util::Rect) -> bool {
        let res = ll::video::SDL_UpperBlit(src.raw_surface, srcrect, self.raw_surface, dstrect);
        return res == 0 as c_int;
    }

    fn blit_surface(src: &Surface) -> bool {
        let res = ll::video::SDL_UpperBlit(src.raw_surface, ptr::null(), self.raw_surface, ptr::null());
        return res == 0 as c_int;
    }

    fn fill_rect(rect: &util::Rect, color: u32) -> bool {
        return ll::video::SDL_FillRect(self.raw_surface, rect, color) == 0 as c_int;
    }

    fn fill(color: u32) -> bool {
        return ll::video::SDL_FillRect(self.raw_surface, ptr::null(), color) == 0 as c_int;
    }
}

//FIXME: This needs to be called multiple times on window resize, so Drop is going to do bad things, possibly. Test it out.
//Consider making videomode surfaces their own type, with a reset method?
pub fn set_video_mode(
    width: int,
    height: int,
    bitsperpixel: int,
    surface_flags: &[SurfaceFlag],
    video_mode_flags: &[VideoModeFlag]) -> Result<~Surface, ~str> {
    let flags = vec::foldl(0u32, surface_flags, |flags, flag| {
        flags | *flag as u32
    });
    let flags = vec::foldl(flags, video_mode_flags, |flags, flag| {
        flags | *flag as u32
    });

    let raw_surface = ll::video::SDL_SetVideoMode(width as c_int, height as c_int, bitsperpixel as c_int, flags);

    if raw_surface == ptr::null() {
        Err(sdl::get_error())
    } else {
        Ok(~Surface{ raw_surface: raw_surface })
    }
}

pub fn load_bmp(file: &str) -> Result<~Surface, ~str> unsafe {
    str::as_buf(file, |buf, _len| {
        let buf = cast::reinterpret_cast(&buf);
        str::as_buf(~"rb", |rbbuf, _len| {
            let rbbuf = cast::reinterpret_cast(&rbbuf);
            let raw_surface = ll::video::SDL_LoadBMP_RW(ll::video::SDL_RWFromFile(buf, rbbuf), 1 as c_int);
            if raw_surface == ptr::null() {
                Err(sdl::get_error())
            } else {
                Ok(~Surface{ raw_surface: raw_surface })
            }
        })
    })
}

pub fn create_rgb_surface(
    surface_flags: &[SurfaceFlag],
    width: int, height: int, bits_per_pixel: int,
    rmask: u32, gmask: u32, bmask: u32, amask: u32) -> Result<~Surface, ~str> {

    let flags = vec::foldl(0u32, surface_flags, |flags, flag| {
        flags | *flag as u32
    });

    let raw_surface = ll::video::SDL_CreateRGBSurface(
        flags, width as c_int, height as c_int, bits_per_pixel as c_int,
        rmask, gmask, bmask, amask);
    if raw_surface == ptr::null() {
        Err(sdl::get_error())
    } else {
        Ok(~Surface{ raw_surface: raw_surface })
    }
}
<commit_msg>Switched the Surface's Drop code to use the new Trait<commit_after>use libc::{c_void, c_int, c_char};
use core::result::{Result, Err, Ok};

pub enum SurfaceFlag {
    SWSurface = 0x00000000,
    HWSurface = 0x00000001,
    AsyncBlit = 0x00000004,
}

pub enum VideoModeFlag {
    AnyFormat = 0x10000000,
    HWPalette = 0x20000000,
    DoubleBuf = 0x40000000,
    Fullscreen = 0x80000000,
    OpenGL = 0x00000002,
    OpenGLBlit = 0x0000000A,
    Resizable  = 0x00000010,
    NoFrame = 0x00000020,
}

pub struct Surface {
    priv raw_surface: *ll::video::SDL_Surface,
}

impl Surface {

    fn display_format() -> Result<~Surface, ~str> {
        let raw_surface = ll::video::SDL_DisplayFormat(self.raw_surface);
        if raw_surface == ptr::null() {
            Err(sdl::get_error())
        } else {
            Ok(~Surface{ raw_surface: raw_surface })
        }
    }

    fn flip() -> bool {
        ll::video::SDL_Flip(self.raw_surface) == 0 as c_int
    }

    fn lock() -> bool {
        return ll::video::SDL_LockSurface(self.raw_surface) == 0 as c_int;
    }

    fn unlock() -> bool {
        return ll::video::SDL_UnlockSurface(self.raw_surface) == 0 as c_int;
    }

    fn blit_surface_rect(src: &Surface, srcrect: &util::Rect, dstrect: &util::Rect) -> bool {
        let res = ll::video::SDL_UpperBlit(src.raw_surface, srcrect, self.raw_surface, dstrect);
        return res == 0 as c_int;
    }

    fn blit_surface(src: &Surface) -> bool {
        let res = ll::video::SDL_UpperBlit(src.raw_surface, ptr::null(), self.raw_surface, ptr::null());
        return res == 0 as c_int;
    }

    fn fill_rect(rect: &util::Rect, color: u32) -> bool {
        return ll::video::SDL_FillRect(self.raw_surface, rect, color) == 0 as c_int;
    }

    fn fill(color: u32) -> bool {
        return ll::video::SDL_FillRect(self.raw_surface, ptr::null(), color) == 0 as c_int;
    }
}

impl Surface : Drop {

    fn finalize(&self) {
        ll::video::SDL_FreeSurface(self.raw_surface)
    }
}

//FIXME: This needs to be called multiple times on window resize, so Drop is going to do bad things, possibly. Test it out.
//Consider making videomode surfaces their own type, with a reset method?
pub fn set_video_mode(
    width: int,
    height: int,
    bitsperpixel: int,
    surface_flags: &[SurfaceFlag],
    video_mode_flags: &[VideoModeFlag]) -> Result<~Surface, ~str> {
    let flags = vec::foldl(0u32, surface_flags, |flags, flag| {
        flags | *flag as u32
    });
    let flags = vec::foldl(flags, video_mode_flags, |flags, flag| {
        flags | *flag as u32
    });

    let raw_surface = ll::video::SDL_SetVideoMode(width as c_int, height as c_int, bitsperpixel as c_int, flags);

    if raw_surface == ptr::null() {
        Err(sdl::get_error())
    } else {
        Ok(~Surface{ raw_surface: raw_surface })
    }
}

pub fn load_bmp(file: &str) -> Result<~Surface, ~str> unsafe {
    str::as_buf(file, |buf, _len| {
        let buf = cast::reinterpret_cast(&buf);
        str::as_buf(~"rb", |rbbuf, _len| {
            let rbbuf = cast::reinterpret_cast(&rbbuf);
            let raw_surface = ll::video::SDL_LoadBMP_RW(ll::video::SDL_RWFromFile(buf, rbbuf), 1 as c_int);
            if raw_surface == ptr::null() {
                Err(sdl::get_error())
            } else {
                Ok(~Surface{ raw_surface: raw_surface })
            }
        })
    })
}

pub fn create_rgb_surface(
    surface_flags: &[SurfaceFlag],
    width: int, height: int, bits_per_pixel: int,
    rmask: u32, gmask: u32, bmask: u32, amask: u32) -> Result<~Surface, ~str> {

    let flags = vec::foldl(0u32, surface_flags, |flags, flag| {
        flags | *flag as u32
    });

    let raw_surface = ll::video::SDL_CreateRGBSurface(
        flags, width as c_int, height as c_int, bits_per_pixel as c_int,
        rmask, gmask, bmask, amask);
    if raw_surface == ptr::null() {
        Err(sdl::get_error())
    } else {
        Ok(~Surface{ raw_surface: raw_surface })
    }
}
<|endoftext|>


<commit_before><commit_msg>Add tests for calling methods on self<commit_after>#[macro_use]
extern crate askama;

use askama::Template;

#[derive(Template)]
#[template(source = "{{ self.get_s() }}", ext = "txt")]
struct MethodTemplate<'a> {
    s: &'a str,
}

impl<'a> MethodTemplate<'a> {
    fn get_s(&self) -> &str {
        self.s
    }
}

#[derive(Template)]
#[template(source = "{{ self.get_s() }} {{ t.get_s() }}", ext = "txt")]
struct NestedMethodTemplate<'a> {
    t: MethodTemplate<'a>,
}

impl<'a> NestedMethodTemplate<'a> {
    fn get_s(&self) -> &str {
        "bar"
    }
}

#[test]
fn test_method() {
    let t = MethodTemplate { s: "foo" };
    assert_eq!(t.render().unwrap(), "foo");
}

#[test]
fn test_nested() {
    let t = NestedMethodTemplate {
        t: MethodTemplate { s: "foo" },
    };
    assert_eq!(t.render().unwrap(), "bar foo");
}
<|endoftext|>


<commit_before><commit_msg>Added a rotation test example for testing rotation speeds<commit_after>extern crate turtle;

use turtle::Turtle;

/// This program demonstrates rotations at multiple speeds
fn main() {
    let mut turtle = Turtle::new();

    turtle.pen_up();
    turtle.set_speed("fastest");
    turtle.left(90.0);
    turtle.forward(300.0);
    turtle.right(180.0);
    turtle.pen_down();

    for i in 1..12 {
        turtle.set_speed(i);
        turtle.right(2.0 * 360.0);

        turtle.pen_up();
        turtle.set_speed("fastest");
        turtle.forward(60.0);
        turtle.pen_down();
    }

    turtle.hide();
    turtle.pen_up();
    turtle.set_speed("fastest");
    turtle.backward(660.0);
    turtle.pen_down();

    for i in 1..12 {
        turtle.set_speed(i);
        circle(&mut turtle);

        turtle.pen_up();
        turtle.set_speed("fastest");
        turtle.forward(60.0);
        turtle.pen_down();
    }
}

fn circle(turtle: &mut Turtle) {
    for _ in 0..180 {
        turtle.forward(1.0);
        turtle.left(2.0);
    }
}
<|endoftext|>


<commit_before><commit_msg>Add a regression test for #47131<commit_after>// run-pass

#![deny(dead_code)]

pub struct GenericFoo<T>(T);

type Foo = GenericFoo<u32>;

impl Foo {
    fn bar(self) -> u8 {
        0
    }
}

fn main() {
    println!("{}", GenericFoo(0).bar());
}
<|endoftext|>


<commit_before><commit_msg>Fix: 'imag-contact show' should increase output counter<commit_after><|endoftext|>


<commit_before>use std::io::fs;
use std::io;
use std::os;

use colours::{Plain, Style, Black, Red, Green, Yellow, Blue, Purple, Cyan};
mod colours;

fn main() {
    match os::args().as_slice() {
        [] => unreachable!(),
        [_] => { list(Path::new(".")) },
        [_, ref p] => { list(Path::new(p.as_slice())) },
        _ => { fail!("args?") },
    }
}

enum Permissions {
    Permissions,
}

enum FileName {
    FileName,
}

struct FileSize {
    useSIPrefixes: bool,
}

trait Column {
    fn display(&self, stat: &io::FileStat, filename: &str) -> ~str;
}

impl Column for FileName {
    fn display(&self, stat: &io::FileStat, filename: &str) -> ~str {
        file_colour(stat, filename).paint(filename.to_owned())
    }
}

impl Column for Permissions {
    fn display(&self, stat: &io::FileStat, filename: &str) -> ~str {
        let bits = stat.perm;
        return format!("{}{}{}{}{}{}{}{}{}{}",
            type_char(stat.kind),
            bit(bits, io::UserRead, ~"r", Yellow.bold()),
            bit(bits, io::UserWrite, ~"w", Red.bold()),
            bit(bits, io::UserExecute, ~"x", Green.bold().underline()),
            bit(bits, io::GroupRead, ~"r", Yellow.normal()),
            bit(bits, io::GroupWrite, ~"w", Red.normal()),
            bit(bits, io::GroupExecute, ~"x", Green.normal()),
            bit(bits, io::OtherRead, ~"r", Yellow.normal()),
            bit(bits, io::OtherWrite, ~"w", Red.normal()),
            bit(bits, io::OtherExecute, ~"x", Green.normal()),
       );
    }
}

impl Column for FileSize {
    fn display(&self, stat: &io::FileStat, filename: &str) -> ~str {
        let sizeStr = if self.useSIPrefixes {
            formatBytes(stat.size, 1024, ~[ "B  ", "KiB", "MiB", "GiB", "TiB" ])
        } else {
            formatBytes(stat.size, 1000, ~[ "B ", "KB", "MB", "GB", "TB" ])
        };

        return if stat.kind == io::TypeDirectory {
            Green.normal()
        } else {
            Green.bold()
        }.paint(sizeStr);
    }
}

fn formatBytes(mut amount: u64, kilo: u64, prefixes: ~[&str]) -> ~str {
    let mut prefix = 0;
    while amount > kilo {
        amount /= kilo;
        prefix += 1;
    }
    return format!("{:4}{}", amount, prefixes[prefix]);
}

fn list(path: Path) {
    let mut files = match fs::readdir(&path) {
        Ok(files) => files,
        Err(e) => fail!("readdir: {}", e),
    };
    files.sort_by(|a, b| a.filename_str().cmp(&b.filename_str()));
    for file in files.iter() {
        let filename: &str = file.filename_str().unwrap();

        // We have to use lstat here instad of file.stat(), as it
        // doesn't follow symbolic links. Otherwise, the stat() call
        // will fail if it encounters a link that's target is
        // non-existent.
        let stat: io::FileStat = match fs::lstat(file) {
            Ok(stat) => stat,
            Err(e) => fail!("Couldn't stat {}: {}", filename, e),
        };

        let columns = ~[
            ~Permissions as ~Column,
            ~FileSize { useSIPrefixes: false } as ~Column,
            ~FileName as ~Column
        ];

        let mut cells = columns.iter().map(|c| c.display(&stat, filename));

        let mut first = true;
        for cell in cells {
            if first {
                first = false;
            } else {
                print!(" ");
            }
            print!("{}", cell);
        }
        print!("\n");
    }
}

fn file_colour(stat: &io::FileStat, filename: &str) -> Style {
    if stat.kind == io::TypeDirectory {
        Blue.normal()
    } else if stat.perm & io::UserExecute == io::UserExecute {
        Green.normal()
    } else if filename.ends_with("~") {
        Black.bold()
    } else {
        Plain
    }
}

fn bit(bits: u32, bit: u32, other: ~str, style: Style) -> ~str {
    if bits & bit == bit {
        style.paint(other)
    } else {
        Black.bold().paint(~"-")
    }
}

fn type_char(t: io::FileType) -> ~str {
    return match t {
        io::TypeFile => ~".",
        io::TypeDirectory => Blue.paint("d"),
        io::TypeNamedPipe => Yellow.paint("|"),
        io::TypeBlockSpecial => Purple.paint("s"),
        io::TypeSymlink => Cyan.paint("l"),
        _ => ~"?",
    }
}
<commit_msg>Keep files and their stat results together<commit_after>use std::io::fs;
use std::io;
use std::os;

use colours::{Plain, Style, Black, Red, Green, Yellow, Blue, Purple, Cyan};
mod colours;

fn main() {
    match os::args().as_slice() {
        [] => unreachable!(),
        [_] => { list(Path::new(".")) },
        [_, ref p] => { list(Path::new(p.as_slice())) },
        _ => { fail!("args?") },
    }
}

enum Permissions {
    Permissions,
}

enum FileName {
    FileName,
}

struct FileSize {
    useSIPrefixes: bool,
}

trait Column {
    fn display(&self, stat: &io::FileStat, filename: &str) -> ~str;
}

impl Column for FileName {
    fn display(&self, stat: &io::FileStat, filename: &str) -> ~str {
        file_colour(stat, filename).paint(filename.to_owned())
    }
}

impl Column for Permissions {
    fn display(&self, stat: &io::FileStat, filename: &str) -> ~str {
        let bits = stat.perm;
        return format!("{}{}{}{}{}{}{}{}{}{}",
            type_char(stat.kind),
            bit(bits, io::UserRead, ~"r", Yellow.bold()),
            bit(bits, io::UserWrite, ~"w", Red.bold()),
            bit(bits, io::UserExecute, ~"x", Green.bold().underline()),
            bit(bits, io::GroupRead, ~"r", Yellow.normal()),
            bit(bits, io::GroupWrite, ~"w", Red.normal()),
            bit(bits, io::GroupExecute, ~"x", Green.normal()),
            bit(bits, io::OtherRead, ~"r", Yellow.normal()),
            bit(bits, io::OtherWrite, ~"w", Red.normal()),
            bit(bits, io::OtherExecute, ~"x", Green.normal()),
       );
    }
}

impl Column for FileSize {
    fn display(&self, stat: &io::FileStat, filename: &str) -> ~str {
        let sizeStr = if self.useSIPrefixes {
            formatBytes(stat.size, 1024, ~[ "B  ", "KiB", "MiB", "GiB", "TiB" ])
        } else {
            formatBytes(stat.size, 1000, ~[ "B ", "KB", "MB", "GB", "TB" ])
        };

        return if stat.kind == io::TypeDirectory {
            Green.normal()
        } else {
            Green.bold()
        }.paint(sizeStr);
    }
}

fn formatBytes(mut amount: u64, kilo: u64, prefixes: ~[&str]) -> ~str {
    let mut prefix = 0;
    while amount > kilo {
        amount /= kilo;
        prefix += 1;
    }
    return format!("{:4}{}", amount, prefixes[prefix]);
}

// Each file is definitely going to get `stat`ted at least once, if
// only to determine what kind of file it is, so carry the `stat`
// result around with the file for safe keeping.
struct File<'a> {
    name: &'a str,
    path: &'a Path,
    stat: io::FileStat,
}

impl<'a> File<'a> {
    fn from_path(path: &'a Path) -> File<'a> {
        let filename: &str = path.filename_str().unwrap();

        // We have to use lstat here instad of file.stat(), as it
        // doesn't follow symbolic links. Otherwise, the stat() call
        // will fail if it encounters a link that's target is
        // non-existent.
        let stat: io::FileStat = match fs::lstat(path) {
            Ok(stat) => stat,
            Err(e) => fail!("Couldn't stat {}: {}", filename, e),
        };

        return File { path: path, stat: stat, name: filename };
    }
}

fn list(path: Path) {
    let mut files = match fs::readdir(&path) {
        Ok(files) => files,
        Err(e) => fail!("readdir: {}", e),
    };
    files.sort_by(|a, b| a.filename_str().cmp(&b.filename_str()));
    for subpath in files.iter() {
        let file = File::from_path(subpath);

        let columns = ~[
            ~Permissions as ~Column,
            ~FileSize { useSIPrefixes: false } as ~Column,
            ~FileName as ~Column
        ];

        let mut cells = columns.iter().map(|c| c.display(&file.stat, file.name));

        let mut first = true;
        for cell in cells {
            if first {
                first = false;
            } else {
                print!(" ");
            }
            print!("{}", cell);
        }
        print!("\n");
    }
}

fn file_colour(stat: &io::FileStat, filename: &str) -> Style {
    if stat.kind == io::TypeDirectory {
        Blue.normal()
    } else if stat.perm & io::UserExecute == io::UserExecute {
        Green.normal()
    } else if filename.ends_with("~") {
        Black.bold()
    } else {
        Plain
    }
}

fn bit(bits: u32, bit: u32, other: ~str, style: Style) -> ~str {
    if bits & bit == bit {
        style.paint(other)
    } else {
        Black.bold().paint(~"-")
    }
}

fn type_char(t: io::FileType) -> ~str {
    return match t {
        io::TypeFile => ~".",
        io::TypeDirectory => Blue.paint("d"),
        io::TypeNamedPipe => Yellow.paint("|"),
        io::TypeBlockSpecial => Purple.paint("s"),
        io::TypeSymlink => Cyan.paint("l"),
        _ => ~"?",
    }
}
<|endoftext|>


<commit_before><commit_msg>test for interestingly aligned field access<commit_after>#![allow(dead_code)]

#[repr(u16)]
enum DeviceKind {
    Nil = 0,
}
#[repr(packed)]
struct DeviceInfo {
    endianness: u8,
    device_kind: DeviceKind,
}
fn main() {
    let _x = None::<(DeviceInfo, u8)>;
    let _y = None::<(DeviceInfo, u16)>;
    let _z = None::<(DeviceInfo, u64)>;
}
<|endoftext|>


<commit_before><commit_msg>Add custom storage to ComponentMapper<commit_after><|endoftext|>


<commit_before>pub const QUIC_INTERNAL_ERROR: u32 = 0x80000001;
pub const QUIC_STREAM_DATA_AFTER_TERMINATION: u32 = 0x80000002;
pub const QUIC_INVALID_PACKET_HEADER: u32 = 0x80000003;
pub const QUIC_INVALID_FRAME_DATA: u32 = 0x80000004;
pub const QUIC_MULTIPLE_TERMINATION_OFFSETS: u32 = 0x80000005;
pub const QUIC_STREAM_CANCELLED: u32 = 0x80000006;
pub const QUIC_MISSING_PAYLOAD: u32 = 0x80000030;
pub const QUIC_INVALID_STREAM_DATA: u32 = 0x8000002E;
pub const QUIC_OVERLAPPING_STREAM_DATA: u32 = 0x80000057;
pub const QUIC_UNENCRYPTED_STREAM_DATA: u32 = 0x8000003D;
pub const QUIC_MAYBE_CORRUPTED_MEMORY: u32 = 0x80000059;
pub const QUIC_INVALID_RST_STREAM_DATA: u32 = 0x80000006;
pub const QUIC_INVALID_CONNECTION_CLOSE_DATA: u32 = 0x80000007;
pub const QUIC_INVALID_GOAWAY_DATA: u32 = 0x80000008;
pub const QUIC_INVALID_WINDOW_UPDATE_DATA: u32 = 0x80000039;
pub const QUIC_INVALID_BLOCKED_DATA: u32 = 0x8000003A;
pub const QUIC_INVALID_STOP_WAITING_DATA: u32 = 0x8000003C;
pub const QUIC_INVALID_PATH_CLOSE_DATA: u32 = 0x8000004E;
pub const QUIC_INVALID_ACK_DATA: u32 = 0x80000009;
pub const QUIC_INVALID_VERSION_NEGOTIATION_PACKET: u32 = 0x8000000A;
pub const QUIC_INVALID_PUBLIC_RST_PACKET: u32 = 0x8000000B;
pub const QUIC_DECRYPTION_FAILURE: u32 = 0x8000000C;
pub const QUIC_ENCRYPTION_FAILURE: u32 = 0x8000000D;
pub const QUIC_PACKET_TOO_LARGE: u32 = 0x8000000e;
pub const QUIC_PEER_GOING_AWAY: u32 = 0x80000010;
pub const QUIC_INVALID_STREAM_ID: u32 = 0x80000011;
pub const QUIC_INVALID_PRIORITY: u32 = 0x80000031;
pub const QUIC_TOO_MANY_OPEN_STREAMS: u32 = 0x80000012;
pub const QUIC_TOO_MANY_AVAILABLE_STREAMS: u32 = 0x8000004C;
pub const QUIC_PUBLIC_RESET: u32 = 0x80000013;
pub const QUIC_INVALID_VERSION: u32 = 0x80000014;
pub const QUIC_INVALID_HEADER_ID: u32 = 0x80000016;
pub const QUIC_INVALID_NEGOTIATED_VALUE: u32 = 0x80000017;
pub const QUIC_DECOMPRESSION_FAILURE: u32 = 0x80000018;
pub const QUIC_NETWORK_IDLE_TIMEOUT: u32 = 0x80000019;
pub const QUIC_HANDSHAKE_TIMEOUT: u32 = 0x80000043;
pub const QUIC_ERROR_MIGRATING_ADDRESS: u32 = 0x8000001A;
pub const QUIC_ERROR_MIGRATING_PORT: u32 = 0x80000056;
pub const QUIC_EMPTY_STREAM_FRAME_NO_FIN: u32 = 0x80000032;
pub const QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA: u32 = 0x8000003B;
pub const QUIC_FLOW_CONTROL_SENT_TOO_MUCH_DATA: u32 = 0x8000003F;
pub const QUIC_FLOW_CONTROL_INVALID_WINDOW: u32 = 0x80000040;
pub const QUIC_CONNECTION_IP_POOLED: u32 = 0x8000003E;
pub const QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS: u32 = 0x80000044;
pub const QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS: u32 = 0x80000045;
pub const QUIC_CONNECTION_CANCELLED: u32 = 0x80000046;
pub const QUIC_BAD_PACKET_LOSS_RATE: u32 = 0x80000047;
pub const QUIC_PUBLIC_RESETS_POST_HANDSHAKE: u32 = 0x80000049;
pub const QUIC_TIMEOUTS_WITH_OPEN_STREAMS: u32 = 0x8000004A;
pub const QUIC_TOO_MANY_RTOS: u32 = 0x80000055;
pub const QUIC_ENCRYPTION_LEVEL_INCORRECT: u32 = 0x8000002C;
pub const QUIC_VERSION_NEGOTIATION_MISMATCH: u32 = 0x80000037;
pub const QUIC_IP_ADDRESS_CHANGED: u32 = 0x80000050;
pub const QUIC_TOO_MANY_FRAME_GAPS: u32 = 0x8000005D;
pub const QUIC_TOO_MANY_SESSIONS_ON_SERVER: u32 = 0x80000060;
<commit_msg>Add a new error code<commit_after>pub const QUIC_INTERNAL_ERROR: u32 = 0x80000001;
pub const QUIC_STREAM_DATA_AFTER_TERMINATION: u32 = 0x80000002;
pub const QUIC_INVALID_PACKET_HEADER: u32 = 0x80000003;
pub const QUIC_INVALID_FRAME_DATA: u32 = 0x80000004;
pub const QUIC_MULTIPLE_TERMINATION_OFFSETS: u32 = 0x80000005;
pub const QUIC_STREAM_CANCELLED: u32 = 0x80000006;
pub const QUIC_MISSING_PAYLOAD: u32 = 0x80000030;
pub const QUIC_INVALID_STREAM_DATA: u32 = 0x8000002E;
pub const QUIC_OVERLAPPING_STREAM_DATA: u32 = 0x80000057;
pub const QUIC_UNENCRYPTED_STREAM_DATA: u32 = 0x8000003D;
pub const QUIC_MAYBE_CORRUPTED_MEMORY: u32 = 0x80000059;
pub const QUIC_INVALID_RST_STREAM_DATA: u32 = 0x80000006;
pub const QUIC_INVALID_CONNECTION_CLOSE_DATA: u32 = 0x80000007;
pub const QUIC_INVALID_GOAWAY_DATA: u32 = 0x80000008;
pub const QUIC_INVALID_WINDOW_UPDATE_DATA: u32 = 0x80000039;
pub const QUIC_INVALID_BLOCKED_DATA: u32 = 0x8000003A;
pub const QUIC_INVALID_STOP_WAITING_DATA: u32 = 0x8000003C;
pub const QUIC_INVALID_PATH_CLOSE_DATA: u32 = 0x8000004E;
pub const QUIC_INVALID_ACK_DATA: u32 = 0x80000009;
pub const QUIC_INVALID_VERSION_NEGOTIATION_PACKET: u32 = 0x8000000A;
pub const QUIC_INVALID_PUBLIC_RST_PACKET: u32 = 0x8000000B;
pub const QUIC_DECRYPTION_FAILURE: u32 = 0x8000000C;
pub const QUIC_ENCRYPTION_FAILURE: u32 = 0x8000000D;
pub const QUIC_PACKET_TOO_LARGE: u32 = 0x8000000e;
pub const QUIC_PEER_GOING_AWAY: u32 = 0x80000010;
pub const QUIC_INVALID_STREAM_ID: u32 = 0x80000011;
pub const QUIC_INVALID_PRIORITY: u32 = 0x80000031;
pub const QUIC_TOO_MANY_OPEN_STREAMS: u32 = 0x80000012;
pub const QUIC_TOO_MANY_AVAILABLE_STREAMS: u32 = 0x8000004C;
pub const QUIC_PUBLIC_RESET: u32 = 0x80000013;
pub const QUIC_INVALID_VERSION: u32 = 0x80000014;
pub const QUIC_INVALID_HEADER_ID: u32 = 0x80000016;
pub const QUIC_INVALID_NEGOTIATED_VALUE: u32 = 0x80000017;
pub const QUIC_DECOMPRESSION_FAILURE: u32 = 0x80000018;
pub const QUIC_NETWORK_IDLE_TIMEOUT: u32 = 0x80000019;
pub const QUIC_HANDSHAKE_TIMEOUT: u32 = 0x80000043;
pub const QUIC_ERROR_MIGRATING_ADDRESS: u32 = 0x8000001A;
pub const QUIC_ERROR_MIGRATING_PORT: u32 = 0x80000056;
pub const QUIC_EMPTY_STREAM_FRAME_NO_FIN: u32 = 0x80000032;
pub const QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA: u32 = 0x8000003B;
pub const QUIC_FLOW_CONTROL_SENT_TOO_MUCH_DATA: u32 = 0x8000003F;
pub const QUIC_FLOW_CONTROL_INVALID_WINDOW: u32 = 0x80000040;
pub const QUIC_CONNECTION_IP_POOLED: u32 = 0x8000003E;
pub const QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS: u32 = 0x80000044;
pub const QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS: u32 = 0x80000045;
pub const QUIC_CONNECTION_CANCELLED: u32 = 0x80000046;
pub const QUIC_BAD_PACKET_LOSS_RATE: u32 = 0x80000047;
pub const QUIC_PUBLIC_RESETS_POST_HANDSHAKE: u32 = 0x80000049;
pub const QUIC_TIMEOUTS_WITH_OPEN_STREAMS: u32 = 0x8000004A;
pub const QUIC_TOO_MANY_RTOS: u32 = 0x80000055;
pub const QUIC_ENCRYPTION_LEVEL_INCORRECT: u32 = 0x8000002C;
pub const QUIC_VERSION_NEGOTIATION_MISMATCH: u32 = 0x80000037;
pub const QUIC_IP_ADDRESS_CHANGED: u32 = 0x80000050;
pub const QUIC_ADDRESS_VALIDATION_FAILURE: u32 = 0x80000051;
pub const QUIC_TOO_MANY_FRAME_GAPS: u32 = 0x8000005D;
pub const QUIC_TOO_MANY_SESSIONS_ON_SERVER: u32 = 0x80000060;
<|endoftext|>


<commit_before><commit_msg>:art: Refactor fetch_rescheduled_tasks<commit_after><|endoftext|>


<commit_before><commit_msg>example JSON parser with better error messages<commit_after>#[macro_use]
extern crate nom;
extern crate jemallocator;

#[global_allocator]
static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;

use nom::{AsBytes, Err, ErrorKind, IResult, Offset, ParseError};
use nom::{alphanumeric, recognize_float, take_while, delimitedc, char, tag, precededc, separated_listc, terminatedc, alt};
use std::str;
use std::iter::repeat;
use std::collections::HashMap;

#[derive(Debug, PartialEq)]
pub enum JsonValue {
  Str(String),
  Boolean(bool),
  Num(f64),
  Array(Vec<JsonValue>),
  Object(HashMap<String, JsonValue>),
}

fn sp<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, &'a str, E> {
  let chars = " \t\r\n";

  take_while(move |c| chars.contains(c))(i)
}

fn float<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, f64, E> {
  flat_map!(i, recognize_float, parse_to!(f64))
}

fn parse_str<'a, E: ParseError<&'a str>>(i: &'a str) ->IResult<&'a str, &'a str, E> {
    escaped!(i, call!(alphanumeric), '\\', one_of!("\"n\\"))
}

fn string<'a, E: ParseError<&'a str>+Ctx<&'a str>>(i: &'a str) ->IResult<&'a str, &'a str, E> {
  //delimitedc(i, char('\"'), parse_str, char('\"'))
  let (i, _) = char('\"')(i)?;

  ctx("string", |i| terminatedc(i, parse_str, char('\"')))(i)
}

fn boolean<'a, E: ParseError<&'a str>>(input: &'a str) ->IResult<&'a str, bool, E> {
  alt( (
      |i| tag("false")(i).map(|(i,_)| (i, false)),
      |i| tag("true")(i).map(|(i,_)| (i, true))
  ))(input)
  /*
  match tag::<&'static str, &'a str, E>("false")(i) {
    Ok((i, _)) => Ok((i, false)),
    Err(_) => tag("true")(i).map(|(i,_)| (i, true))
  }
  */
}

fn array<'a, E: ParseError<&'a str>+Ctx<&'a str>>(i: &'a str) ->IResult<&'a str, Vec<JsonValue>, E> {
  let (i, _) = char('[')(i)?;

  ctx(
    "array",
    |i| terminatedc(i,
      |i| separated_listc(i, |i| precededc(i, sp, char(',')), value),
      |i| precededc(i, sp, char(']')))
     )(i)
}

fn key_value<'a, E: ParseError<&'a str>+Ctx<&'a str>>(i: &'a str) ->IResult<&'a str, (&'a str, JsonValue), E> {
  separated_pair!(i, preceded!(sp, string), preceded!(sp, char!(':')), value)
}

fn hash<'a, E: ParseError<&'a str>+Ctx<&'a str>>(i: &'a str) ->IResult<&'a str, HashMap<String, JsonValue>, E> {
  let (i, _) = char('{')(i)?;
  ctx(
    "map",
    |i| terminatedc(i,
      |i| map!(i,
        separated_list!(preceded!(sp, char!(',')), key_value),
        |tuple_vec| tuple_vec
          .into_iter()
          .map(|(k, v)| (String::from(k), v))
          .collect()
      ),
      |i| precededc(i, sp, char('}')))
     )(i)

/*
  map!(i,
    delimited!(
      char!('{'),
      separated_list!(preceded!(sp, char!(',')), key_value),
      preceded!(sp, char!('}'))
    ),
    |tuple_vec| tuple_vec
      .into_iter()
      .map(|(k, v)| (String::from(k), v))
      .collect()
  )
  */
}

fn value<'a, E: ParseError<&'a str>+Ctx<&'a str>>(i: &'a str) ->IResult<&'a str, JsonValue, E> {
  preceded!(i,
    sp,
    alt!(
      hash    => { |h| JsonValue::Object(h)            } |
      array   => { |v| JsonValue::Array(v)             } |
      string  => { |s| JsonValue::Str(String::from(s)) } |
      float   => { |f| JsonValue::Num(f)               } |
      boolean => { |b| JsonValue::Boolean(b)           }
    ))
}

fn root<'a, E: ParseError<&'a str>+Ctx<&'a str>>(i: &'a str) ->IResult<&'a str, JsonValue, E> {
  delimited!(i,
    sp,
    alt( (
      |input| hash(input).map(|(i,h)| (i, JsonValue::Object(h))),
      |input| array(input).map(|(i,v)| (i, JsonValue::Array(v)))
    ) ),
    /*alt!(
      hash    => { |h| JsonValue::Object(h)            } |
      array   => { |v| JsonValue::Array(v)             }
    ),*/
    not!(complete!(sp)))
}

#[derive(Clone,Debug,PartialEq)]
struct VerboseError<'a> {
  errors: Vec<(&'a str, VerboseErrorKind)>,
}

#[derive(Clone,Debug,PartialEq)]
pub enum VerboseErrorKind {
  Context(&'static str),
  Char(char),
  //Tag(String),
  Nom(ErrorKind),
}

impl<'a> ParseError<&'a str> for VerboseError<'a> {
  fn from_error_kind(input: &'a str, kind: ErrorKind) -> Self {
    VerboseError {
      errors: vec![(input, VerboseErrorKind::Nom(kind))]
    }
  }

  fn append(input: &'a str, kind: ErrorKind, mut other: Self) -> Self {
    other.errors.push((input, VerboseErrorKind::Nom(kind)));
    other
  }

  fn from_char(input: &'a str, c: char) -> Self {
    VerboseError {
      errors: vec![(input, VerboseErrorKind::Char(c))]
    }
  }

  /*fn from_tag<T:AsBytes>(input: &'a str, t: T) -> Self {
    VerboseError {
      errors: vec![(input, VerboseErrorKind::Char(c))]
    }
  }*/
}

trait Ctx<I> {
  fn add_context(input: I, ctx: &'static str, other: Self) -> Self;
}

impl<I> Ctx<I> for (I, ErrorKind) {
  fn add_context(input: I, ctx: &'static str, other: Self) -> Self {
    other
  }
}

impl<'a> Ctx<&'a str> for VerboseError<'a> {
  fn add_context(input: &'a str, ctx: &'static str, mut other: Self) -> Self {
    other.errors.push((input, VerboseErrorKind::Context(ctx)));
    other
  }
}

fn ctx<'a, E: ParseError<&'a str>+Ctx<&'a str>, F, O>(context: &'static str, f: F) -> impl FnOnce(&'a str) -> IResult<&'a str, O, E>
where
  F: Fn(&'a str) -> IResult<&'a str, O, E> {

    move |i: &'a str| {
      match f(i) {
        Ok(o) => Ok(o),
        Err(Err::Incomplete(i)) => Err(Err::Incomplete(i)),
        Err(Err::Error(e)) | Err(Err::Failure(e)) => {
          Err(Err::Failure(E::add_context(i, context, e)))
        }
      }
    }

}

fn convert_error(input: &str, e: VerboseError) -> String {
  let lines: Vec<_> = input.lines().map(String::from).collect();
  //println!("lines: {:#?}", lines);

  let mut result = String::new();

  for (i, (substring, kind)) in e.errors.iter().enumerate() {
    let mut offset = input.offset(substring);

    let mut line = 0;
    let mut column = 0;

    for (j,l) in lines.iter().enumerate() {
      if offset <= l.len() {
        line = j;
        column = offset;
        break;
      } else {
        offset = offset - l.len();
      }
    }

    match kind {
      VerboseErrorKind::Char(c) => {
        result += &format!("{}: at line {}:\n", i, line);
        result += &lines[line];
        result += "\n";
        if column > 0 {
          result += &repeat(' ').take(column-1).collect::<String>();
        }
        result += "^\n";
        result += &format!("expected '{}', found {}\n\n", c, substring.chars().next().unwrap());
      },
      VerboseErrorKind::Context(s) => {
        result += &format!("{}: at line {}, in {}:\n", i, line, s);
        result += &lines[line];
        result += "\n";
        if column > 0 {
          result += &repeat(' ').take(column -1).collect::<String>();
        }
        result += "^\n\n";
      }
      _ => {}
    }
  }

  result
}

fn main() {
  let data = "  { \"a\"\t: 42,
  \"b\": [ \"x\", \"y\", 12 ] ,
  \"c\": { 1\"hello\" : \"world\"
  }
  } ";

  println!("will try to parse:\n\n**********\n{}\n**********\n", data);
  println!("basic errors - `root::<(&str, ErrorKind)>(data)`:\n{:#?}\n", root::<(&str, ErrorKind)>(data));
  println!("parsed verbose: {:#?}", root::<VerboseError>(data));

  match root::<VerboseError>(data) {
    Err(Err::Error(e)) | Err(Err::Failure(e)) => {
      println!("verbose errors - `root::<VerboseError>(data)`:\n{}", convert_error(data, e));
    },
    _ => panic!(),
  }
}
<|endoftext|>


<commit_before><commit_msg>Lack of source info about sign message prefix<commit_after><|endoftext|>


<commit_before>use inflector::Inflector;

use botocore::{Member, Operation, Service, Shape, ShapeType};
use std::borrow::Cow;
use super::GenerateProtocol;
use super::generate_field_name;

pub struct Ec2Generator;

impl GenerateProtocol for Ec2Generator {
    fn generate_methods(&self, service: &Service) -> String {
        service.operations.values().map(|operation| {
            format!(
                "{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 result = try!(self.dispatcher.dispatch(&request));

                    match result.status {{
                        200 => {{
                            let mut reader = EventReader::from_str(&result.body);
                            let mut stack = XmlResponse::new(reader.events().peekable());
                            stack.next();
                            {method_return_value}
                        }},
                        _ => Err({error_type}::from_body(&result.body))
                    }}
                }}
                ",
                documentation = generate_documentation(operation),
                http_method = &operation.http.method,
                endpoint_prefix = &service.metadata.endpoint_prefix,
                method_return_value = generate_method_return_value(operation),
                method_signature = generate_method_signature(operation),
                operation_name = &operation.name,
                error_type = operation.error_type_name(),
                api_version = service.metadata.api_version,
                request_uri = &operation.http.request_uri,
                serialize_input = generate_method_input_serialization(operation),
            )
        }).collect::<Vec<String>>().join("\n")
    }

    fn generate_prelude(&self, _service: &Service) -> String {
        "use std::str::{FromStr, from_utf8};

        use xml::EventReader;

        use param::{Params, ServiceParams};

        use signature::SignedRequest;
        use xml::reader::events::XmlEvent;
        use xmlutil::{Next, Peek, XmlParseError, XmlResponse};
        use xmlutil::{characters, end_element, start_element, skip_tree};
        use xmlerror::*;

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

    fn generate_struct_attributes(&self) -> String {
        "#[derive(Debug, Default, Clone)]".to_owned()
    }

    fn generate_support_types(&self, name: &str, shape: &Shape, _service: &Service) -> Option<String> {
        Some(format!(
            "/// Deserializes `{name}` from XML.
            struct {name}Deserializer;
            impl {name}Deserializer {{
                #[allow(unused_variables)]
                fn deserialize<'a, T: Peek + Next>(tag_name: &str, stack: &mut T)
                -> Result<{name}, XmlParseError> {{
                    {deserializer_body}
                }}
            }}

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

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

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

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_response_tag_name<'a>(member_name: &'a str) -> Cow<'a, str> {
    if member_name.ends_with("Result") {
        format!("{}Response", &member_name[..member_name.len()-6]).into()
    } else {
        member_name.into()
    }
}

fn generate_method_return_value(operation: &Operation) -> String {
    if operation.output.is_some() {
        let output_type = &operation.output.as_ref().unwrap().shape;
        let standard_tag_name = generate_response_tag_name(output_type).into_owned();
        let tag_name = match standard_tag_name.as_ref() {
            "Snapshot" => "CreateSnapshotResponse",
            _ => &standard_tag_name
        };

        format!(
            "Ok(try!({output_type}Deserializer::deserialize(\"{tag_name}\", &mut stack)))",
            output_type = output_type,
            tag_name = tag_name
        )
    } else {
        "Ok(())".to_owned()
    }
}

fn generate_method_signature(operation: &Operation) -> String {
    if operation.input.is_some() {
        format!(
            "pub 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 = operation.error_type_name(),
        )
    } else {
        format!(
            "pub fn {operation_name}(&self) -> Result<{output_type}, {error_type}>",
            operation_name = operation.name.to_snake_case(),
            error_type = operation.error_type_name(),
            output_type = &operation.output_shape_or("()"),
        )
    }
}

fn generate_deserializer_body(name: &str, shape: &Shape) -> String {
    match shape.shape_type {
        ShapeType::List => generate_list_deserializer(shape),
        ShapeType::Structure => generate_struct_deserializer(name, shape),
        _ => generate_primitive_deserializer(shape),
    }
}

fn generate_list_deserializer(shape: &Shape) -> String {

    let location_name = shape.member.as_ref().and_then(|m| m.location_name.as_ref()).map(|name| &name[..]).unwrap_or(shape.member());

    format!(
        "
        let mut obj = vec![];
        try!(start_element(tag_name, stack));

        loop {{
            let next_event = match stack.peek() {{
                Some(&XmlEvent::EndElement {{ .. }}) => DeserializerNext::Close,
                Some(&XmlEvent::StartElement {{ ref name, .. }}) => DeserializerNext::Element(name.local_name.to_owned()),
                _ => DeserializerNext::Skip,
            }};

            match next_event {{
                DeserializerNext::Element(name) => {{
                    if name == \"{location_name}\" {{
                        obj.push(try!({member_name}Deserializer::deserialize(\"{location_name}\", stack)));
                    }} else {{
                        skip_tree(stack);
                    }}
                }},
                DeserializerNext::Close => {{
                    try!(end_element(tag_name, stack));
                    break;
                }}
                DeserializerNext::Skip => {{ stack.next(); }},
            }}
        }}

        Ok(obj)
        ",
        location_name = location_name,
        member_name = shape.member()
    )
}

fn generate_primitive_deserializer(shape: &Shape) -> String {
    let statement =  match shape.shape_type {
        ShapeType::String | ShapeType::Timestamp => "try!(characters(stack))",
        ShapeType::Integer => "i32::from_str(try!(characters(stack)).as_ref()).unwrap()",
        ShapeType::Long => "i64::from_str(try!(characters(stack)).as_ref()).unwrap()",
        ShapeType::Double => "f64::from_str(try!(characters(stack)).as_ref()).unwrap()",
        ShapeType::Float => "f32::from_str(try!(characters(stack)).as_ref()).unwrap()",
        ShapeType::Blob => "try!(characters(stack)).into_bytes()",
        ShapeType::Boolean => "bool::from_str(try!(characters(stack)).as_ref()).unwrap()",
        shape_type => panic!("Unknown primitive shape type: {:?}", shape_type),
    };

    format!(
        "try!(start_element(tag_name, stack));
        let obj = {statement};
        try!(end_element(tag_name, stack));

        Ok(obj)
        ",
        statement = statement,
    )
}

fn generate_struct_deserializer(name: &str, shape: &Shape) -> String {
    if shape.members.as_ref().unwrap().is_empty() {
        return format!(
            "try!(start_element(tag_name, stack));
            stack.next();

            let obj = {name}::default();

            try!(end_element(tag_name, stack));
            stack.next();

            Ok(obj)
            ",
            name = name,
        );
    }

    format!(
        "try!(start_element(tag_name, stack));

        let mut obj = {name}::default();

        loop {{
            let next_event = match stack.peek() {{
                Some(&XmlEvent::EndElement {{ .. }}) => DeserializerNext::Close,   // TODO verify that we received the expected tag?
                Some(&XmlEvent::StartElement {{ ref name, .. }}) => DeserializerNext::Element(name.local_name.to_owned()),
                _ => DeserializerNext::Skip,
            }};

            match next_event {{
                DeserializerNext::Element(name) => {{
                    match &name[..] {{
                        {struct_field_deserializers}
                        _ => skip_tree(stack),
                    }}
                }},
                DeserializerNext::Close => break,
                DeserializerNext::Skip => {{ stack.next(); }},
            }}
        }}

        try!(end_element(tag_name, stack));

        Ok(obj)
        ",
        name = name,
        struct_field_deserializers = generate_struct_field_deserializers(shape),
    )
}

fn generate_struct_field_deserializers(shape: &Shape) -> String {
    shape.members.as_ref().unwrap().iter().map(|(member_name, member)| {
        // look up member.shape in all_shapes.  use that shape.member.location_name
        let location_name = member.location_name.as_ref().unwrap_or(member_name);

        let parse_expression = generate_struct_field_parse_expression(shape, member_name, member, member.location_name.as_ref());
        format!(
            "\"{location_name}\" => {{
                obj.{field_name} = {parse_expression};
            }}",
            field_name = generate_field_name(member_name),
            parse_expression = parse_expression,
            location_name = location_name,
        )

    }).collect::<Vec<String>>().join("\n")
}

fn generate_struct_field_parse_expression(
    shape: &Shape,
    member_name: &str,
    member: &Member,
    location_name: Option<&String>,
) -> String {

    let location_to_use = match location_name {
        Some(loc) => loc.to_string(),
        None => member_name.to_string(),
    };
    let expression = format!(
        "try!({name}Deserializer::deserialize(\"{location}\", stack))",
        name = member.shape,
        location = location_to_use,
    );

    if shape.required(member_name) {
        expression
    } else {
        format!("Some({})", expression)
    }
}

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

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(shape: &Shape) -> String {
    format!(
        "for (index, element) in obj.iter().enumerate() {{
    let key = format!(\"{{}}.{{}}\", name, index);
    {name}Serializer::serialize(params, &key, element);
}}
        ",
        name = shape.member(),
    )
}

fn generate_map_serializer(shape: &Shape) -> String {
    format!(
        "for (index, (key, value)) in obj.iter().enumerate() {{
    let prefix = format!(\"{{}}.{{}}\", name, index);
    {key_name}Serializer::serialize(
        params,
        &format!(\"{{}}.{{}}\", prefix, \"{key_name}\"),
        key,
    );
    {value_name}Serializer::serialize(
        params,
        &format!(\"{{}}.{{}}\", prefix, \"{value_name}\"),
        value,
    );
}}
        ",
        key_name = shape.key(),
        value_name = shape.value(),
    )
}

fn generate_struct_serializer(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(shape),
    )
}

fn generate_struct_field_serializers(shape: &Shape) -> String {
    shape.members.as_ref().unwrap().iter().map(|(member_name, member)| {
        if shape.required(member_name) {
            format!(
                "{member_shape_name}Serializer::serialize(
    params,
    &format!(\"{{}}{tag_name}\", prefix),
    &obj.{field_name},
);
                ",
                field_name = generate_field_name(member_name),
                member_shape_name = member.shape,
                tag_name = member_name,
            )
        } else {
            format!(
                "if let Some(ref field_value) = obj.{field_name} {{
    {member_shape_name}Serializer::serialize(
        params,
        &format!(\"{{}}{tag_name}\", prefix),
        field_value,
    );
}}
                ",
                field_name = generate_field_name(member_name),
                member_shape_name = member.shape,
                tag_name = member.location_name.as_ref().unwrap_or(member_name),
            )
        }
    }).collect::<Vec<String>>().join("\n")
}

fn generate_primitive_serializer(shape: &Shape) -> String {
    let expression = match shape.shape_type {
        ShapeType::String | ShapeType::Timestamp => "obj",
        ShapeType::Integer | ShapeType::Long | ShapeType::Float | ShapeType::Double | ShapeType::Boolean => "&obj.to_string()",
        ShapeType::Blob => "from_utf8(obj).unwrap()",
        shape_type => panic!("Unknown primitive shape type: {:?}", shape_type),
    };

    format!("params.put(name, {});", expression)
}
<commit_msg>Doesn't make serializers or deserializers for inbound or outbound only types.<commit_after>use inflector::Inflector;

use botocore::{Member, Operation, Service, Shape, ShapeType};
use std::borrow::Cow;
use super::GenerateProtocol;
use super::generate_field_name;

pub struct Ec2Generator;

impl GenerateProtocol for Ec2Generator {
    fn generate_methods(&self, service: &Service) -> String {
        service.operations.values().map(|operation| {
            format!(
                "{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 result = try!(self.dispatcher.dispatch(&request));

                    match result.status {{
                        200 => {{
                            let mut reader = EventReader::from_str(&result.body);
                            let mut stack = XmlResponse::new(reader.events().peekable());
                            stack.next();
                            {method_return_value}
                        }},
                        _ => Err({error_type}::from_body(&result.body))
                    }}
                }}
                ",
                documentation = generate_documentation(operation),
                http_method = &operation.http.method,
                endpoint_prefix = &service.metadata.endpoint_prefix,
                method_return_value = generate_method_return_value(operation),
                method_signature = generate_method_signature(operation),
                operation_name = &operation.name,
                error_type = operation.error_type_name(),
                api_version = service.metadata.api_version,
                request_uri = &operation.http.request_uri,
                serialize_input = generate_method_input_serialization(operation),
            )
        }).collect::<Vec<String>>().join("\n")
    }

    fn generate_prelude(&self, _service: &Service) -> String {
        "use std::str::{FromStr, from_utf8};

        use xml::EventReader;

        use param::{Params, ServiceParams};

        use signature::SignedRequest;
        use xml::reader::events::XmlEvent;
        use xmlutil::{Next, Peek, XmlParseError, XmlResponse};
        use xmlutil::{characters, end_element, start_element, skip_tree};
        use xmlerror::*;

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

    fn generate_struct_attributes(&self) -> String {
        "#[derive(Debug, Default, Clone)]".to_owned()
    }

    fn generate_support_types(&self, name: &str, shape: &Shape, _service: &Service) -> Option<String> {
        let mut struct_collector = String::new();
        let serializer = generate_serializer_body(name, shape);

        if serializer.is_some() {
            struct_collector.push_str(&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 = serializer.unwrap())
            );
        }
        let deserializer = generate_deserializer_body(name, shape);
        if deserializer.is_some() {
            struct_collector.push_str(&format!(
            "/// Deserializes `{name}` from XML.
            struct {name}Deserializer;
            impl {name}Deserializer {{
                #[allow(unused_variables)]
                fn deserialize<'a, T: Peek + Next>(tag_name: &str, stack: &mut T)
                -> Result<{name}, XmlParseError> {{
                    {deserializer_body}
                }}
            }}",
            name = name,
            deserializer_body = deserializer.unwrap())
            );
        }
        Some(struct_collector)
    }

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

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

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_response_tag_name<'a>(member_name: &'a str) -> Cow<'a, str> {
    if member_name.ends_with("Result") {
        format!("{}Response", &member_name[..member_name.len()-6]).into()
    } else {
        member_name.into()
    }
}

fn generate_method_return_value(operation: &Operation) -> String {
    if operation.output.is_some() {
        let output_type = &operation.output.as_ref().unwrap().shape;
        let standard_tag_name = generate_response_tag_name(output_type).into_owned();
        let tag_name = match standard_tag_name.as_ref() {
            "Snapshot" => "CreateSnapshotResponse",
            _ => &standard_tag_name
        };

        format!(
            "Ok(try!({output_type}Deserializer::deserialize(\"{tag_name}\", &mut stack)))",
            output_type = output_type,
            tag_name = tag_name
        )
    } else {
        "Ok(())".to_owned()
    }
}

fn generate_method_signature(operation: &Operation) -> String {
    if operation.input.is_some() {
        format!(
            "pub 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 = operation.error_type_name(),
        )
    } else {
        format!(
            "pub fn {operation_name}(&self) -> Result<{output_type}, {error_type}>",
            operation_name = operation.name.to_snake_case(),
            error_type = operation.error_type_name(),
            output_type = &operation.output_shape_or("()"),
        )
    }
}

fn generate_deserializer_body(name: &str, shape: &Shape) -> Option<String> {
    // Requests don't get deserialized, except the ones that do.
    if name.ends_with("Request") {
        match name {
            "CancelledSpotInstanceRequest" => (),
            "PurchaseRequest" => (),
            "SpotInstanceRequest" => (),
            _ => return None,
        }
    }
    match shape.shape_type {
        ShapeType::List => Some(generate_list_deserializer(shape)),
        ShapeType::Structure => Some(generate_struct_deserializer(name, shape)),
        _ => Some(generate_primitive_deserializer(shape)),
    }
}

fn generate_list_deserializer(shape: &Shape) -> String {

    let location_name = shape.member.as_ref().and_then(|m| m.location_name.as_ref()).map(|name| &name[..]).unwrap_or(shape.member());

    format!(
        "
        let mut obj = vec![];
        try!(start_element(tag_name, stack));

        loop {{
            let next_event = match stack.peek() {{
                Some(&XmlEvent::EndElement {{ .. }}) => DeserializerNext::Close,
                Some(&XmlEvent::StartElement {{ ref name, .. }}) => DeserializerNext::Element(name.local_name.to_owned()),
                _ => DeserializerNext::Skip,
            }};

            match next_event {{
                DeserializerNext::Element(name) => {{
                    if name == \"{location_name}\" {{
                        obj.push(try!({member_name}Deserializer::deserialize(\"{location_name}\", stack)));
                    }} else {{
                        skip_tree(stack);
                    }}
                }},
                DeserializerNext::Close => {{
                    try!(end_element(tag_name, stack));
                    break;
                }}
                DeserializerNext::Skip => {{ stack.next(); }},
            }}
        }}

        Ok(obj)
        ",
        location_name = location_name,
        member_name = shape.member()
    )
}

fn generate_primitive_deserializer(shape: &Shape) -> String {
    let statement =  match shape.shape_type {
        ShapeType::String | ShapeType::Timestamp => "try!(characters(stack))",
        ShapeType::Integer => "i32::from_str(try!(characters(stack)).as_ref()).unwrap()",
        ShapeType::Long => "i64::from_str(try!(characters(stack)).as_ref()).unwrap()",
        ShapeType::Double => "f64::from_str(try!(characters(stack)).as_ref()).unwrap()",
        ShapeType::Float => "f32::from_str(try!(characters(stack)).as_ref()).unwrap()",
        ShapeType::Blob => "try!(characters(stack)).into_bytes()",
        ShapeType::Boolean => "bool::from_str(try!(characters(stack)).as_ref()).unwrap()",
        shape_type => panic!("Unknown primitive shape type: {:?}", shape_type),
    };

    format!(
        "try!(start_element(tag_name, stack));
        let obj = {statement};
        try!(end_element(tag_name, stack));

        Ok(obj)
        ",
        statement = statement,
    )
}

fn generate_struct_deserializer(name: &str, shape: &Shape) -> String {
    if shape.members.as_ref().unwrap().is_empty() {
        return format!(
            "try!(start_element(tag_name, stack));
            stack.next();

            let obj = {name}::default();

            try!(end_element(tag_name, stack));
            stack.next();

            Ok(obj)
            ",
            name = name,
        );
    }

    format!(
        "try!(start_element(tag_name, stack));

        let mut obj = {name}::default();

        loop {{
            let next_event = match stack.peek() {{
                Some(&XmlEvent::EndElement {{ .. }}) => DeserializerNext::Close,   // TODO verify that we received the expected tag?
                Some(&XmlEvent::StartElement {{ ref name, .. }}) => DeserializerNext::Element(name.local_name.to_owned()),
                _ => DeserializerNext::Skip,
            }};

            match next_event {{
                DeserializerNext::Element(name) => {{
                    match &name[..] {{
                        {struct_field_deserializers}
                        _ => skip_tree(stack),
                    }}
                }},
                DeserializerNext::Close => break,
                DeserializerNext::Skip => {{ stack.next(); }},
            }}
        }}

        try!(end_element(tag_name, stack));

        Ok(obj)
        ",
        name = name,
        struct_field_deserializers = generate_struct_field_deserializers(shape),
    )
}

fn generate_struct_field_deserializers(shape: &Shape) -> String {
    shape.members.as_ref().unwrap().iter().map(|(member_name, member)| {
        // look up member.shape in all_shapes.  use that shape.member.location_name
        let location_name = member.location_name.as_ref().unwrap_or(member_name);

        let parse_expression = generate_struct_field_parse_expression(shape, member_name, member, member.location_name.as_ref());
        format!(
            "\"{location_name}\" => {{
                obj.{field_name} = {parse_expression};
            }}",
            field_name = generate_field_name(member_name),
            parse_expression = parse_expression,
            location_name = location_name,
        )

    }).collect::<Vec<String>>().join("\n")
}

fn generate_struct_field_parse_expression(
    shape: &Shape,
    member_name: &str,
    member: &Member,
    location_name: Option<&String>,
) -> String {

    let location_to_use = match location_name {
        Some(loc) => loc.to_string(),
        None => member_name.to_string(),
    };
    let expression = format!(
        "try!({name}Deserializer::deserialize(\"{location}\", stack))",
        name = member.shape,
        location = location_to_use,
    );

    if shape.required(member_name) {
        expression
    } else {
        format!("Some({})", expression)
    }
}

fn generate_serializer_body(name: &str, shape: &Shape) -> Option<String> {
    // Don't need to send "Response" objects, don't make the code for their serializers
    if name.ends_with("Response") {
        return None;
    }
    match shape.shape_type {
        ShapeType::List => Some(generate_list_serializer(shape)),
        ShapeType::Map => Some(generate_map_serializer(shape)),
        ShapeType::Structure => Some(generate_struct_serializer(shape)),
        _ => Some(generate_primitive_serializer(shape)),
    }
}

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(shape: &Shape) -> String {
    format!(
        "for (index, element) in obj.iter().enumerate() {{
    let key = format!(\"{{}}.{{}}\", name, index);
    {name}Serializer::serialize(params, &key, element);
}}
        ",
        name = shape.member(),
    )
}

fn generate_map_serializer(shape: &Shape) -> String {
    format!(
        "for (index, (key, value)) in obj.iter().enumerate() {{
    let prefix = format!(\"{{}}.{{}}\", name, index);
    {key_name}Serializer::serialize(
        params,
        &format!(\"{{}}.{{}}\", prefix, \"{key_name}\"),
        key,
    );
    {value_name}Serializer::serialize(
        params,
        &format!(\"{{}}.{{}}\", prefix, \"{value_name}\"),
        value,
    );
}}
        ",
        key_name = shape.key(),
        value_name = shape.value(),
    )
}

fn generate_struct_serializer(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(shape),
    )
}

fn generate_struct_field_serializers(shape: &Shape) -> String {
    shape.members.as_ref().unwrap().iter().map(|(member_name, member)| {
        if shape.required(member_name) {
            format!(
                "{member_shape_name}Serializer::serialize(
    params,
    &format!(\"{{}}{tag_name}\", prefix),
    &obj.{field_name},
);
                ",
                field_name = generate_field_name(member_name),
                member_shape_name = member.shape,
                tag_name = member_name,
            )
        } else {
            format!(
                "if let Some(ref field_value) = obj.{field_name} {{
    {member_shape_name}Serializer::serialize(
        params,
        &format!(\"{{}}{tag_name}\", prefix),
        field_value,
    );
}}
                ",
                field_name = generate_field_name(member_name),
                member_shape_name = member.shape,
                tag_name = member.location_name.as_ref().unwrap_or(member_name),
            )
        }
    }).collect::<Vec<String>>().join("\n")
}

fn generate_primitive_serializer(shape: &Shape) -> String {
    let expression = match shape.shape_type {
        ShapeType::String | ShapeType::Timestamp => "obj",
        ShapeType::Integer | ShapeType::Long | ShapeType::Float | ShapeType::Double | ShapeType::Boolean => "&obj.to_string()",
        ShapeType::Blob => "from_utf8(obj).unwrap()",
        shape_type => panic!("Unknown primitive shape type: {:?}", shape_type),
    };

    format!("params.put(name, {});", expression)
}
<|endoftext|>


<commit_before><commit_msg>add test to connection<commit_after><|endoftext|>


<commit_before><commit_msg>Add Query, InternalQuery<commit_after>use super::{Text, AllowList, Method};
use crate::scripts::grouping::MultiLangScript;

pub struct Query<'a, 'b> {
    pub(crate) text: &'a str,
    pub(crate) allow_list: &'b AllowList,
    pub(crate) method: Method
}

// TODO: find a better name?
// A query after script detection
pub struct InternalQuery<'a, 'b> {
    pub(crate) text: Text<'a>,
    pub(crate) allow_list: &'b AllowList,
    pub(crate) multi_lang_script: MultiLangScript,
}

impl<'a, 'b> Query<'a, 'b> {
    pub(crate) fn to_internal(&self, multi_lang_script: MultiLangScript) -> InternalQuery<'a, 'b> {
        InternalQuery {
            text: Text::new(self.text),
            allow_list: self.allow_list,
            multi_lang_script,
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add light weight f32 image struct for use by distrib::Master<commit_after>//! Provides a simple RGBA_F32 image, used by the distributed master to store results
//! from the worker processes

use std::iter;

use film::Colorf;

pub struct Image {
    dim: (usize, usize),
    pixels: Vec<Colorf>,
}

impl Image {
    pub fn new(dimensions: (usize, usize)) -> Image {
        let pixels = iter::repeat(Colorf::broadcast(0.0)).take(dimensions.0 * dimensions.1).collect();
        Image { dim: dimensions, pixels: pixels }
    }
    /// Add the floating point RGBA_F32 pixels to the image. It is assumed that `pixels` contains
    /// a `dim.0` by `dim.1` pixel image.
    pub fn add_pixels(&mut self, pixels: &Vec<f32>) {
        for y in 0..self.dim.1 {
            for x in 0..self.dim.0 {
                let mut c = &mut self.pixels[y * self.dim.0 + x];
                let px = y * self.dim.0 * 4 + x * 4;
                for i in 0..4 {
                    c[i] = pixels[px + i];
                }
            }
        }
    }
    /// Convert the Image to sRGB8 format and return it
    pub fn get_srgb8(&self) -> Vec<u8> {
        let mut render: Vec<u8> = iter::repeat(0u8).take(self.dim.0 * self.dim.1 * 3).collect();
        for y in 0..self.dim.1 {
            for x in 0..self.dim.0 {
                let c = &self.pixels[y * self.dim.0 + x];
                if c.a > 0.0 {
                    let cn = (*c / c.a).clamp().to_srgb();
                    let px = y  * self.dim.0 * 3 + x * 3;
                    for i in 0..3 {
                        render[px + i] = (cn[i] * 255.0) as u8;
                    }
                }
            }
        }
        render
    }
    pub fn dimensions(&self) -> (usize, usize) {
        self.dim
    }
}

<|endoftext|>


<commit_before><commit_msg>add `pop_timeout` to the unbounded queues<commit_after><|endoftext|>


<commit_before><commit_msg>Add rust code for rotational-cipher<commit_after>#![feature(ascii_ctype)]
use std::ascii::AsciiExt;

pub fn rotate(text: &str, key: usize) -> String {
    text.chars()
        .map(|x| match x {
            _ if x.is_ascii_lowercase() => {
                let v = (x as u8 - b'a' + key as u8) % 26 + b'a';
                v as char
            }
            _ if x.is_ascii_uppercase() => {
                let v = (x as u8 - b'A' + key as u8) % 26 + b'A';
                v as char
            }
            _ => x,
        })
        .collect()
}
<|endoftext|>


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


<commit_before><commit_msg>Adding tests for updater<commit_after>extern crate teleborg;

#[cfg(test)]
mod tests {
    use teleborg::command_handler;
    use teleborg::updater::Updater;

    #[test]
    fn test_updater() {
        let mut commands = command_handler::CommandHandler::new();
        Updater::start(None, None, None, None, commands);
        Updater::stop();
    }
}
<|endoftext|>


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

extern crate cc;
extern crate build_helper;

use std::process::Command;
use std::env;
use std::path::{PathBuf, Path};

use build_helper::output;

fn detect_llvm_link() -> (&'static str, &'static str) {
    // Force the link mode we want, preferring static by default, but
    // possibly overridden by `configure --enable-llvm-link-shared`.
    if env::var_os("LLVM_LINK_SHARED").is_some() {
        ("dylib", "--link-shared")
    } else {
        ("static", "--link-static")
    }
}

fn main() {
    if env::var_os("RUST_CHECK").is_some() {
        // If we're just running `check`, there's no need for LLVM to be built.
        println!("cargo:rerun-if-env-changed=RUST_CHECK");
        return;
    }

    let target = env::var("TARGET").expect("TARGET was not set");
    let llvm_config = env::var_os("LLVM_CONFIG")
        .map(PathBuf::from)
        .unwrap_or_else(|| {
            if let Some(dir) = env::var_os("CARGO_TARGET_DIR").map(PathBuf::from) {
                let to_test = dir.parent()
                    .unwrap()
                    .parent()
                    .unwrap()
                    .join(&target)
                    .join("llvm/bin/llvm-config");
                if Command::new(&to_test).output().is_ok() {
                    return to_test;
                }
            }
            PathBuf::from("llvm-config")
        });

    println!("cargo:rerun-if-changed={}", llvm_config.display());
    println!("cargo:rerun-if-env-changed=LLVM_CONFIG");

    // Test whether we're cross-compiling LLVM. This is a pretty rare case
    // currently where we're producing an LLVM for a different platform than
    // what this build script is currently running on.
    //
    // In that case, there's no guarantee that we can actually run the target,
    // so the build system works around this by giving us the LLVM_CONFIG for
    // the host platform. This only really works if the host LLVM and target
    // LLVM are compiled the same way, but for us that's typically the case.
    //
    // We *want* detect this cross compiling situation by asking llvm-config
    // what it's host-target is. If that's not the TARGET, then we're cross
    // compiling. Unfortunately `llvm-config` seems either be buggy, or we're
    // misconfiguring it, because the `i686-pc-windows-gnu` build of LLVM will
    // report itself with a `--host-target` of `x86_64-pc-windows-gnu`. This
    // tricks us into thinking we're doing a cross build when we aren't, so
    // havoc ensues.
    //
    // In any case, if we're cross compiling, this generally just means that we
    // can't trust all the output of llvm-config becaues it might be targeted
    // for the host rather than the target. As a result a bunch of blocks below
    // are gated on `if !is_crossed`
    let target = env::var("TARGET").expect("TARGET was not set");
    let host = env::var("HOST").expect("HOST was not set");
    let is_crossed = target != host;

    let mut optional_components =
        vec!["x86", "arm", "aarch64", "mips", "powerpc",
             "systemz", "jsbackend", "webassembly", "msp430", "sparc", "nvptx"];

    let mut version_cmd = Command::new(&llvm_config);
    version_cmd.arg("--version");
    let version_output = output(&mut version_cmd);
    let mut parts = version_output.split('.').take(2)
        .filter_map(|s| s.parse::<u32>().ok());
    let (major, _minor) =
        if let (Some(major), Some(minor)) = (parts.next(), parts.next()) {
            (major, minor)
        } else {
            (3, 9)
        };

    if major > 3 {
        optional_components.push("hexagon");
    }

    if major > 6 {
        optional_components.push("riscv");
    }

    // FIXME: surely we don't need all these components, right? Stuff like mcjit
    //        or interpreter the compiler itself never uses.
    let required_components = &["ipo",
                                "bitreader",
                                "bitwriter",
                                "linker",
                                "asmparser",
                                "mcjit",
                                "lto",
                                "interpreter",
                                "instrumentation"];

    let components = output(Command::new(&llvm_config).arg("--components"));
    let mut components = components.split_whitespace().collect::<Vec<_>>();
    components.retain(|c| optional_components.contains(c) || required_components.contains(c));

    for component in required_components {
        if !components.contains(component) {
            panic!("require llvm component {} but wasn't found", component);
        }
    }

    for component in components.iter() {
        println!("cargo:rustc-cfg=llvm_component=\"{}\"", component);
    }

    // Link in our own LLVM shims, compiled with the same flags as LLVM
    let mut cmd = Command::new(&llvm_config);
    cmd.arg("--cxxflags");
    let cxxflags = output(&mut cmd);
    let mut cfg = cc::Build::new();
    cfg.warnings(false);
    for flag in cxxflags.split_whitespace() {
        // Ignore flags like `-m64` when we're doing a cross build
        if is_crossed && flag.starts_with("-m") {
            continue;
        }

        // -Wdate-time is not supported by the netbsd cross compiler
        if is_crossed && target.contains("netbsd") && flag.contains("date-time") {
            continue;
        }

        cfg.flag(flag);
    }

    for component in &components {
        let mut flag = String::from("LLVM_COMPONENT_");
        flag.push_str(&component.to_uppercase());
        cfg.define(&flag, None);
    }

    println!("cargo:rerun-if-changed-env=LLVM_RUSTLLVM");
    if env::var_os("LLVM_RUSTLLVM").is_some() {
        cfg.define("LLVM_RUSTLLVM", None);
    }

    build_helper::rerun_if_changed_anything_in_dir(Path::new("../rustllvm"));
    cfg.file("../rustllvm/PassWrapper.cpp")
       .file("../rustllvm/RustWrapper.cpp")
       .file("../rustllvm/ArchiveWrapper.cpp")
       .file("../rustllvm/Linker.cpp")
       .cpp(true)
       .cpp_link_stdlib(None) // we handle this below
       .compile("rustllvm");

    let (llvm_kind, llvm_link_arg) = detect_llvm_link();

    // Link in all LLVM libraries, if we're uwring the "wrong" llvm-config then
    // we don't pick up system libs because unfortunately they're for the host
    // of llvm-config, not the target that we're attempting to link.
    let mut cmd = Command::new(&llvm_config);
    cmd.arg(llvm_link_arg).arg("--libs");

    if !is_crossed {
        cmd.arg("--system-libs");
    }
    cmd.args(&components);

    for lib in output(&mut cmd).split_whitespace() {
        let name = if lib.starts_with("-l") {
            &lib[2..]
        } else if lib.starts_with("-") {
            &lib[1..]
        } else if Path::new(lib).exists() {
            // On MSVC llvm-config will print the full name to libraries, but
            // we're only interested in the name part
            let name = Path::new(lib).file_name().unwrap().to_str().unwrap();
            name.trim_right_matches(".lib")
        } else if lib.ends_with(".lib") {
            // Some MSVC libraries just come up with `.lib` tacked on, so chop
            // that off
            lib.trim_right_matches(".lib")
        } else {
            continue;
        };

        // Don't need or want this library, but LLVM's CMake build system
        // doesn't provide a way to disable it, so filter it here even though we
        // may or may not have built it. We don't reference anything from this
        // library and it otherwise may just pull in extra dependencies on
        // libedit which we don't want
        if name == "LLVMLineEditor" {
            continue;
        }

        let kind = if name.starts_with("LLVM") {
            llvm_kind
        } else {
            "dylib"
        };
        println!("cargo:rustc-link-lib={}={}", kind, name);
    }

    // LLVM ldflags
    //
    // If we're a cross-compile of LLVM then unfortunately we can't trust these
    // ldflags (largely where all the LLVM libs are located). Currently just
    // hack around this by replacing the host triple with the target and pray
    // that those -L directories are the same!
    let mut cmd = Command::new(&llvm_config);
    cmd.arg(llvm_link_arg).arg("--ldflags");
    for lib in output(&mut cmd).split_whitespace() {
        if lib.starts_with("-LIBPATH:") {
            println!("cargo:rustc-link-search=native={}", &lib[9..]);
        } else if is_crossed {
            if lib.starts_with("-L") {
                println!("cargo:rustc-link-search=native={}",
                         lib[2..].replace(&host, &target));
            }
        } else if lib.starts_with("-l") {
            println!("cargo:rustc-link-lib={}", &lib[2..]);
        } else if lib.starts_with("-L") {
            println!("cargo:rustc-link-search=native={}", &lib[2..]);
        }
    }

    let llvm_static_stdcpp = env::var_os("LLVM_STATIC_STDCPP");

    let stdcppname = if target.contains("openbsd") {
        // llvm-config on OpenBSD doesn't mention stdlib=libc++
        "c++"
    } else if target.contains("freebsd") {
        "c++"
    } else if target.contains("netbsd") && llvm_static_stdcpp.is_some() {
        // NetBSD uses a separate library when relocation is required
        "stdc++_pic"
    } else {
        "stdc++"
    };

    // C++ runtime library
    if !target.contains("msvc") {
        if let Some(s) = llvm_static_stdcpp {
            assert!(!cxxflags.contains("stdlib=libc++"));
            let path = PathBuf::from(s);
            println!("cargo:rustc-link-search=native={}",
                     path.parent().unwrap().display());
            println!("cargo:rustc-link-lib=static={}", stdcppname);
        } else if cxxflags.contains("stdlib=libc++") {
            println!("cargo:rustc-link-lib=c++");
        } else {
            println!("cargo:rustc-link-lib={}", stdcppname);
        }
    }

    // LLVM requires symbols from this library, but apparently they're not printed
    // during llvm-config?
    if target.contains("windows-gnu") {
        println!("cargo:rustc-link-lib=static-nobundle=gcc_s");
        println!("cargo:rustc-link-lib=static-nobundle=pthread");
        println!("cargo:rustc-link-lib=dylib=uuid");
    }
}
<commit_msg>Actually enable the amdgpu component if present.<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

extern crate cc;
extern crate build_helper;

use std::process::Command;
use std::env;
use std::path::{PathBuf, Path};

use build_helper::output;

fn detect_llvm_link() -> (&'static str, &'static str) {
    // Force the link mode we want, preferring static by default, but
    // possibly overridden by `configure --enable-llvm-link-shared`.
    if env::var_os("LLVM_LINK_SHARED").is_some() {
        ("dylib", "--link-shared")
    } else {
        ("static", "--link-static")
    }
}

fn main() {
    if env::var_os("RUST_CHECK").is_some() {
        // If we're just running `check`, there's no need for LLVM to be built.
        println!("cargo:rerun-if-env-changed=RUST_CHECK");
        return;
    }

    let target = env::var("TARGET").expect("TARGET was not set");
    let llvm_config = env::var_os("LLVM_CONFIG")
        .map(PathBuf::from)
        .unwrap_or_else(|| {
            if let Some(dir) = env::var_os("CARGO_TARGET_DIR").map(PathBuf::from) {
                let to_test = dir.parent()
                    .unwrap()
                    .parent()
                    .unwrap()
                    .join(&target)
                    .join("llvm/bin/llvm-config");
                if Command::new(&to_test).output().is_ok() {
                    return to_test;
                }
            }
            PathBuf::from("llvm-config")
        });

    println!("cargo:rerun-if-changed={}", llvm_config.display());
    println!("cargo:rerun-if-env-changed=LLVM_CONFIG");

    // Test whether we're cross-compiling LLVM. This is a pretty rare case
    // currently where we're producing an LLVM for a different platform than
    // what this build script is currently running on.
    //
    // In that case, there's no guarantee that we can actually run the target,
    // so the build system works around this by giving us the LLVM_CONFIG for
    // the host platform. This only really works if the host LLVM and target
    // LLVM are compiled the same way, but for us that's typically the case.
    //
    // We *want* detect this cross compiling situation by asking llvm-config
    // what it's host-target is. If that's not the TARGET, then we're cross
    // compiling. Unfortunately `llvm-config` seems either be buggy, or we're
    // misconfiguring it, because the `i686-pc-windows-gnu` build of LLVM will
    // report itself with a `--host-target` of `x86_64-pc-windows-gnu`. This
    // tricks us into thinking we're doing a cross build when we aren't, so
    // havoc ensues.
    //
    // In any case, if we're cross compiling, this generally just means that we
    // can't trust all the output of llvm-config becaues it might be targeted
    // for the host rather than the target. As a result a bunch of blocks below
    // are gated on `if !is_crossed`
    let target = env::var("TARGET").expect("TARGET was not set");
    let host = env::var("HOST").expect("HOST was not set");
    let is_crossed = target != host;

    let mut optional_components =
        vec!["x86", "arm", "aarch64", "amdgpu", "mips", "powerpc",
             "systemz", "jsbackend", "webassembly", "msp430", "sparc", "nvptx"];

    let mut version_cmd = Command::new(&llvm_config);
    version_cmd.arg("--version");
    let version_output = output(&mut version_cmd);
    let mut parts = version_output.split('.').take(2)
        .filter_map(|s| s.parse::<u32>().ok());
    let (major, _minor) =
        if let (Some(major), Some(minor)) = (parts.next(), parts.next()) {
            (major, minor)
        } else {
            (3, 9)
        };

    if major > 3 {
        optional_components.push("hexagon");
    }

    if major > 6 {
        optional_components.push("riscv");
    }

    // FIXME: surely we don't need all these components, right? Stuff like mcjit
    //        or interpreter the compiler itself never uses.
    let required_components = &["ipo",
                                "bitreader",
                                "bitwriter",
                                "linker",
                                "asmparser",
                                "mcjit",
                                "lto",
                                "interpreter",
                                "instrumentation"];

    let components = output(Command::new(&llvm_config).arg("--components"));
    let mut components = components.split_whitespace().collect::<Vec<_>>();
    components.retain(|c| optional_components.contains(c) || required_components.contains(c));

    for component in required_components {
        if !components.contains(component) {
            panic!("require llvm component {} but wasn't found", component);
        }
    }

    for component in components.iter() {
        println!("cargo:rustc-cfg=llvm_component=\"{}\"", component);
    }

    // Link in our own LLVM shims, compiled with the same flags as LLVM
    let mut cmd = Command::new(&llvm_config);
    cmd.arg("--cxxflags");
    let cxxflags = output(&mut cmd);
    let mut cfg = cc::Build::new();
    cfg.warnings(false);
    for flag in cxxflags.split_whitespace() {
        // Ignore flags like `-m64` when we're doing a cross build
        if is_crossed && flag.starts_with("-m") {
            continue;
        }

        // -Wdate-time is not supported by the netbsd cross compiler
        if is_crossed && target.contains("netbsd") && flag.contains("date-time") {
            continue;
        }

        cfg.flag(flag);
    }

    for component in &components {
        let mut flag = String::from("LLVM_COMPONENT_");
        flag.push_str(&component.to_uppercase());
        cfg.define(&flag, None);
    }

    println!("cargo:rerun-if-changed-env=LLVM_RUSTLLVM");
    if env::var_os("LLVM_RUSTLLVM").is_some() {
        cfg.define("LLVM_RUSTLLVM", None);
    }

    build_helper::rerun_if_changed_anything_in_dir(Path::new("../rustllvm"));
    cfg.file("../rustllvm/PassWrapper.cpp")
       .file("../rustllvm/RustWrapper.cpp")
       .file("../rustllvm/ArchiveWrapper.cpp")
       .file("../rustllvm/Linker.cpp")
       .cpp(true)
       .cpp_link_stdlib(None) // we handle this below
       .compile("rustllvm");

    let (llvm_kind, llvm_link_arg) = detect_llvm_link();

    // Link in all LLVM libraries, if we're uwring the "wrong" llvm-config then
    // we don't pick up system libs because unfortunately they're for the host
    // of llvm-config, not the target that we're attempting to link.
    let mut cmd = Command::new(&llvm_config);
    cmd.arg(llvm_link_arg).arg("--libs");

    if !is_crossed {
        cmd.arg("--system-libs");
    }
    cmd.args(&components);

    for lib in output(&mut cmd).split_whitespace() {
        let name = if lib.starts_with("-l") {
            &lib[2..]
        } else if lib.starts_with("-") {
            &lib[1..]
        } else if Path::new(lib).exists() {
            // On MSVC llvm-config will print the full name to libraries, but
            // we're only interested in the name part
            let name = Path::new(lib).file_name().unwrap().to_str().unwrap();
            name.trim_right_matches(".lib")
        } else if lib.ends_with(".lib") {
            // Some MSVC libraries just come up with `.lib` tacked on, so chop
            // that off
            lib.trim_right_matches(".lib")
        } else {
            continue;
        };

        // Don't need or want this library, but LLVM's CMake build system
        // doesn't provide a way to disable it, so filter it here even though we
        // may or may not have built it. We don't reference anything from this
        // library and it otherwise may just pull in extra dependencies on
        // libedit which we don't want
        if name == "LLVMLineEditor" {
            continue;
        }

        let kind = if name.starts_with("LLVM") {
            llvm_kind
        } else {
            "dylib"
        };
        println!("cargo:rustc-link-lib={}={}", kind, name);
    }

    // LLVM ldflags
    //
    // If we're a cross-compile of LLVM then unfortunately we can't trust these
    // ldflags (largely where all the LLVM libs are located). Currently just
    // hack around this by replacing the host triple with the target and pray
    // that those -L directories are the same!
    let mut cmd = Command::new(&llvm_config);
    cmd.arg(llvm_link_arg).arg("--ldflags");
    for lib in output(&mut cmd).split_whitespace() {
        if lib.starts_with("-LIBPATH:") {
            println!("cargo:rustc-link-search=native={}", &lib[9..]);
        } else if is_crossed {
            if lib.starts_with("-L") {
                println!("cargo:rustc-link-search=native={}",
                         lib[2..].replace(&host, &target));
            }
        } else if lib.starts_with("-l") {
            println!("cargo:rustc-link-lib={}", &lib[2..]);
        } else if lib.starts_with("-L") {
            println!("cargo:rustc-link-search=native={}", &lib[2..]);
        }
    }

    let llvm_static_stdcpp = env::var_os("LLVM_STATIC_STDCPP");

    let stdcppname = if target.contains("openbsd") {
        // llvm-config on OpenBSD doesn't mention stdlib=libc++
        "c++"
    } else if target.contains("freebsd") {
        "c++"
    } else if target.contains("netbsd") && llvm_static_stdcpp.is_some() {
        // NetBSD uses a separate library when relocation is required
        "stdc++_pic"
    } else {
        "stdc++"
    };

    // C++ runtime library
    if !target.contains("msvc") {
        if let Some(s) = llvm_static_stdcpp {
            assert!(!cxxflags.contains("stdlib=libc++"));
            let path = PathBuf::from(s);
            println!("cargo:rustc-link-search=native={}",
                     path.parent().unwrap().display());
            println!("cargo:rustc-link-lib=static={}", stdcppname);
        } else if cxxflags.contains("stdlib=libc++") {
            println!("cargo:rustc-link-lib=c++");
        } else {
            println!("cargo:rustc-link-lib={}", stdcppname);
        }
    }

    // LLVM requires symbols from this library, but apparently they're not printed
    // during llvm-config?
    if target.contains("windows-gnu") {
        println!("cargo:rustc-link-lib=static-nobundle=gcc_s");
        println!("cargo:rustc-link-lib=static-nobundle=pthread");
        println!("cargo:rustc-link-lib=dylib=uuid");
    }
}
<|endoftext|>