<commit_before>#![feature(box_syntax)]

#![unstable]

#[macro_use]
#[no_link]
extern crate compile_msg;

extern crate libc;

use std::ffi::{CString};
use std::sync::mpsc::{Sender};
use std::sync::Mutex;
use std::thread::Thread;

#[doc(hidden)]
pub mod ffi;

/// This static variable  will store the android_app* on creation, and set it back to 0 at
///  destruction.
/// Apart from this, the static is never written, so there is no risk of race condition.
static mut ANDROID_APP: *mut ffi::android_app = 0 as *mut ffi::android_app;

/// This is the structure that serves as user data in the android_app*
#[doc(hidden)]
struct Context {
    senders: Mutex<Vec<Sender<Event>>>,
}

/// An event triggered by the Android environment.
pub enum Event {
    EventUp,
    EventDown,
    EventMove(i32, i32),
}

impl Copy for Event {}

#[cfg(not(target_os = "android"))]
compile_note!("You are not compiling for Android");

#[macro_export]
macro_rules! android_start(
    ($main: ident) => (
        pub mod __android_start {
            extern crate android_glue;

            // this function is here because we are sure that it will be included by the linker
            // so we call app_dummy in it, in order to be sure that the native glue will be included
            #[start]
            pub fn start(_: int, _: *const *const u8) -> int {
                unsafe { android_glue::ffi::app_dummy() };
                1
            }

            #[no_mangle]
            #[inline(never)]
            #[allow(non_snake_case)]
            pub extern "C" fn android_main(app: *mut ()) {
                android_glue::android_main2(app, move|| super::$main());
            }
        }
    )
);

/// This is the function that must be called by `android_main`
#[doc(hidden)]
pub fn android_main2<F>(app: *mut (), main_function: F)
    where F: FnOnce(), F: Send
{
    use std::{mem, ptr};

    write_log("Entering android_main");

    unsafe { ANDROID_APP = std::mem::transmute(app) };
    let app: &mut ffi::android_app = unsafe { std::mem::transmute(app) };

    // creating the context that will be passed to the callback
    let context = Context { senders: Mutex::new(Vec::new()) };
    app.onAppCmd = commands_callback;
    app.onInputEvent = inputs_callback;
    app.userData = unsafe { std::mem::transmute(&context) };

    // executing the main function in parallel
    let g = Thread::spawn(move|| {
        std::io::stdio::set_stdout(box std::io::LineBufferedWriter::new(ToLogWriter));
        std::io::stdio::set_stderr(box std::io::LineBufferedWriter::new(ToLogWriter));
        main_function()
    });

    // polling for events forever
    // note that this must be done in the same thread as android_main because ALooper are
    //  thread-local
    unsafe {
        loop {
            let mut events = mem::uninitialized();
            let mut source = mem::uninitialized();

            // passing -1 means that we are blocking
            let ident = ffi::ALooper_pollAll(-1, ptr::null_mut(), &mut events,
                &mut source);

            // processing the event
            if !source.is_null() {
                let source: *mut ffi::android_poll_source = mem::transmute(source);
                ((*source).process)(ANDROID_APP, source);
            }
        }
    }

    // terminating the application
    unsafe { ANDROID_APP = 0 as *mut ffi::android_app };
}

/// Writer that will redirect what is written to it to the logs.
struct ToLogWriter;

impl Writer for ToLogWriter {
    fn write(&mut self, buf: &[u8]) -> std::io::IoResult<()> {
        let message = CString::from_slice(buf).as_slice_with_nul().as_ptr();
        let tag = b"RustAndroidGlueStdouterr";
        let tag = CString::from_slice(tag).as_slice_with_nul().as_ptr();
        unsafe { ffi::__android_log_write(3, tag, message) };
        Ok(())
    }
}

/// The callback for inputs.
pub extern fn inputs_callback(_: *mut ffi::android_app, event: *const ffi::AInputEvent)
    -> libc::int32_t
{
    fn send_event(event: Event) {
        let senders = get_context().senders.lock().ok().unwrap();
        for sender in senders.iter() {
            sender.send(event);
        }
    }
    let action = unsafe { ffi::AMotionEvent_getAction(event) };
    let action_code = action & ffi::AMOTION_EVENT_ACTION_MASK;
    match action_code {
        ffi::AMOTION_EVENT_ACTION_UP
            | ffi::AMOTION_EVENT_ACTION_OUTSIDE
            | ffi::AMOTION_EVENT_ACTION_CANCEL
            | ffi::AMOTION_EVENT_ACTION_POINTER_UP =>
        {
            send_event(Event::EventUp);
        },
        ffi::AMOTION_EVENT_ACTION_DOWN
            | ffi::AMOTION_EVENT_ACTION_POINTER_DOWN =>
        {
            send_event(Event::EventDown);
        },
        _ => {
            let x = unsafe { ffi::AMotionEvent_getX(event, 0) };
            let y = unsafe { ffi::AMotionEvent_getY(event, 0) };
            send_event(Event::EventMove(x as i32, y as i32));
        },
    }
    0
}

/// The callback for commands.
#[doc(hidden)]
pub extern fn commands_callback(_: *mut ffi::android_app, command: libc::int32_t) {
    let context = get_context();

    match command {
        ffi::APP_CMD_INIT_WINDOW => {

        },

        ffi::APP_CMD_SAVE_STATE => {

        },

        ffi::APP_CMD_TERM_WINDOW => {

        },

        ffi::APP_CMD_GAINED_FOCUS => {

        },

        ffi::APP_CMD_LOST_FOCUS => {

        },

        _ => ()
    }
}

/// Returns the current Context.
fn get_context() -> &'static Context {
    let context = unsafe { (*ANDROID_APP).userData };
    unsafe { std::mem::transmute(context) }
}

/// Adds a sender where events will be sent to.
pub fn add_sender(sender: Sender<Event>) {
    get_context().senders.lock().ok().unwrap().push(sender);
}

/// Returns a handle to the native window.
pub unsafe fn get_native_window() -> ffi::NativeWindowType {
    if ANDROID_APP.is_null() {
        panic!("The application was not initialized from android_main");
    }

    loop {
        let value = (*ANDROID_APP).window;
        if !value.is_null() {
            return value;
        }

        // spin-locking
        std::io::timer::sleep(std::time::Duration::milliseconds(10));
    }
}

///
pub fn write_log(message: &str) {
    let message = message.as_bytes();
    let message = CString::from_slice(message).as_slice_with_nul().as_ptr();
    let tag = b"RustAndroidGlueStdouterr";
    let tag = CString::from_slice(tag).as_slice_with_nul().as_ptr();
    unsafe { ffi::__android_log_write(3, tag, message) };
}

pub enum AssetError {
    AssetMissing,
    EmptyBuffer,
}

pub fn load_asset(filename: &str) -> Result<Vec<u8>, AssetError> {
    struct AssetCloser {
        asset: *const ffi::Asset,
    }

    impl Drop for AssetCloser {
        fn drop(&mut self) {
            unsafe {
                ffi::AAsset_close(self.asset)
            };
        }
    }

    unsafe fn get_asset_manager() -> *const ffi::AAssetManager {
        let app = &*ANDROID_APP;
        let activity = &*app.activity;
        activity.assetManager
    }

    let filename_c_str = CString::from_slice(filename.as_bytes())
        .as_slice_with_nul().as_ptr();
    let asset = unsafe {
        ffi::AAssetManager_open(
            get_asset_manager(), filename_c_str, ffi::MODE_STREAMING)
    };
    if asset.is_null() {
        return Err(AssetError::AssetMissing);
    }
    let _asset_closer = AssetCloser{asset: asset};
    let len = unsafe {
        ffi::AAsset_getLength(asset)
    };
    let buff = unsafe {
        ffi::AAsset_getBuffer(asset)
    };
    if buff.is_null() {
        return Err(AssetError::EmptyBuffer);
    }
    let vec = unsafe {
        Vec::from_raw_buf(buff as *const u8, len as usize)
    };
    Ok(vec)
}
<commit_msg>Send EventMove before sending EventDown<commit_after>#![feature(box_syntax)]

#![unstable]

#[macro_use]
#[no_link]
extern crate compile_msg;

extern crate libc;

use std::ffi::{CString};
use std::sync::mpsc::{Sender};
use std::sync::Mutex;
use std::thread::Thread;

#[doc(hidden)]
pub mod ffi;

/// This static variable  will store the android_app* on creation, and set it back to 0 at
///  destruction.
/// Apart from this, the static is never written, so there is no risk of race condition.
static mut ANDROID_APP: *mut ffi::android_app = 0 as *mut ffi::android_app;

/// This is the structure that serves as user data in the android_app*
#[doc(hidden)]
struct Context {
    senders: Mutex<Vec<Sender<Event>>>,
}

/// An event triggered by the Android environment.
pub enum Event {
    EventUp,
    EventDown,
    EventMove(i32, i32),
}

impl Copy for Event {}

#[cfg(not(target_os = "android"))]
compile_note!("You are not compiling for Android");

#[macro_export]
macro_rules! android_start(
    ($main: ident) => (
        pub mod __android_start {
            extern crate android_glue;

            // this function is here because we are sure that it will be included by the linker
            // so we call app_dummy in it, in order to be sure that the native glue will be included
            #[start]
            pub fn start(_: int, _: *const *const u8) -> int {
                unsafe { android_glue::ffi::app_dummy() };
                1
            }

            #[no_mangle]
            #[inline(never)]
            #[allow(non_snake_case)]
            pub extern "C" fn android_main(app: *mut ()) {
                android_glue::android_main2(app, move|| super::$main());
            }
        }
    )
);

/// This is the function that must be called by `android_main`
#[doc(hidden)]
pub fn android_main2<F>(app: *mut (), main_function: F)
    where F: FnOnce(), F: Send
{
    use std::{mem, ptr};

    write_log("Entering android_main");

    unsafe { ANDROID_APP = std::mem::transmute(app) };
    let app: &mut ffi::android_app = unsafe { std::mem::transmute(app) };

    // creating the context that will be passed to the callback
    let context = Context { senders: Mutex::new(Vec::new()) };
    app.onAppCmd = commands_callback;
    app.onInputEvent = inputs_callback;
    app.userData = unsafe { std::mem::transmute(&context) };

    // executing the main function in parallel
    let g = Thread::spawn(move|| {
        std::io::stdio::set_stdout(box std::io::LineBufferedWriter::new(ToLogWriter));
        std::io::stdio::set_stderr(box std::io::LineBufferedWriter::new(ToLogWriter));
        main_function()
    });

    // polling for events forever
    // note that this must be done in the same thread as android_main because ALooper are
    //  thread-local
    unsafe {
        loop {
            let mut events = mem::uninitialized();
            let mut source = mem::uninitialized();

            // passing -1 means that we are blocking
            let ident = ffi::ALooper_pollAll(-1, ptr::null_mut(), &mut events,
                &mut source);

            // processing the event
            if !source.is_null() {
                let source: *mut ffi::android_poll_source = mem::transmute(source);
                ((*source).process)(ANDROID_APP, source);
            }
        }
    }

    // terminating the application
    unsafe { ANDROID_APP = 0 as *mut ffi::android_app };
}

/// Writer that will redirect what is written to it to the logs.
struct ToLogWriter;

impl Writer for ToLogWriter {
    fn write(&mut self, buf: &[u8]) -> std::io::IoResult<()> {
        let message = CString::from_slice(buf).as_slice_with_nul().as_ptr();
        let tag = b"RustAndroidGlueStdouterr";
        let tag = CString::from_slice(tag).as_slice_with_nul().as_ptr();
        unsafe { ffi::__android_log_write(3, tag, message) };
        Ok(())
    }
}

/// The callback for inputs.
pub extern fn inputs_callback(_: *mut ffi::android_app, event: *const ffi::AInputEvent)
    -> libc::int32_t
{
    fn send_event(event: Event) {
        let senders = get_context().senders.lock().ok().unwrap();
        for sender in senders.iter() {
            sender.send(event);
        }
    }
    fn get_xy(event: *const ffi::AInputEvent) -> (i32, i32) {
        let x = unsafe { ffi::AMotionEvent_getX(event, 0) };
        let y = unsafe { ffi::AMotionEvent_getY(event, 0) };
        (x as i32, y as i32)
    }
    let action = unsafe { ffi::AMotionEvent_getAction(event) };
    let action_code = action & ffi::AMOTION_EVENT_ACTION_MASK;
    match action_code {
        ffi::AMOTION_EVENT_ACTION_UP
            | ffi::AMOTION_EVENT_ACTION_OUTSIDE
            | ffi::AMOTION_EVENT_ACTION_CANCEL
            | ffi::AMOTION_EVENT_ACTION_POINTER_UP =>
        {
            send_event(Event::EventUp);
        },
        ffi::AMOTION_EVENT_ACTION_DOWN
            | ffi::AMOTION_EVENT_ACTION_POINTER_DOWN =>
        {
            let (x, y) = get_xy(event);
            send_event(Event::EventMove(x, y));
            send_event(Event::EventDown);
        },
        _ => {
            let (x, y) = get_xy(event);
            send_event(Event::EventMove(x, y));
        },
    }
    0
}

/// The callback for commands.
#[doc(hidden)]
pub extern fn commands_callback(_: *mut ffi::android_app, command: libc::int32_t) {
    let context = get_context();

    match command {
        ffi::APP_CMD_INIT_WINDOW => {

        },

        ffi::APP_CMD_SAVE_STATE => {

        },

        ffi::APP_CMD_TERM_WINDOW => {

        },

        ffi::APP_CMD_GAINED_FOCUS => {

        },

        ffi::APP_CMD_LOST_FOCUS => {

        },

        _ => ()
    }
}

/// Returns the current Context.
fn get_context() -> &'static Context {
    let context = unsafe { (*ANDROID_APP).userData };
    unsafe { std::mem::transmute(context) }
}

/// Adds a sender where events will be sent to.
pub fn add_sender(sender: Sender<Event>) {
    get_context().senders.lock().ok().unwrap().push(sender);
}

/// Returns a handle to the native window.
pub unsafe fn get_native_window() -> ffi::NativeWindowType {
    if ANDROID_APP.is_null() {
        panic!("The application was not initialized from android_main");
    }

    loop {
        let value = (*ANDROID_APP).window;
        if !value.is_null() {
            return value;
        }

        // spin-locking
        std::io::timer::sleep(std::time::Duration::milliseconds(10));
    }
}

///
pub fn write_log(message: &str) {
    let message = message.as_bytes();
    let message = CString::from_slice(message).as_slice_with_nul().as_ptr();
    let tag = b"RustAndroidGlueStdouterr";
    let tag = CString::from_slice(tag).as_slice_with_nul().as_ptr();
    unsafe { ffi::__android_log_write(3, tag, message) };
}

pub enum AssetError {
    AssetMissing,
    EmptyBuffer,
}

pub fn load_asset(filename: &str) -> Result<Vec<u8>, AssetError> {
    struct AssetCloser {
        asset: *const ffi::Asset,
    }

    impl Drop for AssetCloser {
        fn drop(&mut self) {
            unsafe {
                ffi::AAsset_close(self.asset)
            };
        }
    }

    unsafe fn get_asset_manager() -> *const ffi::AAssetManager {
        let app = &*ANDROID_APP;
        let activity = &*app.activity;
        activity.assetManager
    }

    let filename_c_str = CString::from_slice(filename.as_bytes())
        .as_slice_with_nul().as_ptr();
    let asset = unsafe {
        ffi::AAssetManager_open(
            get_asset_manager(), filename_c_str, ffi::MODE_STREAMING)
    };
    if asset.is_null() {
        return Err(AssetError::AssetMissing);
    }
    let _asset_closer = AssetCloser{asset: asset};
    let len = unsafe {
        ffi::AAsset_getLength(asset)
    };
    let buff = unsafe {
        ffi::AAsset_getBuffer(asset)
    };
    if buff.is_null() {
        return Err(AssetError::EmptyBuffer);
    }
    let vec = unsafe {
        Vec::from_raw_buf(buff as *const u8, len as usize)
    };
    Ok(vec)
}
<|endoftext|>


<commit_before>// -*- coding: utf-8 -*-
// ------------------------------------------------------------------------------------------------
// Copyright © 2020, tree-sitter-python authors.
// See the LICENSE file in this repo for license details.
// ------------------------------------------------------------------------------------------------

//! This crate provides a Python grammar for the [tree-sitter][] parsing library.
//!
//! Typically, you will use the [language][language func] function to add this grammar to a
//! tree-sitter [Parser][], and then use the parser to parse some code:
//!
//! ```
//! use tree_sitter::Parser;
//!
//! let code = r#"
//!     def double(x):
//!         return x * 2
//! "#;
//! let mut parser = Parser::new();
//! parser.set_language(tree_sitter_python::language()).expect("Error loading Python grammar");
//! let parsed = parser.parse(code, None);
//! # let parsed = parsed.unwrap();
//! # let root = parsed.root_node();
//! # assert!(!root.has_error());
//! ```
//!
//! [Language]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Language.html
//! [language func]: fn.language.html
//! [Parser]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Parser.html
//! [tree-sitter]: https://tree-sitter.github.io/

use tree_sitter::Language;

extern "C" {
    fn tree_sitter_python() -> Language;
}

/// Returns the tree-sitter [Language][] for this grammar.
///
/// [Language]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Language.html
pub fn language() -> Language {
    unsafe { tree_sitter_python() }
}

/// The source of the Python tree-sitter grammar description.
pub const GRAMMAR: &'static str = include_str!("../../grammar.js");

/// The syntax highlighting query for this language.
pub const HIGHLIGHT_QUERY: &'static str = include_str!("../../query/highlights.scm");

/// The content of the [`node-types.json`][] file for this grammar.
///
/// [`node-types.json`]: https://tree-sitter.github.io/tree-sitter/using-parsers#static-node-types
pub const NODE_TYPES: &'static str = include_str!("../../src/node-types.json");

/// The symbol tagging query for this language.
pub const TAGGING_QUERY: &'static str = include_str!("../../query/tags.scm");

#[cfg(test)]
mod tests {
    #[test]
    fn can_load_grammar() {
        let mut parser = tree_sitter::Parser::new();
        parser
            .set_language(super::language())
            .expect("Error loading Python grammar");
    }
}
<commit_msg>Fix include_str! file paths<commit_after>// -*- coding: utf-8 -*-
// ------------------------------------------------------------------------------------------------
// Copyright © 2020, tree-sitter-python authors.
// See the LICENSE file in this repo for license details.
// ------------------------------------------------------------------------------------------------

//! This crate provides a Python grammar for the [tree-sitter][] parsing library.
//!
//! Typically, you will use the [language][language func] function to add this grammar to a
//! tree-sitter [Parser][], and then use the parser to parse some code:
//!
//! ```
//! use tree_sitter::Parser;
//!
//! let code = r#"
//!     def double(x):
//!         return x * 2
//! "#;
//! let mut parser = Parser::new();
//! parser.set_language(tree_sitter_python::language()).expect("Error loading Python grammar");
//! let parsed = parser.parse(code, None);
//! # let parsed = parsed.unwrap();
//! # let root = parsed.root_node();
//! # assert!(!root.has_error());
//! ```
//!
//! [Language]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Language.html
//! [language func]: fn.language.html
//! [Parser]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Parser.html
//! [tree-sitter]: https://tree-sitter.github.io/

use tree_sitter::Language;

extern "C" {
    fn tree_sitter_python() -> Language;
}

/// Returns the tree-sitter [Language][] for this grammar.
///
/// [Language]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Language.html
pub fn language() -> Language {
    unsafe { tree_sitter_python() }
}

/// The source of the Python tree-sitter grammar description.
pub const GRAMMAR: &'static str = include_str!("../../grammar.js");

/// The syntax highlighting query for this language.
pub const HIGHLIGHT_QUERY: &'static str = include_str!("../../queries/highlights.scm");

/// The content of the [`node-types.json`][] file for this grammar.
///
/// [`node-types.json`]: https://tree-sitter.github.io/tree-sitter/using-parsers#static-node-types
pub const NODE_TYPES: &'static str = include_str!("../../src/node-types.json");

/// The symbol tagging query for this language.
pub const TAGGING_QUERY: &'static str = include_str!("../../queries/tags.scm");

#[cfg(test)]
mod tests {
    #[test]
    fn can_load_grammar() {
        let mut parser = tree_sitter::Parser::new();
        parser
            .set_language(super::language())
            .expect("Error loading Python grammar");
    }
}
<|endoftext|>


<commit_before>extern crate jsonwebtoken as jwt;
extern crate rustc_serialize;

use jwt::{
    Algorithm,
    encode,
    decode
};

#[derive(Debug, RustcEncodable, RustcDecodable)]
struct Claims {
    sub: String,
    company: String
}

fn main() {
    let my_claims = Claims {
        sub: "b@b.com".to_owned(),
        company: "ACME".to_owned()
    };
    let key = "secret";
    let token = encode::<Claims>(my_claims, key.to_owned(), Algorithm::HS256).unwrap();
    let claims = decode::<Claims>(token.to_owned(), key.to_owned(), Algorithm::HS256).unwrap();
}
<commit_msg>Better example<commit_after>extern crate jsonwebtoken as jwt;
extern crate rustc_serialize;

use jwt::{encode, decode, Algorithm};
use jwt::errors::{Error};

#[derive(Debug, RustcEncodable, RustcDecodable)]
struct Claims {
    sub: String,
    company: String
}

fn main() {
    let my_claims = Claims {
        sub: "b@b.com".to_owned(),
        company: "ACME".to_owned()
    };
    let key = "secret";
    let token = match encode::<Claims>(my_claims, key.to_owned(), Algorithm::HS256) {
        Ok(t) => t,
        Err(_) => panic!() // in practice you would return the error
    };

    let claims = match decode::<Claims>(token.to_owned(), key.to_owned(), Algorithm::HS256) {
        Ok(c) => c,
        Err(err) => match err {
            Error::InvalidToken => panic!(), // Example on how to handle a specific error
            _ => panic!()
        }
    };
}
<|endoftext|>


<commit_before>extern crate roboime_next;
#[macro_use] extern crate glium;
extern crate clock_ticks;
//extern crate image;
extern crate env_logger;
extern crate log;

use std::error::Error;
use std::process::exit;
//use std::io::Cursor;
use glium::Surface;
use glium::glutin;
//use image::image::GenericImage;
//use roboime_next::prelude::*;
use roboime_next::game;
use ::utils::*;
use ::models::TeamSide;

pub mod models;
pub mod colors;
mod utils;
mod draw;

fn main_loop() -> Result<(), Box<Error>> {
    use std::env;
    use std::thread;
    use std::time::Duration;
    use glium::DisplayBuild;
    use glium::glutin::GlRequest;
    use log::LogLevelFilter;
    use env_logger::LogBuilder;

    {
        let mut builder = LogBuilder::new();
        builder.format(|record| {
            format!("{} [{}] {}", record.level(), record.location().module_path(), record.args())
        });
        builder.filter(Some("roboime"), LogLevelFilter::Info);
        if env::var("RUST_LOG").is_ok() {
           builder.parse(&env::var("RUST_LOG").unwrap());
        }
        try!(builder.init());
    }

    // building the display, ie. the main object
    let display = {
        // 1 extra pixel to align the middle lines to the screen
        // TODO: refactor: deduplicate options
        if let Ok(display) = glutin::WindowBuilder::new()
            .with_title(format!("RoboIME Next"))
            .with_dimensions(1041, 741)
            .with_depth_buffer(24)
            .with_gl(GlRequest::Latest)
            .with_multisampling(4)
            .with_vsync()
            .with_srgb(Some(true))
            .build_glium() {
            display
        } else {
            try!(glutin::WindowBuilder::new()
                .with_title(format!("RoboIME Next"))
                .with_dimensions(1041, 741)
                .with_depth_buffer(24)
                .with_gl(GlRequest::Latest)
                .with_multisampling(4)
                .with_vsync()
                .with_srgb(Some(true))
                .build_glium())
        }
    };

    let team_side = TeamSide::BlueIsLeft;
    let mut draw_game = try!(draw::Game::new(&display));
    draw_game.team_side(&display, team_side);

    let mut accumulator = 0;
    let mut previous_clock = clock_ticks::precise_time_ns();
    let game_state = game::SharedState::new();

    // add some robots
    {
        let mut game_state = try!(game_state.write());
        add_initial_robots(game_state.get_robots_blue_mut(), 6, false);
        add_initial_robots(game_state.get_robots_yellow_mut(), 6, true);
    }

    // the main loop
    'main: loop {

        let mut target = display.draw();

        let view = view_matrix(&[0.0, 0.0, 10.0], &[0.0, 0.0, -1.0], &[0.0, 1.0, 0.0]);
        //let view = view_matrix(&[-4.0, -4.0, 4.0], &[1.0, 1.0, -1.0], &[0.0, 0.0, 1.0]);
        //let view = view_matrix(&[4.0, -4.0, 4.0], &[-1.0, 1.0, -1.0], &[0.0, 0.0, 1.0]);
        //let view = view_matrix(&[-0.2, -0.2, 0.6], &[0.2, 0.2, -0.6], &[0.0, 0.0, 1.0]);
        //let view = view_matrix(&[1.0, 2.0, 3.0], &[1.0, 1.0, -3.0], &[0.0, 1.0, 0.0]);
        //let view = view_matrix(&[-4.0, 0.7, 1.6], &[-0.2, -0.2, -0.6], &[0.0, 0.0, 1.0]);
        //let view = view_matrix(&[-5.0, -0.7, 1.6], &[0.2, 0.2, -0.6], &[0.0, 0.0, 1.0]);
        //let view = view_matrix(&[4.0, 0.7, 1.6], &[0.2, -0.2, -0.6], &[0.0, 0.0, 1.0]);
        //let view = view_matrix(&[5.0, -0.7, 1.6], &[-0.2, 0.2, -0.6], &[0.0, 0.0, 1.0]);

        {
            let state = try!(game_state.read());
            try!(draw_game.draw_to(&mut target, &state, view));
        }

        try!(target.finish());

        // polling and handling the events received by the window
        for event in display.poll_events() {
            match event {
                glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) |
                glutin::Event::Closed => break 'main,
                _ => ()
            }
        }

        let now = clock_ticks::precise_time_ns();
        accumulator += now - previous_clock;
        previous_clock = now;

        const FIXED_TIME_STAMP: u64 = 16666667;
        while accumulator >= FIXED_TIME_STAMP {
            accumulator -= FIXED_TIME_STAMP;

            // if you have a game, update the state here
        }

        thread::sleep(Duration::from_millis(((FIXED_TIME_STAMP - accumulator) / 1000000) as u64));
    }

    Ok(())
}

fn main() {
    if let Err(err) = main_loop() {
        println!("Error: {}.", err.description());
        while let Some(err) = err.cause() {
            println!("- caused by {}", err.description());
        }
        exit(1);
    }
}
<commit_msg>Hack to fix infinite loop while printing error causes.<commit_after>extern crate roboime_next;
#[macro_use] extern crate glium;
extern crate clock_ticks;
//extern crate image;
extern crate env_logger;
extern crate log;

use std::error::Error;
use std::process::exit;
//use std::io::Cursor;
use glium::Surface;
use glium::glutin;
//use image::image::GenericImage;
//use roboime_next::prelude::*;
use roboime_next::game;
use ::utils::*;
use ::models::TeamSide;

pub mod models;
pub mod colors;
mod utils;
mod draw;

fn main_loop() -> Result<(), Box<Error>> {
    use std::env;
    use std::thread;
    use std::time::Duration;
    use glium::DisplayBuild;
    use glium::glutin::GlRequest;
    use log::LogLevelFilter;
    use env_logger::LogBuilder;

    {
        let mut builder = LogBuilder::new();
        builder.format(|record| {
            format!("{} [{}] {}", record.level(), record.location().module_path(), record.args())
        });
        builder.filter(Some("roboime"), LogLevelFilter::Info);
        if env::var("RUST_LOG").is_ok() {
           builder.parse(&env::var("RUST_LOG").unwrap());
        }
        try!(builder.init());
    }

    // building the display, ie. the main object
    let display = {
        // 1 extra pixel to align the middle lines to the screen
        // TODO: refactor: deduplicate options
        if let Ok(display) = glutin::WindowBuilder::new()
            .with_title(format!("RoboIME Next"))
            .with_dimensions(1041, 741)
            .with_depth_buffer(24)
            .with_gl(GlRequest::Latest)
            .with_multisampling(4)
            .with_vsync()
            .with_srgb(Some(true))
            .build_glium() {
            display
        } else {
            try!(glutin::WindowBuilder::new()
                .with_title(format!("RoboIME Next"))
                .with_dimensions(1041, 741)
                .with_depth_buffer(24)
                .with_gl(GlRequest::Latest)
                .with_multisampling(4)
                .with_vsync()
                .with_srgb(Some(true))
                .build_glium())
        }
    };

    let team_side = TeamSide::BlueIsLeft;
    let mut draw_game = try!(draw::Game::new(&display));
    draw_game.team_side(&display, team_side);

    let mut accumulator = 0;
    let mut previous_clock = clock_ticks::precise_time_ns();
    let game_state = game::SharedState::new();

    // add some robots
    {
        let mut game_state = try!(game_state.write());
        add_initial_robots(game_state.get_robots_blue_mut(), 6, false);
        add_initial_robots(game_state.get_robots_yellow_mut(), 6, true);
    }

    // the main loop
    'main: loop {

        let mut target = display.draw();

        let view = view_matrix(&[0.0, 0.0, 10.0], &[0.0, 0.0, -1.0], &[0.0, 1.0, 0.0]);
        //let view = view_matrix(&[-4.0, -4.0, 4.0], &[1.0, 1.0, -1.0], &[0.0, 0.0, 1.0]);
        //let view = view_matrix(&[4.0, -4.0, 4.0], &[-1.0, 1.0, -1.0], &[0.0, 0.0, 1.0]);
        //let view = view_matrix(&[-0.2, -0.2, 0.6], &[0.2, 0.2, -0.6], &[0.0, 0.0, 1.0]);
        //let view = view_matrix(&[1.0, 2.0, 3.0], &[1.0, 1.0, -3.0], &[0.0, 1.0, 0.0]);
        //let view = view_matrix(&[-4.0, 0.7, 1.6], &[-0.2, -0.2, -0.6], &[0.0, 0.0, 1.0]);
        //let view = view_matrix(&[-5.0, -0.7, 1.6], &[0.2, 0.2, -0.6], &[0.0, 0.0, 1.0]);
        //let view = view_matrix(&[4.0, 0.7, 1.6], &[0.2, -0.2, -0.6], &[0.0, 0.0, 1.0]);
        //let view = view_matrix(&[5.0, -0.7, 1.6], &[-0.2, 0.2, -0.6], &[0.0, 0.0, 1.0]);

        {
            let state = try!(game_state.read());
            try!(draw_game.draw_to(&mut target, &state, view));
        }

        try!(target.finish());

        // polling and handling the events received by the window
        for event in display.poll_events() {
            match event {
                glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) |
                glutin::Event::Closed => break 'main,
                _ => ()
            }
        }

        let now = clock_ticks::precise_time_ns();
        accumulator += now - previous_clock;
        previous_clock = now;

        const FIXED_TIME_STAMP: u64 = 16666667;
        while accumulator >= FIXED_TIME_STAMP {
            accumulator -= FIXED_TIME_STAMP;

            // if you have a game, update the state here
        }

        thread::sleep(Duration::from_millis(((FIXED_TIME_STAMP - accumulator) / 1000000) as u64));
    }

    Ok(())
}

fn main() {
    if let Err(err) = main_loop() {
        println!("Error: {}.", err.description());
        while let Some(err) = err.cause() {
            println!("- caused by {}", err.description());
            // XXX: hack to avoid infinite loop, also because &std::error:Error doesn't impl PartialEq
            if err.cause().is_some() && err.description() == err.cause().unwrap().description() {
                break;
            }
        }
        exit(1);
    }
}
<|endoftext|>


<commit_before>//! Simple evolution example
#[macro_use]
extern crate ast;
extern crate rand;
extern crate rustc_serialize;

pub use rand::Rng;

use ast::structure::Program;
use ast::simulation;
use ast::serialize;
use ast::simplify::Simplify;
use ast::data::SensorData;
use ast::darwin::evolve;
use std::f32::consts::PI;
use std::path::Path;

const POPULATION_SIZE : usize = 1000;
const TRIALS_PER_PROGRAM : u32 = 10;
const TOURNAMENT_SIZE : usize = 20;
const SAVE_EVERY : u32 = 100;

fn random_start_position<R: rand::Rng>(rng: &mut R) -> SensorData {
    SensorData::new()
        .with_x(0.0)
        .with_y(rng.next_f32() * 100.0 + 50.0)
        .with_o(rng.next_f32() * PI * 2.0)
        .build()
}

/// Score a program by scoring a single run
///
/// Ultimate score is composed of:
/// - How many frames we survived (higher is better)
/// - What our maximum height was (lower is better)
/// - If we landed (if so then FUCK YEAH)
fn score_single_run(program: &Program) -> f64 {
    let mut rng = rand::thread_rng();
    let mut sensor_data = random_start_position(&mut rng);
    let world = simulation::World::new().build();

    let mut frames: u32 = 0;
    let mut max_height: f32 = 0.0;
    while !sensor_data.crashed && !sensor_data.landed {
        simulation::next(&mut sensor_data, &program, &world);
        frames += 1;
        if sensor_data.y > max_height { max_height = sensor_data.y };
    };

    let score = 2.0 * frames as f32 + -max_height + if sensor_data.landed { 500.0 } else { 0.0 };
    score as f64
}

/// Score a program by averaging the score of multiple random runs
fn score_program(program: &Program) -> f64 {
    let mut total = 0.0;
    for _ in 0..TRIALS_PER_PROGRAM {
        total += score_single_run(program);
    };
    total / TRIALS_PER_PROGRAM as f64
}

fn save_trace(generation: u32, program: &Program) {
    let mut sensor_data = random_start_position(&mut rand::thread_rng());
    let world = simulation::World::new().build();
    let mut trace = serialize::GameTrace::new();

    trace.add(&sensor_data);
    while !sensor_data.crashed && !sensor_data.landed {
        simulation::next(&mut sensor_data, &program, &world);
        trace.add(&sensor_data);
    }

    let tracefile = format!("trace_{}.json", generation);
    trace.save(Path::new(&tracefile)).expect("Error saving file");

    let progfile = format!("program_{}.txt", generation);
    let _ = serialize::save_source(Path::new(&progfile), &program.simplify());
}

fn main() {
    // Generate initial random population
    println!("Generating initial population");
    let mut population = evolve::random_population(POPULATION_SIZE);
    let mut rng = rand::thread_rng();

    let mut gen = 0;
    loop {
        println!("[{}] Scoring", gen);
        gen += 1;
        population.score(score_program);
        {
            let (best_program, best_score) = population.best();
            println!("[{}] Best score: {}", gen, best_score);

            if gen % SAVE_EVERY == 0 {
                println!("[{}] Saving", gen);
                save_trace(gen, best_program);
            }
        }

        println!("[{}] Evolving", gen);
        population = population.evolve(TOURNAMENT_SIZE,
                                       10, 10, 5,
                                       &mut rng);
    }
}
<commit_msg>Add rotation into fitness function<commit_after>//! Simple evolution example
#[macro_use]
extern crate ast;
extern crate rand;
extern crate rustc_serialize;

pub use rand::Rng;

use std::ops::Mul;
use ast::structure::Program;
use ast::simulation;
use ast::serialize;
use ast::simplify::Simplify;
use ast::data::SensorData;
use ast::darwin::evolve;
use std::f32::consts::PI;
use std::path::Path;

const POPULATION_SIZE : usize = 2000;
const TRIALS_PER_PROGRAM : u32 = 10;
const TOURNAMENT_SIZE : usize = 20;
const SAVE_EVERY : u32 = 100;

fn random_start_position<R: rand::Rng>(rng: &mut R) -> SensorData {
    SensorData::new()
        .with_x(0.0)
        .with_y(rng.next_f32() * 100.0 + 50.0)
        .with_o(rng.next_f32() * PI * 2.0)
        .build()
}

fn square<T: Mul+Copy>(x: T) -> T::Output {
    x * x
}

fn angle_dist(o: f32) -> f32 {
    let r = o % 2. * PI;
    if r > PI { 2. * PI - r } else { r }
}

/// Score a program by scoring a single run
///
/// Ultimate score is composed of:
/// - How many frames we survived (higher is better)
/// - What our maximum height was (lower is better)
/// - If we landed (if so then FUCK YEAH)
fn score_single_run(program: &Program) -> f64 {
    let mut rng = rand::thread_rng();
    let mut sensor_data = random_start_position(&mut rng);
    let world = simulation::World::new().build();

    let mut frames: u32 = 0;
    let mut total_height: f32 = 0.;
    let mut total_fuel: f32 = 0.;
    let mut total_angle: f32 = 0.;

    while !sensor_data.crashed && !sensor_data.landed {
        total_height += square(sensor_data.y);
        total_fuel += square(sensor_data.fuel);
        total_angle += square(angle_dist(sensor_data.o));

        simulation::next(&mut sensor_data, &program, &world);

        frames += 1;
    };

    let score =
        3.0 * frames as f32
        + -(0.001 * total_height / frames as f32) // Average height is penalty
        + -(3. * total_angle / frames as f32) // Penalty for angle distance
        + (100.0 * total_fuel / frames as f32) // Average fuel is too
        + if sensor_data.landed { 500.0 } else { 0.0 }
        ;
    score as f64
}

/// Score a program by averaging the score of multiple random runs
fn score_program(program: &Program) -> f64 {
    let mut total = 0.0;
    for _ in 0..TRIALS_PER_PROGRAM {
        let score = score_single_run(program);
        if score > total {
            total = score;
        }
    };
    total
}

fn save_trace(generation: u32, program: &Program) {
    let mut sensor_data = random_start_position(&mut rand::thread_rng());
    let world = simulation::World::new().build();
    let mut trace = serialize::GameTrace::new();

    trace.add(&sensor_data);
    while !sensor_data.crashed && !sensor_data.landed {
        simulation::next(&mut sensor_data, &program, &world);
        trace.add(&sensor_data);
    }

    let tracefile = format!("trace_{}.json", generation);
    trace.save(Path::new(&tracefile)).expect("Error saving file");

    let progfile = format!("program_{}.txt", generation);
    let _ = serialize::save_source(Path::new(&progfile), &program.simplify());
}

fn main() {
    // Generate initial random population
    println!("Generating initial population");
    let mut population = evolve::random_population(POPULATION_SIZE);
    let mut rng = rand::thread_rng();

    let mut gen = 0;
    loop {
        println!("[{}] Scoring", gen);
        gen += 1;
        population.score(score_program);
        {
            let (best_program, best_score) = population.best();
            println!("[{}] Best score: {}", gen, best_score);

            if gen % SAVE_EVERY == 0 {
                println!("[{}] Saving", gen);
                save_trace(gen, best_program);
            }
        }

        println!("[{}] Evolving", gen);
        population = population.evolve(TOURNAMENT_SIZE,
                                       10, 10, 5,
                                       &mut rng);
    }
}
<|endoftext|>


<commit_before>#[macro_use] extern crate prettytable;

use prettytable::Slice;

fn main() {
    let mut table = table![[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4], [5, 5, 5]];
    table.set_titles(row![cell!("t1"), cell!("t2"), cell!("t3")]);

    let slice = table.slice(..);
    let slice = slice.slice(2..);
    let slice = slice.slice(..3);

    /*
        Will print
        +----+----+----+
        | t1 | t2 | t3 |
        +====+====+====+
        | 2  | 2  | 2  |
        +----+----+----+
        | 3  | 3  | 3  |
        +----+----+----+
    */
    slice.printstd();

    // This is equivalent to
    let slice = table.slice(2..3);
    slice.printstd();
}
<commit_msg>Fixed slice example<commit_after>#[macro_use] extern crate prettytable;

use prettytable::Slice;

fn main() {
    let mut table = table![[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4], [5, 5, 5]];
    table.set_titles(row!["t1", "t2", "t3"]);

    let slice = table.slice(..);
    let slice = slice.slice(2..);
    let slice = slice.slice(..3);

    /*
        Will print
        +----+----+----+
        | t1 | t2 | t3 |
        +====+====+====+
        | 2  | 2  | 2  |
        +----+----+----+
        | 3  | 3  | 3  |
        +----+----+----+
    */
    slice.printstd();

    // This is equivalent to
    let slice = table.slice(2..5);
    slice.printstd();
}
<|endoftext|>


<commit_before>//! An example of how to use a `MeshBatch`.

use ggez;

use ggez::event;
use ggez::graphics;
use ggez::timer;
use ggez::{Context, GameResult};
use glam::*;
use oorandom::Rand32;
use std::env;
use std::f32::consts::PI;
use std::path;

const TWO_PI: f32 = 2.0 * PI;

struct MainState {
    mesh_batch: graphics::MeshBatch,
}

impl MainState {
    fn new(ctx: &mut Context) -> GameResult<MainState> {
        let mut rng = Rand32::new(12345);
        let mesh = graphics::MeshBuilder::new()
            .circle(
                graphics::DrawMode::stroke(4.0),
                Vec2::new(0.0, 0.0),
                8.0,
                1.0,
                (0, 0, 255).into(),
            )?
            .line(
                &[Vec2::new(0.0, 0.0), Vec2::new(8.0, 0.0)],
                2.0,
                (255, 255, 0).into(),
            )?
            .build(ctx)?;

        let mut mesh_batch = graphics::MeshBatch::new(mesh)?;

        // Generate enough instances to fill the entire screen
        let items_x = (graphics::drawable_size(ctx).0 / 16.0) as u32;
        let items_y = (graphics::drawable_size(ctx).1 / 16.0) as u32;
        for x in 1..items_x {
            for y in 1..items_y {
                let x = x as f32;
                let y = y as f32;

                let p = graphics::DrawParam::new()
                    .dest(Vec2::new(x * 16.0, y * 16.0))
                    .rotation(rng.rand_float() * TWO_PI);

                mesh_batch.add(p);
            }
        }

        // Randomly shuffle generated instances.
        // We will update the first 50 of them later.
        mesh_batch.get_instance_params_mut();
        //.shuffle(&mut thread_rng());

        let s = MainState { mesh_batch };
        Ok(s)
    }
}

impl event::EventHandler for MainState {
    fn update(&mut self, ctx: &mut Context) -> GameResult {
        if timer::ticks(ctx) % 100 == 0 {
            println!("Delta frame time: {:?} ", timer::delta(ctx));
            println!("Average FPS: {}", timer::fps(ctx));
        }

        // Update first 50 instances in the mesh batch
        let delta_time = (timer::duration_to_f64(timer::delta(ctx)) * 1000.0) as f32;
        let instances = self.mesh_batch.get_instance_params_mut();
        for i in 0..50 {
            if let graphics::Transform::Values {
                ref mut rotation, ..
            } = instances[i].trans
            {
                //let rotation = &mut instances[i].rotation;
                if (i % 2) == 0 {
                    *rotation += 0.001 * TWO_PI * delta_time;
                    if *rotation > TWO_PI {
                        *rotation -= TWO_PI;
                    }
                } else {
                    *rotation -= 0.001 * TWO_PI * delta_time;
                    if *rotation < 0.0 {
                        *rotation += TWO_PI;
                    }
                }
            }
        }

        Ok(())
    }

    fn draw(&mut self, ctx: &mut Context) -> GameResult {
        graphics::clear(ctx, graphics::BLACK);

        // Flush the first 50 instances in the batch to make our changes visible
        // to the graphics card.
        self.mesh_batch.flush_range(ctx, graphics::MeshIdx(0), 50)?;

        // Draw the batch
        self.mesh_batch.draw(ctx, graphics::DrawParam::default())?;

        graphics::present(ctx)?;
        Ok(())
    }
}

pub fn main() -> GameResult {
    let resource_dir = if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
        let mut path = path::PathBuf::from(manifest_dir);
        path.push("resources");
        path
    } else {
        path::PathBuf::from("./resources")
    };

    let cb = ggez::ContextBuilder::new("spritebatch", "ggez").add_resource_path(resource_dir);
    let (mut ctx, event_loop) = cb.build()?;

    let state = MainState::new(&mut ctx)?;
    event::run(ctx, event_loop, state)
}
<commit_msg>Fix build<commit_after>//! An example of how to use a `MeshBatch`.

use ggez;

use ggez::event;
use ggez::graphics::{self, Color};
use ggez::timer;
use ggez::{Context, GameResult};
use glam::*;
use oorandom::Rand32;
use std::env;
use std::f32::consts::PI;
use std::path;

const TWO_PI: f32 = 2.0 * PI;

struct MainState {
    mesh_batch: graphics::MeshBatch,
}

impl MainState {
    fn new(ctx: &mut Context) -> GameResult<MainState> {
        let mut rng = Rand32::new(12345);
        let mesh = graphics::MeshBuilder::new()
            .circle(
                graphics::DrawMode::stroke(4.0),
                Vec2::new(0.0, 0.0),
                8.0,
                1.0,
                (0, 0, 255).into(),
            )?
            .line(
                &[Vec2::new(0.0, 0.0), Vec2::new(8.0, 0.0)],
                2.0,
                (255, 255, 0).into(),
            )?
            .build(ctx)?;

        let mut mesh_batch = graphics::MeshBatch::new(mesh)?;

        // Generate enough instances to fill the entire screen
        let items_x = (graphics::drawable_size(ctx).0 / 16.0) as u32;
        let items_y = (graphics::drawable_size(ctx).1 / 16.0) as u32;
        for x in 1..items_x {
            for y in 1..items_y {
                let x = x as f32;
                let y = y as f32;

                let p = graphics::DrawParam::new()
                    .dest(Vec2::new(x * 16.0, y * 16.0))
                    .rotation(rng.rand_float() * TWO_PI);

                mesh_batch.add(p);
            }
        }

        // Randomly shuffle generated instances.
        // We will update the first 50 of them later.
        mesh_batch.get_instance_params_mut();
        //.shuffle(&mut thread_rng());

        let s = MainState { mesh_batch };
        Ok(s)
    }
}

impl event::EventHandler for MainState {
    fn update(&mut self, ctx: &mut Context) -> GameResult {
        if timer::ticks(ctx) % 100 == 0 {
            println!("Delta frame time: {:?} ", timer::delta(ctx));
            println!("Average FPS: {}", timer::fps(ctx));
        }

        // Update first 50 instances in the mesh batch
        let delta_time = (timer::duration_to_f64(timer::delta(ctx)) * 1000.0) as f32;
        let instances = self.mesh_batch.get_instance_params_mut();
        for i in 0..50 {
            if let graphics::Transform::Values {
                ref mut rotation, ..
            } = instances[i].trans
            {
                //let rotation = &mut instances[i].rotation;
                if (i % 2) == 0 {
                    *rotation += 0.001 * TWO_PI * delta_time;
                    if *rotation > TWO_PI {
                        *rotation -= TWO_PI;
                    }
                } else {
                    *rotation -= 0.001 * TWO_PI * delta_time;
                    if *rotation < 0.0 {
                        *rotation += TWO_PI;
                    }
                }
            }
        }

        Ok(())
    }

    fn draw(&mut self, ctx: &mut Context) -> GameResult {
        graphics::clear(ctx, Color::BLACK);

        // Flush the first 50 instances in the batch to make our changes visible
        // to the graphics card.
        self.mesh_batch.flush_range(ctx, graphics::MeshIdx(0), 50)?;

        // Draw the batch
        self.mesh_batch.draw(ctx, graphics::DrawParam::default())?;

        graphics::present(ctx)?;
        Ok(())
    }
}

pub fn main() -> GameResult {
    let resource_dir = if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
        let mut path = path::PathBuf::from(manifest_dir);
        path.push("resources");
        path
    } else {
        path::PathBuf::from("./resources")
    };

    let cb = ggez::ContextBuilder::new("spritebatch", "ggez").add_resource_path(resource_dir);
    let (mut ctx, event_loop) = cb.build()?;

    let state = MainState::new(&mut ctx)?;
    event::run(ctx, event_loop, state)
}
<|endoftext|>


<commit_before>extern crate hwloc;
extern crate libc;

use hwloc::{Topology, ObjectType, CPUBIND_THREAD, CpuSet};
use std::thread;
use std::sync::{Arc,Mutex};

/// Example which spawns one thread per core and then assigns it to each.
///
/// Example Output with 2 cores (no HT) on linux:
///
/// ```
/// Found 2 cores.
/// Thread 0: Before Some(0-1), After Some(0)
/// Thread 1: Before Some(0-1), After Some(1)
/// ```
fn main() {
    let topo = Arc::new(Mutex::new(Topology::new()));

    // Grab the number of cores in a block so that the lock is removed once
    // the end of the block is reached.
    let num_cores = {
        let topo_rc = topo.clone();
        let topo_locked = topo_rc.lock().unwrap();
        (*topo_locked).objects_with_type(&ObjectType::Core).unwrap().len()
    };
    println!("Found {} cores.", num_cores);

    // Spawn one thread for each and pass the topology down into scope.
    let handles: Vec<_> = (0..num_cores).map(|i| {
            let child_topo = topo.clone();
            thread::spawn(move || {
                // Get the current thread id and lock the topology to use.
                let tid = get_thread_id();
                let mut locked_topo = child_topo.lock().unwrap();

                // Thread binding before explicit set.
                let before = locked_topo.get_cpubinding_for_thread(tid, CPUBIND_THREAD);

                // Create a CPU binding for the current thread.
                let mut bind_to = CpuSet::new();
                bind_to.set((i as u32));

                // Set the binding.
                locked_topo.set_cpubinding_for_thread(tid, bind_to, CPUBIND_THREAD).unwrap();

                // Thread binding after explicit set.
                let after = locked_topo.get_cpubinding_for_thread(tid, CPUBIND_THREAD);
                println!("Thread {}: Before {:?}, After {:?}", i, before, after);
            })
        }).collect();

        // Wait for all threads to complete before ending the program.
        for h in handles {
            h.join().unwrap();
        }
}

/// Helper method to get the thread id through libc, with current rust stable (1.5.0) its not
/// possible otherwise I think.
fn get_thread_id() -> libc::pthread_t {
    unsafe { libc::pthread_self() }
}
<commit_msg>grab the right cpuset for example. fixes #14<commit_after>extern crate hwloc;
extern crate libc;

use hwloc::{Topology, ObjectType, CPUBIND_THREAD, CpuSet};
use std::thread;
use std::sync::{Arc,Mutex};

/// Example which spawns one thread per core and then assigns it to each.
///
/// Example Output with 2 cores (no HT) on linux:
///
/// ```
/// Found 2 cores.
/// Thread 0: Before Some(0-1), After Some(0)
/// Thread 1: Before Some(0-1), After Some(1)
/// ```
fn main() {
    let topo = Arc::new(Mutex::new(Topology::new()));

    // Grab the number of cores in a block so that the lock is removed once
    // the end of the block is reached.
    let num_cores = {
        let topo_rc = topo.clone();
        let topo_locked = topo_rc.lock().unwrap();
        (*topo_locked).objects_with_type(&ObjectType::Core).unwrap().len()
    };
    println!("Found {} cores.", num_cores);

    // Spawn one thread for each and pass the topology down into scope.
    let handles: Vec<_> = (0..num_cores).map(|i| {
            let child_topo = topo.clone();
            thread::spawn(move || {
                // Get the current thread id and lock the topology to use.
                let tid = get_thread_id();
                let mut locked_topo = child_topo.lock().unwrap();

                // Thread binding before explicit set.
                let before = locked_topo.get_cpubinding_for_thread(tid, CPUBIND_THREAD);

                // load the cpuset for the given core index.
                let bind_to = cpuset_for_core(&*locked_topo, i);

                // Set the binding.
                locked_topo.set_cpubinding_for_thread(tid, bind_to, CPUBIND_THREAD).unwrap();

                // Thread binding after explicit set.
                let after = locked_topo.get_cpubinding_for_thread(tid, CPUBIND_THREAD);
                println!("Thread {}: Before {:?}, After {:?}", i, before, after);
            })
        }).collect();

        // Wait for all threads to complete before ending the program.
        for h in handles {
            h.join().unwrap();
        }
}

/// Load the CpuSet for the given core index.
fn cpuset_for_core(topology: &Topology, idx: usize) -> CpuSet {
    let cores = (*topology).objects_with_type(&ObjectType::Core).unwrap();
    match cores.get(idx) {
        Some(val) => val.cpuset().unwrap(),
        None => panic!("No Core found with id {}", idx)
    }
}

/// Helper method to get the thread id through libc, with current rust stable (1.5.0) its not
/// possible otherwise I think.
fn get_thread_id() -> libc::pthread_t {
    unsafe { libc::pthread_self() }
}
<|endoftext|>


<commit_before>#![allow(
    clippy::blocks_in_if_conditions,
    clippy::cast_possible_truncation,
    clippy::manual_map,
    clippy::map_unwrap_or,
    clippy::needless_pass_by_value,
    clippy::option_if_let_else,
    clippy::range_plus_one,
    clippy::single_match_else,
    clippy::too_many_lines
)]

extern crate proc_macro;

mod ast;
mod attr;
mod expand;
mod fmt;
mod generics;
mod prop;
mod valid;

use proc_macro::TokenStream;
use syn::{parse_macro_input, DeriveInput};

#[proc_macro_derive(Error, attributes(backtrace, error, from, source))]
pub fn derive_error(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand::derive(&input)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}
<commit_msg>Ignore cast_lossless Clippy pedantic lint<commit_after>#![allow(
    clippy::blocks_in_if_conditions,
    clippy::cast_lossless,
    clippy::cast_possible_truncation,
    clippy::manual_map,
    clippy::map_unwrap_or,
    clippy::needless_pass_by_value,
    clippy::option_if_let_else,
    clippy::range_plus_one,
    clippy::single_match_else,
    clippy::too_many_lines
)]

extern crate proc_macro;

mod ast;
mod attr;
mod expand;
mod fmt;
mod generics;
mod prop;
mod valid;

use proc_macro::TokenStream;
use syn::{parse_macro_input, DeriveInput};

#[proc_macro_derive(Error, attributes(backtrace, error, from, source))]
pub fn derive_error(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand::derive(&input)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}
<|endoftext|>


<commit_before>extern crate env_logger;
#[macro_use]
extern crate log;
extern crate mesos;
extern crate proto;
extern crate uuid;

use proto::{CommandInfo, ExecutorID, Filters, FrameworkID, FrameworkInfo,
            MasterInfo, Offer, OfferID, Resource, SlaveID, TaskID, TaskInfo,
            TaskStatus, Value_Scalar, Value_Type};
use mesos::scheduler::Scheduler;
use mesos::scheduler_driver::{SchedulerDriver, MesosSchedulerDriver};

struct MyScheduler;
#[allow(unused_variables)]
impl Scheduler for MyScheduler {
    fn disconnected(&self, driver: &SchedulerDriver) {}

    // Invoked when there is an unrecoverable error in the scheduler or driver.
    fn error(&self, driver: &SchedulerDriver, message: &str) {}

    // Invoked when an executor has exited/terminated.
    fn executor_lost(&self, driver: &SchedulerDriver, executor_id: &ExecutorID, slave_id: &SlaveID, status: isize) {}

    // Invoked when an executor sends a message.
    fn framework_message(&self, driver: &SchedulerDriver, executor_id: &ExecutorID, slave_id: &SlaveID, data: &[u8]) {}

    // Invoked when an offer is no longer valid (e.g., the slave was lost or another framework used resources in the offer).
    fn offer_rescinded(&self, driver: &SchedulerDriver, offer_id: &OfferID) {
        info!("Offer rescinded {:?}", offer_id);
    }

    // Invoked when the scheduler successfully registers with a Mesos master.
    fn registered(&self, driver: &SchedulerDriver, framework_id: &FrameworkID, master_info: &MasterInfo) {
        info!("Registered {:?} {:?}", framework_id, master_info);
    }

    // Invoked when the scheduler re-registers with a newly elected Mesos master.
    fn reregistered(&self, driver: &SchedulerDriver, master_info: &MasterInfo) {}

    // Invoked when resources have been offered to this framework.
    fn resource_offers(&self, driver: &SchedulerDriver, offers: &Vec<Offer>) {
        info!("Resources offered: {:?} offer", offers.len());

        for offer in offers {
            let mut task_id = TaskID::new();
            task_id.set_value(uuid::Uuid::new_v4().to_string());

            let mut resource1 = Resource::new();
            resource1.set_name("cpus".to_string());
            resource1.set_field_type(Value_Type::SCALAR);
            let mut scalar = Value_Scalar::new();
            scalar.set_value(1.0);
            resource1.set_scalar(scalar);

            let mut resource2 = Resource::new();
            resource2.set_name("mem".to_string());
            resource2.set_field_type(Value_Type::SCALAR);
            let mut scalar = Value_Scalar::new();
            scalar.set_value(64.0);
            resource2.set_scalar(scalar);

            let mut command = CommandInfo::new();
            command.set_shell(true);
            command.set_value("echo Hello Mesos!".to_string());

            let mut task = TaskInfo::new();
            task.set_name(format!("task {:?}", task_id));
            task.set_task_id(task_id);
            task.set_slave_id(offer.get_slave_id().clone());
            task.mut_resources().push(resource1);
            task.mut_resources().push(resource2);
            task.set_command(command);

            info!("Launching task {:?}", task.get_task_id());

            driver.launch_tasks(&vec![offer.get_id().clone()], &vec![task], &Filters::new()).unwrap();
        }
    }

    // Invoked when a slave has been determined unreachable (e.g., machine failure, network partition).
    fn slave_lost(&self, driver: &SchedulerDriver, slave_id: &SlaveID) {}

    // Invoked when the status of a task has changed (e.g., a slave is lost and so the task is lost, a task finishes and an executor sends a status update saying so, etc).
    fn status_update(&self, driver: &SchedulerDriver, status: &TaskStatus) {
        info!("Status updated TaskStatus {:?}", status);
    }
}

fn main() {
    env_logger::init().unwrap();

    let scheduler = MyScheduler;
    let master = "zk://localhost:2181/mesos";
    let mut framework = FrameworkInfo::new();

    framework.set_name("rustframework".to_string());
    framework.set_user("bonifaido".to_string());
    framework.set_failover_timeout(60.0);

    let driver = MesosSchedulerDriver::new(scheduler, framework, master).unwrap();
    driver.run().unwrap();
}<commit_msg>Register framework with $USER as user name<commit_after>extern crate env_logger;
#[macro_use]
extern crate log;
extern crate mesos;
extern crate proto;
extern crate uuid;

use std::env;

use proto::{CommandInfo, ExecutorID, Filters, FrameworkID, FrameworkInfo,
            MasterInfo, Offer, OfferID, Resource, SlaveID, TaskID, TaskInfo,
            TaskStatus, Value_Scalar, Value_Type};
use mesos::scheduler::Scheduler;
use mesos::scheduler_driver::{SchedulerDriver, MesosSchedulerDriver};

struct MyScheduler;
#[allow(unused_variables)]
impl Scheduler for MyScheduler {
    fn disconnected(&self, driver: &SchedulerDriver) {}

    // Invoked when there is an unrecoverable error in the scheduler or driver.
    fn error(&self, driver: &SchedulerDriver, message: &str) {}

    // Invoked when an executor has exited/terminated.
    fn executor_lost(&self, driver: &SchedulerDriver, executor_id: &ExecutorID, slave_id: &SlaveID, status: isize) {}

    // Invoked when an executor sends a message.
    fn framework_message(&self, driver: &SchedulerDriver, executor_id: &ExecutorID, slave_id: &SlaveID, data: &[u8]) {}

    // Invoked when an offer is no longer valid (e.g., the slave was lost or another framework used resources in the offer).
    fn offer_rescinded(&self, driver: &SchedulerDriver, offer_id: &OfferID) {
        info!("Offer rescinded {:?}", offer_id);
    }

    // Invoked when the scheduler successfully registers with a Mesos master.
    fn registered(&self, driver: &SchedulerDriver, framework_id: &FrameworkID, master_info: &MasterInfo) {
        info!("Registered {:?} {:?}", framework_id, master_info);
    }

    // Invoked when the scheduler re-registers with a newly elected Mesos master.
    fn reregistered(&self, driver: &SchedulerDriver, master_info: &MasterInfo) {}

    // Invoked when resources have been offered to this framework.
    fn resource_offers(&self, driver: &SchedulerDriver, offers: &Vec<Offer>) {
        info!("Resources offered: {:?} offer", offers.len());

        for offer in offers {
            let mut task_id = TaskID::new();
            task_id.set_value(uuid::Uuid::new_v4().to_string());

            let mut resource1 = Resource::new();
            resource1.set_name("cpus".to_string());
            resource1.set_field_type(Value_Type::SCALAR);
            let mut scalar = Value_Scalar::new();
            scalar.set_value(1.0);
            resource1.set_scalar(scalar);

            let mut resource2 = Resource::new();
            resource2.set_name("mem".to_string());
            resource2.set_field_type(Value_Type::SCALAR);
            let mut scalar = Value_Scalar::new();
            scalar.set_value(64.0);
            resource2.set_scalar(scalar);

            let mut command = CommandInfo::new();
            command.set_shell(true);
            command.set_value("echo Hello Mesos!".to_string());

            let mut task = TaskInfo::new();
            task.set_name(format!("task {:?}", task_id));
            task.set_task_id(task_id);
            task.set_slave_id(offer.get_slave_id().clone());
            task.mut_resources().push(resource1);
            task.mut_resources().push(resource2);
            task.set_command(command);

            info!("Launching task {:?}", task.get_task_id());

            driver.launch_tasks(&vec![offer.get_id().clone()], &vec![task], &Filters::new()).unwrap();
        }
    }

    // Invoked when a slave has been determined unreachable (e.g., machine failure, network partition).
    fn slave_lost(&self, driver: &SchedulerDriver, slave_id: &SlaveID) {}

    // Invoked when the status of a task has changed (e.g., a slave is lost and so the task is lost, a task finishes and an executor sends a status update saying so, etc).
    fn status_update(&self, driver: &SchedulerDriver, status: &TaskStatus) {
        info!("Status updated TaskStatus {:?}", status);
    }
}

fn main() {
    env_logger::init().unwrap();

    let scheduler = MyScheduler;
    let master = "zk://localhost:2181/mesos";
    let mut framework = FrameworkInfo::new();

    let user_name = env::var("USER").unwrap();

    framework.set_name("rustframework".to_string());
    framework.set_user(user_name);
    framework.set_failover_timeout(60.0);

    let driver = MesosSchedulerDriver::new(scheduler, framework, master).unwrap();
    driver.run().unwrap();
}<|endoftext|>


<commit_before>// Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use std::fs::File;
use std::io::{self, BufRead, BufReader, Cursor, Read, Write};
use std::mem::size_of;
use std::os::unix::fs::FileExt;
use std::os::unix::io::AsRawFd;

use crate::filesystem::{FileSystem, ZeroCopyReader, ZeroCopyWriter};
use crate::server::{Mapper, Reader, Server, Writer};
use crate::sys;
use crate::{Error, Result};

struct DevFuseReader<'a> {
    // File representing /dev/fuse for reading, with sufficient buffer to accommodate a FUSE read
    // transaction.
    reader: &'a mut BufReader<File>,
}

impl<'a> DevFuseReader<'a> {
    pub fn new(reader: &'a mut BufReader<File>) -> Self {
        DevFuseReader { reader }
    }
}

impl Read for DevFuseReader<'_> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.reader.read(buf)
    }
}

impl Reader for DevFuseReader<'_> {}

impl ZeroCopyReader for DevFuseReader<'_> {
    fn read_to(&mut self, f: &mut File, count: usize, off: u64) -> io::Result<usize> {
        let buf = self.reader.fill_buf()?;
        let end = std::cmp::min(count, buf.len());
        let written = f.write_at(&buf[..end], off)?;
        self.reader.consume(written);
        Ok(written)
    }
}

struct DevFuseWriter<'a> {
    // File representing /dev/fuse for writing.
    dev_fuse: &'a mut File,

    // An internal buffer to allow generating data and header out of order, such that they can be
    // flushed at once. This is wrapped by a cursor for tracking the current written position.
    write_buf: &'a mut Cursor<Vec<u8>>,
}

impl<'a> DevFuseWriter<'a> {
    pub fn new(dev_fuse: &'a mut File, write_buf: &'a mut Cursor<Vec<u8>>) -> Self {
        debug_assert_eq!(write_buf.position(), 0);

        DevFuseWriter {
            dev_fuse,
            write_buf,
        }
    }
}

impl Write for DevFuseWriter<'_> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.write_buf.write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.dev_fuse.write_all(&self.write_buf.get_ref()[..])?;
        self.write_buf.set_position(0);
        self.write_buf.get_mut().clear();
        Ok(())
    }
}

impl Writer for DevFuseWriter<'_> {
    type ClosureWriter = Self;

    fn write_at<F>(&mut self, offset: usize, f: F) -> io::Result<usize>
    where
        F: Fn(&mut Self) -> io::Result<usize>,
    {
        // Restore the cursor for idempotent.
        let original = self.write_buf.position();
        self.write_buf.set_position(offset as u64);
        let r = f(self);
        self.write_buf.set_position(original);
        r
    }

    fn has_sufficient_buffer(&self, size: u32) -> bool {
        (self.write_buf.position() as usize + size as usize) < self.write_buf.get_ref().capacity()
    }
}

impl ZeroCopyWriter for DevFuseWriter<'_> {
    fn write_from(&mut self, f: &mut File, count: usize, off: u64) -> io::Result<usize> {
        let pos = self.write_buf.position() as usize;
        let end = pos + count;
        let buf = self.write_buf.get_mut();

        let old_end = buf.len();
        buf.resize(end, 0);
        let read = f.read_at(&mut buf[pos..end], off)?;

        let new_end = pos + read;
        debug_assert!(new_end >= old_end);
        buf.truncate(new_end);
        self.write_buf.set_position(new_end as u64);
        Ok(read)
    }
}

struct DevFuseMapper;

impl DevFuseMapper {
    fn new() -> Self {
        Self {}
    }
}

impl Mapper for DevFuseMapper {
    fn map(
        &self,
        _mem_offset: u64,
        _size: usize,
        _fd: &dyn AsRawFd,
        _file_offset: u64,
        _prot: u32,
    ) -> io::Result<()> {
        Err(io::Error::from_raw_os_error(libc::EOPNOTSUPP))
    }

    fn unmap(&self, _offset: u64, _size: u64) -> io::Result<()> {
        Err(io::Error::from_raw_os_error(libc::EOPNOTSUPP))
    }
}

/// Start the FUSE message handling loop. Returns when an error happens.
pub fn start_message_loop<F: FileSystem + Sync>(
    dev_fuse: File,
    max_write: u32,
    max_read: u32,
    fs: F,
) -> Result<()> {
    let server = Server::new(fs);
    let mut buf_reader = BufReader::with_capacity(
        max_write as usize + size_of::<sys::InHeader>() + size_of::<sys::WriteIn>(),
        dev_fuse.try_clone().map_err(Error::EndpointSetup)?,
    );

    let mut write_buf = Cursor::new(Vec::with_capacity(max_read as usize));
    let mut wfile = dev_fuse.try_clone().map_err(Error::EndpointSetup)?;
    loop {
        let dev_fuse_reader = DevFuseReader::new(&mut buf_reader);
        let dev_fuse_writer = DevFuseWriter::new(&mut wfile, &mut write_buf);
        let dev_fuse_mapper = DevFuseMapper::new();

        if let Err(e) = server.handle_message(dev_fuse_reader, dev_fuse_writer, &dev_fuse_mapper) {
            return Err(e);
        }
    }
}
<commit_msg>Drain the read buffer of DevFuseReader<commit_after>// Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use std::fs::File;
use std::io::{self, BufRead, BufReader, Cursor, Read, Write};
use std::mem::size_of;
use std::os::unix::fs::FileExt;
use std::os::unix::io::AsRawFd;

use crate::filesystem::{FileSystem, ZeroCopyReader, ZeroCopyWriter};
use crate::server::{Mapper, Reader, Server, Writer};
use crate::sys;
use crate::{Error, Result};

struct DevFuseReader {
    // File representing /dev/fuse for reading, with sufficient buffer to accommodate a FUSE read
    // transaction.
    reader: BufReader<File>,
}

impl DevFuseReader {
    pub fn new(reader: BufReader<File>) -> Self {
        DevFuseReader { reader }
    }

    fn drain(&mut self) {
        self.reader.consume(self.reader.buffer().len());
    }
}

impl Read for DevFuseReader {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.reader.read(buf)
    }
}

impl Reader for DevFuseReader {}

impl ZeroCopyReader for DevFuseReader {
    fn read_to(&mut self, f: &mut File, count: usize, off: u64) -> io::Result<usize> {
        let buf = self.reader.fill_buf()?;
        let end = std::cmp::min(count, buf.len());
        let written = f.write_at(&buf[..end], off)?;
        self.reader.consume(written);
        Ok(written)
    }
}

struct DevFuseWriter {
    // File representing /dev/fuse for writing.
    dev_fuse: File,

    // An internal buffer to allow generating data and header out of order, such that they can be
    // flushed at once. This is wrapped by a cursor for tracking the current written position.
    write_buf: Cursor<Vec<u8>>,
}

impl DevFuseWriter {
    pub fn new(dev_fuse: File, write_buf: Cursor<Vec<u8>>) -> Self {
        debug_assert_eq!(write_buf.position(), 0);

        DevFuseWriter {
            dev_fuse,
            write_buf,
        }
    }
}

impl Write for DevFuseWriter {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.write_buf.write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.dev_fuse.write_all(&self.write_buf.get_ref()[..])?;
        self.write_buf.set_position(0);
        self.write_buf.get_mut().clear();
        Ok(())
    }
}

impl Writer for DevFuseWriter {
    type ClosureWriter = Self;

    fn write_at<F>(&mut self, offset: usize, f: F) -> io::Result<usize>
    where
        F: Fn(&mut Self) -> io::Result<usize>,
    {
        // Restore the cursor for idempotent.
        let original = self.write_buf.position();
        self.write_buf.set_position(offset as u64);
        let r = f(self);
        self.write_buf.set_position(original);
        r
    }

    fn has_sufficient_buffer(&self, size: u32) -> bool {
        (self.write_buf.position() as usize + size as usize) < self.write_buf.get_ref().capacity()
    }
}

impl ZeroCopyWriter for DevFuseWriter {
    fn write_from(&mut self, f: &mut File, count: usize, off: u64) -> io::Result<usize> {
        let pos = self.write_buf.position() as usize;
        let end = pos + count;
        let buf = self.write_buf.get_mut();

        let old_end = buf.len();
        buf.resize(end, 0);
        let read = f.read_at(&mut buf[pos..end], off)?;

        let new_end = pos + read;
        debug_assert!(new_end >= old_end);
        buf.truncate(new_end);
        self.write_buf.set_position(new_end as u64);
        Ok(read)
    }
}

struct DevFuseMapper;

impl DevFuseMapper {
    fn new() -> Self {
        Self {}
    }
}

impl Mapper for DevFuseMapper {
    fn map(
        &self,
        _mem_offset: u64,
        _size: usize,
        _fd: &dyn AsRawFd,
        _file_offset: u64,
        _prot: u32,
    ) -> io::Result<()> {
        Err(io::Error::from_raw_os_error(libc::EOPNOTSUPP))
    }

    fn unmap(&self, _offset: u64, _size: u64) -> io::Result<()> {
        Err(io::Error::from_raw_os_error(libc::EOPNOTSUPP))
    }
}

/// Start the FUSE message handling loop. Returns when an error happens.
pub fn start_message_loop<F: FileSystem + Sync>(
    dev_fuse: File,
    max_write: u32,
    max_read: u32,
    fs: F,
) -> Result<()> {
    let server = Server::new(fs);
    let mut dev_fuse_reader = {
        let rfile = dev_fuse.try_clone().map_err(Error::EndpointSetup)?;
        let buf_reader = BufReader::with_capacity(
            max_write as usize + size_of::<sys::InHeader>() + size_of::<sys::WriteIn>(),
            rfile,
        );
        DevFuseReader::new(buf_reader)
    };
    let mut dev_fuse_writer = {
        let wfile = dev_fuse.try_clone().map_err(Error::EndpointSetup)?;
        let write_buf = Cursor::new(Vec::with_capacity(max_read as usize));
        DevFuseWriter::new(wfile, write_buf)
    };
    let dev_fuse_mapper = DevFuseMapper::new();
    loop {
        server.handle_message(&mut dev_fuse_reader, &mut dev_fuse_writer, &dev_fuse_mapper)?;

        // Since we're reusing the buffer to avoid repeated allocation, drain the possible
        // residual from the buffer.
        dev_fuse_reader.drain();
    }
}
<|endoftext|>


<commit_before>#[derive(Clone, Copy)]
struct Point { x: i32, y: i32 }

fn main() {
    let point = Point { x: 0, y: 0 };

    let _copy_of_x = {
        // `ref_to_x` is a reference to the `x` field of `point`
        let Point { x: ref ref_to_x, y: _ } = point;

        // Return a copy of the `x` field of `point`
        *ref_to_x
    };

    // A mutable copy of `point`
    let mut mutable_point = point;

    {
        // `ref` can be paired with `mut` to take mutable references
        let Point { x: _, y: ref mut mut_ref_to_y } = mutable_point;

        // Mutate the `y` field of `mutable_point`, via a mutable reference
        *mut_ref_to_y = 1;
    }

    println!("point is ({}, {})", point.x, point.y);
    println!("mutable_point is ({}, {})", mutable_point.x, mutable_point.y);

    let tuple = (Box::new(5u32), 3u32);

    println!("tuple is {:?}", tuple);
}
<commit_msg>Add simpler example to scope/borrow/ref<commit_after>#[derive(Clone, Copy)]
struct Point { x: i32, y: i32 }

fn main() {
    let c = 'y';

    // A `ref` borrow on the left side of an assignment is equivalent to
    // an `&` borrow on the right side.
    let ref ref_c1 = c;
    let ref_c2 = &c;

    println!("ref_c1 equals ref_c2: {}", *ref_c1 == *ref_c2);

    let point = Point { x: 0, y: 0 };

    // `ref` is also valid when destructuring a struct.
    let _copy_of_x = {
        // `ref_to_x` is a reference to the `x` field of `point`
        let Point { x: ref ref_to_x, y: _ } = point;

        // Return a copy of the `x` field of `point`
        *ref_to_x
    };

    // A mutable copy of `point`
    let mut mutable_point = point;

    {
        // `ref` can be paired with `mut` to take mutable references
        let Point { x: _, y: ref mut mut_ref_to_y } = mutable_point;

        // Mutate the `y` field of `mutable_point`, via a mutable reference
        *mut_ref_to_y = 1;
    }

    println!("point is ({}, {})", point.x, point.y);
    println!("mutable_point is ({}, {})", mutable_point.x, mutable_point.y);

    let tuple = (Box::new(5u32), 3u32);

    println!("tuple is {:?}", tuple);
}
<|endoftext|>


<commit_before>#![cfg(feature = "ds")]

extern crate rusoto_core;
extern crate rusoto_ds;

use rusoto_core::Region;
use rusoto_ds::{
    DescribeDirectoriesRequest, DescribeTrustsRequest, DirectoryService, DirectoryServiceClient,
};

#[test]
fn should_describe_trusts() {
    let client = DirectoryServiceClient::new(Region::UsWest2);
    let request = DescribeTrustsRequest::default();

    client.describe_trusts(request).sync().unwrap();
}

#[test]
fn should_describe_directories() {
    let client = DirectoryServiceClient::new(Region::UsWest2);
    let request = DescribeDirectoriesRequest::default();

    client.describe_directories(request).sync().unwrap();
}
<commit_msg>added a few more integration tests to ds<commit_after>#![cfg(feature = "ds")]

extern crate rusoto_core;
extern crate rusoto_ds;

use rusoto_core::{Region, RusotoError};
use rusoto_ds::{
    DescribeDirectoriesRequest, DescribeTrustsRequest, DirectoryService, DirectoryServiceClient, DescribeEventTopicsRequest, DescribeConditionalForwardersRequest, DescribeDomainControllersRequest, DescribeConditionalForwardersError, DescribeDomainControllersError,
};

#[test]
fn should_describe_trusts() {
    let client = DirectoryServiceClient::new(Region::UsWest2);
    let request = DescribeTrustsRequest::default();

    client.describe_trusts(request).sync().unwrap();
}

#[test]
fn should_describe_directories() {
    let client = DirectoryServiceClient::new(Region::UsWest2);
    let request = DescribeDirectoriesRequest::default();

    client.describe_directories(request).sync().unwrap();
}

#[test]
fn should_conditional_forwarders() {
    let client = DirectoryServiceClient::new(Region::UsWest2);
    let mut request = DescribeConditionalForwardersRequest::default();
	request.directory_id = "d-11111aaaaa".to_string();

    match client.describe_conditional_forwarders(request).sync() {
		  Err(RusotoError::Service(DescribeConditionalForwardersError::EntityDoesNotExist(msg))) => {
            assert!(msg.contains("does not exist."))
        }
        err @ _ => panic!("Expected EntityDoesNotExist error, got {:#?}", err)
	}
}

#[test]
fn should_describe_domain_controllers() {
    let client = DirectoryServiceClient::new(Region::UsWest2);
    let mut request = DescribeDomainControllersRequest::default();
	request.directory_id = "d-11111aaaaa".to_string();

    match client.describe_domain_controllers(request).sync() {
		Err(RusotoError::Service(DescribeDomainControllersError::EntityDoesNotExist(msg))) => {
            assert!(msg.contains("does not exist."))
        }
        err @ _ => panic!("Expected EntityDoesNotExist error, got {:#?}", err)
	}
}

#[test]
fn should_describe_event_topics() {
    let client = DirectoryServiceClient::new(Region::UsWest2);
    let request = DescribeEventTopicsRequest::default();

    client.describe_event_topics(request).sync().unwrap();
}
<|endoftext|>


<commit_before>

// https://github.com/rust-lang/getopts
extern crate getopts;

// https://doc.rust-lang.org/stable/book/ffi.html
extern crate libc;

// Rust FFI for:
// krb5_init_context
// krb5_cc_default
// krb5_cc_get_principal
// com_err
mod krb5;
mod com_err;

use getopts::Options;
use std::env;
use std::ffi::{CStr,CString};
use std::io::{self,Write};
use std::process;
use std::ptr;

pub struct Krb5Context {
    ctx: krb5::krb5_context,
}
impl Krb5Context {
    pub fn new() -> Option<Krb5Context> {
        let mut ctx: krb5::krb5_context = ptr::null_mut();
        unsafe {
            let code = krb5::krb5_init_context(&mut ctx);
            if code != 0 {
                let whoami = CString::new((*PROGNAME).clone())
                    .unwrap().into_raw();
                let detail = CString::new("while initializing krb5").
                    unwrap().into_raw();
                com_err::com_err(whoami, code as i64, detail);
                return None;
            }
        }
        Some(Krb5Context { ctx: ctx, })
    }
}

// This is a silly amount of work, but I wanted to learn how to
// get the progname into a global variable.
//
// https://github.com/Kimundi/lazy-static.rs
#[macro_use]
extern crate lazy_static;
lazy_static! {
    static ref PROGNAME: String = env::current_exe().unwrap() // PathBuf
        .file_name().unwrap()                                 // &OsStr
        .to_string_lossy().into_owned();                      // Cow<str> -> String
}

fn error(err: getopts::Fail) -> ! {
    let mut stderr = io::stderr();
    writeln!(&mut stderr, "Error: {}", err).unwrap();
    writeln!(&mut stderr, "Try '{} --help' for more information.", *PROGNAME).unwrap();
    process::exit(1);
}

fn usage(opts: &Options) -> ! {
    let brief = opts.short_usage(&*PROGNAME);
    println!("{}", opts.usage(&brief));
    process::exit(0);
}

fn main() {

    let progname = CString::new((*PROGNAME).clone())
        .unwrap()
        .into_raw();

    let args: Vec<String> = env::args().collect();
    let mut opts = Options::new();
    opts.optflag("h", "help", "print this help menu");

    let matches = match opts.parse(&args[1..]) {
        Ok(m) => { m }
        Err(f) => { error(f) }
    };

    if matches.opt_present("h") {
        usage(&opts);
    }

    let mut code: krb5::krb5_error_code;

    let ctx = Krb5Context::new().unwrap().ctx;

    let mut cache: krb5::krb5_ccache = ptr::null_mut();
    code = unsafe {krb5::krb5_cc_default(ctx, &mut cache)};
    if code != 0 {
        unsafe {
            com_err::com_err(progname,
                             code as i64,
                             CString::new("while getting default ccache").unwrap().into_raw());
        }
        std::process::exit(1);
    }

    let mut princ: krb5::krb5_principal = ptr::null_mut();
    code = unsafe { krb5::krb5_cc_get_principal(ctx, cache, &mut princ) };
    if code != 0 {
        unsafe {
            com_err::com_err(progname,
                             code as i64,
                             CString::new("while retrieving principal name").unwrap().into_raw());
        }
        std::process::exit(1);
    }

    let kpd = unsafe{(*princ)};
    let len = kpd.length;

    let d = unsafe { (*kpd.data).data };
    let s = unsafe { CStr::from_ptr(d).to_string_lossy() };
    print!("{}", s);

    for i in 1..len {
        let d = unsafe { (*kpd.data.offset(i as isize)).data };
        let s = unsafe { CStr::from_ptr(d).to_string_lossy() };
        print!("/{}", s);
    }
    println!("");

}
<commit_msg>Re-arrange 'unsafe' Rust code<commit_after>

// https://github.com/rust-lang/getopts
extern crate getopts;

extern crate libc;

// Rust FFI for:
// krb5_init_context
// krb5_cc_default
// krb5_cc_get_principal
// com_err
mod krb5;
mod com_err;

use getopts::Options;
use std::env;
use std::ffi::{CStr,CString};
use std::io::{self,Write};
use std::process;
use std::ptr;

pub struct Krb5Context {
    ctx: krb5::krb5_context,
}
impl Krb5Context {
    pub fn new() -> Option<Krb5Context> {
        let mut ctx: krb5::krb5_context = ptr::null_mut();
        unsafe {
            let code = krb5::krb5_init_context(&mut ctx);
            if code != 0 {
                let whoami = CString::new((*PROGNAME).clone())
                    .unwrap().into_raw();
                let detail = CString::new("while initializing krb5")
                    .unwrap().into_raw();
                com_err::com_err(whoami, code as i64, detail);
                return None;
            }
        }
        Some(Krb5Context { ctx: ctx, })
    }
}

pub struct Krb5Cache {
    cache: krb5::krb5_ccache,
}
impl Krb5Cache {
    pub fn get(ctx: &Krb5Context) -> Option<Krb5Cache> {
        let mut cache: krb5::krb5_ccache = ptr::null_mut();
        unsafe {
            let code = krb5::krb5_cc_default(ctx.ctx, &mut cache);
            if code != 0 {
                let whoami = CString::new((*PROGNAME).clone())
                    .unwrap().into_raw();
                let detail = CString::new("while getting default ccache")
                    .unwrap().into_raw();
                com_err::com_err(whoami, code as i64, detail);
                return None;
            }
        }
        Some(Krb5Cache { cache: cache, })
    }
}

pub struct Krb5Princ {
    princ: krb5::krb5_principal,
}
impl Krb5Princ {
    pub fn get(ctx: &Krb5Context, cache: &Krb5Cache) -> Option<Krb5Princ> {
        let mut princ: krb5::krb5_principal = ptr::null_mut();
        unsafe {
            let code = krb5::krb5_cc_get_principal(ctx.ctx,
                                                   cache.cache,
                                                   &mut princ);
            if code != 0 {
                let whoami = CString::new((*PROGNAME).clone())
                    .unwrap().into_raw();
                let detail = CString::new("while retrieving principal name")
                    .unwrap().into_raw();
                com_err::com_err(whoami, code as i64, detail);
                return None;
            }
        }
        Some(Krb5Princ { princ: princ, })
    }
    pub fn realm(&self) -> String {
        let kp = unsafe { *self.princ };
        let d = kp.realm.data;
        let s = unsafe { CStr::from_ptr(d).to_string_lossy() };
        s.into_owned()
    }
    pub fn data(&self) -> String {
        let kp = unsafe { *self.princ };
        let len = kp.length;

        // Pointer offset arithmetic
        // C code is: krb5_principal->(data+(i))->data
        (0..len).map(
            |i|
            unsafe{
                CStr::from_ptr((*kp.data.offset(i as isize)).data)
                    .to_string_lossy()
            })
            .collect::<Vec<_>>()
            .join("/")
    }
}

// This is a silly amount of work, but I wanted to learn how to
// get the progname into a global variable.
//
// https://github.com/Kimundi/lazy-static.rs
#[macro_use]
extern crate lazy_static;
lazy_static! {
    static ref PROGNAME: String = env::current_exe().unwrap() // PathBuf
        .file_name().unwrap()                                 // &OsStr
        .to_string_lossy().into_owned();                      // Cow<str> -> String
}

fn error(err: getopts::Fail) -> ! {
    let mut stderr = io::stderr();
    writeln!(&mut stderr, "Error: {}", err).unwrap();
    writeln!(&mut stderr, "Try '{} --help' for more information.", *PROGNAME).unwrap();
    process::exit(1);
}

fn usage(opts: &Options) -> ! {
    let brief = opts.short_usage(&*PROGNAME);
    println!("{}", opts.usage(&brief));
    process::exit(0);
}

fn main() {

    let args: Vec<String> = env::args().collect();
    let mut opts = Options::new();
    opts.optflag("h", "help", "print this help menu");

    let matches = match opts.parse(&args[1..]) {
        Ok(m) => { m }
        Err(f) => { error(f) }
    };

    if matches.opt_present("h") {
        usage(&opts);
    }

    let k5ctx = Krb5Context::new().unwrap();
    let k5cache = Krb5Cache::get(&k5ctx).unwrap();
    let k5princ = Krb5Princ::get(&k5ctx, &k5cache).unwrap();

    println!("{}", k5princ.data());
}
<|endoftext|>


<commit_before>use std::ops::{Index, IndexMut};

#[macro_use]
extern crate quick_error;

extern crate nalgebra;
use nalgebra::{DMat};

extern crate image;
use image::{ImageBuffer, Luma, DynamicImage};

type FloatType = f64;
type Mat = DMat<FloatType>;

fn horizontal_line<I: Iterator<Item = usize>>(row: usize, cols: I) -> Mat {
    let mut factor: Mat = DMat::new_zeros(10, 10);
    for col in cols {
        *factor.index_mut((row, col)) = 1.;
    }
    factor
}

fn vertical_line<I: Iterator<Item = usize>>(rows: I, col: usize) -> Mat {
    let mut factor: Mat = DMat::new_zeros(10, 10);
    for row in rows {
        *factor.index_mut((row, col)) = 1.;
    }
    factor
}

fn mat_to_image(mat: &Mat) -> DynamicImage {
    let mut image_buffer
        = ImageBuffer::new(mat.ncols() as u32, mat.nrows() as u32);
    for (x, y, pixel) in image_buffer.enumerate_pixels_mut() {
        let value = mat.index((y as usize, x as usize));
        let byte = (*value * 255.).round() as u8;
        *pixel = Luma([byte]);
    }
    DynamicImage::ImageLuma8(image_buffer)
}

quick_error! {
    #[derive(Debug)]
    pub enum ImageSaveError {
        Io(err: std::io::Error) {}
        Image(err: image::ImageError) {}
    }
}

fn save_as_png(mat: &Mat, filename: &str) -> Result<(), ImageSaveError> {
    let image = mat_to_image(&mat);
    let path = std::path::Path::new(filename);
    let mut file = try!(std::fs::File::create(&path)
                        .map_err(ImageSaveError::Io));
    image.save(&mut file, image::PNG).map_err(ImageSaveError::Image)
}

fn main() {
    let mut factors: Vec<Mat> = Vec::new();

    factors.push(horizontal_line(9, 0..5));
    for row in (0..9).rev() {
        factors.push(horizontal_line(row, 0..10));
    }

    factors.push(vertical_line(5..10, 0));
    for col in 1..10 {
        factors.push(vertical_line(0..10, col));
    }

    println!("factors:\n");
    for (i, factor) in factors.iter().enumerate() {
        save_as_png(&factor, &format!("factor-{}.png", i)[..]).unwrap();
        println!("{:?}", factor);
    }

    let mut horizontal_evolving: Vec<Mat> = Vec::new();
    for start_col in 0..6 {
        horizontal_evolving.push(horizontal_line(9, start_col..(start_col + 5)));
    }

    println!("short horizontal bar that moves from left to right:\n");
    for factor in horizontal_evolving {
        println!("{:?}", factor);
    }

    let mut vertical_evolving: Vec<Mat> = Vec::new();
    for start_row in (0..6).rev() {
        vertical_evolving.push(vertical_line(start_row..(start_row + 5), 0));
    }

    println!("short vertical bar that moves from bottom to top:\n");
    for factor in vertical_evolving {
        println!("{:?}", factor);
    }
}
<commit_msg>write out all factors as png images<commit_after>use std::ops::{Index, IndexMut};

#[macro_use]
extern crate quick_error;

extern crate nalgebra;
use nalgebra::{DMat};

extern crate image;
use image::{ImageBuffer, Luma, DynamicImage};

type FloatType = f64;
type Mat = DMat<FloatType>;

fn horizontal_line<I: Iterator<Item = usize>>(row: usize, cols: I) -> Mat {
    let mut factor: Mat = DMat::new_zeros(10, 10);
    for col in cols {
        *factor.index_mut((row, col)) = 1.;
    }
    factor
}

fn vertical_line<I: Iterator<Item = usize>>(rows: I, col: usize) -> Mat {
    let mut factor: Mat = DMat::new_zeros(10, 10);
    for row in rows {
        *factor.index_mut((row, col)) = 1.;
    }
    factor
}

fn mat_to_image(mat: &Mat) -> DynamicImage {
    let mut image_buffer
        = ImageBuffer::new(mat.ncols() as u32, mat.nrows() as u32);
    for (x, y, pixel) in image_buffer.enumerate_pixels_mut() {
        let value = mat.index((y as usize, x as usize));
        let byte = (*value * 255.).round() as u8;
        *pixel = Luma([byte]);
    }
    DynamicImage::ImageLuma8(image_buffer)
}

quick_error! {
    #[derive(Debug)]
    pub enum ImageSaveError {
        Io(err: std::io::Error) {}
        Image(err: image::ImageError) {}
    }
}

fn save_as_png(mat: &Mat, filename: &str) -> Result<(), ImageSaveError> {
    let image = mat_to_image(&mat);
    let path = std::path::Path::new(filename);
    let mut file = try!(std::fs::File::create(&path)
                        .map_err(ImageSaveError::Io));
    image.save(&mut file, image::PNG).map_err(ImageSaveError::Image)
}

fn main() {
    let mut factors: Vec<Mat> = Vec::new();

    factors.push(horizontal_line(9, 0..5));
    for row in (0..9).rev() {
        factors.push(horizontal_line(row, 0..10));
    }

    factors.push(vertical_line(5..10, 0));
    for col in 1..10 {
        factors.push(vertical_line(0..10, col));
    }

    println!("factors:\n");
    for (i, factor) in factors.iter().enumerate() {
        save_as_png(&factor, &format!("factor-{}.png", i)[..]).unwrap();
        println!("{:?}", factor);
    }

    let mut horizontal_evolving: Vec<Mat> = Vec::new();
    for start_col in 0..6 {
        horizontal_evolving.push(horizontal_line(9, start_col..(start_col + 5)));
    }

    println!("short horizontal bar that moves from left to right:\n");
    for (i, factor) in horizontal_evolving.iter().enumerate() {
        save_as_png(&factor, &format!("horizontal-{}.png", i)[..]).unwrap();
        println!("{:?}", factor);
    }

    let mut vertical_evolving: Vec<Mat> = Vec::new();
    for start_row in (0..6).rev() {
        vertical_evolving.push(vertical_line(start_row..(start_row + 5), 0));
    }

    println!("short vertical bar that moves from bottom to top:\n");
    for (i, factor) in vertical_evolving.iter().enumerate() {
        save_as_png(&factor, &format!("vertical-{}.png", i)[..]).unwrap();
        println!("{:?}", factor);
    }
}
<|endoftext|>


<commit_before>use crate::discord_client::CommandHandler;

pub struct PingCommand;

impl CommandHandler for PingCommand {
    fn process_command(
        &self,
        _command: &str,
        send_message_callback: &Fn(&str) -> (),
    ) -> Result<(), Box<std::error::Error>> {
        send_message_callback("Pong!");

        Ok(())
    }
}
<commit_msg>Adds a basic test to the ping command<commit_after>use crate::discord_client::CommandHandler;

pub struct PingCommand;

impl CommandHandler for PingCommand {
    fn process_command(
        &self,
        _command: &str,
        send_message_callback: &Fn(&str) -> (),
    ) -> Result<(), Box<std::error::Error>> {
        send_message_callback("Pong!");

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::sync::{Arc, Mutex};
    use std::thread;
    use std::time::{Duration, Instant};
    use super::*;

    #[test]
    fn test_ping() {
        let ping = PingCommand;

        let result = Arc::new(Mutex::new(Box::new(String::new())));
        let closure_result = result.clone();
        assert!(ping.process_command("", &|message| *closure_result.lock().unwrap() = Box::new(String::from(message))).is_ok());

        let expected_message = String::from("Pong!");
        let timeout = Instant::now();
        while (timeout.elapsed() < Duration::from_secs(2)) && (**result.lock().unwrap() != expected_message) {
            thread::sleep(Duration::from_millis(200));
        }

        assert_eq!(expected_message, **result.lock().unwrap());
    }
}<|endoftext|>