<commit_before>export OSMain;
export Msg, BeginDrawing, Draw, AddKeyHandler, Exit;

import azure::*;
import azure::bindgen::*;
import azure::cairo;
import azure::cairo::bindgen::*;
import comm::*;
import azure::cairo::cairo_surface_t;
import gfx::renderer::{Sink};
import layers::ImageLayer;
import geom::size::Size2D;
import std::cmp::fuzzy_eq;

type OSMain = chan<Msg>;

enum Msg {
    BeginDrawing(chan<AzDrawTargetRef>),
    Draw(chan<AzDrawTargetRef>, AzDrawTargetRef),
    AddKeyHandler(chan<()>),
    Exit
}

fn OSMain() -> OSMain {
    do on_osmain::<Msg> |po| {
        do platform::runmain {
            #debug("preparing to enter main loop");
	        mainloop(po);
        }
    }
}

fn mainloop(po: port<Msg>) {
    let mut key_handlers: [chan<()>] = [];

    glut::init();
    glut::init_display_mode(glut::DOUBLE);

    let surfaces = surface_set();

    let window = glut::create_window("Servo");
    glut::reshape_window(window, 800, 600);

    let context = layers::rendergl::init_render_context();

    let image = @layers::layers::Image(0, 0, layers::layers::RGB24Format, ~[]);
    let image_layer = @layers::layers::ImageLayer(image);
    image_layer.common.set_transform
        (image_layer.common.transform.scale(800.0f32, 600.0f32, 1.0f32));

    let scene = @mut layers::scene::Scene(layers::layers::ImageLayerKind(image_layer),
                                          Size2D(800.0f32, 600.0f32));

    loop {
        do glut::display_func() {
            #debug("osmain: drawing to screen");

            layers::rendergl::render_scene(context, *scene);
            glut::swap_buffers();
            glut::post_redisplay();
        }

        // Handle messages
        if po.peek() {
            alt check po.recv() {
              AddKeyHandler(key_ch) {
                key_handlers += [key_ch];
              }
              BeginDrawing(sender) {
                lend_surface(surfaces, sender);
              }
              Draw(sender, dt) {
                return_surface(surfaces, dt);
                lend_surface(surfaces, sender);
                //assert surfaces.s1.surf.az_target == dt;

                let mut image_data;
                unsafe {
                    let buffer = cairo_image_surface_get_data(surfaces.s1.surf.cairo_surf);
                    image_data = vec::unsafe::from_buf(buffer, 800 * 600 * 4);
                }

                let image =
                    @layers::layers::Image(800, 600, layers::layers::RGB24Format,
                                           layers::util::convert_rgb32_to_rgb24(image_data));
                image_layer.set_image(image);

                glut::post_redisplay();
              }
              exit { break; }
            }
        }

        glut::check_loop();
    }
    destroy_surface(surfaces.s1.surf);
    destroy_surface(surfaces.s2.surf);
}

#[doc = "
Implementation to allow the osmain channel to be used as a graphics
sink for the renderer
"]
impl OSMain of Sink for OSMain {
    fn begin_drawing(next_dt: chan<AzDrawTargetRef>) {
        self.send(BeginDrawing(next_dt))
    }
    fn draw(next_dt: chan<AzDrawTargetRef>, draw_me: AzDrawTargetRef) {
        self.send(Draw(next_dt, draw_me))
    }
}

type surface_set = {
    mut s1: {
        surf: surface,
        have: bool
    },
    mut s2: {
        surf: surface,
        have: bool
    }
};

fn lend_surface(surfaces: surface_set, recvr: chan<AzDrawTargetRef>) {
    // We are in a position to lend out the surface?
    assert surfaces.s1.have;
    // Ok then take it
    let dt1 = surfaces.s1.surf.az_target;
    #debug("osmain: lending surface %?", dt1);
    recvr.send(dt1);
    // Now we don't have it
    surfaces.s1 = {
        have: false
        with surfaces.s1
    };
    // But we (hopefully) have another!
    surfaces.s1 <-> surfaces.s2;
    // Let's look
    assert surfaces.s1.have;
}

fn return_surface(surfaces: surface_set, dt: AzDrawTargetRef) {
    #debug("osmain: returning surface %?", dt);
    // We have room for a return
    assert surfaces.s1.have;
    assert !surfaces.s2.have;
    assert surfaces.s2.surf.az_target == dt;
    // Now we have it again
    surfaces.s2 = {
        have: true
        with surfaces.s2
    };
}

fn surface_set() -> surface_set {
    {
        mut s1: {
            surf: mk_surface(),
            have: true
        },
        mut s2: {
            surf: mk_surface(),
            have: true
        }
    }
}

type surface = {
    cairo_surf: *cairo_surface_t,
    az_target: AzDrawTargetRef
};

fn mk_surface() -> surface {
    let cairo_surf = cairo_image_surface_create(cairo::CAIRO_FORMAT_RGB24, 800, 600);
    assert !ptr::is_null(cairo_surf);

    let azure_target = AzCreateDrawTargetForCairoSurface(cairo_surf);
    assert !ptr::is_null(azure_target);

    {
        cairo_surf: cairo_surf,
        az_target: azure_target
    }
}

fn destroy_surface(surface: surface) {
    AzReleaseDrawTarget(surface.az_target);
    cairo_surface_destroy(surface.cairo_surf);
}

#[doc = "A function for spawning into the platform's main thread"]
fn on_osmain<T: send>(+f: fn~(comm::port<T>)) -> comm::chan<T> {
    let builder = task::builder();
    let opts = {
        sched: some({
            mode: task::osmain,
            foreign_stack_size: none
        })
        with task::get_opts(builder)
    };
    task::set_opts(builder, opts);
    ret task::run_listener(builder, f);
}

// #[cfg(target_os = "linux")]
mod platform {
    fn runmain(f: fn()) {
        f()
    }
}

/*
#[cfg(target_os = "macos")]
mod platform {
    use cocoa;
    import cocoa::base::*;

    mod NSApplication {
        fn sharedApplication() -> id {
            let klass = str::as_c_str("NSApplication", |s| objc::objc_getClass(s));

            let sel = str::as_c_str("sharedApplication", |s| objc::sel_registerName(s));

            let nsapp = objc::objc_msgSend(klass, sel);
            #debug("nsapp: %d", (nsapp as int));

	    ret nsapp;
        }
    }

    mod NSAutoreleasePool {
        fn alloc() -> id {
            let klass = str::as_c_str("NSAutoreleasePool", |s| objc::objc_getClass(s));
            let sel = str::as_c_str("alloc", |s| objc::sel_registerName(s));
            let pool = objc::objc_msgSend(klass, sel);
            #debug("autorelease pool: %?", pool);
            ret pool;
        }
        fn init(pool: id) {
            let sel = str::as_c_str("init", |s| objc::sel_registerName(s));
            objc::objc_msgSend(pool, sel);
        }
        fn release(pool: id) {
            let sel = str::as_c_str("release", |s| objc::sel_registerName(s));
            objc::objc_msgSend(pool, sel);
        }
    }

    mod NSApp {
         fn setDelegate(nsapp: id, main: id) {
	         #debug("NSApp::setDelegate");
	         let sel = str::as_c_str("setDelegate:", |s| objc::sel_registerName(s));
	         cocoa::msgSend1Id(nsapp, sel, main);
         }

        fn run(nsapp: id) {
	        #debug("NSApp::run");
            let sel = str::as_c_str("run", |s| objc::sel_registerName(s));
            objc::objc_msgSend(nsapp, sel);
         }
    }

    mod MainObj {
         extern fn applicationDidFinishLaunching(this: id, _sel: SEL) {
	         #debug("applicationDidFinishLaunching");

	         let fptr: *fn() = ptr::null();
	         str::as_c_str("fptr", |name| {
	             let outValue = unsafe { unsafe::reinterpret_cast(ptr::addr_of(fptr)) };
                 #debug("*fptr %?", outValue);
                 objc::object_getInstanceVariable(this, name, outValue)
             });

	         #debug("getting osmain fptr: %?", fptr);

	         unsafe {
	             // FIXME: We probably don't want to run the main routine in a foreign function
                 (*fptr)();
             }
	     }

    	fn create(f: fn()) -> id {
            let NSObject = str::as_c_str("NSObject", |s| objc::objc_getClass(s));
	        let MainObj = str::as_c_str("MainObj", |s| {
	            objc::objc_allocateClassPair(NSObject, s, 0 as libc::size_t)
	        });

             // Add a field to our class to contain a pointer to a rust closure
	        let res = str::as_c_str("fptr", |name| {
                str::as_c_str("^i", |types| {
                     objc::class_addIvar(MainObj, name,
                                         sys::size_of::<libc::uintptr_t>() as libc::size_t,
                                         16u8, types)
                })
            });
 	        assert res == true;

	        let launchfn = str::as_c_str("applicationDidFinishLaunching:", |s| {
	            objc::sel_registerName(s)
	        });
	        let _ = str::as_c_str("@@:", |types| {
	            objc::class_addMethod(MainObj, launchfn, applicationDidFinishLaunching, types)
	        });

	        objc::objc_registerClassPair(MainObj);

            let sel = str::as_c_str("alloc", |s| objc::sel_registerName(s));
            let mainobj = objc::objc_msgSend(MainObj, sel);

            let sel = str::as_c_str("init", |s| objc::sel_registerName(s));
            objc::objc_msgSend(mainobj, sel);

	        let fptr = ptr::addr_of(f);
	        str::as_c_str("fptr", |name| {
	            #debug("setting osmain fptr: %?", fptr);
		        let value = unsafe { unsafe::reinterpret_cast(fptr) };
                #debug("*fptr: %?", value);
                objc::object_setInstanceVariable(mainobj, name, value)
            });

	        ret mainobj;
	    }
	    fn release(mainobj: id) {
            let sel = str::as_c_str("release", |s| objc::sel_registerName(s));
            objc::objc_msgSend(mainobj, sel);
	    }
    }

    fn runmain(f: fn()) {
	let pool = NSAutoreleasePool::alloc();
	NSAutoreleasePool::init(pool);
        let NSApp = NSApplication::sharedApplication();

        let mainobj = MainObj::create(f);
	NSApp::setDelegate(NSApp, mainobj);
	NSApp::run(NSApp);

	MainObj::release(mainobj);
	NSAutoreleasePool::release(pool);
    }
}
*/

<commit_msg>Delete commented-out code<commit_after>export OSMain;
export Msg, BeginDrawing, Draw, AddKeyHandler, Exit;

import azure::*;
import azure::bindgen::*;
import azure::cairo;
import azure::cairo::bindgen::*;
import comm::*;
import azure::cairo::cairo_surface_t;
import gfx::renderer::{Sink};
import layers::ImageLayer;
import geom::size::Size2D;
import std::cmp::fuzzy_eq;

type OSMain = chan<Msg>;

enum Msg {
    BeginDrawing(chan<AzDrawTargetRef>),
    Draw(chan<AzDrawTargetRef>, AzDrawTargetRef),
    AddKeyHandler(chan<()>),
    Exit
}

fn OSMain() -> OSMain {
    do on_osmain::<Msg> |po| {
        do platform::runmain {
            #debug("preparing to enter main loop");
	        mainloop(po);
        }
    }
}

fn mainloop(po: port<Msg>) {
    let mut key_handlers: [chan<()>] = [];

    glut::init();
    glut::init_display_mode(glut::DOUBLE);

    let surfaces = surface_set();

    let window = glut::create_window("Servo");
    glut::reshape_window(window, 800, 600);

    let context = layers::rendergl::init_render_context();

    let image = @layers::layers::Image(0, 0, layers::layers::RGB24Format, ~[]);
    let image_layer = @layers::layers::ImageLayer(image);
    image_layer.common.set_transform
        (image_layer.common.transform.scale(800.0f32, 600.0f32, 1.0f32));

    let scene = @mut layers::scene::Scene(layers::layers::ImageLayerKind(image_layer),
                                          Size2D(800.0f32, 600.0f32));

    loop {
        do glut::display_func() {
            #debug("osmain: drawing to screen");

            layers::rendergl::render_scene(context, *scene);
            glut::swap_buffers();
            glut::post_redisplay();
        }

        // Handle messages
        if po.peek() {
            alt check po.recv() {
              AddKeyHandler(key_ch) {
                key_handlers += [key_ch];
              }
              BeginDrawing(sender) {
                lend_surface(surfaces, sender);
              }
              Draw(sender, dt) {
                return_surface(surfaces, dt);
                lend_surface(surfaces, sender);

                let mut image_data;
                unsafe {
                    let buffer = cairo_image_surface_get_data(surfaces.s1.surf.cairo_surf);
                    image_data = vec::unsafe::from_buf(buffer, 800 * 600 * 4);
                }

                let image =
                    @layers::layers::Image(800, 600, layers::layers::RGB24Format,
                                           layers::util::convert_rgb32_to_rgb24(image_data));
                image_layer.set_image(image);

                glut::post_redisplay();
              }
              exit { break; }
            }
        }

        glut::check_loop();
    }
    destroy_surface(surfaces.s1.surf);
    destroy_surface(surfaces.s2.surf);
}

#[doc = "
Implementation to allow the osmain channel to be used as a graphics
sink for the renderer
"]
impl OSMain of Sink for OSMain {
    fn begin_drawing(next_dt: chan<AzDrawTargetRef>) {
        self.send(BeginDrawing(next_dt))
    }
    fn draw(next_dt: chan<AzDrawTargetRef>, draw_me: AzDrawTargetRef) {
        self.send(Draw(next_dt, draw_me))
    }
}

type surface_set = {
    mut s1: {
        surf: surface,
        have: bool
    },
    mut s2: {
        surf: surface,
        have: bool
    }
};

fn lend_surface(surfaces: surface_set, recvr: chan<AzDrawTargetRef>) {
    // We are in a position to lend out the surface?
    assert surfaces.s1.have;
    // Ok then take it
    let dt1 = surfaces.s1.surf.az_target;
    #debug("osmain: lending surface %?", dt1);
    recvr.send(dt1);
    // Now we don't have it
    surfaces.s1 = {
        have: false
        with surfaces.s1
    };
    // But we (hopefully) have another!
    surfaces.s1 <-> surfaces.s2;
    // Let's look
    assert surfaces.s1.have;
}

fn return_surface(surfaces: surface_set, dt: AzDrawTargetRef) {
    #debug("osmain: returning surface %?", dt);
    // We have room for a return
    assert surfaces.s1.have;
    assert !surfaces.s2.have;
    assert surfaces.s2.surf.az_target == dt;
    // Now we have it again
    surfaces.s2 = {
        have: true
        with surfaces.s2
    };
}

fn surface_set() -> surface_set {
    {
        mut s1: {
            surf: mk_surface(),
            have: true
        },
        mut s2: {
            surf: mk_surface(),
            have: true
        }
    }
}

type surface = {
    cairo_surf: *cairo_surface_t,
    az_target: AzDrawTargetRef
};

fn mk_surface() -> surface {
    let cairo_surf = cairo_image_surface_create(cairo::CAIRO_FORMAT_RGB24, 800, 600);
    assert !ptr::is_null(cairo_surf);

    let azure_target = AzCreateDrawTargetForCairoSurface(cairo_surf);
    assert !ptr::is_null(azure_target);

    {
        cairo_surf: cairo_surf,
        az_target: azure_target
    }
}

fn destroy_surface(surface: surface) {
    AzReleaseDrawTarget(surface.az_target);
    cairo_surface_destroy(surface.cairo_surf);
}

#[doc = "A function for spawning into the platform's main thread"]
fn on_osmain<T: send>(+f: fn~(comm::port<T>)) -> comm::chan<T> {
    let builder = task::builder();
    let opts = {
        sched: some({
            mode: task::osmain,
            foreign_stack_size: none
        })
        with task::get_opts(builder)
    };
    task::set_opts(builder, opts);
    ret task::run_listener(builder, f);
}

// #[cfg(target_os = "linux")]
mod platform {
    fn runmain(f: fn()) {
        f()
    }
}

<|endoftext|>


<commit_before><commit_msg>languages/rust/learn-rust/1-chapter/0-code.rs<commit_after><|endoftext|>


<commit_before><commit_msg>chore: generator<commit_after><|endoftext|>


<commit_before><commit_msg>Dump the presentation mode values alongside their string representations<commit_after><|endoftext|>


<commit_before><commit_msg>WIP: Add an xfailed test for bind-by-move (#2329)<commit_after>// xfail-test
use std;
import std::arc;
fn dispose(+_x: arc::arc<bool>) unsafe { }

fn main() {
    let p = arc::arc(true);
    let x = some(p);
    match move x {
        some(move z) => { dispose(z); },
        none => fail
    }
}
<|endoftext|>


<commit_before><commit_msg>test: Add a crust function stress test<commit_after>// This creates a bunch of yielding tasks that run concurrently
// while holding onto C stacks

native mod rustrt {
    fn rust_dbg_call(cb: *u8,
                     data: ctypes::uintptr_t) -> ctypes::uintptr_t;
}

crust fn cb(data: ctypes::uintptr_t) -> ctypes::uintptr_t {
    if data == 1u {
        data
    } else {
        task::yield();
        count(data - 1u) + count(data - 1u)
    }
}

fn count(n: uint) -> uint {
    rustrt::rust_dbg_call(cb, n)
}

fn main() {
    iter::repeat(100u) {||
        task::spawn {||
            count(5u);
        };
    }
}<|endoftext|>


<commit_before><commit_msg>Add more context in error messages<commit_after><|endoftext|>


<commit_before><commit_msg>Add the facility to disassemble SPIR-V prior to and after running the optimiser<commit_after><|endoftext|>


<commit_before><commit_msg>Add example for embedded named R function call.<commit_after>extern crate libc;
extern crate libr;
use libc::c_int;
use std::ptr;
use std::env;
use std::ffi::{CStr, CString};

use libr::ffi::internals::*;
use libr::ffi::embedded::{self, Rf_endEmbeddedR, Rf_initEmbeddedR};

unsafe fn source(path: *const ::libc::c_char) {
    let mut e: SEXP = Rf_lang2(Rf_install(CString::new("source").unwrap().into_raw()),
                               Rf_mkString(path));
    Rf_protect(e);
    R_tryEval(e, R_GlobalEnv, ptr::null_mut::<libc::c_int>());
    Rf_unprotect(1);
}

fn main() {
    if let Err(_) = env::var("R_HOME") {
        panic!("Rembedded test need R_HOME be setted");
    }

    let mut s = Box::new(vec![CString::new("R").unwrap().into_raw(),
                              CString::new("--quiet").unwrap().into_raw(),
                              CString::new("--no-save").unwrap().into_raw()]);
    unsafe {
        embedded::Rf_initEmbeddedR(s.len() as i32, s.as_mut_ptr());
        source(CString::new("foo.R").unwrap().into_raw());
        embedded::Rf_endEmbeddedR(0);
    }
}
<|endoftext|>


<commit_before><commit_msg>add test for https://github.com/rust-lang/miri/issues/2068<commit_after>#![feature(pin_macro)]

use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};

use std::sync::Arc;

struct NopWaker;

impl std::task::Wake for NopWaker {
    fn wake(self: Arc<Self>) {}
}

pub fn fuzzing_block_on<O, F: Future<Output = O>>(fut: F) -> O {
    let mut fut = std::pin::pin!(fut);
    let waker = std::task::Waker::from(Arc::new(NopWaker));
    let mut context = std::task::Context::from_waker(&waker);
    loop {
        match fut.as_mut().poll(&mut context) {
            Poll::Ready(v) => return v,
            Poll::Pending => {}
        }
    }
}

pub struct LastFuture<S> {
    last: S,
}

impl<S> Future for LastFuture<S>
where
    Self: Unpin,
    S: Unpin + Copy,
{
    type Output = S;

    fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
        return Poll::Ready(self.last);
    }
}

fn main() {
    fuzzing_block_on(async {
        LastFuture { last: &0u32 }.await;
        LastFuture { last: Option::<u32>::None }.await;
    });
}
<|endoftext|>


<commit_before><commit_msg>Added lights::get_light(id) function that wraps the /lights/id call.<commit_after><|endoftext|>


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

use platform::{self, OsIpcReceiver, OsIpcSender};

use serde::json;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::cell::RefCell;
use std::marker::PhantomData;
use std::mem;

thread_local! {
    static OS_IPC_SENDERS_FOR_DESERIALIZATION: RefCell<Vec<OsIpcSender>> = RefCell::new(Vec::new())
}
thread_local! {
    static OS_IPC_SENDERS_FOR_SERIALIZATION: RefCell<Vec<OsIpcSender>> = RefCell::new(Vec::new())
}

pub fn channel<T>() -> Result<(IpcSender<T>, IpcReceiver<T>),()> where T: Deserialize + Serialize {
    let (os_sender, os_receiver) = match platform::channel() {
        Ok((os_sender, os_receiver)) => (os_sender, os_receiver),
        Err(_) => return Err(()),
    };
    let ipc_receiver = IpcReceiver {
        os_receiver: os_receiver,
        phantom: PhantomData,
    };
    let ipc_sender = IpcSender {
        os_sender: os_sender,
        phantom: PhantomData,
    };
    Ok((ipc_sender, ipc_receiver))
}

pub struct IpcReceiver<T> where T: Deserialize + Serialize {
    os_receiver: OsIpcReceiver,
    phantom: PhantomData<T>,
}

impl<T> IpcReceiver<T> where T: Deserialize + Serialize {
    pub fn recv(&self) -> Result<T,()> {
        let (data, mut os_ipc_senders) = match self.os_receiver.recv() {
            Ok((data, os_ipc_senders)) => (data, os_ipc_senders),
            Err(_) => return Err(()),
        };
        OS_IPC_SENDERS_FOR_DESERIALIZATION.with(|os_ipc_senders_for_deserialization| {
            mem::swap(&mut *os_ipc_senders_for_deserialization.borrow_mut(), &mut os_ipc_senders);
            let mut deserializer = match json::Deserializer::new(data.iter()
                                                                     .map(|byte| Ok(*byte))) {
                Ok(deserializer) => deserializer,
                Err(_) => return Err(()),
            };
            let result = match Deserialize::deserialize(&mut deserializer) {
                Ok(result) => result,
                Err(_) => return Err(()),
            };
            mem::swap(&mut *os_ipc_senders_for_deserialization.borrow_mut(), &mut os_ipc_senders);
            Ok(result)
        })
    }

    pub fn register_global_name(&self) -> Result<String,()> {
        self.os_receiver.register_global_name().map_err(|_| ())
    }

    pub fn unregister_global_name(name: String) -> Result<(),()> {
        OsIpcReceiver::unregister_global_name(name).map_err(|_| ())
    }
}

#[derive(Clone)]
pub struct IpcSender<T> where T: Serialize {
    os_sender: OsIpcSender,
    phantom: PhantomData<T>,
}

impl<T> IpcSender<T> where T: Serialize {
    pub fn from_global_name(name: String) -> Result<IpcSender<T>,()> {
        let os_sender = match OsIpcSender::from_global_name(name) {
            Ok(os_sender) => os_sender,
            Err(_) => return Err(()),
        };
        Ok(IpcSender {
            os_sender: os_sender,
            phantom: PhantomData,
        })
    }

    pub fn send(&self, data: T) -> Result<(),()> {
        let mut bytes = Vec::with_capacity(4096);
        OS_IPC_SENDERS_FOR_SERIALIZATION.with(|os_ipc_senders_for_serialization| {
            let old_os_ipc_senders =
                mem::replace(&mut *os_ipc_senders_for_serialization.borrow_mut(), Vec::new());
            let os_ipc_senders = {
                let mut serializer = json::Serializer::new(&mut bytes);
                data.serialize(&mut serializer).unwrap();
                mem::replace(&mut *os_ipc_senders_for_serialization.borrow_mut(),
                             old_os_ipc_senders)
            };
            self.os_sender.send(&bytes[..], os_ipc_senders).map_err(|_| ())
        })
    }
}

impl<T> Deserialize for IpcSender<T> where T: Serialize {
    fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error> where D: Deserializer {
        let index: usize = try!(Deserialize::deserialize(deserializer));
        let os_sender =
            OS_IPC_SENDERS_FOR_DESERIALIZATION.with(|os_ipc_senders_for_deserialization| {
                // FIXME(pcwalton): This could panic. Return some sort of nice error.
                os_ipc_senders_for_deserialization.borrow_mut()[index].clone()
            });
        Ok(IpcSender {
            os_sender: os_sender,
            phantom: PhantomData,
        })
    }
}

impl<T> Serialize for IpcSender<T> where T: Serialize {
    fn serialize<S>(&self, serializer: &mut S) -> Result<(),S::Error> where S: Serializer {
        let index = OS_IPC_SENDERS_FOR_SERIALIZATION.with(|os_ipc_senders_for_serialization| {
            let mut os_ipc_senders_for_serialization =
                os_ipc_senders_for_serialization.borrow_mut();
            let index = os_ipc_senders_for_serialization.len();
            os_ipc_senders_for_serialization.push(self.os_sender.clone());
            index
        });
        index.serialize(serializer)
    }
}

<|endoftext|>


<commit_before><commit_msg>Starting an optimized line intersection function algorithm<commit_after>extern crate polydraw;

use polydraw::geom::point::Point;
use polydraw::geom::ring::Ring;

fn h_intersect_line(p1: Point, p2: Point, step: i64, inters: &mut Ring<i64>)  {
}

fn main() {
   let mut inters = Ring::new(10000);
   let p1 = Point::new(2135, 2476);
   let p2 = Point::new(16753, 12398);
   h_intersect_line(p1, p2, 1000, &mut inters);
}

<|endoftext|>


<commit_before><commit_msg>forever loop guess<commit_after>extern crate rand;

use std::io;
use std::cmp::Ordering;
use rand::Rng;

fn main() {
    println!("Guess the number!");
    let secret_number = rand::thread_rng().gen_range(1, 101);

    println!("The secret number is : {}", secret_number);

    loop{

        println!("Please input your guess:");

    let mut guess = String::new();

    io::stdin().read_line(&mut guess)
        .expect("Failed to read line");

    let guess: u32 = guess.trim().parse()
        .expect("Please type a number");

    println!("You have guessed : {}", guess);

    match guess.cmp(&secret_number) {
        Ordering::Less => println!("Too small!"),
        Ordering::Greater => println!("Too big!"),
        Ordering::Equal => println!("You win!"),

    }

        }

}
<|endoftext|>


<commit_before><commit_msg>Adding BMPDecoder trait.<commit_after><|endoftext|>


<commit_before><commit_msg>Update docs<commit_after><|endoftext|>


<commit_before><commit_msg>Buildable trait update<commit_after><|endoftext|>


<commit_before>#[test]
fn it_works() {
}
<commit_msg>Implement rough block splitting<commit_after>#![feature(phase)]
#[phase(plugin)]
extern crate regex_macros;
extern crate regex;
use regex::Regex;

static SPLIT : Regex = regex!("(\\{%.*?%\\})|(\\{\\{.*?\\}\\})");

fn split_blocks(text: &str) -> Vec<String>{
    let mut tokens = vec![];
    let mut current = 0;
    for (begin, end) in SPLIT.find_iter(text) {
        match text.slice(current, begin){
            "" => {}
            t => tokens.push(t.to_string())
        };
        tokens.push(text.slice(begin, end).to_string());
        current = end;
    }
    match text.slice(current, text.len()){
        "" => {}
        t => tokens.push(t.to_string())
    };
    tokens
}

#[test]
fn test_split_blocks() {
    assert_eq!(split_blocks("asdlkjfn\n{{askdljfbalkjsdbf}} asdjlfb"),
                vec!["asdlkjfn\n".to_string(), "{{askdljfbalkjsdbf}}".to_string(), " asdjlfb".to_string()]);
}
<|endoftext|>


<commit_before><commit_msg>cfg update<commit_after><|endoftext|>


<commit_before>use self::grammar::job_list;

#[derive(Debug, PartialEq)]
pub struct Job {
    pub command: String,
    pub args: Vec<String>,
}

impl Job {
    fn new(command: String, args: Vec<String>) -> Job {
        Job {
            command: command,
            args: args,
        }
    }
}

pub fn parse(code: &str) -> Vec<Job> {
    job_list(code).unwrap()  // TODO don't unwrap, handle parse error
}

peg! grammar(r#"
use super::Job;

#[pub]
job_list -> Vec<Job>
    = jobs:job ++ job_ending { jobs }
    / blank_line ** job_ending { vec![] }

job -> Job
    = res:_job whitespace? comment? { res }

_job -> Job
    = args:word ++ whitespace { let mut args = args.clone(); Job::new(args.remove(0), args) }

word -> String
    = double_quoted_word
    / single_quoted_word
    / [^ \t\r\n#;]+ { match_str.to_string() }

double_quoted_word -> String
    = ["] word:_double_quoted_word ["] { word }

_double_quoted_word -> String
    = [^"]+ { match_str.to_string() }

single_quoted_word -> String
    = ['] word:_single_quoted_word ['] { word }

_single_quoted_word -> String
    = [^']+ { match_str.to_string() }

blank_line -> ()
    = whitespace comment? { () }
    / comment

comment -> ()
    = [#] [^\r\n]*

whitespace -> ()
    = [ \t]+

job_ending -> ()
    = [;]
    / newline ** (blank_line*)
    / newline

newline -> ()
    = [\r\n]
"#);

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

    #[test]
    fn single_job_no_args() {
        let jobs = job_list("cat").unwrap();
        assert_eq!(1, jobs.len());
        assert_eq!("cat", jobs[0].command);
        assert_eq!(0, jobs[0].args.len());
    }

    #[test]
    fn single_job_with_args() {
        let jobs = job_list("ls -al dir").unwrap();
        assert_eq!(1, jobs.len());
        assert_eq!("ls", jobs[0].command);
        assert_eq!("-al", jobs[0].args[0]);
        assert_eq!("dir", jobs[0].args[1]);
    }

    #[test]
    fn multiple_jobs_with_args() {
        let jobs = job_list("ls -al;cat tmp.txt").unwrap();
        assert_eq!(2, jobs.len());
        assert_eq!("ls", jobs[0].command);
        assert_eq!("-al", jobs[0].args[0]);
        assert_eq!("cat", jobs[1].command);
        assert_eq!("tmp.txt", jobs[1].args[0]);
    }

    #[test]
    fn parse_empty_string() {
        let jobs = job_list("").unwrap();
        assert_eq!(0, jobs.len());
    }

    #[test]
    fn multiple_white_space_between_words() {
        let jobs = job_list("ls \t -al\t\tdir").unwrap();
        assert_eq!(1, jobs.len());
        assert_eq!("ls", jobs[0].command);
        assert_eq!("-al", jobs[0].args[0]);
        assert_eq!("dir", jobs[0].args[1]);
    }

    #[test]
    fn trailing_whitespace() {
        let jobs = job_list("ls -al\t ").unwrap();
        assert_eq!(1, jobs.len());
        assert_eq!("ls", jobs[0].command);
        assert_eq!("-al", jobs[0].args[0]);
    }

    #[test]
    fn double_quoting() {
        let jobs = job_list("echo \"Hello World\"").unwrap();
        assert_eq!(1, jobs[0].args.len());
        assert_eq!("Hello World", jobs[0].args[0]);
    }

    #[test]
    fn all_whitespace() {
        let jobs = job_list("  \t ").unwrap();
        assert_eq!(0, jobs.len());
    }

    #[test]
    fn lone_comment() {
        let jobs = job_list("# ; \t as!!+dfa").unwrap();
        assert_eq!(0, jobs.len());
    }

    #[test]
    fn command_followed_by_comment() {
        let jobs = job_list("cat # ; \t as!!+dfa").unwrap();
        assert_eq!(1, jobs.len());
        assert_eq!(0, jobs[0].args.len());
    }

    //#[test]
    //fn comments_in_multiline_script() {
    //    let jobs = job_list("echo\n# a comment;\necho#asfasdf").unwrap();
    //    assert_eq!(2, jobs.len());
    //}

    #[test]
    fn multiple_newlines() {
        let jobs = job_list("echo\n\ncat").unwrap();
        assert_eq!(2, jobs.len());
    }

    #[test]
    fn leading_whitespace() {
        let jobs = job_list("    \techo").unwrap();
        assert_eq!(1, jobs.len());
        assert_eq!("echo", jobs[0].command);
    }

    #[test]
    fn indentation_on_multiple_lines() {
        let jobs = job_list("echo\n  cat").unwrap();
        assert_eq!(2, jobs.len());
        assert_eq!("echo", jobs[0].command);
        assert_eq!("cat", jobs[1].command);
    }

    #[test]
    fn single_quoting() {
        let jobs = job_list("echo '#!!;\"\\'").unwrap();
        assert_eq!("#!!;\"\\", jobs[0].args[0]);
    }

    #[test]
    fn mixed_quoted_and_unquoted() {
        let jobs = job_list("echo '#!!;\"\\' and \t some \"more' 'stuff\"").unwrap();
        assert_eq!("#!!;\"\\", jobs[0].args[0]);
        assert_eq!("and", jobs[0].args[1]);
        assert_eq!("some", jobs[0].args[2]);
        assert_eq!("more' 'stuff", jobs[0].args[3]);
    }
}
<commit_msg>Add base case for testing<commit_after>use self::grammar::job_list;

#[derive(Debug, PartialEq)]
pub struct Job {
    pub command: String,
    pub args: Vec<String>,
}

impl Job {
    fn new(command: String, args: Vec<String>) -> Job {
        Job {
            command: command,
            args: args,
        }
    }
}

pub fn parse(code: &str) -> Vec<Job> {
    job_list(code).unwrap()  // TODO don't unwrap, handle parse error
}

peg! grammar(r#"
use super::Job;

#[pub]
job_list -> Vec<Job>
    = jobs:job ++ job_ending { jobs }
    / blank_line ** job_ending { vec![] }
    / .* { vec![] }

job -> Job
    = res:_job whitespace? comment? { res }

_job -> Job
    = args:word ++ whitespace { let mut args = args.clone(); Job::new(args.remove(0), args) }

word -> String
    = double_quoted_word
    / single_quoted_word
    / [^ \t\r\n#;]+ { match_str.to_string() }

double_quoted_word -> String
    = ["] word:_double_quoted_word ["] { word }

_double_quoted_word -> String
    = [^"]+ { match_str.to_string() }

single_quoted_word -> String
    = ['] word:_single_quoted_word ['] { word }

_single_quoted_word -> String
    = [^']+ { match_str.to_string() }

blank_line -> ()
    = whitespace comment? { () }
    / comment

comment -> ()
    = [#] [^\r\n]*

whitespace -> ()
    = [ \t]+

job_ending -> ()
    = [;]
    / newline ** (blank_line*)
    / newline

newline -> ()
    = [\r\n]
"#);

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

    #[test]
    fn single_job_no_args() {
        let jobs = job_list("cat").unwrap();
        assert_eq!(1, jobs.len());
        assert_eq!("cat", jobs[0].command);
        assert_eq!(0, jobs[0].args.len());
    }

    #[test]
    fn single_job_with_args() {
        let jobs = job_list("ls -al dir").unwrap();
        assert_eq!(1, jobs.len());
        assert_eq!("ls", jobs[0].command);
        assert_eq!("-al", jobs[0].args[0]);
        assert_eq!("dir", jobs[0].args[1]);
    }

    #[test]
    fn multiple_jobs_with_args() {
        let jobs = job_list("ls -al;cat tmp.txt").unwrap();
        assert_eq!(2, jobs.len());
        assert_eq!("ls", jobs[0].command);
        assert_eq!("-al", jobs[0].args[0]);
        assert_eq!("cat", jobs[1].command);
        assert_eq!("tmp.txt", jobs[1].args[0]);
    }

    #[test]
    fn parse_empty_string() {
        let jobs = job_list("").unwrap();
        assert_eq!(0, jobs.len());
    }

    #[test]
    fn multiple_white_space_between_words() {
        let jobs = job_list("ls \t -al\t\tdir").unwrap();
        assert_eq!(1, jobs.len());
        assert_eq!("ls", jobs[0].command);
        assert_eq!("-al", jobs[0].args[0]);
        assert_eq!("dir", jobs[0].args[1]);
    }

    #[test]
    fn trailing_whitespace() {
        let jobs = job_list("ls -al\t ").unwrap();
        assert_eq!(1, jobs.len());
        assert_eq!("ls", jobs[0].command);
        assert_eq!("-al", jobs[0].args[0]);
    }

    #[test]
    fn double_quoting() {
        let jobs = job_list("echo \"Hello World\"").unwrap();
        assert_eq!(1, jobs[0].args.len());
        assert_eq!("Hello World", jobs[0].args[0]);
    }

    #[test]
    fn all_whitespace() {
        let jobs = job_list("  \t ").unwrap();
        assert_eq!(0, jobs.len());
    }

    #[test]
    fn lone_comment() {
        let jobs = job_list("# ; \t as!!+dfa").unwrap();
        assert_eq!(0, jobs.len());
    }

    #[test]
    fn command_followed_by_comment() {
        let jobs = job_list("cat # ; \t as!!+dfa").unwrap();
        assert_eq!(1, jobs.len());
        assert_eq!(0, jobs[0].args.len());
    }

    //#[test]
    //fn comments_in_multiline_script() {
    //    let jobs = job_list("echo\n# a comment;\necho#asfasdf").unwrap();
    //    assert_eq!(2, jobs.len());
    //}

    #[test]
    fn multiple_newlines() {
        let jobs = job_list("echo\n\ncat").unwrap();
        assert_eq!(2, jobs.len());
    }

    #[test]
    fn leading_whitespace() {
        let jobs = job_list("    \techo").unwrap();
        assert_eq!(1, jobs.len());
        assert_eq!("echo", jobs[0].command);
    }

    #[test]
    fn indentation_on_multiple_lines() {
        let jobs = job_list("echo\n  cat").unwrap();
        assert_eq!(2, jobs.len());
        assert_eq!("echo", jobs[0].command);
        assert_eq!("cat", jobs[1].command);
    }

    #[test]
    fn single_quoting() {
        let jobs = job_list("echo '#!!;\"\\'").unwrap();
        assert_eq!("#!!;\"\\", jobs[0].args[0]);
    }

    #[test]
    fn mixed_quoted_and_unquoted() {
        let jobs = job_list("echo '#!!;\"\\' and \t some \"more' 'stuff\"").unwrap();
        assert_eq!("#!!;\"\\", jobs[0].args[0]);
        assert_eq!("and", jobs[0].args[1]);
        assert_eq!("some", jobs[0].args[2]);
        assert_eq!("more' 'stuff", jobs[0].args[3]);
    }
}
<|endoftext|>


<commit_before><commit_msg>Added shootout benchmark<commit_after>// The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers

// Copyright (c) 2013-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in
//   the documentation and/or other materials provided with the
//   distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
//   the name of "The Computer Language Shootout Benchmarks" nor the
//   names of its contributors may be used to endorse or promote
//   products derived from this software without specific prior
//   written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.

extern crate num;
extern crate test;

use std::from_str::FromStr;
use std::num::One;
use std::num::Zero;
use std::num::FromPrimitive;

use test::Bencher;

use num::Integer;
use num::bigint::BigInt;

struct Context {
    numer: BigInt,
    accum: BigInt,
    denom: BigInt,
}

impl Context {
    fn new() -> Context {
        Context {
            numer: One::one(),
            accum: Zero::zero(),
            denom: One::one(),
        }
    }

    fn from_int(i: int) -> BigInt {
        FromPrimitive::from_int(i).unwrap()
    }

    fn extract_digit(&self) -> int {
        if self.numer > self.accum {return -1;}
        let (q, r) =
            (self.numer * Context::from_int(3) + self.accum)
            .div_rem(&self.denom);
        if r + self.numer >= self.denom {return -1;}
        q.to_int().unwrap()
    }

    fn next_term(&mut self, k: int) {
        let y2 = Context::from_int(k * 2 + 1);
        self.accum = (self.accum + (self.numer << 1)) * y2;
        self.numer = self.numer * Context::from_int(k);
        self.denom = self.denom * y2;
    }

    fn eliminate_digit(&mut self, d: int) {
        let d = Context::from_int(d);
        let ten = Context::from_int(10);
        self.accum = (self.accum - self.denom * d) * ten;
        self.numer = self.numer * ten;
    }
}

fn pidigits(n: int) {
    let mut k = 0;
    let mut context = Context::new();

    for i in range(1, n + 1) {
        let mut d;
        loop {
            k += 1;
            context.next_term(k);
            d = context.extract_digit();
            if d != -1 {break;}
        }

        print!("{}", d);
        if i % 10 == 0 {print!("\t:{}\n", i);}

        context.eliminate_digit(d);
    }

    let m = n % 10;
    if m != 0 {
        for _ in range(m, 10) { print!(" "); }
        print!("\t:{}\n", n);
    }
}

static DEFAULT_DIGITS: int = 512;

#[bench]
fn use_bencher(b: &mut Bencher) {
    b.iter(|| pidigits(DEFAULT_DIGITS))
}

fn main() {
    let args = std::os::args();
    let args = args.as_slice();
    let n = if args.len() < 2 {
        DEFAULT_DIGITS
    } else {
        FromStr::from_str(args[1].as_slice()).unwrap()
    };
    pidigits(n);
}
<|endoftext|>


<commit_before><commit_msg>Complete implementation of ToRGB for HSV<commit_after><|endoftext|>


<commit_before><commit_msg>Add test case for issue #333. Closes #333<commit_after>fn quux[T](&T x) -> T{
  auto f = id[T];
  ret f(x);
}

fn id[T](&T x) -> T {
  ret x;
}

fn main() {
  assert quux(10) == 10;
}<|endoftext|>


<commit_before>extern crate ws;
extern crate serde;
extern crate serde_json;

use serde_json::Value;
use serde_json::value::Map;

struct BenchHandler {
    ws: ws::Sender,
    count: u32
}

impl ws::Handler for BenchHandler {
    fn on_message(&mut self, msg: ws::Message) -> ws::Result<()> {
        if let Some((Some(msg_type), payload)) = msg.into_text().ok()
            .map(|v| v.as_str().to_owned())
            .and_then(|body: String| serde_json::from_str(body.as_str()).ok())
            .and_then(|j: Value| j.as_object().map(move |obj: &Map<String, Value>| {
                let t = obj.get("type").and_then(|t| t.as_str()).map(|s| s.to_owned());
                let p: Value = obj.get("payload").unwrap_or(&Value::Null).clone();
                (t, p)
            })) {
                match msg_type.as_ref() {
                    "echo" => {
                        try!(self.ws.send(format!("{}", payload)));
                    },
                    "broadcast" => {
                        try!(self.ws.broadcast(format!("{}", payload)));
                        try!(self.ws.send(format!("{{\"type\": \"broadcastResult\", \"listenCount\": {}, \"payload\": {}}}", self.count, payload)))
                    },
                    _ => {}
                };
            };
        Ok(())
    }

    fn on_open(&mut self, _: ws::Handshake) -> ws::Result<()> {
        self.count += 1;
        println!("Connection Open! {}", self.count);
        Ok(())
    }

    fn on_close(&mut self,_: ws::CloseCode, _: &str) {
        self.count -= 1;
        println!("Connection Closed! {}", self.count);
    }
}

fn main() {
    if let Err(error) = ws::listen("127.0.0.1:3012", |out| {
        BenchHandler { ws: out, count: 0 }
    }) {
        println!("Failed to create WebSocket due to {:?}", error);
    }
}
<commit_msg>Add argument parsing<commit_after>extern crate ws;
extern crate clap;
extern crate serde;
extern crate serde_json;

use serde_json::Value;
use serde_json::value::Map;

use clap::{App, Arg};

struct BenchHandler {
    ws: ws::Sender,
    count: u32
}

impl ws::Handler for BenchHandler {
    fn on_message(&mut self, msg: ws::Message) -> ws::Result<()> {
        if let Some((Some(msg_type), payload)) = msg.into_text().ok()
            .map(|v| v.as_str().to_owned())
            .and_then(|body: String| serde_json::from_str(body.as_str()).ok())
            .and_then(|j: Value| j.as_object().map(move |obj: &Map<String, Value>| {
                let t = obj.get("type").and_then(|t| t.as_str()).map(|s| s.to_owned());
                let p: Value = obj.get("payload").unwrap_or(&Value::Null).clone();
                (t, p)
            })) {
                match msg_type.as_ref() {
                    "echo" => {
                        try!(self.ws.send(format!("{}", payload)));
                    },
                    "broadcast" => {
                        try!(self.ws.broadcast(format!("{}", payload)));
                        try!(self.ws.send(format!("{{\"type\": \"broadcastResult\", \"listenCount\": {}, \"payload\": {}}}", self.count, payload)))
                    },
                    _ => {}
                };
            };
        Ok(())
    }

    fn on_open(&mut self, _: ws::Handshake) -> ws::Result<()> {
        self.count += 1;
        println!("Connection Open! {}", self.count);
        Ok(())
    }

    fn on_close(&mut self,_: ws::CloseCode, _: &str) {
        self.count -= 1;
        println!("Connection Closed! {}", self.count);
    }
}

fn main() {
    let matches = App::new("rust-ws-server")
        .version("1.0")
        .arg(Arg::with_name("address")
                    .short("a")
                    .long("address")
                    .required(true)
                    .takes_value(true)
                    .default_value("127.0.0.1"))
        .arg(Arg::with_name("port")
            .short("p")
            .long("port")
            .required(true)
            .takes_value(true)
            .default_value("3000"))
        .get_matches();
    if let (Some(address), Some(port)) = (matches.value_of("address"), matches.value_of("port")) {
        if let Err(error) = ws::listen(format!("{}:{}", address, port).as_str(), |out| {
            BenchHandler { ws: out, count: 0 }
        }) {
            println!("Failed to create WebSocket due to {:?}", error);
        }
    } else {
        println!("{}", matches.usage());
    }
}
<|endoftext|>


<commit_before><commit_msg>Test that associated types are not required as type parameters<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.

trait Foo {
    type T;
}

// should be able to use a trait with an associated type without specifying it as an argument
trait Bar<F: Foo> {
    fn bar(foo: &F);
}

pub fn main() {
}
<|endoftext|>


<commit_before><commit_msg>add an `os::errno` function<commit_after><|endoftext|>


<commit_before>use inflector::Inflector;

use botocore::{Service, Shape, Operation};

use self::json::JsonGenerator;
use self::query::QueryGenerator;
use self::rest_json::RestJsonGenerator;

use std::collections::HashMap;

mod json;
mod query;
mod rest_json;

pub trait GenerateProtocol {
    fn generate_methods(&self, service: &Service) -> String;

    fn generate_prelude(&self, service: &Service) -> String;

    fn generate_struct_attributes(&self) -> String;

    fn generate_support_types(&self, _name: &str, _shape: &Shape, _service: &Service)
        -> Option<String> {
        None
    }
}

pub fn generate_source(service: &Service) -> String {
    match &service.metadata.protocol[..] {
        "json" => generate(service, JsonGenerator),
        "query" => generate(service, QueryGenerator),
        "rest-json" => generate(service, RestJsonGenerator),
        protocol => panic!("Unknown protocol {}", protocol),
    }
}

fn generate<P>(service: &Service, protocol_generator: P) -> String where P: GenerateProtocol {
    format!(
        "{prelude}

        {types}
        {error_types}

        {client}",
        client = generate_client(service, &protocol_generator),
        prelude = &protocol_generator.generate_prelude(service),
        types = generate_types(service, &protocol_generator),
        error_types = generate_error_types(service).unwrap_or("".to_string()),
    )
}

fn generate_client<P>(service: &Service, protocol_generator: &P) -> String
where P: GenerateProtocol {
    format!(
        "/// A client for the {service_name} API.
        pub struct {type_name}<P> where P: ProvideAwsCredentials {{
            credentials_provider: P,
            region: Region,
        }}

        impl<P> {type_name}<P> where P: ProvideAwsCredentials {{
            pub fn new(credentials_provider: P, region: Region) -> Self {{
                {type_name} {{
                    credentials_provider: credentials_provider,
                    region: region,
                }}
            }}

            {methods}
        }}
        ",
        methods = protocol_generator.generate_methods(service),
        service_name = match &service.metadata.service_abbreviation {
            &Some(ref service_abbreviation) => service_abbreviation.as_str(),
            &None => {
                match service.metadata.endpoint_prefix {
                    ref x if x == "elastictranscoder" => "Amazon Elastic Transcoder",
                    _ => panic!("Unable to determine service abbreviation"),
                }
            },
        },
        type_name = service.client_type_name(),
    )
}

fn generate_list(name: &str, shape: &Shape) -> String {
    format!("pub type {} = Vec<{}>;", name, shape.member())
}

fn generate_map(name: &str, shape: &Shape) -> String {
    format!(
        "pub type {} = ::std::collections::HashMap<{}, {}>;",
        name,
        shape.key(),
        shape.value(),
    )
}

fn generate_primitive_type(name: &str, shape_type: &str) -> String {
    let primitive_type = match shape_type {
        "blob" => "Vec<u8>",
        "boolean" => "bool",
        "double" | "timestamp" => "f64",
        "float" => "f32",
        "integer" => "i32",
        "long" => "i64",
        "string" => "String",
        primitive_type => panic!("Unknown primitive type: {}", primitive_type),
    };

    format!("pub type {} = {};", name, primitive_type)
}

fn generate_types<P>(service: &Service, protocol_generator: &P) -> String
where P: GenerateProtocol {
    service.shapes.iter().filter_map(|(name, shape)| {
        if name == "String" {
            return protocol_generator.generate_support_types(name, shape, &service);
        }

        if shape.exception() && service.typed_errors() {
            return None;
        }

        let mut parts = Vec::with_capacity(3);

        if let Some(ref docs) = shape.documentation {
            parts.push(format!("#[doc=\"{}\"]", docs.replace("\"", "\\\"")));
        }

        match &shape.shape_type[..] {
            "structure" => parts.push(generate_struct(service, name, shape, protocol_generator)),
            "map" => parts.push(generate_map(name, shape)),
            "list" => parts.push(generate_list(name, shape)),
            shape_type => parts.push(generate_primitive_type(name, shape_type)),
        }

        if let Some(support_types) = protocol_generator.generate_support_types(name, shape, &service) {
            parts.push(support_types);
        }

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

fn generate_error_types(service: &Service) -> Option<String> {
    if service.typed_errors() {

        // grab error type documentation for use with error enums in generated code
        // botocore presents errors as structs.  we filter those out in generate_types.
        let mut error_documentation = HashMap::new();

        for (name, shape) in service.shapes.iter() {
            if shape.exception() && shape.documentation.is_some() {
                error_documentation.insert(name, shape.documentation.as_ref().unwrap());
            }
        }

       Some(service.operations.iter()
        .filter_map(|(_, operation)| generate_error_type(operation, &error_documentation) )
        .collect::<Vec<String>>()
        .join("\n")
        )
    } else {
       None
    }
}

fn generate_struct<P>(
    service: &Service,
    name: &str,
    shape: &Shape,
    protocol_generator: &P,
) -> String where P: GenerateProtocol {
    if shape.members.is_none() || shape.members.as_ref().unwrap().is_empty() {
        format!(
            "{attributes}
            pub struct {name};
            ",
            attributes = protocol_generator.generate_struct_attributes(),
            name = name,
        )
    } else {
        format!(
            "{attributes}
            pub struct {name} {{
                {struct_fields}
            }}
            ",
            attributes = protocol_generator.generate_struct_attributes(),
            name = name,
            struct_fields = generate_struct_fields(service, shape),
        )
    }

}

fn generate_struct_fields(service: &Service, shape: &Shape) -> String {
    shape.members.as_ref().unwrap().iter().map(|(member_name, member)| {
        let mut lines = Vec::with_capacity(4);
        let name = member_name.to_snake_case();

        if let Some(ref docs) = member.documentation {
            lines.push(format!("#[doc=\"{}\"]", docs.replace("\"", "\\\"")));
        }

        lines.push("#[allow(unused_attributes)]".to_owned());
        lines.push(format!("#[serde(rename=\"{}\")]", member_name));

        if let Some(shape_type) = service.shape_type_for_member(member) {
            if shape_type == "blob" {
                lines.push(
                    "#[serde(
                        deserialize_with=\"::serialization::SerdeBlob::deserialize_blob\",
                        serialize_with=\"::serialization::SerdeBlob::serialize_blob\",
                    )]".to_owned()
                );
            }
        }

        if shape.required(member_name) {
            lines.push(format!("pub {}: {},",  name, member.shape));
        } else if name == "type" {
            lines.push(format!("pub aws_{}: Option<{}>,",  name, member.shape));
        } else {
            lines.push(format!("pub {}: Option<{}>,",  name, member.shape));
        }

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

impl Operation {
    pub fn error_type_name(&self) -> String {
        format!("{}Error", self.name)
    }
}

pub fn generate_error_type(operation: &Operation, error_documentation: &HashMap<&String, &String>) -> Option<String> {

    let error_type_name = operation.error_type_name();

    Some(format!("
        #[derive(Debug, PartialEq)]
        pub enum {type_name} {{
            {error_types}
        }}

        impl {type_name} {{
            pub fn from_body(body: &str) -> {type_name} {{
                match from_str::<Value>(body) {{
                    Ok(json) => {{
                        let error_type: &str = match json.find(\"__type\") {{
                            Some(error_type) => error_type.as_string().unwrap_or(\"UnknownException\"),
                            None => \"UnknownException\",
                        }};

                        match error_type {{
                            {type_matchers}
                            _ => {type_name}::UnknownException(String::from(error_type))
                        }}
                    }},
                    Err(_) => {type_name}::UnknownException(String::from(body))
                }}
            }}
        }}
        impl From<AwsError> for {type_name} {{
            fn from(err: AwsError) -> {type_name} {{
                {type_name}::UnknownException(err.message)
            }}
        }}
        impl fmt::Display for {type_name} {{
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {{
                write!(f, \"{{}}\", self.description())
            }}
        }}
        impl Error for {type_name} {{
            fn description(&self) -> &str {{
               match *self {{
                   {description_matchers}
                   {type_name}::UnknownException(ref cause) => cause
               }}
           }}
       }}
       ",
       type_name = error_type_name,
       error_types = generate_error_enum_types(operation, error_documentation).unwrap_or(String::from("")),
       type_matchers = generate_error_type_matchers(operation).unwrap_or(String::from("")),
       description_matchers = generate_error_description_matchers(operation).unwrap_or(String::from(""))))
    }

fn generate_error_enum_types(operation: &Operation, error_documentation: &HashMap<&String, &String>) -> Option<String> {
    let mut enum_types: Vec<String> = Vec::new();

    if operation.errors.is_some() {
        for error in operation.errors.as_ref().unwrap().iter() {
            enum_types.push(format!("\n///{}\n{}(String)",
                error_documentation.get(&error.shape).unwrap_or(&&String::from("")),
                error.shape));
        }
    }

    enum_types.push("/// An unknown exception occurred.  The raw HTTP response is provided.\nUnknownException(String)".to_string());
    Some(enum_types.join(","))
}

fn generate_error_type_matchers(operation: &Operation) -> Option<String> {
    operation.errors.as_ref().and_then(|errors|
        Some(errors.iter()
        .map(|error|
            format!("\"{error_shape}\" => {error_type}::{error_shape}(String::from(body)),",
                error_shape = error.shape,
                error_type = operation.error_type_name())
            )
        .collect::<Vec<String>>()
        .join("\n")))
}

fn generate_error_description_matchers(operation: &Operation) -> Option<String> {
    operation.errors.as_ref().and_then(|errors|
    Some(errors.iter()
        .map(|error|
            format!("{error_type}::{error_shape}(ref cause) => cause,",
                error_type = operation.error_type_name(),
                error_shape = error.shape)
            )
        .collect::<Vec<String>>()
        .join("\n")))
}

<commit_msg>Include ValidationError in typed errors.  AWS throws it, botocore doesn't explicitly specify it.<commit_after>use inflector::Inflector;

use botocore::{Service, Shape, Operation};

use self::json::JsonGenerator;
use self::query::QueryGenerator;
use self::rest_json::RestJsonGenerator;

use std::collections::HashMap;

mod json;
mod query;
mod rest_json;

pub trait GenerateProtocol {
    fn generate_methods(&self, service: &Service) -> String;

    fn generate_prelude(&self, service: &Service) -> String;

    fn generate_struct_attributes(&self) -> String;

    fn generate_support_types(&self, _name: &str, _shape: &Shape, _service: &Service)
        -> Option<String> {
        None
    }
}

pub fn generate_source(service: &Service) -> String {
    match &service.metadata.protocol[..] {
        "json" => generate(service, JsonGenerator),
        "query" => generate(service, QueryGenerator),
        "rest-json" => generate(service, RestJsonGenerator),
        protocol => panic!("Unknown protocol {}", protocol),
    }
}

fn generate<P>(service: &Service, protocol_generator: P) -> String where P: GenerateProtocol {
    format!(
        "{prelude}

        {types}
        {error_types}

        {client}",
        client = generate_client(service, &protocol_generator),
        prelude = &protocol_generator.generate_prelude(service),
        types = generate_types(service, &protocol_generator),
        error_types = generate_error_types(service).unwrap_or("".to_string()),
    )
}

fn generate_client<P>(service: &Service, protocol_generator: &P) -> String
where P: GenerateProtocol {
    format!(
        "/// A client for the {service_name} API.
        pub struct {type_name}<P> where P: ProvideAwsCredentials {{
            credentials_provider: P,
            region: Region,
        }}

        impl<P> {type_name}<P> where P: ProvideAwsCredentials {{
            pub fn new(credentials_provider: P, region: Region) -> Self {{
                {type_name} {{
                    credentials_provider: credentials_provider,
                    region: region,
                }}
            }}

            {methods}
        }}
        ",
        methods = protocol_generator.generate_methods(service),
        service_name = match &service.metadata.service_abbreviation {
            &Some(ref service_abbreviation) => service_abbreviation.as_str(),
            &None => {
                match service.metadata.endpoint_prefix {
                    ref x if x == "elastictranscoder" => "Amazon Elastic Transcoder",
                    _ => panic!("Unable to determine service abbreviation"),
                }
            },
        },
        type_name = service.client_type_name(),
    )
}

fn generate_list(name: &str, shape: &Shape) -> String {
    format!("pub type {} = Vec<{}>;", name, shape.member())
}

fn generate_map(name: &str, shape: &Shape) -> String {
    format!(
        "pub type {} = ::std::collections::HashMap<{}, {}>;",
        name,
        shape.key(),
        shape.value(),
    )
}

fn generate_primitive_type(name: &str, shape_type: &str) -> String {
    let primitive_type = match shape_type {
        "blob" => "Vec<u8>",
        "boolean" => "bool",
        "double" | "timestamp" => "f64",
        "float" => "f32",
        "integer" => "i32",
        "long" => "i64",
        "string" => "String",
        primitive_type => panic!("Unknown primitive type: {}", primitive_type),
    };

    format!("pub type {} = {};", name, primitive_type)
}

fn generate_types<P>(service: &Service, protocol_generator: &P) -> String
where P: GenerateProtocol {
    service.shapes.iter().filter_map(|(name, shape)| {
        if name == "String" {
            return protocol_generator.generate_support_types(name, shape, &service);
        }

        if shape.exception() && service.typed_errors() {
            return None;
        }

        let mut parts = Vec::with_capacity(3);

        if let Some(ref docs) = shape.documentation {
            parts.push(format!("#[doc=\"{}\"]", docs.replace("\"", "\\\"")));
        }

        match &shape.shape_type[..] {
            "structure" => parts.push(generate_struct(service, name, shape, protocol_generator)),
            "map" => parts.push(generate_map(name, shape)),
            "list" => parts.push(generate_list(name, shape)),
            shape_type => parts.push(generate_primitive_type(name, shape_type)),
        }

        if let Some(support_types) = protocol_generator.generate_support_types(name, shape, &service) {
            parts.push(support_types);
        }

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

fn generate_error_types(service: &Service) -> Option<String> {
    if service.typed_errors() {

        // grab error type documentation for use with error enums in generated code
        // botocore presents errors as structs.  we filter those out in generate_types.
        let mut error_documentation = HashMap::new();

        for (name, shape) in service.shapes.iter() {
            if shape.exception() && shape.documentation.is_some() {
                error_documentation.insert(name, shape.documentation.as_ref().unwrap());
            }
        }

       Some(service.operations.iter()
        .filter_map(|(_, operation)| generate_error_type(operation, &error_documentation) )
        .collect::<Vec<String>>()
        .join("\n")
        )
    } else {
       None
    }
}

fn generate_struct<P>(
    service: &Service,
    name: &str,
    shape: &Shape,
    protocol_generator: &P,
) -> String where P: GenerateProtocol {
    if shape.members.is_none() || shape.members.as_ref().unwrap().is_empty() {
        format!(
            "{attributes}
            pub struct {name};
            ",
            attributes = protocol_generator.generate_struct_attributes(),
            name = name,
        )
    } else {
        format!(
            "{attributes}
            pub struct {name} {{
                {struct_fields}
            }}
            ",
            attributes = protocol_generator.generate_struct_attributes(),
            name = name,
            struct_fields = generate_struct_fields(service, shape),
        )
    }

}

fn generate_struct_fields(service: &Service, shape: &Shape) -> String {
    shape.members.as_ref().unwrap().iter().map(|(member_name, member)| {
        let mut lines = Vec::with_capacity(4);
        let name = member_name.to_snake_case();

        if let Some(ref docs) = member.documentation {
            lines.push(format!("#[doc=\"{}\"]", docs.replace("\"", "\\\"")));
        }

        lines.push("#[allow(unused_attributes)]".to_owned());
        lines.push(format!("#[serde(rename=\"{}\")]", member_name));

        if let Some(shape_type) = service.shape_type_for_member(member) {
            if shape_type == "blob" {
                lines.push(
                    "#[serde(
                        deserialize_with=\"::serialization::SerdeBlob::deserialize_blob\",
                        serialize_with=\"::serialization::SerdeBlob::serialize_blob\",
                    )]".to_owned()
                );
            }
        }

        if shape.required(member_name) {
            lines.push(format!("pub {}: {},",  name, member.shape));
        } else if name == "type" {
            lines.push(format!("pub aws_{}: Option<{}>,",  name, member.shape));
        } else {
            lines.push(format!("pub {}: Option<{}>,",  name, member.shape));
        }

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

impl Operation {
    pub fn error_type_name(&self) -> String {
        format!("{}Error", self.name)
    }
}

pub fn generate_error_type(operation: &Operation, error_documentation: &HashMap<&String, &String>) -> Option<String> {

    let error_type_name = operation.error_type_name();

    Some(format!("
        #[derive(Debug, PartialEq)]
        pub enum {type_name} {{
            {error_types}
        }}

        impl {type_name} {{
            pub fn from_body(body: &str) -> {type_name} {{
                match from_str::<Value>(body) {{
                    Ok(json) => {{
                        let error_type: &str = match json.find(\"__type\") {{
                            Some(error_type) => error_type.as_string().unwrap_or(\"UnknownException\"),
                            None => \"UnknownException\",
                        }};

                        match error_type {{
                            {type_matchers}
                        }}
                    }},
                    Err(_) => {type_name}::UnknownException(String::from(body))
                }}
            }}
        }}
        impl From<AwsError> for {type_name} {{
            fn from(err: AwsError) -> {type_name} {{
                {type_name}::UnknownException(err.message)
            }}
        }}
        impl fmt::Display for {type_name} {{
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {{
                write!(f, \"{{}}\", self.description())
            }}
        }}
        impl Error for {type_name} {{
            fn description(&self) -> &str {{
               match *self {{
                   {description_matchers}
               }}
           }}
       }}
       ",
       type_name = error_type_name,
       error_types = generate_error_enum_types(operation, error_documentation).unwrap_or(String::from("")),
       type_matchers = generate_error_type_matchers(operation).unwrap_or(String::from("")),
       description_matchers = generate_error_description_matchers(operation).unwrap_or(String::from(""))))
    }

fn generate_error_enum_types(operation: &Operation, error_documentation: &HashMap<&String, &String>) -> Option<String> {
    let mut enum_types: Vec<String> = Vec::new();

    if operation.errors.is_some() {
        for error in operation.errors.as_ref().unwrap().iter() {
            enum_types.push(format!("\n///{}\n{}(String)",
                error_documentation.get(&error.shape).unwrap_or(&&String::from("")),
                error.shape));
        }
    }

    enum_types.push("/// A validation exception occurred.  Details from AWS are provided.\nValidationException(String)".to_string());
    enum_types.push("/// An unknown exception occurred.  The raw HTTP response is provided.\nUnknownException(String)".to_string());
    Some(enum_types.join(","))
}

fn generate_error_type_matchers(operation: &Operation) -> Option<String> {
    let mut type_matchers: Vec<String> = Vec::new();
    let error_type = operation.error_type_name();

    if operation.errors.is_some() {
        for error in operation.errors.as_ref().unwrap().iter() {
            type_matchers.push(format!("\"{error_shape}\" => {error_type}::{error_shape}(String::from(body))",
                error_shape = error.shape,
                error_type = error_type))
        }
    }

   type_matchers.push(format!("\"ValidationException\" => {error_type}::ValidationException(String::from(body))", error_type = error_type));
   type_matchers.push(format!("_ => {error_type}::UnknownException(String::from(body))",  error_type = error_type));
   Some(type_matchers.join(","))
}

fn generate_error_description_matchers(operation: &Operation) -> Option<String> {
    let mut type_matchers: Vec<String> = Vec::new();
    let error_type = operation.error_type_name();

    if operation.errors.is_some() {
        for error in operation.errors.as_ref().unwrap().iter() {
            type_matchers.push(format!("{error_type}::{error_shape}(ref cause) => cause",
                error_type = operation.error_type_name(),
                error_shape = error.shape))
        }
    }

   type_matchers.push(format!("{error_type}::ValidationException(ref cause) => cause", error_type = error_type));
   type_matchers.push(format!("{error_type}::UnknownException(ref cause) => cause", error_type = error_type));
   Some(type_matchers.join(","))
}

<|endoftext|>


<commit_before><commit_msg>Add ATM example from paper<commit_after>#[macro_use] extern crate session_types;
use session_types::*;
use std::thread::spawn;

type Id = String;
type Atm = Recv<Id, Choose<Rec<AtmInner>, Eps>>;

type AtmInner = Offer<AtmDeposit,
                Offer<AtmWithdraw,
                Offer<AtmBalance,
                      Eps>>>;

type AtmDeposit = Recv<u64, Send<u64, Var<Z>>>;
type AtmWithdraw = Recv<u64, Choose<Var<Z>, Var<Z>>>;
type AtmBalance = Send<u64, Var<Z>>;

type Client = <Atm as HasDual>::Dual;

fn approved(id: &Id) -> bool {
    !id.is_empty()
}

fn atm(c: Chan<(), Atm>) {
    let mut c = {
        let (c, id) = c.recv();
        if !approved(&id) {
            c.sel2().close();
            return;
        }
        c.sel1().enter()
    };
    let mut balance = 0;
    loop {
        c = offer! {
            c,
            Deposit => {
                let (c, amt) = c.recv();
                balance += amt;
                c.send(balance).zero()
            },
            Withdraw => {
                let (c, amt) = c.recv();
                if amt > balance {
                    c.sel2().zero()
                } else {
                    balance -= amt;
                    c.sel1().zero()
                }
            },
            Balance => {
                c.send(balance).zero()
            },
            Quit => {
                c.close();
                break
            }
        }
    }
}

fn deposit_client(c: Chan<(), Client>) {
    let c = match c.send("Deposit Client".to_string()).offer() {
        Left(c) => c.enter(),
        Right(_) => panic!("deposit_client: expected to be approved")
    };

    let (c, new_balance) = c.sel1().send(200).recv();
    println!("deposit_client: new balance: {}", new_balance);
    c.zero().skip3().close();
}

fn withdraw_client(c: Chan<(), Client>) {
    let c = match c.send("Withdraw Client".to_string()).offer() {
        Left(c) => c.enter(),
        Right(_) => panic!("withdraw_client: expected to be approved")
    };

    match c.sel2().sel1().send(100).offer() {
        Left(c) => {
            println!("withdraw_client: Successfully withdrew 100");
            c.zero().skip3().close();
        }
        Right(c) => {
            println!("withdraw_client: Could not withdraw. Depositing instead.");
            c.zero().sel1().send(50).recv().0.zero().skip3().close();
        }
    }
}

fn main() {
    let (atm_chan, client_chan) = session_channel();
    spawn(|| atm(atm_chan));
    deposit_client(client_chan);

    let (atm_chan, client_chan) = session_channel();
    spawn(|| atm(atm_chan));
    withdraw_client(client_chan);

}
<|endoftext|>


<commit_before><commit_msg>multiple pattern matching added<commit_after><|endoftext|>


<commit_before><commit_msg>Measure trim/commit latencies.<commit_after><|endoftext|>


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

// Test that changing what a `type` points to does not go unnoticed.

// compile-flags: -Z query-dep-graph

#![feature(rustc_attrs)]
#![allow(dead_code)]
#![allow(unused_variables)]

fn main() { }

#[rustc_if_this_changed]
type TypeAlias = u32;

#[rustc_then_this_would_need(ItemSignature)] //~ ERROR OK
struct Struct {
    x: TypeAlias,
    y: u32
}

#[rustc_then_this_would_need(ItemSignature)] //~ ERROR OK
enum Enum {
    Variant1(TypeAlias),
    Variant2(i32)
}

#[rustc_then_this_would_need(ItemSignature)] //~ ERROR OK
trait Trait {
    fn method(&self, _: TypeAlias);
}

struct SomeType;

#[rustc_then_this_would_need(ItemSignature)] //~ ERROR OK
impl SomeType {
    fn method(&self, _: TypeAlias) {}
}

#[rustc_then_this_would_need(ItemSignature)] //~ ERROR OK
type TypeAlias2 = TypeAlias;

#[rustc_then_this_would_need(ItemSignature)] //~ ERROR OK
fn function(_: TypeAlias) {

}
<|endoftext|>


<commit_before><commit_msg>Tests (#9)<commit_after>#[macro_use]
extern crate yoga;

use yoga::{Direction, Node, Point, Undefined};
use yoga::FlexStyle::*;

#[test]
fn test_nested_overflowing_child() {
	let mut root = Node::new();

	style!(root,
		Width(100 pt),
		Height(100 pt)
	);

	let mut root_child_0 = Node::new();

	root.insert_child(&mut root_child_0, 0);

	let mut root_child_0_child_0 = Node::new();

	style!(root_child_0_child_0,
		Width(200 pt),
		Height(200 pt)
	);

	root_child_0.insert_child(&mut root_child_0_child_0, 0);
	root.calculate_layout(Undefined, Undefined, Direction::LTR);

	let root_layout = root.get_layout();
	let root_child_0_layout = root_child_0.get_layout();
	let root_child_0_child_0_layout = root_child_0_child_0.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, root_child_0_layout.left);
	assert_eq!(0.0, root_child_0_layout.top);
	assert_eq!(100.0, root_child_0_layout.width);
	assert_eq!(200.0, root_child_0_layout.height);

	assert_eq!(0.0, root_child_0_child_0_layout.left);
	assert_eq!(0.0, root_child_0_child_0_layout.top);
	assert_eq!(200.0, root_child_0_child_0_layout.width);
	assert_eq!(200.0, root_child_0_child_0_layout.height);

	root.calculate_layout(Undefined, Undefined, Direction::RTL);

	let root_layout = root.get_layout();
	let root_child_0_layout = root_child_0.get_layout();
	let root_child_0_child_0_layout = root_child_0_child_0.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, root_child_0_layout.left);
	assert_eq!(0.0, root_child_0_layout.top);
	assert_eq!(100.0, root_child_0_layout.width);
	assert_eq!(200.0, root_child_0_layout.height);

	assert_eq!(-100.0, root_child_0_child_0_layout.left);
	assert_eq!(0.0, root_child_0_child_0_layout.top);
	assert_eq!(200.0, root_child_0_child_0_layout.width);
	assert_eq!(200.0, root_child_0_child_0_layout.height);
}

#[test]
fn test_nested_overflowing_child_in_constraint_parent() {
	let mut root = Node::new();

	style!(root,
		Width(100 pt),
		Height(100 pt)
	);

	let mut root_child_0 = Node::new();

	style!(root_child_0,
		Width(100 pt),
		Height(100 pt)
	);

	root.insert_child(&mut root_child_0, 0);

	let mut root_child_0_child_0 = Node::new();

	style!(root_child_0_child_0,
		Width(200 pt),
		Height(200 pt)
	);

	root_child_0.insert_child(&mut root_child_0_child_0, 0);
	root.calculate_layout(Undefined, Undefined, Direction::LTR);

	let root_layout = root.get_layout();
	let root_child_0_layout = root_child_0.get_layout();
	let root_child_0_child_0_layout = root_child_0_child_0.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, root_child_0_layout.left);
	assert_eq!(0.0, root_child_0_layout.top);
	assert_eq!(100.0, root_child_0_layout.width);
	assert_eq!(100.0, root_child_0_layout.height);

	assert_eq!(0.0, root_child_0_child_0_layout.left);
	assert_eq!(0.0, root_child_0_child_0_layout.top);
	assert_eq!(200.0, root_child_0_child_0_layout.width);
	assert_eq!(200.0, root_child_0_child_0_layout.height);

	root.calculate_layout(Undefined, Undefined, Direction::RTL);

	let root_layout = root.get_layout();
	let root_child_0_layout = root_child_0.get_layout();
	let root_child_0_child_0_layout = root_child_0_child_0.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, root_child_0_layout.left);
	assert_eq!(0.0, root_child_0_layout.top);
	assert_eq!(100.0, root_child_0_layout.width);
	assert_eq!(100.0, root_child_0_layout.height);

	assert_eq!(-100.0, root_child_0_child_0_layout.left);
	assert_eq!(0.0, root_child_0_child_0_layout.top);
	assert_eq!(200.0, root_child_0_child_0_layout.width);
	assert_eq!(200.0, root_child_0_child_0_layout.height);
}

#[test]
fn test_parent_wrap_child_size_overflowing_parent() {
	let mut root = Node::new();

	style!(root,
		Width(100 pt),
		Height(100 pt)
	);

	let mut root_child_0 = Node::new();

	style!(root_child_0,
		Width(100 pt)
	);

	root.insert_child(&mut root_child_0, 0);

	let mut root_child_0_child_0 = Node::new();

	style!(root_child_0_child_0,
		Width(100 pt),
		Height(200 pt)
	);

	root_child_0.insert_child(&mut root_child_0_child_0, 0);
	root.calculate_layout(Undefined, Undefined, Direction::LTR);

	let root_layout = root.get_layout();
	let root_child_0_layout = root_child_0.get_layout();
	let root_child_0_child_0_layout = root_child_0_child_0.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, root_child_0_layout.left);
	assert_eq!(0.0, root_child_0_layout.top);
	assert_eq!(100.0, root_child_0_layout.width);
	assert_eq!(200.0, root_child_0_layout.height);

	assert_eq!(0.0, root_child_0_child_0_layout.left);
	assert_eq!(0.0, root_child_0_child_0_layout.top);
	assert_eq!(100.0, root_child_0_child_0_layout.width);
	assert_eq!(200.0, root_child_0_child_0_layout.height);

	root.calculate_layout(Undefined, Undefined, Direction::RTL);

	let root_layout = root.get_layout();
	let root_child_0_layout = root_child_0.get_layout();
	let root_child_0_child_0_layout = root_child_0_child_0.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, root_child_0_layout.left);
	assert_eq!(0.0, root_child_0_layout.top);
	assert_eq!(100.0, root_child_0_layout.width);
	assert_eq!(200.0, root_child_0_layout.height);

	assert_eq!(0.0, root_child_0_child_0_layout.left);
	assert_eq!(0.0, root_child_0_child_0_layout.top);
	assert_eq!(100.0, root_child_0_child_0_layout.width);
	assert_eq!(200.0, root_child_0_child_0_layout.height);
}
<|endoftext|>


<commit_before>//! Tests for public/private dependencies.

use cargo_test_support::registry::Package;
use cargo_test_support::{is_nightly, project};

#[cargo_test]
fn exported_priv_warning() {
    if !is_nightly() {
        return;
    }
    Package::new("priv_dep", "0.1.0")
        .file("src/lib.rs", "pub struct FromPriv;")
        .publish();

    let p = project()
        .file(
            "Cargo.toml",
            r#"
            cargo-features = ["public-dependency"]

            [package]
            name = "foo"
            version = "0.0.1"

            [dependencies]
            priv_dep = "0.1.0"
        "#,
        )
        .file(
            "src/lib.rs",
            "
            extern crate priv_dep;
            pub fn use_priv(_: priv_dep::FromPriv) {}
        ",
        )
        .build();

    p.cargo("build --message-format=short")
        .masquerade_as_nightly_cargo()
        .with_stderr_contains(
            "\
src/lib.rs:3:13: warning: type `priv_dep::FromPriv` from private dependency 'priv_dep' in public interface
"
        )
        .run()
}

#[cargo_test]
fn exported_pub_dep() {
    if !is_nightly() {
        return;
    }
    Package::new("pub_dep", "0.1.0")
        .file("src/lib.rs", "pub struct FromPub;")
        .publish();

    let p = project()
        .file(
            "Cargo.toml",
            r#"
            cargo-features = ["public-dependency"]

            [package]
            name = "foo"
            version = "0.0.1"

            [dependencies]
            pub_dep = {version = "0.1.0", public = true}
        "#,
        )
        .file(
            "src/lib.rs",
            "
            extern crate pub_dep;
            pub fn use_pub(_: pub_dep::FromPub) {}
        ",
        )
        .build();

    p.cargo("build --message-format=short")
        .masquerade_as_nightly_cargo()
        .with_stderr(
            "\
[UPDATING] `[..]` index
[DOWNLOADING] crates ...
[DOWNLOADED] pub_dep v0.1.0 ([..])
[COMPILING] pub_dep v0.1.0
[COMPILING] foo v0.0.1 ([CWD])
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
        )
        .run()
}

#[cargo_test]
pub fn requires_nightly_cargo() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
            cargo-features = ["public-dependency"]
        "#,
        )
        .file("src/lib.rs", "")
        .build();

    p.cargo("build --message-format=short")
        .with_status(101)
        .with_stderr(
            "\
error: failed to parse manifest at `[..]`

Caused by:
  the cargo feature `public-dependency` requires a nightly version of Cargo, but this is the `stable` channel
  See https://doc.rust-lang.org/book/appendix-07-nightly-rust.html for more information about Rust release channels.
"
        )
        .run()
}

#[cargo_test]
fn requires_feature() {
    Package::new("pub_dep", "0.1.0")
        .file("src/lib.rs", "")
        .publish();

    let p = project()
        .file(
            "Cargo.toml",
            r#"

            [package]
            name = "foo"
            version = "0.0.1"

            [dependencies]
            pub_dep = { version = "0.1.0", public = true }
        "#,
        )
        .file("src/lib.rs", "")
        .build();

    p.cargo("build --message-format=short")
        .masquerade_as_nightly_cargo()
        .with_status(101)
        .with_stderr(
            "\
error: failed to parse manifest at `[..]`

Caused by:
  feature `public-dependency` is required

  consider adding `cargo-features = [\"public-dependency\"]` to the manifest
",
        )
        .run()
}

#[cargo_test]
fn pub_dev_dependency() {
    Package::new("pub_dep", "0.1.0")
        .file("src/lib.rs", "pub struct FromPub;")
        .publish();

    let p = project()
        .file(
            "Cargo.toml",
            r#"
            cargo-features = ["public-dependency"]

            [package]
            name = "foo"
            version = "0.0.1"

            [dev-dependencies]
            pub_dep = {version = "0.1.0", public = true}
        "#,
        )
        .file(
            "src/lib.rs",
            "
            extern crate pub_dep;
            pub fn use_pub(_: pub_dep::FromPub) {}
        ",
        )
        .build();

    p.cargo("build --message-format=short")
        .masquerade_as_nightly_cargo()
        .with_status(101)
        .with_stderr(
            "\
error: failed to parse manifest at `[..]`

Caused by:
  'public' specifier can only be used on regular dependencies, not Development dependencies
",
        )
        .run()
}
<commit_msg>Auto merge of #8678 - ehuss:fix-priv-test, r=alexcrichton<commit_after>//! Tests for public/private dependencies.

use cargo_test_support::registry::Package;
use cargo_test_support::{is_nightly, project};

#[cargo_test]
fn exported_priv_warning() {
    if !is_nightly() {
        return;
    }
    Package::new("priv_dep", "0.1.0")
        .file("src/lib.rs", "pub struct FromPriv;")
        .publish();

    let p = project()
        .file(
            "Cargo.toml",
            r#"
            cargo-features = ["public-dependency"]

            [package]
            name = "foo"
            version = "0.0.1"

            [dependencies]
            priv_dep = "0.1.0"
        "#,
        )
        .file(
            "src/lib.rs",
            "
            extern crate priv_dep;
            pub fn use_priv(_: priv_dep::FromPriv) {}
        ",
        )
        .build();

    p.cargo("build --message-format=short")
        .masquerade_as_nightly_cargo()
        .with_stderr_contains(
            "\
src/lib.rs:3:13: warning: type `[..]FromPriv` from private dependency 'priv_dep' in public interface
",
        )
        .run()
}

#[cargo_test]
fn exported_pub_dep() {
    if !is_nightly() {
        return;
    }
    Package::new("pub_dep", "0.1.0")
        .file("src/lib.rs", "pub struct FromPub;")
        .publish();

    let p = project()
        .file(
            "Cargo.toml",
            r#"
            cargo-features = ["public-dependency"]

            [package]
            name = "foo"
            version = "0.0.1"

            [dependencies]
            pub_dep = {version = "0.1.0", public = true}
        "#,
        )
        .file(
            "src/lib.rs",
            "
            extern crate pub_dep;
            pub fn use_pub(_: pub_dep::FromPub) {}
        ",
        )
        .build();

    p.cargo("build --message-format=short")
        .masquerade_as_nightly_cargo()
        .with_stderr(
            "\
[UPDATING] `[..]` index
[DOWNLOADING] crates ...
[DOWNLOADED] pub_dep v0.1.0 ([..])
[COMPILING] pub_dep v0.1.0
[COMPILING] foo v0.0.1 ([CWD])
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
        )
        .run()
}

#[cargo_test]
pub fn requires_nightly_cargo() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
            cargo-features = ["public-dependency"]
        "#,
        )
        .file("src/lib.rs", "")
        .build();

    p.cargo("build --message-format=short")
        .with_status(101)
        .with_stderr(
            "\
error: failed to parse manifest at `[..]`

Caused by:
  the cargo feature `public-dependency` requires a nightly version of Cargo, but this is the `stable` channel
  See https://doc.rust-lang.org/book/appendix-07-nightly-rust.html for more information about Rust release channels.
"
        )
        .run()
}

#[cargo_test]
fn requires_feature() {
    Package::new("pub_dep", "0.1.0")
        .file("src/lib.rs", "")
        .publish();

    let p = project()
        .file(
            "Cargo.toml",
            r#"

            [package]
            name = "foo"
            version = "0.0.1"

            [dependencies]
            pub_dep = { version = "0.1.0", public = true }
        "#,
        )
        .file("src/lib.rs", "")
        .build();

    p.cargo("build --message-format=short")
        .masquerade_as_nightly_cargo()
        .with_status(101)
        .with_stderr(
            "\
error: failed to parse manifest at `[..]`

Caused by:
  feature `public-dependency` is required

  consider adding `cargo-features = [\"public-dependency\"]` to the manifest
",
        )
        .run()
}

#[cargo_test]
fn pub_dev_dependency() {
    Package::new("pub_dep", "0.1.0")
        .file("src/lib.rs", "pub struct FromPub;")
        .publish();

    let p = project()
        .file(
            "Cargo.toml",
            r#"
            cargo-features = ["public-dependency"]

            [package]
            name = "foo"
            version = "0.0.1"

            [dev-dependencies]
            pub_dep = {version = "0.1.0", public = true}
        "#,
        )
        .file(
            "src/lib.rs",
            "
            extern crate pub_dep;
            pub fn use_pub(_: pub_dep::FromPub) {}
        ",
        )
        .build();

    p.cargo("build --message-format=short")
        .masquerade_as_nightly_cargo()
        .with_status(101)
        .with_stderr(
            "\
error: failed to parse manifest at `[..]`

Caused by:
  'public' specifier can only be used on regular dependencies, not Development dependencies
",
        )
        .run()
}
<|endoftext|>


<commit_before><commit_msg>Build a graph of locations by segment.<commit_after><|endoftext|>


<commit_before><commit_msg>handle lack of a result<commit_after><|endoftext|>


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


<commit_before><commit_msg>Created thread for handling messages from UI to API<commit_after><|endoftext|>


<commit_before><commit_msg>added documentation<commit_after><|endoftext|>