<commit_before>pub use winit::os::unix::x11::{XError, XNotSupported, XConnection};

use api::glx::ffi;

use CreationError;
use std::{mem, ptr};
use std::sync::{Arc};

use winit;
use winit::os::unix::WindowExt;
use winit::os::unix::WindowBuilderExt;
use winit::os::unix::get_x11_xconnection;
use winit::NativeMonitorId;

use Api;
use ContextError;
use GlAttributes;
use GlContext;
use GlRequest;
use PixelFormat;
use PixelFormatRequirements;

use std::ffi::CString;

use api::glx::Context as GlxContext;
use api::egl;
use api::egl::Context as EglContext;
use api::glx::ffi::glx::Glx;
use api::egl::ffi::egl::Egl;
use api::dlopen;

struct GlxOrEgl {
    glx: Option<Glx>,
    egl: Option<Egl>,
}

impl GlxOrEgl {
    fn new() -> GlxOrEgl {
        // TODO: use something safer than raw "dlopen"
        let glx = {
            let mut libglx = unsafe {
                dlopen::dlopen(b"libGL.so.1\0".as_ptr() as *const _, dlopen::RTLD_NOW)
            };
            if libglx.is_null() {
                libglx = unsafe {
                    dlopen::dlopen(b"libGL.so\0".as_ptr() as *const _, dlopen::RTLD_NOW)
                };
            }
            if libglx.is_null() {
                None
            } else {
                Some(Glx::load_with(|sym| {
                    let sym = CString::new(sym).unwrap();
                    unsafe { dlopen::dlsym(libglx, sym.as_ptr()) }
                }))
            }
        };
        // TODO: use something safer than raw "dlopen"
        let egl = {
            let mut libegl = unsafe {
                dlopen::dlopen(b"libEGL.so.1\0".as_ptr() as *const _, dlopen::RTLD_NOW)
            };
            if libegl.is_null() {
                libegl = unsafe {
                    dlopen::dlopen(b"libEGL.so\0".as_ptr() as *const _, dlopen::RTLD_NOW)
                };
            }
            if libegl.is_null() {
                None
            } else {
                Some(Egl::load_with(|sym| {
                    let sym = CString::new(sym).unwrap();
                    unsafe { dlopen::dlsym(libegl, sym.as_ptr()) }
                }))
            }
        };
        GlxOrEgl {
            glx: glx,
            egl: egl,
        }
    }
}

enum Context {
    Glx(GlxContext),
    Egl(EglContext),
    None,
}

pub struct Window {
    display: Arc<XConnection>,
    colormap: ffi::Colormap,
    context: Context,
}

unsafe impl Send for Window {}
unsafe impl Sync for Window {}

impl Drop for Window {
    fn drop(&mut self) {
        unsafe {
            // we don't call MakeCurrent(0, 0) because we are not sure that the context
            // is still the current one
            self.context = Context::None;

            (self.display.xlib.XFreeColormap)(self.display.display, self.colormap);
        }
    }
}

impl Window {
    pub fn new(
        pf_reqs: &PixelFormatRequirements,
        opengl: &GlAttributes<&Window>,
        winit_builder: winit::WindowBuilder,
    ) -> Result<(Window, winit::Window), CreationError> {
        let display = get_x11_xconnection().unwrap();
        let screen_id = match winit_builder.window.monitor {
            Some(ref m) => match m.get_native_identifier() {
                NativeMonitorId::Numeric(monitor) => monitor as i32,
                _ => panic!(),
            },
            _ => unsafe { (display.xlib.XDefaultScreen)(display.display) },
        };

        // start the context building process
        enum Prototype<'a> {
            Glx(::api::glx::ContextPrototype<'a>),
            Egl(::api::egl::ContextPrototype<'a>),
        }
        let builder_clone_opengl_glx = opengl.clone().map_sharing(|_| unimplemented!());      // FIXME:
        let builder_clone_opengl_egl = opengl.clone().map_sharing(|_| unimplemented!());      // FIXME:
        let backend = GlxOrEgl::new();
        let context = match opengl.version {
            GlRequest::Latest | GlRequest::Specific(Api::OpenGl, _) | GlRequest::GlThenGles { .. } => {
                // GLX should be preferred over EGL, otherwise crashes may occur
                // on X11 – issue #314
                if let Some(ref glx) = backend.glx {
                    Prototype::Glx(try!(GlxContext::new(
                        glx.clone(),
                        &display.xlib,
                        pf_reqs,
                        &builder_clone_opengl_glx,
                        display.display,
                        screen_id,
                    )))
                } else if let Some(ref egl) = backend.egl {
                    Prototype::Egl(try!(EglContext::new(
                            egl.clone(),
                        pf_reqs,
                        &builder_clone_opengl_egl,
                        egl::NativeDisplay::X11(Some(display.display as *const _)),
                    )))
                } else {
                    return Err(CreationError::NotSupported);
                }
            },
            GlRequest::Specific(Api::OpenGlEs, _) => {
                if let Some(ref egl) = backend.egl {
                    Prototype::Egl(try!(EglContext::new(
                        egl.clone(),
                        pf_reqs,
                        &builder_clone_opengl_egl,
                        egl::NativeDisplay::X11(Some(display.display as *const _)),
                    )))
                } else {
                    return Err(CreationError::NotSupported);
                }
            },
            GlRequest::Specific(_, _) => {
                return Err(CreationError::NotSupported);
            },
        };

        // getting the `visual_infos` (a struct that contains information about the visual to use)
        let visual_infos = match context {
            Prototype::Glx(ref p) => p.get_visual_infos().clone(),
            Prototype::Egl(ref p) => {
                unsafe {
                    let mut template: ffi::XVisualInfo = mem::zeroed();
                    template.visualid = p.get_native_visual_id() as ffi::VisualID;

                    let mut num_visuals = 0;
                    let vi = (display.xlib.XGetVisualInfo)(display.display, ffi::VisualIDMask,
                                                           &mut template, &mut num_visuals);
                    display.check_errors().expect("Failed to call XGetVisualInfo");
                    assert!(!vi.is_null());
                    assert!(num_visuals == 1);

                    let vi_copy = ptr::read(vi as *const _);
                    (display.xlib.XFree)(vi as *mut _);
                    vi_copy
                }
            },
        };

        let winit_window = winit_builder
            .with_x11_visual(&visual_infos as *const _)
            .with_x11_screen(screen_id)
            .build().unwrap();

        let xlib_window = winit_window.get_xlib_window().unwrap();
        // finish creating the OpenGL context
        let context = match context {
            Prototype::Glx(ctxt) => {
                Context::Glx(try!(ctxt.finish(xlib_window as _)))
            },
            Prototype::Egl(ctxt) => {
                Context::Egl(try!(ctxt.finish(xlib_window)))
            },
        };

        // getting the root window
        let root = unsafe { (display.xlib.XDefaultRootWindow)(display.display) };
        display.check_errors().expect("Failed to get root window");

        // creating the color map
        let cmap = unsafe {
            let cmap = (display.xlib.XCreateColormap)(display.display, root,
                                                      visual_infos.visual as *mut _,
                                                      ffi::AllocNone);
            display.check_errors().expect("Failed to call XCreateColormap");
            cmap
        };

        Ok((Window {
            display: display.clone(),
            context: context,
            colormap: cmap,
        },
        winit_window))
    }
}

impl GlContext for Window {
    #[inline]
    unsafe fn make_current(&self) -> Result<(), ContextError> {
        match self.context {
            Context::Glx(ref ctxt) => ctxt.make_current(),
            Context::Egl(ref ctxt) => ctxt.make_current(),
            Context::None => Ok(())
        }
    }

    #[inline]
    fn is_current(&self) -> bool {
        match self.context {
            Context::Glx(ref ctxt) => ctxt.is_current(),
            Context::Egl(ref ctxt) => ctxt.is_current(),
            Context::None => panic!()
        }
    }

    #[inline]
    fn get_proc_address(&self, addr: &str) -> *const () {
        match self.context {
            Context::Glx(ref ctxt) => ctxt.get_proc_address(addr),
            Context::Egl(ref ctxt) => ctxt.get_proc_address(addr),
            Context::None => ptr::null()
        }
    }

    #[inline]
    fn swap_buffers(&self) -> Result<(), ContextError> {
        match self.context {
            Context::Glx(ref ctxt) => ctxt.swap_buffers(),
            Context::Egl(ref ctxt) => ctxt.swap_buffers(),
            Context::None => Ok(())
        }
    }

    #[inline]
    fn get_api(&self) -> Api {
        match self.context {
            Context::Glx(ref ctxt) => ctxt.get_api(),
            Context::Egl(ref ctxt) => ctxt.get_api(),
            Context::None => panic!()
        }
    }

    #[inline]
    fn get_pixel_format(&self) -> PixelFormat {
        match self.context {
            Context::Glx(ref ctxt) => ctxt.get_pixel_format(),
            Context::Egl(ref ctxt) => ctxt.get_pixel_format(),
            Context::None => panic!()
        }
    }
}
<commit_msg>Replace unwrap call with proper error handling<commit_after>pub use winit::os::unix::x11::{XError, XNotSupported, XConnection};

use api::glx::ffi;

use CreationError;
use std::{mem, ptr, fmt, error};
use std::sync::{Arc};

use winit;
use winit::os::unix::WindowExt;
use winit::os::unix::WindowBuilderExt;
use winit::os::unix::get_x11_xconnection;
use winit::NativeMonitorId;

use Api;
use ContextError;
use GlAttributes;
use GlContext;
use GlRequest;
use PixelFormat;
use PixelFormatRequirements;

use std::ffi::CString;

use api::glx::Context as GlxContext;
use api::egl;
use api::egl::Context as EglContext;
use api::glx::ffi::glx::Glx;
use api::egl::ffi::egl::Egl;
use api::dlopen;

#[derive(Debug)]
struct NoX11Connection;

impl error::Error for NoX11Connection {
    fn description(&self) -> &str {
        "failed to get x11 connection"
    }
}

impl fmt::Display for NoX11Connection {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(error::Error::description(self))
    }
}

struct GlxOrEgl {
    glx: Option<Glx>,
    egl: Option<Egl>,
}

impl GlxOrEgl {
    fn new() -> GlxOrEgl {
        // TODO: use something safer than raw "dlopen"
        let glx = {
            let mut libglx = unsafe {
                dlopen::dlopen(b"libGL.so.1\0".as_ptr() as *const _, dlopen::RTLD_NOW)
            };
            if libglx.is_null() {
                libglx = unsafe {
                    dlopen::dlopen(b"libGL.so\0".as_ptr() as *const _, dlopen::RTLD_NOW)
                };
            }
            if libglx.is_null() {
                None
            } else {
                Some(Glx::load_with(|sym| {
                    let sym = CString::new(sym).unwrap();
                    unsafe { dlopen::dlsym(libglx, sym.as_ptr()) }
                }))
            }
        };
        // TODO: use something safer than raw "dlopen"
        let egl = {
            let mut libegl = unsafe {
                dlopen::dlopen(b"libEGL.so.1\0".as_ptr() as *const _, dlopen::RTLD_NOW)
            };
            if libegl.is_null() {
                libegl = unsafe {
                    dlopen::dlopen(b"libEGL.so\0".as_ptr() as *const _, dlopen::RTLD_NOW)
                };
            }
            if libegl.is_null() {
                None
            } else {
                Some(Egl::load_with(|sym| {
                    let sym = CString::new(sym).unwrap();
                    unsafe { dlopen::dlsym(libegl, sym.as_ptr()) }
                }))
            }
        };
        GlxOrEgl {
            glx: glx,
            egl: egl,
        }
    }
}

enum Context {
    Glx(GlxContext),
    Egl(EglContext),
    None,
}

pub struct Window {
    display: Arc<XConnection>,
    colormap: ffi::Colormap,
    context: Context,
}

unsafe impl Send for Window {}
unsafe impl Sync for Window {}

impl Drop for Window {
    fn drop(&mut self) {
        unsafe {
            // we don't call MakeCurrent(0, 0) because we are not sure that the context
            // is still the current one
            self.context = Context::None;

            (self.display.xlib.XFreeColormap)(self.display.display, self.colormap);
        }
    }
}

impl Window {
    pub fn new(
        pf_reqs: &PixelFormatRequirements,
        opengl: &GlAttributes<&Window>,
        winit_builder: winit::WindowBuilder,
    ) -> Result<(Window, winit::Window), CreationError> {
        let display = match get_x11_xconnection() {
            Some(display) => display,
            None => return Err(CreationError::NoBackendAvailable(Box::new(NoX11Connection))),
        };
        let screen_id = match winit_builder.window.monitor {
            Some(ref m) => match m.get_native_identifier() {
                NativeMonitorId::Numeric(monitor) => monitor as i32,
                _ => panic!(),
            },
            _ => unsafe { (display.xlib.XDefaultScreen)(display.display) },
        };

        // start the context building process
        enum Prototype<'a> {
            Glx(::api::glx::ContextPrototype<'a>),
            Egl(::api::egl::ContextPrototype<'a>),
        }
        let builder_clone_opengl_glx = opengl.clone().map_sharing(|_| unimplemented!());      // FIXME:
        let builder_clone_opengl_egl = opengl.clone().map_sharing(|_| unimplemented!());      // FIXME:
        let backend = GlxOrEgl::new();
        let context = match opengl.version {
            GlRequest::Latest | GlRequest::Specific(Api::OpenGl, _) | GlRequest::GlThenGles { .. } => {
                // GLX should be preferred over EGL, otherwise crashes may occur
                // on X11 – issue #314
                if let Some(ref glx) = backend.glx {
                    Prototype::Glx(try!(GlxContext::new(
                        glx.clone(),
                        &display.xlib,
                        pf_reqs,
                        &builder_clone_opengl_glx,
                        display.display,
                        screen_id,
                    )))
                } else if let Some(ref egl) = backend.egl {
                    Prototype::Egl(try!(EglContext::new(
                            egl.clone(),
                        pf_reqs,
                        &builder_clone_opengl_egl,
                        egl::NativeDisplay::X11(Some(display.display as *const _)),
                    )))
                } else {
                    return Err(CreationError::NotSupported);
                }
            },
            GlRequest::Specific(Api::OpenGlEs, _) => {
                if let Some(ref egl) = backend.egl {
                    Prototype::Egl(try!(EglContext::new(
                        egl.clone(),
                        pf_reqs,
                        &builder_clone_opengl_egl,
                        egl::NativeDisplay::X11(Some(display.display as *const _)),
                    )))
                } else {
                    return Err(CreationError::NotSupported);
                }
            },
            GlRequest::Specific(_, _) => {
                return Err(CreationError::NotSupported);
            },
        };

        // getting the `visual_infos` (a struct that contains information about the visual to use)
        let visual_infos = match context {
            Prototype::Glx(ref p) => p.get_visual_infos().clone(),
            Prototype::Egl(ref p) => {
                unsafe {
                    let mut template: ffi::XVisualInfo = mem::zeroed();
                    template.visualid = p.get_native_visual_id() as ffi::VisualID;

                    let mut num_visuals = 0;
                    let vi = (display.xlib.XGetVisualInfo)(display.display, ffi::VisualIDMask,
                                                           &mut template, &mut num_visuals);
                    display.check_errors().expect("Failed to call XGetVisualInfo");
                    assert!(!vi.is_null());
                    assert!(num_visuals == 1);

                    let vi_copy = ptr::read(vi as *const _);
                    (display.xlib.XFree)(vi as *mut _);
                    vi_copy
                }
            },
        };

        let winit_window = winit_builder
            .with_x11_visual(&visual_infos as *const _)
            .with_x11_screen(screen_id)
            .build().unwrap();

        let xlib_window = winit_window.get_xlib_window().unwrap();
        // finish creating the OpenGL context
        let context = match context {
            Prototype::Glx(ctxt) => {
                Context::Glx(try!(ctxt.finish(xlib_window as _)))
            },
            Prototype::Egl(ctxt) => {
                Context::Egl(try!(ctxt.finish(xlib_window)))
            },
        };

        // getting the root window
        let root = unsafe { (display.xlib.XDefaultRootWindow)(display.display) };
        display.check_errors().expect("Failed to get root window");

        // creating the color map
        let cmap = unsafe {
            let cmap = (display.xlib.XCreateColormap)(display.display, root,
                                                      visual_infos.visual as *mut _,
                                                      ffi::AllocNone);
            display.check_errors().expect("Failed to call XCreateColormap");
            cmap
        };

        Ok((Window {
            display: display.clone(),
            context: context,
            colormap: cmap,
        },
        winit_window))
    }
}

impl GlContext for Window {
    #[inline]
    unsafe fn make_current(&self) -> Result<(), ContextError> {
        match self.context {
            Context::Glx(ref ctxt) => ctxt.make_current(),
            Context::Egl(ref ctxt) => ctxt.make_current(),
            Context::None => Ok(())
        }
    }

    #[inline]
    fn is_current(&self) -> bool {
        match self.context {
            Context::Glx(ref ctxt) => ctxt.is_current(),
            Context::Egl(ref ctxt) => ctxt.is_current(),
            Context::None => panic!()
        }
    }

    #[inline]
    fn get_proc_address(&self, addr: &str) -> *const () {
        match self.context {
            Context::Glx(ref ctxt) => ctxt.get_proc_address(addr),
            Context::Egl(ref ctxt) => ctxt.get_proc_address(addr),
            Context::None => ptr::null()
        }
    }

    #[inline]
    fn swap_buffers(&self) -> Result<(), ContextError> {
        match self.context {
            Context::Glx(ref ctxt) => ctxt.swap_buffers(),
            Context::Egl(ref ctxt) => ctxt.swap_buffers(),
            Context::None => Ok(())
        }
    }

    #[inline]
    fn get_api(&self) -> Api {
        match self.context {
            Context::Glx(ref ctxt) => ctxt.get_api(),
            Context::Egl(ref ctxt) => ctxt.get_api(),
            Context::None => panic!()
        }
    }

    #[inline]
    fn get_pixel_format(&self) -> PixelFormat {
        match self.context {
            Context::Glx(ref ctxt) => ctxt.get_pixel_format(),
            Context::Egl(ref ctxt) => ctxt.get_pixel_format(),
            Context::None => panic!()
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add test for issue #81193<commit_after>// check-pass

#![feature(associated_type_bounds)]

trait A<'a, 'b> {}

trait B<'a, 'b, 'c> {}

fn err<'u, 'a, F>()
where
    for<'b> F: Iterator<Item: for<'c> B<'a, 'b, 'c> + for<'c> A<'a, 'c>>,
{
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Add manual page to seq, -h and --help options.<commit_after><|endoftext|>


<commit_before><commit_msg>Refactor to not call exit() anywhere<commit_after><|endoftext|>


<commit_before><commit_msg>:hammer: Fix build warning<commit_after><|endoftext|>


<commit_before><commit_msg>git work<commit_after><|endoftext|>


<commit_before>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

extern crate clap;
#[macro_use] extern crate version;
#[macro_use] extern crate log;
extern crate walkdir;
extern crate toml;
extern crate toml_query;

extern crate libimagrt;
extern crate libimagerror;

use std::env;
use std::process::exit;
use std::process::Command;
use std::process::Stdio;
use std::io::ErrorKind;
use std::collections::BTreeMap;

use walkdir::WalkDir;
use clap::{Arg, ArgMatches, AppSettings, SubCommand};
use toml::Value;
use toml_query::read::TomlValueReadExt;

use libimagrt::runtime::Runtime;
use libimagerror::trace::trace_error;

/// Returns the helptext, putting the Strings in cmds as possible
/// subcommands into it
fn help_text(cmds: Vec<String>) -> String {
    format!(r#"

     _
    (_)_ __ ___   __ _  __ _
    | | '_ \` _ \/ _\`|/ _\`|
    | | | | | | | (_| | (_| |
    |_|_| |_| |_|\__,_|\__, |
                       |___/
    -------------------------

    Usage: imag [--version | --versions | -h | --help] <command> <args...>

    imag - the personal information management suite for the commandline

    imag is a PIM suite for the commandline. It consists of several commands,
    called "modules". Each module implements one PIM aspect and all of these
    modules can be used independently.

    Available commands:

    {imagbins}

    Call a command with 'imag <command> <args>'
    Each command can be called with "--help" to get the respective helptext.

    Please visit https://github.com/matthiasbeyer/imag to view the source code,
    follow the development of imag or maybe even contribute to imag.

    imag is free software. It is released under the terms of LGPLv2.1

    (c) 2016 Matthias Beyer and contributors"#,
        imagbins = cmds
            .into_iter()
            .map(|cmd| format!("\t{}\n", cmd))
            .fold(String::new(), |s, c| {
                let s = s + c.as_str();
                s
            }))
}

/// Returns the list of imag-* executables found in $PATH
fn get_commands() -> Vec<String> {
    match env::var("PATH") {
        Err(e) => {
            println!("PATH error: {:?}", e);
            exit(1);
        },

        Ok(path) => path
            .split(":")
            .flat_map(|elem| {
                WalkDir::new(elem)
                    .max_depth(1)
                    .into_iter()
                    .filter(|path| match *path {
                        Ok(ref p) => p.file_name().to_str().map_or(false, |f| f.starts_with("imag-")),
                        Err(_)    => false,
                    })
                    .filter_map(Result::ok)
                    .filter_map(|path| path
                        .file_name()
                       .to_str()
                       .and_then(|s| s.splitn(2, "-").nth(1).map(String::from))
                    )
            })
            .collect()
    }
}

fn main() {
    // Initialize the Runtime and build the CLI
    let appname  = "imag";
    let version  = &version!();
    let about    = "imag - the PIM suite for the commandline";
    let commands = get_commands();
    let helptext = help_text(commands.clone());
    let app      = Runtime::get_default_cli_builder(appname, version, about)
        .settings(&[AppSettings::AllowExternalSubcommands, AppSettings::ArgRequiredElseHelp])
        .arg(Arg::with_name("version")
             .long("version")
             .takes_value(false)
             .required(false)
             .multiple(false)
             .help("Get the version of imag"))
        .arg(Arg::with_name("versions")
             .long("versions")
             .takes_value(false)
             .required(false)
             .multiple(false)
             .help("Get the versions of the imag commands"))
        .subcommand(SubCommand::with_name("help").help("Show help"))
        .help(helptext.as_str());
    let rt = Runtime::new(app)
        .unwrap_or_else(|e| {
            println!("Runtime couldn't be setup. Exiting");
            trace_error(&e);
            exit(1);
        });
    let matches = rt.cli();

    debug!("matches: {:?}", matches);

    // Begin checking for arguments

    if matches.is_present("version") {
        debug!("Showing version");
        println!("imag {}", &version!()[..]);
        exit(0);
    }

    if matches.is_present("versions") {
        debug!("Showing versions");
        commands
            .iter()
            .map(|command| {
                match Command::new(format!("imag-{}", command))
                    .arg("--version")
                    .output()
                    .map(|v| v.stdout)
                {
                    Ok(s) => match String::from_utf8(s) {
                        Ok(s) => format!("{:10} -> {}", command, s),
                        Err(e) => format!("UTF8 Error while working with output of imag{}: {:?}", command, e),
                    },
                    Err(e) => format!("Failed calling imag-{} -> {:?}", command, e),
                }
            })
            .fold((), |_, line| {
                // The amount of newlines may differ depending on the subprocess
                println!("{}", line.trim());
            });

        exit(0);
    }

    let aliases = match fetch_aliases(&rt) {
        Ok(aliases) => aliases,
        Err(e)      => {
            println!("Error while fetching aliases from configuration file");
            debug!("Error = {:?}", e);
            println!("Aborting");
            exit(1);
        }
    };

    // Matches any subcommand given
    match matches.subcommand() {
        (subcommand, Some(scmd)) => {
            // Get all given arguments and further subcommands to pass to
            // the imag-<> binary
            // Providing no arguments is OK, and is therefore ignored here
            let mut subcommand_args : Vec<String> = match scmd.values_of("") {
                Some(values) => values.map(String::from).collect(),
                None => Vec::new()
            };

            forward_commandline_arguments(&matches, &mut subcommand_args);

            let subcommand = String::from(subcommand);
            let subcommand = aliases.get(&subcommand).cloned().unwrap_or(subcommand);

            debug!("Calling 'imag-{}' with args: {:?}", subcommand, subcommand_args);

            // Create a Command, and pass it the gathered arguments
            match Command::new(format!("imag-{}", subcommand))
                .stdin(Stdio::inherit())
                .stdout(Stdio::inherit())
                .stderr(Stdio::inherit())
                .args(&subcommand_args[..])
                .spawn()
                .and_then(|mut c| c.wait())
            {
                Ok(exit_status) => {
                    if !exit_status.success() {
                        debug!("{} exited with non-zero exit code: {:?}", subcommand, exit_status);
                        println!("{} exited with non-zero exit code", subcommand);
                        exit(exit_status.code().unwrap_or(1));
                    }
                    debug!("Successful exit!");
                },

                Err(e) => {
                    debug!("Error calling the subcommand");
                    match e.kind() {
                        ErrorKind::NotFound => {
                            println!("No such command: 'imag-{}'", subcommand);
                            println!("See 'imag --help' for available subcommands");
                            exit(1);
                        },
                        ErrorKind::PermissionDenied => {
                            println!("No permission to execute: 'imag-{}'", subcommand);
                            exit(1);
                        },
                        _ => {
                            println!("Error spawning: {:?}", e);
                            exit(1);
                        }
                    }
                }
            }
        },
        // Calling for example 'imag --versions' will lead here, as this option does not exit.
        // There's nothing to do in such a case
        _ => {},
    }
}

fn fetch_aliases(rt: &Runtime) -> Result<BTreeMap<String, String>, String> {
    let cfg   = try!(rt.config().ok_or_else(|| String::from("No configuration found")));
    let value = cfg
        .config()
        .read("imag.aliases")
        .map_err(|_| String::from("Reading from config failed"));

    match try!(value) {
        None                         => Ok(BTreeMap::new()),
        Some(&Value::Table(ref tbl)) => {
            let mut alias_mappings = BTreeMap::new();

            for (k, v) in tbl {
                match v {
                    &Value::String(ref alias)      => {
                        alias_mappings.insert(alias.clone(), k.clone());
                    },
                    &Value::Array(ref aliases) => {
                        for alias in aliases {
                            match alias {
                                &Value::String(ref s) => {
                                    alias_mappings.insert(s.clone(), k.clone());
                                },
                                _ => {
                                    let e = format!("Not all values are a String in 'imag.aliases.{}'", k);
                                    return Err(e);
                                }
                            }
                        }
                    },

                    _ => {
                        let msg = format!("Type Error: 'imag.aliases.{}' is not a table or string", k);
                        return Err(msg);
                    },
                }
            }

            Ok(alias_mappings)
        },

        Some(_) => Err(String::from("Type Error: 'imag.aliases' is not a table")),
    }
}

fn forward_commandline_arguments(m: &ArgMatches, scmd: &mut Vec<String>) {
    let push = |flag: Option<&str>, val_name: &str, m: &ArgMatches, v: &mut Vec<String>| {
        let _ = m
            .value_of(val_name)
            .map(|val| {
                let flag = format!("--{}", flag.unwrap_or(val_name));
                v.insert(0, String::from(val));
                v.insert(0, flag);
            });
    };

    push(Some("verbose"),
         Runtime::arg_verbosity_name(), m , scmd);

    push(Some("debug"),
         Runtime::arg_debugging_name(), m , scmd);

    push(Some("no-color"),
         Runtime::arg_no_color_output_name(), m , scmd);

    push(Some("config"),
         Runtime::arg_config_name(), m , scmd);

    push(Some("override-config"),
         Runtime::arg_config_override_name(), m , scmd);

    push(Some("rtp"),
         Runtime::arg_runtimepath_name(), m , scmd);

    push(Some("store"),
         Runtime::arg_storepath_name(), m , scmd);

    push(Some("editor"),
         Runtime::arg_editor_name(), m , scmd);

    push(Some("generate-commandline-completion"),
         Runtime::arg_generate_compl(), m , scmd);

    push(None , Runtime::arg_logdest_name()                         , m , scmd);
    push(None , Runtime::arg_override_module_logging_setting_name() , m , scmd);
    push(None , Runtime::arg_override_trace_logging_format()        , m , scmd);
    push(None , Runtime::arg_override_debug_logging_format()        , m , scmd);
    push(None , Runtime::arg_override_info_logging_format()         , m , scmd);
    push(None , Runtime::arg_override_warn_logging_format()         , m , scmd);
    push(None , Runtime::arg_override_error_logging_format()        , m , scmd);

}

<commit_msg>Remove override passing in imag binary command<commit_after>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

extern crate clap;
#[macro_use] extern crate version;
#[macro_use] extern crate log;
extern crate walkdir;
extern crate toml;
extern crate toml_query;

extern crate libimagrt;
extern crate libimagerror;

use std::env;
use std::process::exit;
use std::process::Command;
use std::process::Stdio;
use std::io::ErrorKind;
use std::collections::BTreeMap;

use walkdir::WalkDir;
use clap::{Arg, ArgMatches, AppSettings, SubCommand};
use toml::Value;
use toml_query::read::TomlValueReadExt;

use libimagrt::runtime::Runtime;
use libimagerror::trace::trace_error;

/// Returns the helptext, putting the Strings in cmds as possible
/// subcommands into it
fn help_text(cmds: Vec<String>) -> String {
    format!(r#"

     _
    (_)_ __ ___   __ _  __ _
    | | '_ \` _ \/ _\`|/ _\`|
    | | | | | | | (_| | (_| |
    |_|_| |_| |_|\__,_|\__, |
                       |___/
    -------------------------

    Usage: imag [--version | --versions | -h | --help] <command> <args...>

    imag - the personal information management suite for the commandline

    imag is a PIM suite for the commandline. It consists of several commands,
    called "modules". Each module implements one PIM aspect and all of these
    modules can be used independently.

    Available commands:

    {imagbins}

    Call a command with 'imag <command> <args>'
    Each command can be called with "--help" to get the respective helptext.

    Please visit https://github.com/matthiasbeyer/imag to view the source code,
    follow the development of imag or maybe even contribute to imag.

    imag is free software. It is released under the terms of LGPLv2.1

    (c) 2016 Matthias Beyer and contributors"#,
        imagbins = cmds
            .into_iter()
            .map(|cmd| format!("\t{}\n", cmd))
            .fold(String::new(), |s, c| {
                let s = s + c.as_str();
                s
            }))
}

/// Returns the list of imag-* executables found in $PATH
fn get_commands() -> Vec<String> {
    match env::var("PATH") {
        Err(e) => {
            println!("PATH error: {:?}", e);
            exit(1);
        },

        Ok(path) => path
            .split(":")
            .flat_map(|elem| {
                WalkDir::new(elem)
                    .max_depth(1)
                    .into_iter()
                    .filter(|path| match *path {
                        Ok(ref p) => p.file_name().to_str().map_or(false, |f| f.starts_with("imag-")),
                        Err(_)    => false,
                    })
                    .filter_map(Result::ok)
                    .filter_map(|path| path
                        .file_name()
                       .to_str()
                       .and_then(|s| s.splitn(2, "-").nth(1).map(String::from))
                    )
            })
            .collect()
    }
}

fn main() {
    // Initialize the Runtime and build the CLI
    let appname  = "imag";
    let version  = &version!();
    let about    = "imag - the PIM suite for the commandline";
    let commands = get_commands();
    let helptext = help_text(commands.clone());
    let app      = Runtime::get_default_cli_builder(appname, version, about)
        .settings(&[AppSettings::AllowExternalSubcommands, AppSettings::ArgRequiredElseHelp])
        .arg(Arg::with_name("version")
             .long("version")
             .takes_value(false)
             .required(false)
             .multiple(false)
             .help("Get the version of imag"))
        .arg(Arg::with_name("versions")
             .long("versions")
             .takes_value(false)
             .required(false)
             .multiple(false)
             .help("Get the versions of the imag commands"))
        .subcommand(SubCommand::with_name("help").help("Show help"))
        .help(helptext.as_str());
    let rt = Runtime::new(app)
        .unwrap_or_else(|e| {
            println!("Runtime couldn't be setup. Exiting");
            trace_error(&e);
            exit(1);
        });
    let matches = rt.cli();

    debug!("matches: {:?}", matches);

    // Begin checking for arguments

    if matches.is_present("version") {
        debug!("Showing version");
        println!("imag {}", &version!()[..]);
        exit(0);
    }

    if matches.is_present("versions") {
        debug!("Showing versions");
        commands
            .iter()
            .map(|command| {
                match Command::new(format!("imag-{}", command))
                    .arg("--version")
                    .output()
                    .map(|v| v.stdout)
                {
                    Ok(s) => match String::from_utf8(s) {
                        Ok(s) => format!("{:10} -> {}", command, s),
                        Err(e) => format!("UTF8 Error while working with output of imag{}: {:?}", command, e),
                    },
                    Err(e) => format!("Failed calling imag-{} -> {:?}", command, e),
                }
            })
            .fold((), |_, line| {
                // The amount of newlines may differ depending on the subprocess
                println!("{}", line.trim());
            });

        exit(0);
    }

    let aliases = match fetch_aliases(&rt) {
        Ok(aliases) => aliases,
        Err(e)      => {
            println!("Error while fetching aliases from configuration file");
            debug!("Error = {:?}", e);
            println!("Aborting");
            exit(1);
        }
    };

    // Matches any subcommand given
    match matches.subcommand() {
        (subcommand, Some(scmd)) => {
            // Get all given arguments and further subcommands to pass to
            // the imag-<> binary
            // Providing no arguments is OK, and is therefore ignored here
            let mut subcommand_args : Vec<String> = match scmd.values_of("") {
                Some(values) => values.map(String::from).collect(),
                None => Vec::new()
            };

            forward_commandline_arguments(&matches, &mut subcommand_args);

            let subcommand = String::from(subcommand);
            let subcommand = aliases.get(&subcommand).cloned().unwrap_or(subcommand);

            debug!("Calling 'imag-{}' with args: {:?}", subcommand, subcommand_args);

            // Create a Command, and pass it the gathered arguments
            match Command::new(format!("imag-{}", subcommand))
                .stdin(Stdio::inherit())
                .stdout(Stdio::inherit())
                .stderr(Stdio::inherit())
                .args(&subcommand_args[..])
                .spawn()
                .and_then(|mut c| c.wait())
            {
                Ok(exit_status) => {
                    if !exit_status.success() {
                        debug!("{} exited with non-zero exit code: {:?}", subcommand, exit_status);
                        println!("{} exited with non-zero exit code", subcommand);
                        exit(exit_status.code().unwrap_or(1));
                    }
                    debug!("Successful exit!");
                },

                Err(e) => {
                    debug!("Error calling the subcommand");
                    match e.kind() {
                        ErrorKind::NotFound => {
                            println!("No such command: 'imag-{}'", subcommand);
                            println!("See 'imag --help' for available subcommands");
                            exit(1);
                        },
                        ErrorKind::PermissionDenied => {
                            println!("No permission to execute: 'imag-{}'", subcommand);
                            exit(1);
                        },
                        _ => {
                            println!("Error spawning: {:?}", e);
                            exit(1);
                        }
                    }
                }
            }
        },
        // Calling for example 'imag --versions' will lead here, as this option does not exit.
        // There's nothing to do in such a case
        _ => {},
    }
}

fn fetch_aliases(rt: &Runtime) -> Result<BTreeMap<String, String>, String> {
    let cfg   = try!(rt.config().ok_or_else(|| String::from("No configuration found")));
    let value = cfg
        .config()
        .read("imag.aliases")
        .map_err(|_| String::from("Reading from config failed"));

    match try!(value) {
        None                         => Ok(BTreeMap::new()),
        Some(&Value::Table(ref tbl)) => {
            let mut alias_mappings = BTreeMap::new();

            for (k, v) in tbl {
                match v {
                    &Value::String(ref alias)      => {
                        alias_mappings.insert(alias.clone(), k.clone());
                    },
                    &Value::Array(ref aliases) => {
                        for alias in aliases {
                            match alias {
                                &Value::String(ref s) => {
                                    alias_mappings.insert(s.clone(), k.clone());
                                },
                                _ => {
                                    let e = format!("Not all values are a String in 'imag.aliases.{}'", k);
                                    return Err(e);
                                }
                            }
                        }
                    },

                    _ => {
                        let msg = format!("Type Error: 'imag.aliases.{}' is not a table or string", k);
                        return Err(msg);
                    },
                }
            }

            Ok(alias_mappings)
        },

        Some(_) => Err(String::from("Type Error: 'imag.aliases' is not a table")),
    }
}

fn forward_commandline_arguments(m: &ArgMatches, scmd: &mut Vec<String>) {
    let push = |flag: Option<&str>, val_name: &str, m: &ArgMatches, v: &mut Vec<String>| {
        let _ = m
            .value_of(val_name)
            .map(|val| {
                let flag = format!("--{}", flag.unwrap_or(val_name));
                v.insert(0, String::from(val));
                v.insert(0, flag);
            });
    };

    push(Some("verbose"),
         Runtime::arg_verbosity_name(), m , scmd);

    push(Some("debug"),
         Runtime::arg_debugging_name(), m , scmd);

    push(Some("no-color"),
         Runtime::arg_no_color_output_name(), m , scmd);

    push(Some("config"),
         Runtime::arg_config_name(), m , scmd);

    push(Some("override-config"),
         Runtime::arg_config_override_name(), m , scmd);

    push(Some("rtp"),
         Runtime::arg_runtimepath_name(), m , scmd);

    push(Some("store"),
         Runtime::arg_storepath_name(), m , scmd);

    push(Some("editor"),
         Runtime::arg_editor_name(), m , scmd);

    push(Some("generate-commandline-completion"),
         Runtime::arg_generate_compl(), m , scmd);

    push(None , Runtime::arg_logdest_name()                         , m , scmd);

}

<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/// Reference-counted pointers to flows.
///
/// Eventually, with dynamically sized types in Rust, much of this code will be superfluous.

use flow::Flow;
use flow;

use std::mem;
use std::ops::{Deref, DerefMut};
use std::ptr;
use std::raw;
use std::sync::atomic::Ordering;

#[unsafe_no_drop_flag]
pub struct FlowRef {
    object: raw::TraitObject,
}

unsafe impl Send for FlowRef {}
unsafe impl Sync for FlowRef {}

impl FlowRef {
    pub fn new(mut flow: Box<Flow>) -> FlowRef {
        unsafe {
            let result = {
                let flow_ref: &mut Flow = &mut *flow;
                let object = mem::transmute::<&mut Flow, raw::TraitObject>(flow_ref);
                FlowRef { object: object }
            };
            mem::forget(flow);
            result
        }
    }
}

impl<'a> Deref for FlowRef {
    type Target = Flow + 'a;
    fn deref(&self) -> &(Flow + 'a) {
        unsafe {
            mem::transmute_copy::<raw::TraitObject, &(Flow + 'a)>(&self.object)
        }
    }
}

impl DerefMut for FlowRef {
    fn deref_mut<'a>(&mut self) -> &mut (Flow + 'a) {
        unsafe {
            mem::transmute_copy::<raw::TraitObject, &mut (Flow + 'a)>(&self.object)
        }
    }
}

impl Drop for FlowRef {
    fn drop(&mut self) {
        unsafe {
            if self.object.vtable.is_null() {
                return
            }
            if flow::base(&**self).ref_count().fetch_sub(1, Ordering::SeqCst) > 1 {
                return
            }
            let flow_ref: FlowRef = mem::replace(self, FlowRef {
                object: raw::TraitObject {
                    vtable: ptr::null_mut(),
                    data: ptr::null_mut(),
                }
            });
            drop(mem::transmute::<raw::TraitObject, Box<Flow>>(flow_ref.object));
            mem::forget(flow_ref);
            self.object.vtable = ptr::null_mut();
            self.object.data = ptr::null_mut();
        }
    }
}

impl Clone for FlowRef {
    fn clone(&self) -> FlowRef {
        unsafe {
            drop(flow::base(&**self).ref_count().fetch_add(1, Ordering::SeqCst));
            FlowRef {
                object: raw::TraitObject {
                    vtable: self.object.vtable,
                    data: self.object.data,
                }
            }
        }
    }
}
<commit_msg>Fix the documentation comment syntax in flow_ref.rs.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! Reference-counted pointers to flows.
//!
//! Eventually, with dynamically sized types in Rust, much of this code will be superfluous.

use flow::Flow;
use flow;

use std::mem;
use std::ops::{Deref, DerefMut};
use std::ptr;
use std::raw;
use std::sync::atomic::Ordering;

#[unsafe_no_drop_flag]
pub struct FlowRef {
    object: raw::TraitObject,
}

unsafe impl Send for FlowRef {}
unsafe impl Sync for FlowRef {}

impl FlowRef {
    pub fn new(mut flow: Box<Flow>) -> FlowRef {
        unsafe {
            let result = {
                let flow_ref: &mut Flow = &mut *flow;
                let object = mem::transmute::<&mut Flow, raw::TraitObject>(flow_ref);
                FlowRef { object: object }
            };
            mem::forget(flow);
            result
        }
    }
}

impl<'a> Deref for FlowRef {
    type Target = Flow + 'a;
    fn deref(&self) -> &(Flow + 'a) {
        unsafe {
            mem::transmute_copy::<raw::TraitObject, &(Flow + 'a)>(&self.object)
        }
    }
}

impl DerefMut for FlowRef {
    fn deref_mut<'a>(&mut self) -> &mut (Flow + 'a) {
        unsafe {
            mem::transmute_copy::<raw::TraitObject, &mut (Flow + 'a)>(&self.object)
        }
    }
}

impl Drop for FlowRef {
    fn drop(&mut self) {
        unsafe {
            if self.object.vtable.is_null() {
                return
            }
            if flow::base(&**self).ref_count().fetch_sub(1, Ordering::SeqCst) > 1 {
                return
            }
            let flow_ref: FlowRef = mem::replace(self, FlowRef {
                object: raw::TraitObject {
                    vtable: ptr::null_mut(),
                    data: ptr::null_mut(),
                }
            });
            drop(mem::transmute::<raw::TraitObject, Box<Flow>>(flow_ref.object));
            mem::forget(flow_ref);
            self.object.vtable = ptr::null_mut();
            self.object.data = ptr::null_mut();
        }
    }
}

impl Clone for FlowRef {
    fn clone(&self) -> FlowRef {
        unsafe {
            drop(flow::base(&**self).ref_count().fetch_add(1, Ordering::SeqCst));
            FlowRef {
                object: raw::TraitObject {
                    vtable: self.object.vtable,
                    data: self.object.data,
                }
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Smoke test<commit_after>extern crate bytes;
extern crate regex;
extern crate futures;
extern crate httpbis;
extern crate tokio_core;
#[macro_use]
extern crate log;
extern crate env_logger;

mod test_misc;

use futures::future;
use futures::future::Future;

use httpbis::Client;
use test_misc::*;

#[test]
fn smoke() {
    env_logger::init().ok();

    let server = ServerTest::new();

    let client: Client =
        Client::new_plain("::1", server.port, Default::default()).expect("client");

    let mut futures = Vec::new();
    for _ in 0..10 {
        futures.push(client.start_get("/blocks/200000/5", "localhost").collect());
    }

    let r = future::join_all(futures).wait().expect("wait");
    for rr in r {
        assert_eq!(200000 * 5, rr.body.len());
    }
}
<|endoftext|>


<commit_before><commit_msg>Add offline_and_locked_and_no_frozen test<commit_after><|endoftext|>


<commit_before><commit_msg>random test<commit_after><|endoftext|>


<commit_before><commit_msg>Use Windows 10 instead of 7 in user agent string<commit_after><|endoftext|>


<commit_before><commit_msg>Add test: Killer Sudoku.<commit_after>//! Killer Sudoku.
//!
//! https://en.wikipedia.org/wiki/Killer_sudoku

extern crate puzzle_solver;

use puzzle_solver::{LinExpr,Puzzle,Solution,Val,VarToken};

const SQRT_SIZE: usize = 3;
const SIZE: usize = 9;
type Board = [[Val; SIZE]; SIZE];
type Point = (usize, usize);

fn make_killer_sudoku(board: &[(Val, Vec<Point>)]) -> (Puzzle, Vec<Vec<VarToken>>) {
    let mut sys = Puzzle::new();
    let vars = sys.new_vars_with_candidates_2d(SIZE, SIZE, &[1,2,3,4,5,6,7,8,9]);

    for y in 0..SIZE {
        sys.all_different(&vars[y]);
    }

    for x in 0..SIZE {
        sys.all_different(vars.iter().map(|row| &row[x]));
    }

    for block in 0..SIZE {
        let x0 = SQRT_SIZE * (block % SQRT_SIZE);
        let y0 = SQRT_SIZE * (block / SQRT_SIZE);
        sys.all_different((0..SIZE).map(|n|
                &vars[y0 + (n / SQRT_SIZE)][x0 + (n % SQRT_SIZE)]));
    }

    for &(total, ref points) in board.iter() {
        sys.equals(total, points.iter().fold(LinExpr::from(0), |sum, &(x,y)| sum + vars[y][x]));
    }

    (sys, vars)
}

fn print_sudoku(dict: &Solution, vars: &Vec<Vec<VarToken>>) {
    for y in 0..SIZE {
        if y % SQRT_SIZE == 0 {
            println!();
        }

        for x in 0..SIZE {
            print!("{}{}",
                   if x % SQRT_SIZE == 0 { " " } else { "" },
                   dict[vars[y][x]]);
        }
        println!();
    }
}

fn verify_sudoku(dict: &Solution, vars: &Vec<Vec<VarToken>>, expected: &Board) {
    for y in 0..SIZE {
        for x in 0..SIZE {
            assert_eq!(dict[vars[y][x]], expected[y][x]);
        }
    }
}

#[test]
fn killersudoku_wikipedia() {
    let puzzle = [
        ( 3, vec![(0,0), (1,0)]),
        (15, vec![(2,0), (3,0), (4,0)]),
        (22, vec![(5,0), (4,1), (5,1), (4,2)]),
        ( 4, vec![(6,0), (6,1)]),
        (16, vec![(7,0), (7,1)]),
        (15, vec![(8,0), (8,1), (8,2), (8,3)]),
        (25, vec![(0,1), (1,1), (0,2), (1,2)]),
        (17, vec![(2,1), (3,1)]),
        ( 9, vec![(2,2), (3,2), (3,3)]),
        ( 8, vec![(5,2), (5,3), (5,4)]),
        (20, vec![(6,2), (7,2), (6,3)]),
        ( 6, vec![(0,3), (0,4)]),
        (14, vec![(1,3), (2,3)]),
        (17, vec![(4,3), (4,4), (4,5)]),
        (17, vec![(7,3), (6,4), (7,4)]),
        (13, vec![(1,4), (2,4), (1,5)]),
        (20, vec![(3,4), (3,5), (3,6)]),
        (12, vec![(8,4), (8,5)]),
        (27, vec![(0,5), (0,6), (0,7), (0,8)]),
        ( 6, vec![(2,5), (1,6), (2,6)]),
        (20, vec![(5,5), (5,6), (6,6)]),
        ( 6, vec![(6,5), (7,5)]),
        (10, vec![(4,6), (3,7), (4,7), (3,8)]),
        (14, vec![(7,6), (8,6), (7,7), (8,7)]),
        ( 8, vec![(1,7), (1,8)]),
        (16, vec![(2,7), (2,8)]),
        (15, vec![(5,7), (6,7)]),
        (13, vec![(4,8), (5,8), (6,8)]),
        (17, vec![(7,8), (8,8)]),
    ];

    let expected = [
        [ 2,1,5,  6,4,7,  3,9,8 ],
        [ 3,6,8,  9,5,2,  1,7,4 ],
        [ 7,9,4,  3,8,1,  6,5,2 ],

        [ 5,8,6,  2,7,4,  9,3,1 ],
        [ 1,4,2,  5,9,3,  8,6,7 ],
        [ 9,7,3,  8,1,6,  4,2,5 ],

        [ 8,2,1,  7,3,9,  5,4,6 ],
        [ 6,5,9,  4,2,8,  7,1,3 ],
        [ 4,3,7,  1,6,5,  2,8,9 ] ];

    let (mut sys, vars) = make_killer_sudoku(&puzzle);
    let dict = sys.solve_any().expect("solution");
    print_sudoku(&dict, &vars);
    verify_sudoku(&dict, &vars, &expected);
    println!("killersudoku_wikipedia: {} guesses", sys.num_guesses());
}
<|endoftext|>


<commit_before><commit_msg>next step is hover and events handling<commit_after><|endoftext|>


<commit_before><commit_msg>Added new example<commit_after>extern crate tetrahedrane;

fn main() {
    let mut window = tetrahedrane::init::Window::new(20, 20, 640, 480, &"Hello World");
    let mut framebuffer = tetrahedrane::render::Framebuffer::new(640, 480);

    let red = tetrahedrane::render::Color::new(255, 0, 0);

    loop {
        for x in 0..100 {
            for y in 0..100 {
                framebuffer.set_pixel(x, y, &red);
            }
        }

        window.apply_buf(&framebuffer);

        window.sync();

        std::thread::sleep(std::time::Duration::from_millis(33));
    }
}
<|endoftext|>


<commit_before><commit_msg>Fix: Subcommand is named "deleted"<commit_after><|endoftext|>


<commit_before><commit_msg>Removed excess comments<commit_after><|endoftext|>


<commit_before>use alloc::arc::Arc;

use collections::string::{String, ToString};
use collections::vec::Vec;

use core::cell::UnsafeCell;
use core::ops::DerefMut;
use core::{mem, ptr};

use common::elf::Elf;
use common::memory;

use scheduler::context::{CONTEXT_STACK_SIZE, CONTEXT_STACK_ADDR, context_switch,
context_userspace, Context, ContextMemory};

use schemes::Url;

use sync::Intex;

/// Execute an executable
pub fn execute(url: Url, mut args: Vec<String>) {
    let mut context_ptr: *mut Context = 0 as *mut Context;
    let mut entry: usize = 0;

    if let Ok(mut resource) = url.open() {
        let mut vec: Vec<u8> = Vec::new();
        resource.read_to_end(&mut vec);

        let executable = Elf::from_data(vec.as_ptr() as usize);
        entry = unsafe { executable.entry() };
        let mut memory = Vec::new();
        unsafe {
            for segment in executable.load_segment().iter() {
                let virtual_address = segment.vaddr as usize;
                let virtual_size = segment.mem_len as usize;

                //TODO: Warning: Investigate this hack!
                let hack = virtual_address % 4096;

                let physical_address = memory::alloc(virtual_size + hack);

                if physical_address > 0 {
                    debugln!("VADDR: {:X} OFF: {:X} FLG: {:X} HACK: {:X}", segment.vaddr, segment.off, segment.flags, hack);

                    // Copy progbits
                    ::memcpy((physical_address + hack) as *mut u8,
                             (executable.data + segment.off as usize) as *const u8,
                             segment.file_len as usize);
                    // Zero bss
                    if segment.mem_len > segment.file_len {
                        debugln!("BSS: {:X} {}", segment.vaddr + segment.file_len, segment.mem_len - segment.file_len);
                        ::memset((physical_address + hack + segment.file_len as usize) as *mut u8,
                                0,
                                segment.mem_len as usize - segment.file_len as usize);
                    }

                    memory.push(ContextMemory {
                        physical_address: physical_address,
                        virtual_address: virtual_address - hack,
                        virtual_size: virtual_size + hack,
                        writeable: segment.flags & 2 == 2
                    });
                }
            }
        }

        if entry > 0 && ! memory.is_empty() {
            args.insert(0, url.to_string());

            let mut contexts = ::env().contexts.lock();
            if let Some(mut context) = contexts.current_mut() {
                context.name = url.string;
                context.args = Arc::new(UnsafeCell::new(args));
                context.cwd = Arc::new(UnsafeCell::new(unsafe { (*context.cwd.get()).clone() }));

                unsafe { context.unmap() };
                context.memory = Arc::new(UnsafeCell::new(memory));
                unsafe { context.map() };

                context_ptr = context.deref_mut();
            }
        } else {
            debug!("{}: Invalid memory or entry\n", url.string);
        }
    } else {
        debug!("{}: Failed to open\n", url.string);
    }

    if context_ptr as usize > 0 {
        Context::spawn("kexec".to_string(), box move || {
            unsafe {
                let _intex = Intex::static_lock();

                let context = &mut *context_ptr;

                let mut context_args: Vec<usize> = Vec::new();
                context_args.push(0); // ENVP
                context_args.push(0); // ARGV NULL
                let mut argc = 0;
                for i in 0..(*context.args.get()).len() {
                    let reverse_i = (*context.args.get()).len() - i - 1;
                    if let Some(ref mut arg) = (*context.args.get()).get_mut(reverse_i) {
                        if ! arg.ends_with('\0') {
                            arg.push('\0');
                        }
                        context_args.push(arg.as_ptr() as usize);
                        argc += 1;
                    }
                }
                context_args.push(argc);

                context.sp = context.kernel_stack + CONTEXT_STACK_SIZE - 128;

                context.stack = Some(ContextMemory {
                    physical_address: memory::alloc(CONTEXT_STACK_SIZE),
                    virtual_address: CONTEXT_STACK_ADDR,
                    virtual_size: CONTEXT_STACK_SIZE,
                    writeable: true
                });

                let user_sp = if let Some(ref stack) = context.stack {
                    let mut sp = stack.physical_address + stack.virtual_size - 128;
                    for arg in context_args.iter() {
                        sp -= mem::size_of::<usize>();
                        ptr::write(sp as *mut usize, *arg);
                    }
                    sp - stack.physical_address + stack.virtual_address
                } else {
                    0
                };

                context.push(0x20 | 3);
                context.push(user_sp);
                context.push(/*1 << 9*/ 0);
                context.push(0x18 | 3);
                context.push(entry);
                context.push(context_userspace as usize);
            }
        });

        loop {
            unsafe { context_switch(false) };
        }
    }
}
<commit_msg>Segment unsafe code from safe code in executor.rs<commit_after>use alloc::arc::Arc;

use collections::string::{String, ToString};
use collections::vec::Vec;

use core::cell::UnsafeCell;
use core::ops::DerefMut;
use core::{mem, ptr};

use common::elf::Elf;
use common::memory;

use scheduler::context::{CONTEXT_STACK_SIZE, CONTEXT_STACK_ADDR, context_switch,
context_userspace, Context, ContextMemory};

use schemes::Url;

use sync::Intex;

/// Execute an executable
pub fn execute(url: Url, mut args: Vec<String>) {
    let mut context_ptr: *mut Context = 0 as *mut Context;
    let mut entry: usize = 0;

    if let Ok(mut resource) = url.open() {
        let mut vec: Vec<u8> = Vec::new();
        resource.read_to_end(&mut vec);

        let executable = Elf::from_data(vec.as_ptr() as usize);
        entry = unsafe { executable.entry() };
        let mut memory = Vec::new();
        unsafe {
            for segment in executable.load_segment().iter() {
                let virtual_address = segment.vaddr as usize;
                let virtual_size = segment.mem_len as usize;

                //TODO: Warning: Investigate this hack!
                let hack = virtual_address % 4096;

                let physical_address = memory::alloc(virtual_size + hack);

                if physical_address > 0 {
                    debugln!("VADDR: {:X} OFF: {:X} FLG: {:X} HACK: {:X}", segment.vaddr, segment.off, segment.flags, hack);

                    // Copy progbits
                    ::memcpy((physical_address + hack) as *mut u8,
                             (executable.data + segment.off as usize) as *const u8,
                             segment.file_len as usize);
                    // Zero bss
                    if segment.mem_len > segment.file_len {
                        debugln!("BSS: {:X} {}", segment.vaddr + segment.file_len, segment.mem_len - segment.file_len);
                        ::memset((physical_address + hack + segment.file_len as usize) as *mut u8,
                                0,
                                segment.mem_len as usize - segment.file_len as usize);
                    }

                    memory.push(ContextMemory {
                        physical_address: physical_address,
                        virtual_address: virtual_address - hack,
                        virtual_size: virtual_size + hack,
                        writeable: segment.flags & 2 == 2
                    });
                }
            }
        }

        if entry > 0 && ! memory.is_empty() {
            args.insert(0, url.to_string());

            let mut contexts = ::env().contexts.lock();
            if let Some(mut context) = contexts.current_mut() {
                context.name = url.string;
                context.args = Arc::new(UnsafeCell::new(args));
                context.cwd = Arc::new(UnsafeCell::new(unsafe { (*context.cwd.get()).clone() }));

                unsafe { context.unmap() };
                context.memory = Arc::new(UnsafeCell::new(memory));
                unsafe { context.map() };

                context_ptr = context.deref_mut();
            }
        } else {
            debug!("{}: Invalid memory or entry\n", url.string);
        }
    } else {
        debug!("{}: Failed to open\n", url.string);
    }

    if context_ptr as usize > 0 {
        Context::spawn("kexec".to_string(), box move || {
            let _intex = Intex::static_lock();

            let context = unsafe { &mut *context_ptr };

            let mut context_args: Vec<usize> = Vec::new();
            context_args.push(0); // ENVP
            context_args.push(0); // ARGV NULL
            let mut argc = 0;
            for i in 0..unsafe { (*context.args.get()).len() } {
                let reverse_i = unsafe { (*context.args.get()).len() } - i - 1;
                if let Some(ref mut arg) = unsafe { (*context.args.get()).get_mut(reverse_i) } {
                    if ! arg.ends_with('\0') {
                        arg.push('\0');
                    }
                    context_args.push(arg.as_ptr() as usize);
                    argc += 1;
                }
            }
            context_args.push(argc);

            context.sp = context.kernel_stack + CONTEXT_STACK_SIZE - 128;

            context.stack = Some(ContextMemory {
                physical_address: unsafe { memory::alloc(CONTEXT_STACK_SIZE) },
                virtual_address: CONTEXT_STACK_ADDR,
                virtual_size: CONTEXT_STACK_SIZE,
                writeable: true
            });

            let user_sp = if let Some(ref stack) = context.stack {
                let mut sp = stack.physical_address + stack.virtual_size - 128;
                for arg in context_args.iter() {
                    sp -= mem::size_of::<usize>();
                    unsafe { ptr::write(sp as *mut usize, *arg) };
                }
                sp - stack.physical_address + stack.virtual_address
            } else {
                0
            };

            unsafe {
                context.push(0x20 | 3);
                context.push(user_sp);
                context.push(/*1 << 9*/ 0);
                context.push(0x18 | 3);
                context.push(entry);
                context.push(context_userspace as usize);
            }
        });

        loop {
            unsafe { context_switch(false) };
        }
    }
}
<|endoftext|>


<commit_before>use toml::Value;

use libimagerror::into::IntoError;
use libimagstore::storeid::StoreId;

use vcs::git::error::GitHookErrorKind as GHEK;
use vcs::git::error::MapErrInto;
use vcs::git::result::Result;

use vcs::git::action::StoreAction;

use git2::Repository;

/// Check the configuration whether we should commit interactively
pub fn commit_interactive(config: &Value, action: &StoreAction) -> bool {
    match config.lookup("commit.interactive") {
        Some(&Value::Boolean(b)) => b,
        Some(_) => {
            warn!("Configuration error, 'store.hooks.stdhook_git_{}.commit.interactive' must be a Boolean.",
                  action);
            warn!("Defaulting to commit.interactive = false");
            false
        }
        None => {
            warn!("Unavailable configuration for");
            warn!("\t'store.hooks.stdhook_git_{}.commit.interactive'", action);
            warn!("Defaulting to false");
            false
        }
    }
}

/// Check the configuration whether we should commit with the editor
fn commit_with_editor(config: &Value, action: &StoreAction) -> bool {
    match config.lookup("commit.interactive_editor") {
        Some(&Value::Boolean(b)) => b,
        Some(_) => {
            warn!("Configuration error, 'store.hooks.stdhook_git_{}.commit.interactive_editor' must be a Boolean.",
                  action);
            warn!("Defaulting to commit.interactive_editor = false");
            false
        }
        None => {
            warn!("Unavailable configuration for");
            warn!("\t'store.hooks.stdhook_git_{}.commit.interactive_editor'", action);
            warn!("Defaulting to false");
            false
        }
    }
}

/// Get the commit default message
fn commit_default_msg<'a>(config: &'a Value, action: &'a StoreAction) -> &'a str {
    match config.lookup("commit.message") {
        Some(&Value::String(ref b)) => b,
        Some(_) => {
            warn!("Configuration error, 'store.hooks.stdhook_git_{}.commit.message' must be a String.",
                  action);
            warn!("Defaulting to commit.message = '{}'", action.as_commit_message());
            action.as_commit_message()
        }
        None => {
            warn!("Unavailable configuration for");
            warn!("\t'store.hooks.stdhook_git_{}.commit.message'", action);
            warn!("Defaulting to commit.message = '{}'", action.as_commit_message());
            action.as_commit_message()
        }
    }
}

/// Get the commit template
///
/// TODO: Implement good template string
fn commit_template(action: &StoreAction, id: &StoreId) -> String {
    format!(r#"
# Please commit your changes and remove these lines.
#
# You're about to commit changes via the {action} Hook
#
#   Altered file: {id}
#
    "#,
    action = action,
    id = id.local().display())
}

/// Generate a commit message
///
/// Uses the functions `commit_interactive()` and `commit_with_editor()`
/// or reads one from the commandline or uses the `commit_default_msg()` string to create a commit
/// message.
pub fn commit_message(repo: &Repository, config: &Value, action: StoreAction, id: &StoreId) -> Result<String> {
    use libimaginteraction::ask::ask_string;
    use libimagutil::edit::edit_in_tmpfile_with_command;
    use std::process::Command;

    if commit_interactive(config, &action) {
        if commit_with_editor(config, &action) {
            repo.config()
                .map_err_into(GHEK::GitConfigFetchError)
                .and_then(|c| c.get_string("core.editor").map_err_into(GHEK::GitConfigEditorFetchError))
                .map_err_into(GHEK::ConfigError)
                .map(Command::new)
                .and_then(|cmd| {
                    let mut s = commit_template(&action, id);
                    edit_in_tmpfile_with_command(cmd, &mut s).map(|_| s)
                        .map_err_into(GHEK::EditorError)
                })
        } else {
            Ok(ask_string("Commit Message", None, false, false, None, "> "))
        }
    } else {
        Ok(String::from(commit_default_msg(config, &action)))
    }
}

/// Check whether the hook should abort if the repository cannot be initialized
pub fn abort_on_repo_init_err(cfg: &Value) -> bool {
    get_bool_cfg(Some(cfg), "abort_on_repo_init_failure", true, true)
}

/// Get the branch which must be checked out before running the hook (if any).
///
/// If there is no configuration for this, this is `Ok(None)`, otherwise we try to find the
/// configuration `String`.
pub fn ensure_branch(cfg: Option<&Value>) -> Result<Option<String>> {
    match cfg {
        Some(cfg) => {
            match cfg.lookup("ensure_branch") {
                Some(&Value::String(ref s)) => Ok(Some(s.clone())),
                Some(_) => {
                    warn!("Configuration error, 'ensure_branch' must be a String.");
                    Err(GHEK::ConfigTypeError.into_error())
                        .map_err_into(GHEK::ConfigTypeError)
                },
                None => {
                    debug!("No key `ensure_branch'");
                    Ok(None)
                },
            }
        },
        None => Ok(None),
    }
}

/// Check whether we should check out a branch before committing.
pub fn do_checkout_ensure_branch(cfg: Option<&Value>) -> bool {
    get_bool_cfg(cfg, "try_checkout_ensure_branch", true, true)
}

/// Helper to get a boolean value from the configuration.
fn get_bool_cfg(cfg: Option<&Value>, name: &str, on_fail: bool, on_unavail: bool) -> bool {
    cfg.map(|cfg| {
        match cfg.lookup(name) {
            Some(&Value::Boolean(b)) => b,
            Some(_) => {
                warn!("Configuration error, '{}' must be a Boolean (true|false).", name);
                warn!("Assuming '{}' now.", on_fail);
                on_fail
            },
            None => {
                debug!("No key '{}' - Assuming '{}'", name, on_unavail);
                on_unavail
            },
        }
    })
    .unwrap_or(on_unavail)
}

<commit_msg>Add config helper to check whether hook is enabled or not<commit_after>use toml::Value;

use libimagerror::into::IntoError;
use libimagstore::storeid::StoreId;

use vcs::git::error::GitHookErrorKind as GHEK;
use vcs::git::error::MapErrInto;
use vcs::git::result::Result;

use vcs::git::action::StoreAction;

use git2::Repository;

/// Check the configuration whether we should commit interactively
pub fn commit_interactive(config: &Value, action: &StoreAction) -> bool {
    match config.lookup("commit.interactive") {
        Some(&Value::Boolean(b)) => b,
        Some(_) => {
            warn!("Configuration error, 'store.hooks.stdhook_git_{}.commit.interactive' must be a Boolean.",
                  action);
            warn!("Defaulting to commit.interactive = false");
            false
        }
        None => {
            warn!("Unavailable configuration for");
            warn!("\t'store.hooks.stdhook_git_{}.commit.interactive'", action);
            warn!("Defaulting to false");
            false
        }
    }
}

/// Check the configuration whether we should commit with the editor
fn commit_with_editor(config: &Value, action: &StoreAction) -> bool {
    match config.lookup("commit.interactive_editor") {
        Some(&Value::Boolean(b)) => b,
        Some(_) => {
            warn!("Configuration error, 'store.hooks.stdhook_git_{}.commit.interactive_editor' must be a Boolean.",
                  action);
            warn!("Defaulting to commit.interactive_editor = false");
            false
        }
        None => {
            warn!("Unavailable configuration for");
            warn!("\t'store.hooks.stdhook_git_{}.commit.interactive_editor'", action);
            warn!("Defaulting to false");
            false
        }
    }
}

/// Get the commit default message
fn commit_default_msg<'a>(config: &'a Value, action: &'a StoreAction) -> &'a str {
    match config.lookup("commit.message") {
        Some(&Value::String(ref b)) => b,
        Some(_) => {
            warn!("Configuration error, 'store.hooks.stdhook_git_{}.commit.message' must be a String.",
                  action);
            warn!("Defaulting to commit.message = '{}'", action.as_commit_message());
            action.as_commit_message()
        }
        None => {
            warn!("Unavailable configuration for");
            warn!("\t'store.hooks.stdhook_git_{}.commit.message'", action);
            warn!("Defaulting to commit.message = '{}'", action.as_commit_message());
            action.as_commit_message()
        }
    }
}

/// Get the commit template
///
/// TODO: Implement good template string
fn commit_template(action: &StoreAction, id: &StoreId) -> String {
    format!(r#"
# Please commit your changes and remove these lines.
#
# You're about to commit changes via the {action} Hook
#
#   Altered file: {id}
#
    "#,
    action = action,
    id = id.local().display())
}

/// Generate a commit message
///
/// Uses the functions `commit_interactive()` and `commit_with_editor()`
/// or reads one from the commandline or uses the `commit_default_msg()` string to create a commit
/// message.
pub fn commit_message(repo: &Repository, config: &Value, action: StoreAction, id: &StoreId) -> Result<String> {
    use libimaginteraction::ask::ask_string;
    use libimagutil::edit::edit_in_tmpfile_with_command;
    use std::process::Command;

    if commit_interactive(config, &action) {
        if commit_with_editor(config, &action) {
            repo.config()
                .map_err_into(GHEK::GitConfigFetchError)
                .and_then(|c| c.get_string("core.editor").map_err_into(GHEK::GitConfigEditorFetchError))
                .map_err_into(GHEK::ConfigError)
                .map(Command::new)
                .and_then(|cmd| {
                    let mut s = commit_template(&action, id);
                    edit_in_tmpfile_with_command(cmd, &mut s).map(|_| s)
                        .map_err_into(GHEK::EditorError)
                })
        } else {
            Ok(ask_string("Commit Message", None, false, false, None, "> "))
        }
    } else {
        Ok(String::from(commit_default_msg(config, &action)))
    }
}

/// Check whether the hook should abort if the repository cannot be initialized
pub fn abort_on_repo_init_err(cfg: &Value) -> bool {
    get_bool_cfg(Some(cfg), "abort_on_repo_init_failure", true, true)
}

/// Get the branch which must be checked out before running the hook (if any).
///
/// If there is no configuration for this, this is `Ok(None)`, otherwise we try to find the
/// configuration `String`.
pub fn ensure_branch(cfg: Option<&Value>) -> Result<Option<String>> {
    match cfg {
        Some(cfg) => {
            match cfg.lookup("ensure_branch") {
                Some(&Value::String(ref s)) => Ok(Some(s.clone())),
                Some(_) => {
                    warn!("Configuration error, 'ensure_branch' must be a String.");
                    Err(GHEK::ConfigTypeError.into_error())
                        .map_err_into(GHEK::ConfigTypeError)
                },
                None => {
                    debug!("No key `ensure_branch'");
                    Ok(None)
                },
            }
        },
        None => Ok(None),
    }
}

/// Check whether we should check out a branch before committing.
pub fn do_checkout_ensure_branch(cfg: Option<&Value>) -> bool {
    get_bool_cfg(cfg, "try_checkout_ensure_branch", true, true)
}

/// Helper to get a boolean value from the configuration.
fn get_bool_cfg(cfg: Option<&Value>, name: &str, on_fail: bool, on_unavail: bool) -> bool {
    cfg.map(|cfg| {
        match cfg.lookup(name) {
            Some(&Value::Boolean(b)) => b,
            Some(_) => {
                warn!("Configuration error, '{}' must be a Boolean (true|false).", name);
                warn!("Assuming '{}' now.", on_fail);
                on_fail
            },
            None => {
                debug!("No key '{}' - Assuming '{}'", name, on_unavail);
                on_unavail
            },
        }
    })
    .unwrap_or(on_unavail)
}

/// Check whether the hook is enabled or not. If the config is not there, the hook is _enabled_ by
/// default.
pub fn is_enabled(cfg: &Value) -> bool {
    get_bool_cfg(Some(cfg), "enabled", true, true)
}

<|endoftext|>


<commit_before><commit_msg>Check before dumping data in kill_stream.<commit_after><|endoftext|>


<commit_before>extern crate libimagstore;

pub mod error;
pub mod result;
pub mod viewer;

<commit_msg>Enable lints<commit_after>#![deny(
    dead_code,
    non_camel_case_types,
    non_snake_case,
    path_statements,
    trivial_numeric_casts,
    unstable_features,
    unused_allocation,
    unused_import_braces,
    unused_imports,
    unused_must_use,
    unused_mut,
    unused_qualifications,
    while_true,
)]

extern crate libimagstore;

pub mod error;
pub mod result;
pub mod viewer;

<|endoftext|>


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


<commit_before><commit_msg>Added files via upload<commit_after>

fn t() {

            let s = "Hello World";

            assert_eq!(s, "Hello World");

}

#[test] fn non_macro() { t() }

//#[test] fn _macro() { t("hello_world_macro") }
<|endoftext|>


<commit_before>extern crate byteorder;

use std::error::Error;
use std::io::prelude::*;

use backend::Backend;
use self::byteorder::{ReadBytesExt, WriteBytesExt, BigEndian};
use types::{self, FromSql, ToSql, IsNull};

impl<DB: Backend<RawValue=[u8]>> FromSql<types::Float, DB> for f32 {
    fn from_sql(bytes: Option<&[u8]>) -> Result<Self, Box<Error+Send+Sync>> {
        let mut bytes = not_none!(bytes);
        bytes.read_f32::<BigEndian>().map_err(|e| Box::new(e) as Box<Error+Send+Sync>)
    }
}

impl<DB: Backend> ToSql<types::Float, DB> for f32 {
    fn to_sql<W: Write>(&self, out: &mut W) -> Result<IsNull, Box<Error+Send+Sync>> {
        out.write_f32::<BigEndian>(*self)
            .map(|_| IsNull::No)
            .map_err(|e| Box::new(e) as Box<Error+Send+Sync>)
    }
}

impl<DB: Backend<RawValue=[u8]>> FromSql<types::Double, DB> for f64 {
    fn from_sql(bytes: Option<&[u8]>) -> Result<Self, Box<Error+Send+Sync>> {
        let mut bytes = not_none!(bytes);
        bytes.read_f64::<BigEndian>().map_err(|e| Box::new(e) as Box<Error+Send+Sync>)
    }
}

impl<DB: Backend> ToSql<types::Double, DB> for f64 {
    fn to_sql<W: Write>(&self, out: &mut W) -> Result<IsNull, Box<Error+Send+Sync>> {
        out.write_f64::<BigEndian>(*self)
            .map(|_| IsNull::No)
            .map_err(|e| Box::new(e) as Box<Error+Send+Sync>)
    }
}
<commit_msg>Add the same debug check we do for integers to floats<commit_after>extern crate byteorder;

use std::error::Error;
use std::io::prelude::*;

use backend::Backend;
use self::byteorder::{ReadBytesExt, WriteBytesExt, BigEndian};
use types::{self, FromSql, ToSql, IsNull};

impl<DB: Backend<RawValue=[u8]>> FromSql<types::Float, DB> for f32 {
    fn from_sql(bytes: Option<&[u8]>) -> Result<Self, Box<Error+Send+Sync>> {
        let mut bytes = not_none!(bytes);
        debug_assert!(bytes.len() <= 4, "Received more than 4 bytes while decoding \
                      an f32. Was a double accidentally marked as float?");
        bytes.read_f32::<BigEndian>().map_err(|e| Box::new(e) as Box<Error+Send+Sync>)
    }
}

impl<DB: Backend> ToSql<types::Float, DB> for f32 {
    fn to_sql<W: Write>(&self, out: &mut W) -> Result<IsNull, Box<Error+Send+Sync>> {
        out.write_f32::<BigEndian>(*self)
            .map(|_| IsNull::No)
            .map_err(|e| Box::new(e) as Box<Error+Send+Sync>)
    }
}

impl<DB: Backend<RawValue=[u8]>> FromSql<types::Double, DB> for f64 {
    fn from_sql(bytes: Option<&[u8]>) -> Result<Self, Box<Error+Send+Sync>> {
        let mut bytes = not_none!(bytes);
        debug_assert!(bytes.len() <= 8, "Received more than 8 bytes while decoding \
                      an f64. Was a numeric accidentally marked as dobule?");
        bytes.read_f64::<BigEndian>().map_err(|e| Box::new(e) as Box<Error+Send+Sync>)
    }
}

impl<DB: Backend> ToSql<types::Double, DB> for f64 {
    fn to_sql<W: Write>(&self, out: &mut W) -> Result<IsNull, Box<Error+Send+Sync>> {
        out.write_f64::<BigEndian>(*self)
            .map(|_| IsNull::No)
            .map_err(|e| Box::new(e) as Box<Error+Send+Sync>)
    }
}
<|endoftext|>


<commit_before><commit_msg>gtk testing sample<commit_after><|endoftext|>


<commit_before>use alloc::boxed::Box;

use collections::vec::Vec;

use core::intrinsics::{volatile_load, volatile_store};
use core::mem::size_of;
use core::ptr::{self, read, write};
use core::slice;

use common::debug;
use common::memory;
use common::time::{self, Duration};

use drivers::mmio::Mmio;
use drivers::pciconfig::PciConfig;

use schemes::KScheme;

use super::hci::{UsbHci, UsbMsg};
use super::setup::Setup;

#[repr(packed)]
#[derive(Copy, Clone, Debug, Default)]
struct Qtd {
    next: u32,
    next_alt: u32,
    token: u32,
    buffers: [u32; 5],
}

#[repr(packed)]
struct QueueHead {
    next: u32,
    characteristics: u32,
    capabilities: u32,
    qtd_ptr: u32,
    qtd: Qtd,
}

pub struct Ehci {
    pub pci: PciConfig,
    pub base: usize,
    pub irq: u8,
}

impl KScheme for Ehci {
    #[allow(non_snake_case)]
    fn on_irq(&mut self, irq: u8) {
        if irq == self.irq {
            // debug::d("EHCI handle");

            unsafe {
                let cap_length = &mut *(self.base as *mut Mmio<u8>);

                let op_base = self.base + cap_length.read() as usize;

                let usb_sts = &mut *((op_base + 4) as *mut Mmio<u32>);
                // debug::d(" usb_sts ");
                // debug::dh(*usb_sts as usize);

                usb_sts.writef(0b111111, true);

                // debug::d(" usb_sts ");
                // debug::dh(*usb_sts as usize);

                // let FRINDEX = (opbase + 0xC) as *mut Mmio<u32>;
                // debug::d(" FRINDEX ");
                // debug::dh(*FRINDEX as usize);
            }

            // debug::dl();
        }
    }
}

impl Ehci {
    pub unsafe fn new(mut pci: PciConfig) -> Box<Self> {
        let mut module = box Ehci {
            pci: pci,
            base: pci.read(0x10) as usize & 0xFFFFFFF0,
            irq: pci.read(0x3C) as u8 & 0xF,
        };

        module.init();

        module
    }

    #[allow(non_snake_case)]
    pub unsafe fn init(&mut self) {
        debug!("EHCI on: {:X}, IRQ {:X}", self.base, self.irq);

        self.pci.flag(4, 4, true); // Bus master

        let cap_length = &mut *(self.base as *mut Mmio<u8>);
        let hcs_params = &mut *((self.base + 4) as *mut Mmio<u32>);
        let hcc_params = &mut *((self.base + 8) as *mut Mmio<u32>);

        let ports = (hcs_params.read() & 0b1111) as usize;
        debug::d(" PORTS ");
        debug::dd(ports);

        let eecp = (hcc_params.read() >> 8) as u8;
        debug::d(" EECP ");
        debug::dh(eecp as usize);

        debug::dl();

        if eecp > 0 {
            if self.pci.read(eecp) & (1 << 24 | 1 << 16) == 1 << 16 {
                debug::d("Taking Ownership");
                debug::d(" ");
                debug::dh(self.pci.read(eecp) as usize);

                self.pci.flag(eecp, 1 << 24, true);

                debug::d(" ");
                debug::dh(self.pci.read(eecp) as usize);
                debug::dl();

                debug::d("Waiting");
                debug::d(" ");
                debug::dh(self.pci.read(eecp) as usize);

                while self.pci.read(eecp) & (1 << 24 | 1 << 16) != 1 << 24 {}

                debug::d(" ");
                debug::dh(self.pci.read(eecp) as usize);
                debug::dl();
            }
        }

        let op_base = self.base + cap_length.read() as usize;

        let usb_cmd = &mut *(op_base as *mut Mmio<u32>);
        let usb_sts = &mut *((op_base + 4) as *mut Mmio<u32>);
        let usb_intr = &mut *((op_base + 8) as *mut Mmio<u32>);
        let config_flag = &mut *((op_base + 0x40) as *mut Mmio<u32>);
        let port_scs = &mut slice::from_raw_parts_mut((op_base + 0x44) as *mut Mmio<u32>, ports);

        /*
        let FRINDEX = (opbase + 0xC) as *mut Mmio<u32>;
        let CTRLDSSEGMENT = (opbase + 0x10) as *mut Mmio<u32>;
        let PERIODICLISTBASE = (opbase + 0x14) as *mut Mmio<u32>;
        let ASYNCLISTADDR = (opbase + 0x18) as *mut Mmio<u32>;
        */

        //Halt
        if usb_sts.read() & 1 << 12 == 0 {
            usb_cmd.writef(0xF, false);
            while ! usb_sts.readf(1 << 12) {}
        }

        //Reset
        usb_cmd.writef(1 << 1, true);
        while usb_cmd.readf(1 << 1) {}

        //Enable
        usb_intr.write(0b111111);
        usb_cmd.writef(1, true);
        config_flag.write(1);
        while usb_sts.readf(1 << 12) {}

        for i in 0..port_scs.len() {
            let port_sc = &mut port_scs[i];
            if port_sc.readf(1) {
                debugln!("Device on port {}: {:X}", i, port_sc.read());

                if port_sc.readf(1 << 1) {
                    debugln!("Connection Change");

                    port_sc.writef(1 << 1, true);
                }

                if ! port_sc.readf(1 << 2) {
                    debugln!("Reset");

                    while ! port_sc.readf(1 << 8) {
                        port_sc.writef(1 << 8, true);
                    }

                    let mut spin = 1000000000;
                    while spin > 0 {
                        spin -= 1;
                    }

                    while port_sc.readf(1 << 8) {
                        port_sc.writef(1 << 8, false);
                    }
                }

                debugln!("Port Enabled {:X}", port_sc.read());

                self.device(i as u8 + 1);
            }
        }
    }
}

impl UsbHci for Ehci {
    fn msg(&mut self, address: u8, endpoint: u8, msgs: &[UsbMsg]) -> usize {
        let mut tds = Vec::new();
        for msg in msgs.iter().rev() {
            let link_ptr = match tds.last() {
                Some(td) => (td as *const Qtd) as u32,
                None => 1
            };

            match *msg {
                UsbMsg::Setup(setup) => tds.push(Qtd {
                    next: link_ptr,
                    next_alt: 1,
                    token: (size_of::<Setup>() as u32) << 16 | 0b10 << 8 | 1 << 7,
                    buffers: [(setup as *const Setup) as u32, 0, 0, 0, 0]
                }),
                UsbMsg::In(ref data) => tds.push(Qtd {
                    next: link_ptr,
                    next_alt: 1,
                    token: ((data.len() as u32) & 0x7FFF) << 16 | 0b01 << 8 | 1 << 7,
                    buffers: [data.as_ptr() as u32, 0, 0, 0, 0]
                }),
                UsbMsg::InIso(ref data) => tds.push(Qtd {
                    next: link_ptr,
                    next_alt: 1,
                    token: ((data.len() as u32) & 0x7FFF) << 16 | 0b01 << 8 | 1 << 7,
                    buffers: [data.as_ptr() as u32, 0, 0, 0, 0]
                }),
                UsbMsg::Out(ref data) => tds.push(Qtd {
                    next: link_ptr,
                    next_alt: 1,
                    token: ((data.len() as u32) & 0x7FFF) << 16 | 0b00 << 8 | 1 << 7,
                    buffers: [data.as_ptr() as u32, 0, 0, 0, 0]
                }),
                UsbMsg::OutIso(ref data) => tds.push(Qtd {
                    next: link_ptr,
                    next_alt: 1,
                    token: ((data.len() as u32) & 0x7FFF) << 16 | 0b00 << 8 | 1 << 7,
                    buffers: [data.as_ptr() as u32, 0, 0, 0, 0]
                })
            }
        }

        let mut count = 0;

        if ! tds.is_empty() {
            unsafe {
                let cap_length = &mut *(self.base as *mut Mmio<u8>);

                let op_base = self.base + cap_length.read() as usize;

                let usb_cmd = &mut *(op_base as *mut Mmio<u32>);
                let usb_sts = &mut *((op_base + 4) as *mut Mmio<u32>);
                let async_list = &mut *((op_base + 0x18) as *mut Mmio<u32>);

                let queuehead = box QueueHead {
                    next: 1,
                    characteristics: 1024 << 16 | 1 << 15 | 1 << 14 | 0b10 << 12 | (endpoint as u32) << 8 | address as u32,
                    capabilities: 0b01 << 30,
                    qtd_ptr: (tds.last().unwrap() as *const Qtd) as u32,
                    qtd: *tds.last().unwrap()
                };

                async_list.write((&*queuehead as *const QueueHead) as u32 | 2);
                usb_cmd.writef(1 << 5 | 1, true);

                /*
                for td in tds.iter().rev() {
                    while unsafe { volatile_load(td as *const Qtd).token } & 1 << 7 == 1 << 7 {
                        //unsafe { context_switch(false) };
                    }
                }
                */

                while usb_sts.readf(0xA000) {}

                usb_cmd.writef(1 << 5 | 1, false);
                async_list.write(0);
            }
        }

        count
    }
}
<commit_msg>EHCI works with touchscreen<commit_after>use alloc::boxed::Box;

use collections::vec::Vec;

use core::intrinsics::{volatile_load, volatile_store};
use core::mem::size_of;
use core::ptr::{self, read, write};
use core::slice;

use common::debug;
use common::memory;
use common::time::{self, Duration};

use drivers::mmio::Mmio;
use drivers::pciconfig::PciConfig;

use schemes::KScheme;

use super::hci::{UsbHci, UsbMsg};
use super::setup::Setup;

#[repr(packed)]
#[derive(Copy, Clone, Debug, Default)]
struct Qtd {
    next: u32,
    next_alt: u32,
    token: u32,
    buffers: [u32; 5],
}

#[repr(packed)]
struct QueueHead {
    next: u32,
    characteristics: u32,
    capabilities: u32,
    qtd_ptr: u32,
    qtd: Qtd,
}

pub struct Ehci {
    pub pci: PciConfig,
    pub base: usize,
    pub irq: u8,
}

impl KScheme for Ehci {
    #[allow(non_snake_case)]
    fn on_irq(&mut self, irq: u8) {
        if irq == self.irq {
            // debug::d("EHCI handle");

            unsafe {
                let cap_length = &mut *(self.base as *mut Mmio<u8>);

                let op_base = self.base + cap_length.read() as usize;

                let usb_sts = &mut *((op_base + 4) as *mut Mmio<u32>);
                // debug::d(" usb_sts ");
                // debug::dh(*usb_sts as usize);

                usb_sts.writef(0b111111, true);

                // debug::d(" usb_sts ");
                // debug::dh(*usb_sts as usize);

                // let FRINDEX = (opbase + 0xC) as *mut Mmio<u32>;
                // debug::d(" FRINDEX ");
                // debug::dh(*FRINDEX as usize);
            }

            // debug::dl();
        }
    }
}

impl Ehci {
    pub unsafe fn new(mut pci: PciConfig) -> Box<Self> {
        let mut module = box Ehci {
            pci: pci,
            base: pci.read(0x10) as usize & 0xFFFFFFF0,
            irq: pci.read(0x3C) as u8 & 0xF,
        };

        module.init();

        module
    }

    #[allow(non_snake_case)]
    pub unsafe fn init(&mut self) {
        debug!("EHCI on: {:X}, IRQ {:X}", self.base, self.irq);

        self.pci.flag(4, 4, true); // Bus master

        let cap_length = &mut *(self.base as *mut Mmio<u8>);
        let hcs_params = &mut *((self.base + 4) as *mut Mmio<u32>);
        let hcc_params = &mut *((self.base + 8) as *mut Mmio<u32>);

        let ports = (hcs_params.read() & 0b1111) as usize;
        debug::d(" PORTS ");
        debug::dd(ports);

        let eecp = (hcc_params.read() >> 8) as u8;
        debug::d(" EECP ");
        debug::dh(eecp as usize);

        debug::dl();

        if eecp > 0 {
            if self.pci.read(eecp) & (1 << 24 | 1 << 16) == 1 << 16 {
                debug::d("Taking Ownership");
                debug::d(" ");
                debug::dh(self.pci.read(eecp) as usize);

                self.pci.flag(eecp, 1 << 24, true);

                debug::d(" ");
                debug::dh(self.pci.read(eecp) as usize);
                debug::dl();

                debug::d("Waiting");
                debug::d(" ");
                debug::dh(self.pci.read(eecp) as usize);

                while self.pci.read(eecp) & (1 << 24 | 1 << 16) != 1 << 24 {}

                debug::d(" ");
                debug::dh(self.pci.read(eecp) as usize);
                debug::dl();
            }
        }

        let op_base = self.base + cap_length.read() as usize;

        let usb_cmd = &mut *(op_base as *mut Mmio<u32>);
        let usb_sts = &mut *((op_base + 4) as *mut Mmio<u32>);
        let usb_intr = &mut *((op_base + 8) as *mut Mmio<u32>);
        let config_flag = &mut *((op_base + 0x40) as *mut Mmio<u32>);
        let port_scs = &mut slice::from_raw_parts_mut((op_base + 0x44) as *mut Mmio<u32>, ports);

        /*
        let FRINDEX = (opbase + 0xC) as *mut Mmio<u32>;
        let CTRLDSSEGMENT = (opbase + 0x10) as *mut Mmio<u32>;
        let PERIODICLISTBASE = (opbase + 0x14) as *mut Mmio<u32>;
        let ASYNCLISTADDR = (opbase + 0x18) as *mut Mmio<u32>;
        */

        //Halt
        if usb_sts.read() & 1 << 12 == 0 {
            usb_cmd.writef(0xF, false);
            while ! usb_sts.readf(1 << 12) {}
        }

        //Reset
        usb_cmd.writef(1 << 1, true);
        while usb_cmd.readf(1 << 1) {}

        //Enable
        usb_intr.write(0b111111);
        usb_cmd.writef(1, true);
        config_flag.write(1);
        while usb_sts.readf(1 << 12) {}

        for i in 0..port_scs.len() {
            let port_sc = &mut port_scs[i];
            if port_sc.readf(1) {
                debugln!("Device on port {}: {:X}", i, port_sc.read());

                if port_sc.readf(1 << 1) {
                    debugln!("Connection Change");

                    port_sc.writef(1 << 1, true);
                }

                if ! port_sc.readf(1 << 2) {
                    debugln!("Reset");

                    while ! port_sc.readf(1 << 8) {
                        port_sc.writef(1 << 8, true);
                    }

                    let mut spin = 1000000000;
                    while spin > 0 {
                        spin -= 1;
                    }

                    while port_sc.readf(1 << 8) {
                        port_sc.writef(1 << 8, false);
                    }
                }

                debugln!("Port Enabled {:X}", port_sc.read());

                self.device(i as u8 + 1);
            }
        }
    }
}

impl UsbHci for Ehci {
    fn msg(&mut self, address: u8, endpoint: u8, msgs: &[UsbMsg]) -> usize {
        let mut tds = Vec::new();
        for msg in msgs.iter().rev() {
            let link_ptr = match tds.last() {
                Some(td) => (td as *const Qtd) as u32,
                None => 1
            };

            match *msg {
                UsbMsg::Setup(setup) => tds.push(Qtd {
                    next: link_ptr,
                    next_alt: 1,
                    token: (size_of::<Setup>() as u32) << 16 | 0b10 << 8 | 1 << 7,
                    buffers: [(setup as *const Setup) as u32, 0, 0, 0, 0]
                }),
                UsbMsg::In(ref data) => tds.push(Qtd {
                    next: link_ptr,
                    next_alt: 1,
                    token: ((data.len() as u32) & 0x7FFF) << 16 | 0b01 << 8 | 1 << 7,
                    buffers: [data.as_ptr() as u32, 0, 0, 0, 0]
                }),
                UsbMsg::InIso(ref data) => tds.push(Qtd {
                    next: link_ptr,
                    next_alt: 1,
                    token: ((data.len() as u32) & 0x7FFF) << 16 | 0b01 << 8 | 1 << 7,
                    buffers: [data.as_ptr() as u32, 0, 0, 0, 0]
                }),
                UsbMsg::Out(ref data) => tds.push(Qtd {
                    next: link_ptr,
                    next_alt: 1,
                    token: ((data.len() as u32) & 0x7FFF) << 16 | 0b00 << 8 | 1 << 7,
                    buffers: [data.as_ptr() as u32, 0, 0, 0, 0]
                }),
                UsbMsg::OutIso(ref data) => tds.push(Qtd {
                    next: link_ptr,
                    next_alt: 1,
                    token: ((data.len() as u32) & 0x7FFF) << 16 | 0b00 << 8 | 1 << 7,
                    buffers: [data.as_ptr() as u32, 0, 0, 0, 0]
                })
            }
        }

        let mut count = 0;

        if ! tds.is_empty() {
            unsafe {
                let cap_length = &mut *(self.base as *mut Mmio<u8>);

                let op_base = self.base + cap_length.read() as usize;

                let usb_cmd = &mut *(op_base as *mut Mmio<u32>);
                let usb_sts = &mut *((op_base + 4) as *mut Mmio<u32>);
                let async_list = &mut *((op_base + 0x18) as *mut Mmio<u32>);

                let queuehead = box QueueHead {
                    next: 1,
                    characteristics: 1024 << 16 | 1 << 15 | 1 << 14 | 0b10 << 12 | (endpoint as u32) << 8 | address as u32,
                    capabilities: 0b01 << 30,
                    qtd_ptr: (tds.last().unwrap() as *const Qtd) as u32,
                    qtd: *tds.last().unwrap()
                };

                //TODO: Calculate actual bytes
                for td in tds.iter().rev() {
                    count += (td.token as usize >> 16) & 0x7FFF;
                }

                async_list.write((&*queuehead as *const QueueHead) as u32 | 2);
                usb_cmd.writef(1 << 5 | 1, true);

                let mut i = 0;
                for td in tds.iter().rev() {
                    while unsafe { volatile_load(td as *const Qtd).token } & 1 << 7 == 1 << 7 {
                        //unsafe { context_switch(false) };
                    }
                }

                usb_cmd.writef(1 << 5 | 1, false);
                async_list.write(0);
            }
        }

        count
    }
}
<|endoftext|>