<commit_before>// This module implements the bridge to handlebars.
use std::convert;
use std::io::Read;
use std::io::Write;
use std::io::Result as IOResult;
use std::fs::File;
use std::path::PathBuf;

use serialize::json::ToJson;
use handlebars::RenderError;
use handlebars::Context;
use handlebars::RenderContext;
use handlebars::Template;
use handlebars::Renderable;

use app::Pencil;
use types::{PencilResult, PenString, PenUserError, UserError, PencilError};

impl convert::From<RenderError> for PencilError {
    fn from(err: RenderError) -> PencilError {
        return PenUserError(UserError::new(&err.desc));
    }
}

pub fn render_template<T: ToJson>(app: &mut Pencil, template_name: &str, context: &T) -> PencilResult {
    {
        let registry_read_rv = app.handlebars_registry.read();
        if registry_read_rv.is_err() {
            return Err(PenUserError(UserError::new("Can't acquire handlebars registry")));
        }
        let registry = registry_read_rv.unwrap();
        let template_rv = registry.get_template(template_name);
        if template_rv.is_some() {
            let rv = try!(registry.render(template_name, context));
            return Ok(PenString(rv));
        }
    }

    // Try to load the template here.
    let registry_write_rv = app.handlebars_registry.write();
    if registry_write_rv.is_err() {
        return Err(PenUserError(UserError::new("Can't write handlebars registry")));
    }
    let mut registry = registry_write_rv.unwrap();
    match load_template(template_name) {
        Some(source_rv) => {
            match source_rv {
                Ok(source) => {
                    match registry.register_template_string(template_name, source) {
                        Ok(_) => {
                            let rv = try!(registry.render(template_name, context));
                            return Ok(PenString(rv));
                        },
                        Err(err) => {
                            return Err(PenUserError(UserError::new(format!("Template compile error: {}", err))));
                        }
                    }
                },
                Err(err) => {
                    return Err(PenUserError(UserError::new(format!("Template {} can't be loaded: {}", template_name, err))));
                }
            }
        },
        None => {
            return Err(PenUserError(UserError::new(format!("Template not found: {}", template_name))));
        }
    }
}

struct StringWriter {
    buf: Vec<u8>
}

impl StringWriter {
    pub fn new() -> StringWriter {
        StringWriter {
            buf: Vec::new()
        }
    }

    pub fn to_string(self) -> String {
        if let Ok(s) = String::from_utf8(self.buf) {
            s
        } else {
            String::new()
        }
    }
}

impl Write for StringWriter {
    fn write(&mut self, buf: &[u8]) -> IOResult<usize> {
        for b in buf {
            self.buf.push(*b);
        }
        Ok(buf.len())
    }

    fn flush(&mut self) -> IOResult<()> {
        Ok(())
    }
}

pub fn render_template_string<T: ToJson>(app: &Pencil, source: &str, context: &T) -> PencilResult {
    match app.handlebars_registry.read() {
        Ok(registry) => {
            match Template::compile(source.to_owned()) {
                Ok(template) => {
                    let c = Context::wraps(context);
                    let mut writer = StringWriter::new();
                    {
                        let mut render_context = RenderContext::new(&mut writer);
                        try!(template.render(&c, &**registry, &mut render_context));
                    }
                    Ok(PenString(writer.to_string()))
                },
                Err(err) => {
                    Err(PenUserError(UserError::new(format!("Template compile error: {}", err))))
                }
            }
        },
        Err(_) => {
            Err(PenUserError(UserError::new("Can't acquire handlebars registry")))
        }
    }
}

/// The template loader trait allows for loading template source.
trait TemplateLoader {
    /// Get the template source for a template name.
    fn get_source(&self, template_name: &str) -> Option<IOResult<String>>;
}

/// A template loader that loads templates from the file system.
pub struct FileSystemLoader {
    search_path: String,
}

impl FileSystemLoader {
    /// Create one file system loader.
    /// This loader can find templates in folders on the file system.
    ///
    /// The loader takes the path to the templates:
    ///
    /// ```rust,no_run
    /// let loader = FileSystemLoader::new("/path/to/templates")
    /// let source = loader.get_source("index.html")
    /// ```
    pub fn new(search_path: &str) -> FileSystemLoader {
        FileSystemLoader {
            search_path: search_path.to_string(),
        }
    }
}

impl TemplateLoader for FileSystemLoader {
    fn get_source(&self, template_name: &str) -> Option<IOResult<String>> {
        let mut pathbuf = PathBuf::from(&self.search_path);
        pathbuf.push(template_name);
        match File::open(&pathbuf.as_path()) {
            Ok(mut file) => {
                let mut s = String::new();
                match file.read_to_string(&mut s) {
                    Ok(_) => Some(Ok(s)),
                    Err(err) => Some(Err(err)),
                }
            },
            Err(_) => None
        }
    }
}

fn load_template(template_name: &str) -> Option<IOResult<String>> {
    let template_loader = FileSystemLoader::new("/templates");
    return template_loader.get_source(template_name);
}
<commit_msg>Fixed the build<commit_after>// This module implements the bridge to handlebars.
use std::convert;
use std::io::Read;
use std::io::Write;
use std::io::Result as IOResult;
use std::fs::File;
use std::path::PathBuf;

use serialize::json::ToJson;
use handlebars::RenderError;
use handlebars::Context;
use handlebars::RenderContext;
use handlebars::Template;
use handlebars::Renderable;

use app::Pencil;
use types::{PencilResult, PenString, PenUserError, UserError, PencilError};

impl convert::From<RenderError> for PencilError {
    fn from(err: RenderError) -> PencilError {
        return PenUserError(UserError::new(&err.desc));
    }
}

pub fn render_template<T: ToJson>(app: &mut Pencil, template_name: &str, context: &T) -> PencilResult {
    {
        let registry_read_rv = app.handlebars_registry.read();
        if registry_read_rv.is_err() {
            return Err(PenUserError(UserError::new("Can't acquire handlebars registry")));
        }
        let registry = registry_read_rv.unwrap();
        let template_rv = registry.get_template(template_name);
        if template_rv.is_some() {
            let rv = try!(registry.render(template_name, context));
            return Ok(PenString(rv));
        }
    }

    // Try to load the template here.
    let registry_write_rv = app.handlebars_registry.write();
    if registry_write_rv.is_err() {
        return Err(PenUserError(UserError::new("Can't write handlebars registry")));
    }
    let mut registry = registry_write_rv.unwrap();
    match load_template(template_name) {
        Some(source_rv) => {
            match source_rv {
                Ok(source) => {
                    match registry.register_template_string(template_name, source) {
                        Ok(_) => {
                            let rv = try!(registry.render(template_name, context));
                            return Ok(PenString(rv));
                        },
                        Err(err) => {
                            return Err(PenUserError(UserError::new(format!("Template compile error: {}", err))));
                        }
                    }
                },
                Err(err) => {
                    return Err(PenUserError(UserError::new(format!("Template {} can't be loaded: {}", template_name, err))));
                }
            }
        },
        None => {
            return Err(PenUserError(UserError::new(format!("Template not found: {}", template_name))));
        }
    }
}

struct StringWriter {
    buf: Vec<u8>
}

impl StringWriter {
    pub fn new() -> StringWriter {
        StringWriter {
            buf: Vec::new()
        }
    }

    pub fn to_string(self) -> String {
        if let Ok(s) = String::from_utf8(self.buf) {
            s
        } else {
            String::new()
        }
    }
}

impl Write for StringWriter {
    fn write(&mut self, buf: &[u8]) -> IOResult<usize> {
        for b in buf {
            self.buf.push(*b);
        }
        Ok(buf.len())
    }

    fn flush(&mut self) -> IOResult<()> {
        Ok(())
    }
}

pub fn render_template_string<T: ToJson>(app: &Pencil, source: &str, context: &T) -> PencilResult {
    match app.handlebars_registry.read() {
        Ok(registry) => {
            match Template::compile(source.to_owned()) {
                Ok(template) => {
                    let c = Context::wraps(context);
                    let mut writer = StringWriter::new();
                    {
                        let mut render_context = RenderContext::new(&mut writer);
                        try!(template.render(&c, &**registry, &mut render_context));
                    }
                    Ok(PenString(writer.to_string()))
                },
                Err(err) => {
                    Err(PenUserError(UserError::new(format!("Template compile error: {}", err))))
                }
            }
        },
        Err(_) => {
            Err(PenUserError(UserError::new("Can't acquire handlebars registry")))
        }
    }
}

/// The template loader trait allows for loading template source.
trait TemplateLoader {
    /// Get the template source for a template name.
    fn get_source(&self, template_name: &str) -> Option<IOResult<String>>;
}

/// A template loader that loads templates from the file system.
pub struct FileSystemLoader {
    search_path: String,
}

impl FileSystemLoader {
    /// Create one file system loader.
    /// This loader can find templates in folders on the file system.
    ///
    /// The loader takes the path to the templates:
    ///
    /// ```ignore
    /// let loader = FileSystemLoader::new("/path/to/templates");
    /// let source = loader.get_source("index.html");
    /// ```
    pub fn new(search_path: &str) -> FileSystemLoader {
        FileSystemLoader {
            search_path: search_path.to_string(),
        }
    }
}

impl TemplateLoader for FileSystemLoader {
    fn get_source(&self, template_name: &str) -> Option<IOResult<String>> {
        let mut pathbuf = PathBuf::from(&self.search_path);
        pathbuf.push(template_name);
        match File::open(&pathbuf.as_path()) {
            Ok(mut file) => {
                let mut s = String::new();
                match file.read_to_string(&mut s) {
                    Ok(_) => Some(Ok(s)),
                    Err(err) => Some(Err(err)),
                }
            },
            Err(_) => None
        }
    }
}

fn load_template(template_name: &str) -> Option<IOResult<String>> {
    let template_loader = FileSystemLoader::new("/templates");
    return template_loader.get_source(template_name);
}
<|endoftext|>


<commit_before>use std::io::net::tcp::TcpStream;
use std::io::IoResult;
use std::num;

#[deriving(Clone)]
pub enum Payload {
    Text(Box<String>),
    Binary(Vec<u8>),
    Empty
}

#[deriving(Clone, FromPrimitive)]
pub enum Opcode {
    ContinuationOp = 0x0,
    TextOp         = 0x1,
    BinaryOp       = 0x2,
    CloseOp        = 0x8,
    PingOp         = 0x9,
    PongOp         = 0xA,
}

// this struct will eventually encapsulate data framing, opcodes, ws extensions, masks etc
// right now, only single frames, with a text payload are supported
#[deriving(Clone)]
pub struct Message {
    pub payload: Payload,
    pub opcode: Opcode
}

impl Message {
    pub fn load(stream: &mut TcpStream) -> IoResult<Box<Message>> {
        let vec1 = try!(stream.read_exact(2));
        let buf1 = vec1.as_slice();
        println!("buf1: {:t} {:t}", buf1[0], buf1[1]);

        //let fin    = buf1[0] & 0b1000_0000; // TODO check this, required for handling fragmented messages

        /* we ignore these, as they are only used if a websocket protocol has been enabled, and optionally at that
        let rsv1   = buf1[0] & 0b0100_0000;
        let rsv2   = buf1[0] & 0b0010_0000;
        let rsv3   = buf1[0] & 0b0001_0000;
        */
        let opcode = buf1[0] & 0b0000_1111;
        let opcode: Opcode = num::from_u8(opcode).unwrap(); // all valid RFC 6455 Opcodes specified, invalid ones will fail!()

        //let mask    = buf1[1] & 0b1000_0000; TODO use this to determine whether to unmask or not
        let pay_len = buf1[1] & 0b0111_1111;

        let payload_length = match pay_len {
            127 => try!(stream.read_be_u64()), // 8 bytes in network byte order
            126 => try!(stream.read_be_u16()) as u64, // 2 bytes in network byte order
            _   => pay_len as u64
        };
        println!("payload_length: {}", payload_length);

        let masking_key_vec = try!(stream.read_exact(4));
        let masking_key_buf = masking_key_vec.as_slice();
        println!("masking_key_buf: {:t} {:t} {:t} {:t}", masking_key_buf[0], masking_key_buf[1], masking_key_buf[2], masking_key_buf[3]);

        let masked_payload_buf = try!(stream.read_exact(payload_length as uint));

        // unmask the payload
        let mut payload_buf = vec!(); // instead of a mutable vector, a map_with_index would be nice. or maybe just mutate the existing buffer in place.
        for (i, &octet) in masked_payload_buf.iter().enumerate() {
            payload_buf.push(octet ^ masking_key_buf[i % 4]);
        }

        let payload: Payload = match opcode {
            TextOp   => Text(box String::from_utf8(payload_buf).unwrap()), // unsafe unwrap? failures during autobahn
            BinaryOp => Binary(payload_buf),
            CloseOp  => Empty,
            _        => unimplemented!(), // TODO ping/pong/close/continuation
        };

        let message = box Message {
            payload: payload,
            opcode: opcode
        };

        return Ok(message);
    }

    // FIXME support for clients - masking for clients, but need know whether
    // it's a client or server doing the sending. maybe a private `send` with
    // the common code, and public `client_send` and `server_send` methods.
    // these methods will be called by the WebSokcetClient and WebSocketServer
    // traits respectively, and the interface for both clients and servers is
    // the same - just send on the channel, and the trait takes care of it
    pub fn send(&self, stream: &mut TcpStream) -> IoResult<()> {
        let payload_length = match self.payload {
            Text(ref p) => p.len(),
            Binary(ref p) => p.len(),
            Empty => 0,
        };

        try!(stream.write_u8(0b1000_0000 | self.opcode as u8)); // fin: 1, rsv: 000, opcode: see Opcode

        // FIXME: this assumes a server. the first bit, which is the "mask" bit, is implicitly set as 0 here, as required for ws servers
        if payload_length <= 125 {
            try!(stream.write_u8(payload_length as u8));
        } else if payload_length <= 65536 {
            try!(stream.write_u8(126));
            try!(stream.write_be_u16(payload_length as u16));
        } else if payload_length > 65536 {
            try!(stream.write_u8(127));
            try!(stream.write_be_u64(payload_length as u64));
        }

        match self.payload {
            Text(ref p)   => try!(stream.write((*p).as_slice().as_bytes())),
            Binary(ref p) => try!(stream.write((*p).as_slice())),
            Empty => {},
        }

        try!(stream.flush());

        return Ok(());
    }
}
<commit_msg>fix off-by-one bug with message payload length<commit_after>use std::io::net::tcp::TcpStream;
use std::io::IoResult;
use std::num;

#[deriving(Clone)]
pub enum Payload {
    Text(Box<String>),
    Binary(Vec<u8>),
    Empty
}

#[deriving(Clone, FromPrimitive)]
pub enum Opcode {
    ContinuationOp = 0x0,
    TextOp         = 0x1,
    BinaryOp       = 0x2,
    CloseOp        = 0x8,
    PingOp         = 0x9,
    PongOp         = 0xA,
}

// this struct will eventually encapsulate data framing, opcodes, ws extensions, masks etc
// right now, only single frames, with a text payload are supported
#[deriving(Clone)]
pub struct Message {
    pub payload: Payload,
    pub opcode: Opcode
}

impl Message {
    pub fn load(stream: &mut TcpStream) -> IoResult<Box<Message>> {
        let vec1 = try!(stream.read_exact(2));
        let buf1 = vec1.as_slice();
        println!("buf1: {:t} {:t}", buf1[0], buf1[1]);

        //let fin    = buf1[0] & 0b1000_0000; // TODO check this, required for handling fragmented messages

        /* we ignore these, as they are only used if a websocket protocol has been enabled, and optionally at that
        let rsv1   = buf1[0] & 0b0100_0000;
        let rsv2   = buf1[0] & 0b0010_0000;
        let rsv3   = buf1[0] & 0b0001_0000;
        */
        let opcode = buf1[0] & 0b0000_1111;
        let opcode: Opcode = num::from_u8(opcode).unwrap(); // all valid RFC 6455 Opcodes specified, invalid ones will fail!()

        //let mask    = buf1[1] & 0b1000_0000; TODO use this to determine whether to unmask or not
        let pay_len = buf1[1] & 0b0111_1111;

        let payload_length = match pay_len {
            127 => try!(stream.read_be_u64()), // 8 bytes in network byte order
            126 => try!(stream.read_be_u16()) as u64, // 2 bytes in network byte order
            _   => pay_len as u64
        };
        println!("payload_length: {}", payload_length);

        let masking_key_vec = try!(stream.read_exact(4));
        let masking_key_buf = masking_key_vec.as_slice();
        println!("masking_key_buf: {:t} {:t} {:t} {:t}", masking_key_buf[0], masking_key_buf[1], masking_key_buf[2], masking_key_buf[3]);

        let masked_payload_buf = try!(stream.read_exact(payload_length as uint));

        // unmask the payload
        let mut payload_buf = vec!(); // instead of a mutable vector, a map_with_index would be nice. or maybe just mutate the existing buffer in place.
        for (i, &octet) in masked_payload_buf.iter().enumerate() {
            payload_buf.push(octet ^ masking_key_buf[i % 4]);
        }

        let payload: Payload = match opcode {
            TextOp   => Text(box String::from_utf8(payload_buf).unwrap()), // unsafe unwrap? failures during autobahn
            BinaryOp => Binary(payload_buf),
            CloseOp  => Empty,
            _        => unimplemented!(), // TODO ping/pong/close/continuation
        };

        let message = box Message {
            payload: payload,
            opcode: opcode
        };

        return Ok(message);
    }

    // FIXME support for clients - masking for clients, but need know whether
    // it's a client or server doing the sending. maybe a private `send` with
    // the common code, and public `client_send` and `server_send` methods.
    // these methods will be called by the WebSokcetClient and WebSocketServer
    // traits respectively, and the interface for both clients and servers is
    // the same - just send on the channel, and the trait takes care of it
    pub fn send(&self, stream: &mut TcpStream) -> IoResult<()> {
        let payload_length = match self.payload {
            Text(ref p) => p.len(),
            Binary(ref p) => p.len(),
            Empty => 0,
        };

        try!(stream.write_u8(0b1000_0000 | self.opcode as u8)); // fin: 1, rsv: 000, opcode: see Opcode

        // FIXME: this assumes a server. the first bit, which is the "mask" bit, is implicitly set as 0 here, as required for ws servers
        if payload_length <= 125 {
            try!(stream.write_u8(payload_length as u8));
        } else if payload_length <= 65535 {
            try!(stream.write_u8(126));
            try!(stream.write_be_u16(payload_length as u16));
        } else if payload_length > 65535 {
            try!(stream.write_u8(127));
            try!(stream.write_be_u64(payload_length as u64));
        }

        match self.payload {
            Text(ref p)   => try!(stream.write((*p).as_slice().as_bytes())),
            Binary(ref p) => try!(stream.write((*p).as_slice())),
            Empty => {},
        }

        try!(stream.flush());

        return Ok(());
    }
}
<|endoftext|>


<commit_before>extern crate x11;
extern crate libc;

use std::ffi;
use std::process::Command;
use std::boxed::Box;
use std::ptr;

use x11::xlib;
use x11::xlib::{ Display, Window };
use super::WindowManager;
use super::workspace::Workspaces;
use super::layout;

#[derive(Hash, Eq, PartialEq, Debug)]
pub struct KeyBind {
    pub key: u64,
    pub mask: u32,
}

impl KeyBind {
    pub fn build(mod_key: u32, tokens: &[&str]) -> KeyBind {
        let mut mask = 0;
        let mut sym = 0;
        for key in tokens {
            match *key {
                "$mod" => mask = mask | mod_key,
                "Shift" => mask = mask | xlib::ShiftMask,
                "Ctrl" => mask = mask | xlib::ControlMask,
                "Mod1" => mask = mask | xlib::Mod1Mask,
                "Mod2" => mask = mask | xlib::Mod2Mask,
                "Mod3" => mask = mask | xlib::Mod3Mask,
                "Mod4" => mask = mask | xlib::Mod4Mask,
                "Mod5" => mask = mask | xlib::Mod5Mask,
                _ => {
                    let tmp = ffi::CString::new(*key).unwrap();
                    unsafe{
                        sym = xlib::XStringToKeysym(tmp.as_ptr());
                    }
                }
            }
        }

        println!("bind {} {}", mask, sym);
        KeyBind {
            mask: mask,
            key: sym
        }
    }
}

pub trait Handler {
    fn handle(&mut self, workspaces: &mut Workspaces, display: *mut Display, screen_num: libc::c_int);
}

pub struct ExecHandler {
    pub cmd: Command
}

pub struct LayoutHandler {
    layout_type: layout::Type,
}

/// switch to another workspace
pub struct WorkspaceHandler {
    pub key: char,
}

/// move window to target workspace
pub struct WindowToWorkspaceHandler {
    pub key: char,
}

impl Handler for WindowToWorkspaceHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, display: *mut Display, screen_num: libc::c_int) {
        debug!("handle window move form {} to {}", workspaces.current_name(), self.key);
        let mut window: Window = 0;
        let mut revert_to: libc::c_int = 0;
        unsafe{
            let s = xlib::XGetInputFocus(display, &mut window, &mut revert_to);
            println!("window {}", window);
        }

        let mut root: Window = 0;
        let mut parent: Window = window;
        let mut children: *mut Window = ptr::null_mut();
        let mut nchildren: libc::c_uint = 0;

        // while parent != root {
            window = parent;
            unsafe{
                let s = xlib::XQueryTree(display, window, &mut root, &mut parent, &mut children, &mut nchildren);
                if s > 0 {
                    println!("parent {} root {}", parent, root);
                    xlib::XFree(children as *mut libc::c_void);
                }
                else{
                    println!("error");
                }
            }
        // }

        println!("focused window {}", window);
        workspaces.current().p();
        let from = workspaces.current_name();
        workspaces.move_window(window, from, self.key);
        workspaces.current().config(display, screen_num);

        match workspaces.get(self.key) {
            Some(w) => {
                w.config(display, screen_num);
            }
            None => {}
        }

    }
}

impl Handler for WorkspaceHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, display: *mut Display, screen_num: libc::c_int) {
        debug!("handle workspace");
        workspaces.switch_current(self.key, display);
    }
}

impl Handler for ExecHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, display: *mut Display, screen_num: libc::c_int) {
        debug!("handle exec");
        self.cmd.spawn();
    }
}

impl Handler for LayoutHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, display: *mut xlib::Display, screen_num: libc::c_int) {
        debug!("handle layout");
        let current = workspaces.current();
        let t = self.layout_type.clone();
        current.change_layout(t);
        current.config(display, screen_num);
    }
}

impl LayoutHandler {
    pub fn new(layout: layout::Type) -> LayoutHandler{
        LayoutHandler {
            layout_type: layout
        }
    }
}

impl ExecHandler {
    pub fn new(tokens: &[&str]) -> ExecHandler {
        let (name, args) = tokens.split_at(1);
        let mut cmd = Command::new(name[0]);

        for arg in args {
            println!("{}", arg);
            cmd.arg(arg);
        }

        let handler = ExecHandler {
            cmd: cmd,
        };
        handler
    }
}
<commit_msg>add WindowFocusHandler<commit_after>extern crate x11;
extern crate libc;

use std::ffi;
use std::process::Command;
use std::boxed::Box;
use std::ptr;

use x11::xlib;
use x11::xlib::{ Display, Window };
use super::WindowManager;
use super::workspace::Workspaces;
use super::layout;

#[derive(Hash, Eq, PartialEq, Debug)]
pub struct KeyBind {
    pub key: u64,
    pub mask: u32,
}

impl KeyBind {
    pub fn build(mod_key: u32, tokens: &[&str]) -> KeyBind {
        let mut mask = 0;
        let mut sym = 0;
        for key in tokens {
            match *key {
                "$mod" => mask = mask | mod_key,
                "Shift" => mask = mask | xlib::ShiftMask,
                "Ctrl" => mask = mask | xlib::ControlMask,
                "Mod1" => mask = mask | xlib::Mod1Mask,
                "Mod2" => mask = mask | xlib::Mod2Mask,
                "Mod3" => mask = mask | xlib::Mod3Mask,
                "Mod4" => mask = mask | xlib::Mod4Mask,
                "Mod5" => mask = mask | xlib::Mod5Mask,
                _ => {
                    let tmp = ffi::CString::new(*key).unwrap();
                    unsafe{
                        sym = xlib::XStringToKeysym(tmp.as_ptr());
                    }
                }
            }
        }

        println!("bind {} {}", mask, sym);
        KeyBind {
            mask: mask,
            key: sym
        }
    }
}

pub trait Handler {
    fn handle(&mut self, workspaces: &mut Workspaces, display: *mut Display, screen_num: libc::c_int);
}

pub struct ExecHandler {
    pub cmd: Command
}

pub struct LayoutHandler {
    layout_type: layout::Type,
}

/// switch to another workspace
pub struct WorkspaceHandler {
    pub key: char,
}

/// move window to target workspace
pub struct WindowToWorkspaceHandler {
    pub key: char,
}

pub struct WindowFocusHandler {
    pub direction: layout::Direction,
}

impl Handler for WindowFocusHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, display: *mut Display, screen_num: libc::c_int) {
        debug!("change focus in current workspace");
        let mut window: Window = 0;
        let mut revert_to: libc::c_int = 0;
        unsafe {
            let s = xlib::XGetInputFocus(display, &mut window, &mut revert_to);
            println!("window {}", window);
            let current = workspaces.current();
            match current.contain(window) {
                Some(i) => {
                    let next = if (i+1) >= current.size() { 0 } else { i+1 };
                    xlib::XSetInputFocus(display, current.get(next), 0, 0);
                }
                None => {}
            }
        }
    }
}
impl Handler for WindowToWorkspaceHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, display: *mut Display, screen_num: libc::c_int) {
        debug!("handle window move form {} to {}", workspaces.current_name(), self.key);
        let mut window: Window = 0;
        let mut revert_to: libc::c_int = 0;
        unsafe{
            let s = xlib::XGetInputFocus(display, &mut window, &mut revert_to);
            println!("window {}", window);
        }

        let mut root: Window = 0;
        let mut parent: Window = window;
        let mut children: *mut Window = ptr::null_mut();
        let mut nchildren: libc::c_uint = 0;

        // while parent != root {
            window = parent;
            unsafe{
                let s = xlib::XQueryTree(display, window, &mut root, &mut parent, &mut children, &mut nchildren);
                if s > 0 {
                    println!("parent {} root {}", parent, root);
                    xlib::XFree(children as *mut libc::c_void);
                }
                else{
                    println!("error");
                }
            }
        // }

        println!("focused window {}", window);
        workspaces.current().p();
        let from = workspaces.current_name();
        workspaces.move_window(window, from, self.key);
        workspaces.current().config(display, screen_num);

        match workspaces.get(self.key) {
            Some(w) => {
                w.config(display, screen_num);
            }
            None => {}
        }

    }
}

impl Handler for WorkspaceHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, display: *mut Display, screen_num: libc::c_int) {
        debug!("handle workspace");
        workspaces.switch_current(self.key, display);
    }
}

impl Handler for ExecHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, display: *mut Display, screen_num: libc::c_int) {
        debug!("handle exec");
        self.cmd.spawn();
    }
}

impl Handler for LayoutHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, display: *mut xlib::Display, screen_num: libc::c_int) {
        debug!("handle layout");
        let current = workspaces.current();
        let t = self.layout_type.clone();
        current.change_layout(t);
        current.config(display, screen_num);
    }
}

impl LayoutHandler {
    pub fn new(layout: layout::Type) -> LayoutHandler{
        LayoutHandler {
            layout_type: layout
        }
    }
}

impl ExecHandler {
    pub fn new(tokens: &[&str]) -> ExecHandler {
        let (name, args) = tokens.split_at(1);
        let mut cmd = Command::new(name[0]);

        for arg in args {
            println!("{}", arg);
            cmd.arg(arg);
        }

        let handler = ExecHandler {
            cmd: cmd,
        };
        handler
    }
}
<|endoftext|>


<commit_before>// ignore-windows: No libc on Windows
// ignore-macos: pthread_condattr_setclock is not supported on MacOS.
// compile-flags: -Zmiri-disable-isolation

#![feature(rustc_private)]

/// Test that conditional variable timeouts are working properly with both
/// monotonic and system clocks.
extern crate libc;

use std::mem;
use std::time::Instant;

fn test_timed_wait_timeout(clock_id: i32) {
    unsafe {
        let mut attr: libc::pthread_condattr_t = mem::zeroed();
        assert_eq!(libc::pthread_condattr_init(&mut attr as *mut _), 0);
        assert_eq!(libc::pthread_condattr_setclock(&mut attr as *mut _, clock_id), 0);

        let mut cond: libc::pthread_cond_t = mem::zeroed();
        assert_eq!(libc::pthread_cond_init(&mut cond as *mut _, &attr as *const _), 0);
        assert_eq!(libc::pthread_condattr_destroy(&mut attr as *mut _), 0);

        let mut mutex: libc::pthread_mutex_t = mem::zeroed();

        let mut now: libc::timespec = mem::zeroed();
        assert_eq!(libc::clock_gettime(clock_id, &mut now), 0);
        let timeout = libc::timespec { tv_sec: now.tv_sec + 1, tv_nsec: now.tv_nsec };

        assert_eq!(libc::pthread_mutex_lock(&mut mutex as *mut _), 0);
        let current_time = Instant::now();
        assert_eq!(
            libc::pthread_cond_timedwait(&mut cond as *mut _, &mut mutex as *mut _, &timeout),
            libc::ETIMEDOUT
        );
        let elapsed_time = current_time.elapsed().as_millis();
        assert!(900 <= elapsed_time && elapsed_time <= 1100);
        assert_eq!(libc::pthread_mutex_unlock(&mut mutex as *mut _), 0);
        assert_eq!(libc::pthread_mutex_destroy(&mut mutex as *mut _), 0);
        assert_eq!(libc::pthread_cond_destroy(&mut cond as *mut _), 0);
    }
}

fn main() {
    test_timed_wait_timeout(libc::CLOCK_MONOTONIC);
    test_timed_wait_timeout(libc::CLOCK_REALTIME);
}
<commit_msg>Increase the elapsed time window.<commit_after>// ignore-windows: No libc on Windows
// ignore-macos: pthread_condattr_setclock is not supported on MacOS.
// compile-flags: -Zmiri-disable-isolation

#![feature(rustc_private)]

/// Test that conditional variable timeouts are working properly with both
/// monotonic and system clocks.
extern crate libc;

use std::mem;
use std::time::Instant;

fn test_timed_wait_timeout(clock_id: i32) {
    unsafe {
        let mut attr: libc::pthread_condattr_t = mem::zeroed();
        assert_eq!(libc::pthread_condattr_init(&mut attr as *mut _), 0);
        assert_eq!(libc::pthread_condattr_setclock(&mut attr as *mut _, clock_id), 0);

        let mut cond: libc::pthread_cond_t = mem::zeroed();
        assert_eq!(libc::pthread_cond_init(&mut cond as *mut _, &attr as *const _), 0);
        assert_eq!(libc::pthread_condattr_destroy(&mut attr as *mut _), 0);

        let mut mutex: libc::pthread_mutex_t = mem::zeroed();

        let mut now: libc::timespec = mem::zeroed();
        assert_eq!(libc::clock_gettime(clock_id, &mut now), 0);
        let timeout = libc::timespec { tv_sec: now.tv_sec + 1, tv_nsec: now.tv_nsec };

        assert_eq!(libc::pthread_mutex_lock(&mut mutex as *mut _), 0);
        let current_time = Instant::now();
        assert_eq!(
            libc::pthread_cond_timedwait(&mut cond as *mut _, &mut mutex as *mut _, &timeout),
            libc::ETIMEDOUT
        );
        let elapsed_time = current_time.elapsed().as_millis();
        assert!(900 <= elapsed_time && elapsed_time <= 1300);
        assert_eq!(libc::pthread_mutex_unlock(&mut mutex as *mut _), 0);
        assert_eq!(libc::pthread_mutex_destroy(&mut mutex as *mut _), 0);
        assert_eq!(libc::pthread_cond_destroy(&mut cond as *mut _), 0);
    }
}

fn main() {
    test_timed_wait_timeout(libc::CLOCK_MONOTONIC);
    test_timed_wait_timeout(libc::CLOCK_REALTIME);
}
<|endoftext|>


<commit_before>

#![feature(conservative_impl_trait)]
#![deny(needless_lifetimes)]
#![allow(dead_code)]

trait Foo {}

struct Bar {}

struct Baz<'a> {
    bar: &'a Bar,
}

impl<'a> Foo for Baz<'a> {}

impl Bar {
    fn baz<'a>(&'a self) -> impl Foo + 'a {
        Baz { bar: self }
    }
}

fn main() {}
<commit_msg>Update needless_lifetimes_impl_trait.rs<commit_after>
#![allow(stable_features)]
#![feature(conservative_impl_trait)]
#![deny(needless_lifetimes)]
#![allow(dead_code)]

trait Foo {}

struct Bar {}

struct Baz<'a> {
    bar: &'a Bar,
}

impl<'a> Foo for Baz<'a> {}

impl Bar {
    fn baz<'a>(&'a self) -> impl Foo + 'a {
        Baz { bar: self }
    }
}

fn main() {}
<|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/. */

use dom::bindings::codegen::BindingDeclarations::HTMLParamElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLParamElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::error::ErrorResult;
use dom::document::Document;
use dom::element::HTMLParamElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;

#[deriving(Encodable)]
pub struct HTMLParamElement {
    pub htmlelement: HTMLElement
}

impl HTMLParamElementDerived for EventTarget {
    fn is_htmlparamelement(&self) -> bool {
        self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLParamElementTypeId))
    }
}

impl HTMLParamElement {
    pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLParamElement {
        HTMLParamElement {
            htmlelement: HTMLElement::new_inherited(HTMLParamElementTypeId, localName, document)
        }
    }

    pub fn new(localName: DOMString, document: &JSRef<Document>) -> Temporary<HTMLParamElement> {
        let element = HTMLParamElement::new_inherited(localName, document);
        Node::reflect_node(box element, document, HTMLParamElementBinding::Wrap)
    }
}

pub trait HTMLParamElementMethods {
    fn Name(&self) -> DOMString;
    fn SetName(&mut self, _name: DOMString) -> ErrorResult;
    fn Value(&self) -> DOMString;
    fn SetValue(&mut self, _value: DOMString) -> ErrorResult;
    fn Type(&self) -> DOMString;
    fn SetType(&mut self, _type: DOMString) -> ErrorResult;
    fn ValueType(&self) -> DOMString;
    fn SetValueType(&mut self, _value_type: DOMString) -> ErrorResult;
}

impl<'a> HTMLParamElementMethods for JSRef<'a, HTMLParamElement> {
    fn Name(&self) -> DOMString {
        "".to_owned()
    }

    fn SetName(&mut self, _name: DOMString) -> ErrorResult {
        Ok(())
    }

    fn Value(&self) -> DOMString {
        "".to_owned()
    }

    fn SetValue(&mut self, _value: DOMString) -> ErrorResult {
        Ok(())
    }

    fn Type(&self) -> DOMString {
        "".to_owned()
    }

    fn SetType(&mut self, _type: DOMString) -> ErrorResult {
        Ok(())
    }

    fn ValueType(&self) -> DOMString {
        "".to_owned()
    }

    fn SetValueType(&mut self, _value_type: DOMString) -> ErrorResult {
        Ok(())
    }
}
<commit_msg>Remove needless '&mut self' from HTMLParamElementMethods.<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/. */

use dom::bindings::codegen::BindingDeclarations::HTMLParamElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLParamElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::error::ErrorResult;
use dom::document::Document;
use dom::element::HTMLParamElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;

#[deriving(Encodable)]
pub struct HTMLParamElement {
    pub htmlelement: HTMLElement
}

impl HTMLParamElementDerived for EventTarget {
    fn is_htmlparamelement(&self) -> bool {
        self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLParamElementTypeId))
    }
}

impl HTMLParamElement {
    pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLParamElement {
        HTMLParamElement {
            htmlelement: HTMLElement::new_inherited(HTMLParamElementTypeId, localName, document)
        }
    }

    pub fn new(localName: DOMString, document: &JSRef<Document>) -> Temporary<HTMLParamElement> {
        let element = HTMLParamElement::new_inherited(localName, document);
        Node::reflect_node(box element, document, HTMLParamElementBinding::Wrap)
    }
}

pub trait HTMLParamElementMethods {
    fn Name(&self) -> DOMString;
    fn SetName(&self, _name: DOMString) -> ErrorResult;
    fn Value(&self) -> DOMString;
    fn SetValue(&self, _value: DOMString) -> ErrorResult;
    fn Type(&self) -> DOMString;
    fn SetType(&self, _type: DOMString) -> ErrorResult;
    fn ValueType(&self) -> DOMString;
    fn SetValueType(&self, _value_type: DOMString) -> ErrorResult;
}

impl<'a> HTMLParamElementMethods for JSRef<'a, HTMLParamElement> {
    fn Name(&self) -> DOMString {
        "".to_owned()
    }

    fn SetName(&self, _name: DOMString) -> ErrorResult {
        Ok(())
    }

    fn Value(&self) -> DOMString {
        "".to_owned()
    }

    fn SetValue(&self, _value: DOMString) -> ErrorResult {
        Ok(())
    }

    fn Type(&self) -> DOMString {
        "".to_owned()
    }

    fn SetType(&self, _type: DOMString) -> ErrorResult {
        Ok(())
    }

    fn ValueType(&self) -> DOMString {
        "".to_owned()
    }

    fn SetValueType(&self, _value_type: DOMString) -> ErrorResult {
        Ok(())
    }
}
<|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/. */

/*!
An adapter for ImageCacheTask that does local caching to avoid
extra message traffic, it also avoids waiting on the same image
multiple times and thus triggering reflows multiple times.
*/

use image_cache_task::{Decode, GetImage, ImageCacheTask, ImageFailed, ImageNotReady, ImageReady};
use image_cache_task::{ImageResponseMsg, Prefetch, WaitForImage};

use clone_arc = std::arc::clone;
use core::comm::Port;
use servo_util::url::{UrlMap, url_map};
use std::net::url::Url;

pub fn LocalImageCache(image_cache_task: ImageCacheTask) -> LocalImageCache {
    LocalImageCache {
        image_cache_task: image_cache_task,
        round_number: 1,
        mut on_image_available: None,
        state_map: url_map()
    }
}

pub struct LocalImageCache {
    priv image_cache_task: ImageCacheTask,
    priv round_number: uint,
    priv on_image_available: Option<@fn() -> ~fn(ImageResponseMsg)>,
    priv state_map: UrlMap<@mut ImageState>
}

priv struct ImageState {
    prefetched: bool,
    decoded: bool,
    last_request_round: uint,
    last_response: ImageResponseMsg
}

#[allow(non_implicitly_copyable_typarams)] // Using maps of Urls
pub impl LocalImageCache {
    /// The local cache will only do a single remote request for a given
    /// URL in each 'round'. Layout should call this each time it begins
    // FIXME: 'pub' is an unexpected token?
    /* pub */ fn next_round(&mut self, on_image_available: @fn() -> ~fn(ImageResponseMsg)) {
        self.round_number += 1;
        self.on_image_available = Some(on_image_available);
    }

    pub fn prefetch(&self, url: &Url) {
        let state = self.get_state(url);
        if !state.prefetched {
            self.image_cache_task.send(Prefetch(copy *url));
            state.prefetched = true;
        }
    }

    pub fn decode(&self, url: &Url) {
        let state = self.get_state(url);
        if !state.decoded {
            self.image_cache_task.send(Decode(copy *url));
            state.decoded = true;
        }
    }

    // FIXME: Should return a Future
    pub fn get_image(&self, url: &Url) -> Port<ImageResponseMsg> {
        let state = self.get_state(url);

        // Save the previous round number for comparison
        let last_round = state.last_request_round;
        // Set the current round number for this image
        state.last_request_round = self.round_number;

        match state.last_response {
            ImageReady(ref image) => {
                let (port, chan) = comm::stream();
                chan.send(ImageReady(clone_arc(image)));
                return port;
            }
            ImageNotReady => {
                if last_round == self.round_number {
                    let (port, chan) = comm::stream();
                    chan.send(ImageNotReady);
                    return port;
                } else {
                    // We haven't requested the image from the
                    // remote cache this round
                }
            }
            ImageFailed => {
                let (port, chan) = comm::stream();
                chan.send(ImageFailed);
                return port;
            }
        }

        let (response_port, response_chan) = comm::stream();
        self.image_cache_task.send(GetImage(copy *url, response_chan));

        let response = response_port.recv();
        match response {
            ImageNotReady => {
                // Need to reflow when the image is available
                // FIXME: Instead we should be just passing a Future
                // to the caller, then to the display list. Finally,
                // the compositor should be resonsible for waiting
                // on the image to load and triggering layout
                let image_cache_task = self.image_cache_task.clone();
                assert!(self.on_image_available.is_some());
                let on_image_available = self.on_image_available.get()();
                let url = copy *url;
                do task::spawn {
                    let (response_port, response_chan) = comm::stream();
                    image_cache_task.send(WaitForImage(copy url, response_chan));
                    on_image_available(response_port.recv());
                }
            }
            _ => ()
        }

        // Put a copy of the response in the cache
        let response_copy = match response {
            ImageReady(ref image) => ImageReady(clone_arc(image)),
            ImageNotReady => ImageNotReady,
            ImageFailed => ImageFailed
        };
        state.last_response = response_copy;

        let (port, chan) = comm::stream();
        chan.send(response);
        return port;
    }

    priv fn get_state(&self, url: &Url) -> @mut ImageState {
        let state = do self.state_map.find_or_insert_with(url.clone()) |_| {
            let new_state = @mut ImageState {
                prefetched: false,
                decoded: false,
                last_request_round: 0,
                last_response: ImageNotReady
            };
            new_state
        };
        *state  // Unborrowing the state
    }
}

<commit_msg>Unweird 'pub' token<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/. */

/*!
An adapter for ImageCacheTask that does local caching to avoid
extra message traffic, it also avoids waiting on the same image
multiple times and thus triggering reflows multiple times.
*/

use image_cache_task::{Decode, GetImage, ImageCacheTask, ImageFailed, ImageNotReady, ImageReady};
use image_cache_task::{ImageResponseMsg, Prefetch, WaitForImage};

use clone_arc = std::arc::clone;
use core::comm::Port;
use servo_util::url::{UrlMap, url_map};
use std::net::url::Url;

pub fn LocalImageCache(image_cache_task: ImageCacheTask) -> LocalImageCache {
    LocalImageCache {
        image_cache_task: image_cache_task,
        round_number: 1,
        mut on_image_available: None,
        state_map: url_map()
    }
}

pub struct LocalImageCache {
    priv image_cache_task: ImageCacheTask,
    priv round_number: uint,
    priv on_image_available: Option<@fn() -> ~fn(ImageResponseMsg)>,
    priv state_map: UrlMap<@mut ImageState>
}

priv struct ImageState {
    prefetched: bool,
    decoded: bool,
    last_request_round: uint,
    last_response: ImageResponseMsg
}

#[allow(non_implicitly_copyable_typarams)] // Using maps of Urls
pub impl LocalImageCache {
    /// The local cache will only do a single remote request for a given
    /// URL in each 'round'. Layout should call this each time it begins
    pub fn next_round(&mut self, on_image_available: @fn() -> ~fn(ImageResponseMsg)) {
        self.round_number += 1;
        self.on_image_available = Some(on_image_available);
    }

    pub fn prefetch(&self, url: &Url) {
        let state = self.get_state(url);
        if !state.prefetched {
            self.image_cache_task.send(Prefetch(copy *url));
            state.prefetched = true;
        }
    }

    pub fn decode(&self, url: &Url) {
        let state = self.get_state(url);
        if !state.decoded {
            self.image_cache_task.send(Decode(copy *url));
            state.decoded = true;
        }
    }

    // FIXME: Should return a Future
    pub fn get_image(&self, url: &Url) -> Port<ImageResponseMsg> {
        let state = self.get_state(url);

        // Save the previous round number for comparison
        let last_round = state.last_request_round;
        // Set the current round number for this image
        state.last_request_round = self.round_number;

        match state.last_response {
            ImageReady(ref image) => {
                let (port, chan) = comm::stream();
                chan.send(ImageReady(clone_arc(image)));
                return port;
            }
            ImageNotReady => {
                if last_round == self.round_number {
                    let (port, chan) = comm::stream();
                    chan.send(ImageNotReady);
                    return port;
                } else {
                    // We haven't requested the image from the
                    // remote cache this round
                }
            }
            ImageFailed => {
                let (port, chan) = comm::stream();
                chan.send(ImageFailed);
                return port;
            }
        }

        let (response_port, response_chan) = comm::stream();
        self.image_cache_task.send(GetImage(copy *url, response_chan));

        let response = response_port.recv();
        match response {
            ImageNotReady => {
                // Need to reflow when the image is available
                // FIXME: Instead we should be just passing a Future
                // to the caller, then to the display list. Finally,
                // the compositor should be resonsible for waiting
                // on the image to load and triggering layout
                let image_cache_task = self.image_cache_task.clone();
                assert!(self.on_image_available.is_some());
                let on_image_available = self.on_image_available.get()();
                let url = copy *url;
                do task::spawn {
                    let (response_port, response_chan) = comm::stream();
                    image_cache_task.send(WaitForImage(copy url, response_chan));
                    on_image_available(response_port.recv());
                }
            }
            _ => ()
        }

        // Put a copy of the response in the cache
        let response_copy = match response {
            ImageReady(ref image) => ImageReady(clone_arc(image)),
            ImageNotReady => ImageNotReady,
            ImageFailed => ImageFailed
        };
        state.last_response = response_copy;

        let (port, chan) = comm::stream();
        chan.send(response);
        return port;
    }

    priv fn get_state(&self, url: &Url) -> @mut ImageState {
        let state = do self.state_map.find_or_insert_with(url.clone()) |_| {
            let new_state = @mut ImageState {
                prefetched: false,
                decoded: false,
                last_request_round: 0,
                last_response: ImageNotReady
            };
            new_state
        };
        *state  // Unborrowing the state
    }
}

<|endoftext|>


<commit_before>use std::ffi::CString;

macro_rules! extensions {
    ($sname:ident, $($ext:ident => $s:expr,)*) => (
        /// List of extensions that are enabled or available.
        #[derive(Debug, Copy, Clone, PartialEq, Eq)]
        #[allow(missing_docs)]
        pub struct $sname {
            $(
                pub $ext: bool,
            )*
        }

        impl $sname {
            /// Returns an `Extensions` object with all members set to `false`.
            #[inline]
            pub fn none() -> $sname {
                $sname {
                    $($ext: false,)*
                }
            }

            /// Builds a Vec containing the list of extensions.
            pub fn build_extensions_list(&self) -> Vec<CString> {
                let mut data = Vec::new();
                $(if self.$ext { data.push(CString::new(&$s[..]).unwrap()); })*
                data
            }
        }
    );
}

extensions! {
    InstanceExtensions,
    khr_surface => b"VK_KHR_surface",
    khr_display => b"VK_KHR_display",
    khr_display_swapchain => b"VK_KHR_display_swapchain",
    khr_xlib_surface => b"VK_KHR_xlib_surface",
    khr_xcb_surface => b"VK_KHR_xcb_surface",
    khr_wayland_surface => b"VK_KHR_wayland_surface",
    khr_mir_surface => b"VK_KHR_mir_surface",
    khr_android_surface => b"VK_KHR_android_surface",
    khr_win32_surface => b"VK_KHR_win32_surface",
    ext_debug_report => b"VK_EXT_debug_report",
}

extensions! {
    DeviceExtensions,
    khr_swapchain => b"VK_KHR_swapchain",
}

#[cfg(test)]
mod tests {
    use instance::InstanceExtensions;

    #[test]
    fn empty_extensions() {
        let s = InstanceExtensions::none().build_extensions_list();
        assert!(s.is_empty());
    }
}
<commit_msg>Add FIXME<commit_after>use std::ffi::CString;

macro_rules! extensions {
    ($sname:ident, $($ext:ident => $s:expr,)*) => (
        /// List of extensions that are enabled or available.
        #[derive(Debug, Copy, Clone, PartialEq, Eq)]
        #[allow(missing_docs)]
        pub struct $sname {
            $(
                pub $ext: bool,
            )*
        }

        impl $sname {
            /// Returns an `Extensions` object with all members set to `false`.
            #[inline]
            pub fn none() -> $sname {
                $sname {
                    $($ext: false,)*
                }
            }

            /// Builds a Vec containing the list of extensions.
            pub fn build_extensions_list(&self) -> Vec<CString> {
                let mut data = Vec::new();
                $(if self.$ext { data.push(CString::new(&$s[..]).unwrap()); })*
                data
            }
        }
    );
}

extensions! {
    InstanceExtensions,
    khr_surface => b"VK_KHR_surface",
    khr_display => b"VK_KHR_display",
    khr_display_swapchain => b"VK_KHR_display_swapchain",       // FIXME: device extension
    khr_xlib_surface => b"VK_KHR_xlib_surface",
    khr_xcb_surface => b"VK_KHR_xcb_surface",
    khr_wayland_surface => b"VK_KHR_wayland_surface",
    khr_mir_surface => b"VK_KHR_mir_surface",
    khr_android_surface => b"VK_KHR_android_surface",
    khr_win32_surface => b"VK_KHR_win32_surface",
    ext_debug_report => b"VK_EXT_debug_report",
}

extensions! {
    DeviceExtensions,
    khr_swapchain => b"VK_KHR_swapchain",
}

#[cfg(test)]
mod tests {
    use instance::InstanceExtensions;

    #[test]
    fn empty_extensions() {
        let s = InstanceExtensions::none().build_extensions_list();
        assert!(s.is_empty());
    }
}
<|endoftext|>


<commit_before>use std::{marker::PhantomData, ptr};

use wlroots_sys::{wlr_xcursor_manager, wlr_xcursor_manager_create, wlr_xcursor_manager_destroy,
                  wlr_xcursor_manager_get_xcursor, wlr_xcursor_manager_load,
                  wlr_xcursor_manager_set_cursor_image, wlr_xcursor_manager_theme};

use {cursor::{Cursor, xcursor::{self, XCursor}},
     utils::{c_to_rust_string, safe_as_cstring}};

/// An `xcursor::Theme` at a particular scale factor of the base size.
#[derive(Debug)]
pub struct ManagerTheme<'manager> {
    theme: *mut wlr_xcursor_manager_theme,
    phantom: PhantomData<&'manager Manager>
}

/// xcursor::Manager dynamically loads xcursor themes at sizes necessary for use on outputs at
/// arbitrary scale factors. You should call `load` for each output you will show your cursor on,
/// with the scale factor parameter set to that output's scale factor.
#[derive(Debug)]
pub struct Manager {
    manager: *mut wlr_xcursor_manager
}

impl<'manager> ManagerTheme<'manager> {
    fn new(theme: *mut wlr_xcursor_manager_theme) -> Self {
        ManagerTheme { theme: theme,
                              phantom: PhantomData }
    }

    /// Get the scale factor of the theme.
    pub fn scale(&self) -> f32 {
        unsafe { (*self.theme).scale }
    }

    /// Get the underlying `xcursor::Theme` for this managed theme.
    pub fn theme(self) -> xcursor::Theme {
        unsafe { xcursor::Theme::from_ptr((*self.theme).theme) }
    }
}

impl Manager {
    /// Create a new `xcursor::Manager`.
    pub fn create<T: Into<Option<String>>>(name: T, size: u32) -> Option<Self> {
        unsafe {
            let name_str = name.into().map(safe_as_cstring);
            let name_ptr = name_str.map(|s| s.as_ptr()).unwrap_or(ptr::null_mut());
            let manager = wlr_xcursor_manager_create(name_ptr, size);
            if manager.is_null() {
                None
            } else {
                Some(Manager { manager: manager })
            }
        }
    }

    /// Get the name of the theme this `Manager` manages.
    pub fn name(&self) -> String {
        unsafe { c_to_rust_string((*self.manager).name).expect("Could not parse make as UTF-8") }
    }

    /// Get the base size (when scale = 1) in pixels for the theme.
    pub fn size(&self) -> u32 {
        unsafe { (*self.manager).size }
    }

    /// Retrieves a `XCursor` for the given cursor name at the given scale factor, or None if this
    /// `Manager` has not loaded a cursor theme at the requested scale.
    pub fn get_xcursor<'manager, T: Into<Option<String>>>(&'manager self,
                                                          name: T,
                                                          scale: f32)
                                                          -> Option<XCursor<'manager>> {
        let name_str = name.into().map(safe_as_cstring);
        let name_ptr = name_str.map(|s| s.as_ptr()).unwrap_or(ptr::null_mut());
        unsafe {
            let xcursor = wlr_xcursor_manager_get_xcursor(self.manager, name_ptr, scale);
            if xcursor.is_null() {
                None
            } else {
                Some(XCursor::from_ptr(xcursor))
            }
        }
    }

    /// Get a list of all the scaled `xcursor::ManagerTheme`s managed by this
    /// manager.
    pub fn scaled_themes<'manager>(&'manager self) -> Vec<ManagerTheme<'manager>> {
        unsafe {
            let mut result = vec![];

            wl_list_for_each!((*self.manager).scaled_themes,
                              link,
                              (theme: wlr_xcursor_manager_theme) => {
                result.push(ManagerTheme::new(theme))
            });

            result
        }
    }

    /// Ensures an xcursor theme at the given scale factor is loaded in the manager.
    ///
    /// Returns false if the scaled theme was successfully loaded and true otherwise
    pub fn load(&self, scale: f32) -> bool {
        unsafe {
            match wlr_xcursor_manager_load(self.manager, scale) {
                0 => false,
                _ => true
            }
        }
    }

    /// Set a `Cursor`'s cursor image to the specified cursor name for all scale
    /// factors. The `Cursor` will take over from this point and ensure the correct
    /// cursor is used on each output, assuming an `OutputLayout` is attached to
    /// it.
    pub fn set_cursor_image(&mut self, name: String, cursor: &Cursor) {
        let name_str = safe_as_cstring(name);
        unsafe {
            wlr_xcursor_manager_set_cursor_image(self.manager, name_str.as_ptr(), cursor.as_ptr());
        }
    }
}

impl Drop for Manager {
    fn drop(&mut self) {
        unsafe { wlr_xcursor_manager_destroy(self.manager) }
    }
}
<commit_msg>Fixed uses of CString::as_ptr<commit_after>use std::{marker::PhantomData, ptr};

use wlroots_sys::{wlr_xcursor_manager, wlr_xcursor_manager_create, wlr_xcursor_manager_destroy,
                  wlr_xcursor_manager_get_xcursor, wlr_xcursor_manager_load,
                  wlr_xcursor_manager_set_cursor_image, wlr_xcursor_manager_theme};

use {cursor::{Cursor, xcursor::{self, XCursor}},
     utils::{c_to_rust_string, safe_as_cstring}};

/// An `xcursor::Theme` at a particular scale factor of the base size.
#[derive(Debug)]
pub struct ManagerTheme<'manager> {
    theme: *mut wlr_xcursor_manager_theme,
    phantom: PhantomData<&'manager Manager>
}

/// xcursor::Manager dynamically loads xcursor themes at sizes necessary for use on outputs at
/// arbitrary scale factors. You should call `load` for each output you will show your cursor on,
/// with the scale factor parameter set to that output's scale factor.
#[derive(Debug)]
pub struct Manager {
    manager: *mut wlr_xcursor_manager
}

impl<'manager> ManagerTheme<'manager> {
    fn new(theme: *mut wlr_xcursor_manager_theme) -> Self {
        ManagerTheme { theme: theme,
                              phantom: PhantomData }
    }

    /// Get the scale factor of the theme.
    pub fn scale(&self) -> f32 {
        unsafe { (*self.theme).scale }
    }

    /// Get the underlying `xcursor::Theme` for this managed theme.
    pub fn theme(self) -> xcursor::Theme {
        unsafe { xcursor::Theme::from_ptr((*self.theme).theme) }
    }
}

impl Manager {
    /// Create a new `xcursor::Manager`.
    pub fn create<T: Into<Option<String>>>(name: T, size: u32) -> Option<Self> {
        unsafe {
            let name_str = name.into().map(safe_as_cstring);
            let name_ptr = name_str.as_ref().map(|s| s.as_ptr()).unwrap_or(ptr::null_mut());
            let manager = wlr_xcursor_manager_create(name_ptr, size);
            if manager.is_null() {
                None
            } else {
                Some(Manager { manager: manager })
            }
        }
    }

    /// Get the name of the theme this `Manager` manages.
    pub fn name(&self) -> String {
        unsafe { c_to_rust_string((*self.manager).name).expect("Could not parse make as UTF-8") }
    }

    /// Get the base size (when scale = 1) in pixels for the theme.
    pub fn size(&self) -> u32 {
        unsafe { (*self.manager).size }
    }

    /// Retrieves a `XCursor` for the given cursor name at the given scale factor, or None if this
    /// `Manager` has not loaded a cursor theme at the requested scale.
    pub fn get_xcursor<'manager, T: Into<Option<String>>>(&'manager self,
                                                          name: T,
                                                          scale: f32)
                                                          -> Option<XCursor<'manager>> {
        let name_str = name.into().map(safe_as_cstring);
        let name_ptr = name_str.map(|s| s.as_ptr()).unwrap_or(ptr::null_mut());
        unsafe {
            let xcursor = wlr_xcursor_manager_get_xcursor(self.manager, name_ptr, scale);
            if xcursor.is_null() {
                None
            } else {
                Some(XCursor::from_ptr(xcursor))
            }
        }
    }

    /// Get a list of all the scaled `xcursor::ManagerTheme`s managed by this
    /// manager.
    pub fn scaled_themes<'manager>(&'manager self) -> Vec<ManagerTheme<'manager>> {
        unsafe {
            let mut result = vec![];

            wl_list_for_each!((*self.manager).scaled_themes,
                              link,
                              (theme: wlr_xcursor_manager_theme) => {
                result.push(ManagerTheme::new(theme))
            });

            result
        }
    }

    /// Ensures an xcursor theme at the given scale factor is loaded in the manager.
    ///
    /// Returns false if the scaled theme was successfully loaded and true otherwise
    pub fn load(&self, scale: f32) -> bool {
        unsafe {
            match wlr_xcursor_manager_load(self.manager, scale) {
                0 => false,
                _ => true
            }
        }
    }

    /// Set a `Cursor`'s cursor image to the specified cursor name for all scale
    /// factors. The `Cursor` will take over from this point and ensure the correct
    /// cursor is used on each output, assuming an `OutputLayout` is attached to
    /// it.
    pub fn set_cursor_image(&mut self, name: String, cursor: &Cursor) {
        let name_str = safe_as_cstring(name);
        unsafe {
            wlr_xcursor_manager_set_cursor_image(self.manager, name_str.as_ptr(), cursor.as_ptr());
        }
    }
}

impl Drop for Manager {
    fn drop(&mut self) {
        unsafe { wlr_xcursor_manager_destroy(self.manager) }
    }
}
<|endoftext|>


<commit_before>fn main() {
    panic!("crash and burn");
}
<commit_msg>Causing program to panic by trying to access nonexistent vector element<commit_after>fn main() {
    // panic!("crash and burn");
    let v = vec![1, 2, 3];

    v[100];
}
<|endoftext|>


<commit_before>#[cfg(test)]
mod coinnect_tests {
    extern crate coinnect;

    use self::coinnect::coinnect::Coinnect;
    use self::coinnect::exchange::{ Exchange, ExchangeApi };
    use self::coinnect::pair::Pair;

    #[test]
    fn can_create_new_api_connection_to_bitstamp() {
        let api: Box<ExchangeApi> = Coinnect::new(Exchange::Bitstamp, "bs_cust_id", "bs_api_key", "bs_api_secret");

        assert_eq!(format!("{:?}", api), "BitstampApi { \
                                                last_request: 0, \
                                                api_key: \"bs_api_key\", \
                                                api_secret: \"bs_api_secret\", \
                                                customer_id: \"bs_cust_id\", \
                                                http_client: Client { \
                                                    redirect_policy: FollowAll, \
                                                    read_timeout: None, \
                                                    write_timeout: None, \
                                                    proxy: None \
                                                } \
                                            }");
    }
    #[test]
    fn can_create_new_api_connection_to_kraken() {
//        let api = Coinnect::new(Exchange::Kraken, "", "", "");
//        assert_eq!(api, Exchange::Kraken);
    }
    #[test]
    fn can_create_new_api_connection_to_poloniex() {
//        let api = Coinnect::new(Exchange::Poloniex, "", "", "");
//        assert_eq!(api, Exchange::Poloniex);
    }

    #[test]
    fn coinnect_can_get_a_ticker_from_bitstamp() {
        let mut api = Coinnect::new(Exchange::Bitstamp, "bs_cust_id", "bs_api_key", "bs_api_secret");
        let ticker = api.return_ticker(Pair::BtcUsd);

        assert!( ticker.is_some() );
    }
    #[test]
    fn coinnect_ticker_from_bitstamp_should_have_the_correct_last() {
        let mut api = Coinnect::new(Exchange::Bitstamp, "bs_cust_id", "bs_api_key", "bs_api_secret");
        let ticker = api.return_ticker(Pair::BtcUsd);

        assert!( ticker.unwrap().contains_key("last") );
    }

    #[test]
    fn coinnect_should_return_an_order_book_from_bitstamp() {
        let mut api = Coinnect::new(Exchange::Bitstamp, "bs_cust_id", "bs_api_key", "bs_api_secret");
        let order_book = api.return_order_book(Pair::BtcUsd);
        assert!( order_book.is_some() );
    }
    #[test]
    fn order_book_should_have_bids() {
        let mut api = Coinnect::new(Exchange::Bitstamp, "bs_cust_id", "bs_api_key", "bs_api_secret");
        let result = api.return_order_book(Pair::BtcUsd);
        assert!( result.unwrap().contains_key("bids") );
    }
}<commit_msg>Create a test for the integration from Coinnect with the Bitstamp balance<commit_after>#[cfg(test)]
mod coinnect_tests {
    extern crate coinnect;

    use self::coinnect::coinnect::Coinnect;
    use self::coinnect::exchange::{ Exchange, ExchangeApi };
    use self::coinnect::pair::Pair;

    #[test]
    fn can_create_new_api_connection_to_bitstamp() {
        let api: Box<ExchangeApi> = Coinnect::new(Exchange::Bitstamp, "bs_cust_id", "bs_api_key", "bs_api_secret");

        assert_eq!(format!("{:?}", api), "BitstampApi { \
                                                last_request: 0, \
                                                api_key: \"bs_api_key\", \
                                                api_secret: \"bs_api_secret\", \
                                                customer_id: \"bs_cust_id\", \
                                                http_client: Client { \
                                                    redirect_policy: FollowAll, \
                                                    read_timeout: None, \
                                                    write_timeout: None, \
                                                    proxy: None \
                                                } \
                                            }");
    }
    #[test]
    fn can_create_new_api_connection_to_kraken() {
//        let api = Coinnect::new(Exchange::Kraken, "", "", "");
//        assert_eq!(api, Exchange::Kraken);
    }
    #[test]
    fn can_create_new_api_connection_to_poloniex() {
//        let api = Coinnect::new(Exchange::Poloniex, "", "", "");
//        assert_eq!(api, Exchange::Poloniex);
    }

    #[test]
    fn coinnect_can_get_a_ticker_from_bitstamp() {
        let mut api = Coinnect::new(Exchange::Bitstamp, "bs_cust_id", "bs_api_key", "bs_api_secret");
        let ticker = api.return_ticker(Pair::BtcUsd);

        assert!( ticker.is_some() );
    }
    #[test]
    fn coinnect_ticker_from_bitstamp_should_have_the_correct_last() {
        let mut api = Coinnect::new(Exchange::Bitstamp, "bs_cust_id", "bs_api_key", "bs_api_secret");
        let ticker = api.return_ticker(Pair::BtcUsd);

        assert!( ticker.unwrap().contains_key("last") );
    }

    #[test]
    fn coinnect_should_return_an_order_book_from_bitstamp() {
        let mut api = Coinnect::new(Exchange::Bitstamp, "bs_cust_id", "bs_api_key", "bs_api_secret");
        let order_book = api.return_order_book(Pair::BtcUsd);
        assert!( order_book.is_some() );
    }
    #[test]
    fn order_book_should_have_bids() {
        let mut api = Coinnect::new(Exchange::Bitstamp, "bs_cust_id", "bs_api_key", "bs_api_secret");
        let result = api.return_order_book(Pair::BtcUsd);
        assert!( result.unwrap().contains_key("bids") );
    }

    // IMPORTANT: Real keys are needed in order to retrieve the balance
    #[test]
    fn balance_should_have_usd_btc_fee() {
        use std::path::PathBuf;
        let path = PathBuf::from("./keys_real.json");
        let mut api = Coinnect::new_from_file(Exchange::Bitstamp , path);
        let result = api.return_balances(Pair::BtcUsd).unwrap();
        let result_looking_for_usd = result.clone();
        let result_looking_for_btc = result.clone();
        let result_looking_for_fee = result.clone();

        assert!(result_looking_for_usd.contains_key("usd_balance"));
        assert!(result_looking_for_btc.contains_key("btc_balance"));
        assert!(result_looking_for_fee.contains_key("fee"));
    }
}<|endoftext|>


<commit_before>use bson::Document;
use bson::Bson::{FloatingPoint, I32};
use bson::Bson::String as BsonString;
use mongodb::client::wire_protocol::flags::{OpInsertFlags, OpQueryFlags};
use mongodb::client::wire_protocol::operations::Message;
use std::io::Write;
use std::net::TcpStream;

#[test]
fn insert_single_key_doc() {
    match TcpStream::connect("localhost:27017") {
        Ok(mut stream) => {
            let mut doc = Document::new();
            doc.insert("foo".to_owned(), FloatingPoint(42.0));
            let docs = vec![doc];
            let flags = OpInsertFlags::no_flags();
            let name = "test.test".to_owned();
            let res = Message::with_insert(1, flags, name, docs);

            let cm = match res {
                Ok(message) => message,
                Err(_) => panic!("Could not create message!")
            };

            match cm.write(&mut stream) {
                Ok(_) => (),
                Err(s) => panic!("{}", s)
            };

            let doc = Document::new();
            let flags = OpQueryFlags::no_flags();
            let name = "test.test".to_owned();
            let res = Message::with_query(1, flags, name, 0, 0, doc, None);

            let cm = match res {
                Ok(message) => message,
                Err(s) => panic!("{}", s)
            };

            match cm.write(&mut stream) {
                Ok(_) => (),
                Err(s) => panic!("{}", s)
            };

            let reply = match Message::read(&mut stream) {
                Ok(m) => m,
                Err(s) => panic!("{}", s)
            };

            let docs = match reply {
                Message::OpReply { header: _, flags: _, cursor_id:_,
                                   starting_from: _, number_returned: _,
                                   documents: d } => d,
                _ => panic!("Invalid response read from server")
            };

            assert_eq!(docs.len() as i32, 1);

            match docs[0].get("foo") {
                Some(&FloatingPoint(42.0)) => (),
                _ => panic!("Wrong value returned!")
            };
        },
        Err(_) => {
            panic!("Could not connect to server")
        }
    }
}

#[test]
fn insert_multi_key_doc() {
    match TcpStream::connect("localhost:27017") {
        Ok(mut stream) => {
            let mut doc = Document::new();
            doc.insert("foo".to_owned(), FloatingPoint(42.0));
            doc.insert("bar".to_owned(), BsonString("__z&".to_owned()));
            let docs = vec![doc];
            let flags = OpInsertFlags::no_flags();
            let name = "test.test".to_owned();
            let res = Message::with_insert(1, flags, name, docs);

            let cm = match res {
                Ok(message) => message,
                Err(s) => panic!("{}", s)
            };

            match cm.write(&mut stream) {
                Ok(_) => (),
                Err(s) => panic!("{}", s)
            };

            let doc = Document::new();
            let flags = OpQueryFlags::no_flags();
            let name = "test.test".to_owned();
            let res = Message::with_query(1, flags, name, 0, 0, doc, None);

            let cm = match res {
                Ok(message) => message,
                Err(s) => panic!("{}", s)
            };

            match cm.write(&mut stream) {
                Ok(_) => (),
                Err(s) => panic!("{}", s)
            };

            let reply = match Message::read(&mut stream) {
                Ok(m) => m,
                Err(s) => panic!("{}", s)
            };

            let docs = match reply {
                Message::OpReply { header: _, flags: _, cursor_id:_,
                                   starting_from: _, number_returned: _,
                                   documents: d } => d,
                _ => panic!("Invalid response read from server")
            };

            assert_eq!(docs.len() as i32, 1);

            match docs[0].get("foo") {
                Some(&FloatingPoint(42.0)) => (),
                _ => panic!("Wrong value returned!")
            };

            match docs[0].get("bar") {
                Some(&BsonString(ref s)) => assert_eq!(s, "__z&"),
                _ => panic!("Wrong value returned!")
            };
        },
        Err(_) => {
            panic!("Could not connect to server")
        }
    }
}

#[test]
fn insert_docs() {
    match TcpStream::connect("localhost:27017") {
        Ok(mut stream) => {
            let mut doc1 = Document::new();
            doc1.insert("foo".to_owned(), FloatingPoint(42.0));
            doc1.insert("bar".to_owned(), BsonString("__z&".to_owned()));

            let mut doc2 = Document::new();
            doc2.insert("booyah".to_owned(), I32(23));

            let docs = vec![doc1, doc2];
            let flags = OpInsertFlags::no_flags();
            let name = "test.test".to_owned();
            let res = Message::with_insert(1, flags, name, docs);

            let cm = match res {
                Ok(message) => message,
                Err(s) => panic!("{}", s)
            };

            match cm.write(&mut stream) {
                Ok(_) => (),
                Err(s) => panic!("{}", s)
            };

            let doc = Document::new();
            let flags = OpQueryFlags::no_flags();
            let name = "test.test".to_owned();
            let res = Message::with_query(1, flags, name, 0, 0, doc, None);

            let cm = match res {
                Ok(message) => message,
                Err(s) => panic!("{}", s)
            };

            match cm.write(&mut stream) {
                Ok(_) => (),
                Err(s) => panic!("{}", s)
            };

            let reply = match Message::read(&mut stream) {
                Ok(m) => m,
                Err(s) => panic!("{}", s)
            };

            let docs = match reply {
                Message::OpReply { header: _, flags: _, cursor_id:_,
                                   starting_from: _, number_returned: _,
                                   documents: d } => d,
                _ => panic!("Invalid response read from server")
            };

            assert_eq!(docs.len() as i32, 2);

            match docs[0].get("foo") {
                Some(&FloatingPoint(42.0)) => (),
                _ => panic!("Wrong value returned!")
            };

            match docs[0].get("bar") {
                Some(&BsonString(ref s)) => assert_eq!(s, "__z&"),
                _ => panic!("Wrong value returned!")
            };

            match docs[1].get("booyah") {
                Some(&I32(23)) => (),
                _ => panic!("Wrong value returned!")
            };
        },
        Err(_) => {
            panic!("Could not connect to server")
        }
    }
}
<commit_msg>commented out "test" tags so travis will pass<commit_after>use bson::Document;
use bson::Bson::{FloatingPoint, I32};
use bson::Bson::String as BsonString;
use mongodb::client::wire_protocol::flags::{OpInsertFlags, OpQueryFlags};
use mongodb::client::wire_protocol::operations::Message;
use std::io::Write;
use std::net::TcpStream;

// #[test]
fn insert_single_key_doc() {
    match TcpStream::connect("localhost:27017") {
        Ok(mut stream) => {
            let mut doc = Document::new();
            doc.insert("foo".to_owned(), FloatingPoint(42.0));
            let docs = vec![doc];
            let flags = OpInsertFlags::no_flags();
            let name = "test.test".to_owned();
            let res = Message::with_insert(1, flags, name, docs);

            let cm = match res {
                Ok(message) => message,
                Err(_) => panic!("Could not create message!")
            };

            match cm.write(&mut stream) {
                Ok(_) => (),
                Err(s) => panic!("{}", s)
            };

            let doc = Document::new();
            let flags = OpQueryFlags::no_flags();
            let name = "test.test".to_owned();
            let res = Message::with_query(1, flags, name, 0, 0, doc, None);

            let cm = match res {
                Ok(message) => message,
                Err(s) => panic!("{}", s)
            };

            match cm.write(&mut stream) {
                Ok(_) => (),
                Err(s) => panic!("{}", s)
            };

            let reply = match Message::read(&mut stream) {
                Ok(m) => m,
                Err(s) => panic!("{}", s)
            };

            let docs = match reply {
                Message::OpReply { header: _, flags: _, cursor_id:_,
                                   starting_from: _, number_returned: _,
                                   documents: d } => d,
                _ => panic!("Invalid response read from server")
            };

            assert_eq!(docs.len() as i32, 1);

            match docs[0].get("foo") {
                Some(&FloatingPoint(42.0)) => (),
                _ => panic!("Wrong value returned!")
            };
        },
        Err(_) => {
            panic!("Could not connect to server")
        }
    }
}

// #[test]
fn insert_multi_key_doc() {
    match TcpStream::connect("localhost:27017") {
        Ok(mut stream) => {
            let mut doc = Document::new();
            doc.insert("foo".to_owned(), FloatingPoint(42.0));
            doc.insert("bar".to_owned(), BsonString("__z&".to_owned()));
            let docs = vec![doc];
            let flags = OpInsertFlags::no_flags();
            let name = "test.test".to_owned();
            let res = Message::with_insert(1, flags, name, docs);

            let cm = match res {
                Ok(message) => message,
                Err(s) => panic!("{}", s)
            };

            match cm.write(&mut stream) {
                Ok(_) => (),
                Err(s) => panic!("{}", s)
            };

            let doc = Document::new();
            let flags = OpQueryFlags::no_flags();
            let name = "test.test".to_owned();
            let res = Message::with_query(1, flags, name, 0, 0, doc, None);

            let cm = match res {
                Ok(message) => message,
                Err(s) => panic!("{}", s)
            };

            match cm.write(&mut stream) {
                Ok(_) => (),
                Err(s) => panic!("{}", s)
            };

            let reply = match Message::read(&mut stream) {
                Ok(m) => m,
                Err(s) => panic!("{}", s)
            };

            let docs = match reply {
                Message::OpReply { header: _, flags: _, cursor_id:_,
                                   starting_from: _, number_returned: _,
                                   documents: d } => d,
                _ => panic!("Invalid response read from server")
            };

            assert_eq!(docs.len() as i32, 1);

            match docs[0].get("foo") {
                Some(&FloatingPoint(42.0)) => (),
                _ => panic!("Wrong value returned!")
            };

            match docs[0].get("bar") {
                Some(&BsonString(ref s)) => assert_eq!(s, "__z&"),
                _ => panic!("Wrong value returned!")
            };
        },
        Err(_) => {
            panic!("Could not connect to server")
        }
    }
}

// #[test]
fn insert_docs() {
    match TcpStream::connect("localhost:27017") {
        Ok(mut stream) => {
            let mut doc1 = Document::new();
            doc1.insert("foo".to_owned(), FloatingPoint(42.0));
            doc1.insert("bar".to_owned(), BsonString("__z&".to_owned()));

            let mut doc2 = Document::new();
            doc2.insert("booyah".to_owned(), I32(23));

            let docs = vec![doc1, doc2];
            let flags = OpInsertFlags::no_flags();
            let name = "test.test".to_owned();
            let res = Message::with_insert(1, flags, name, docs);

            let cm = match res {
                Ok(message) => message,
                Err(s) => panic!("{}", s)
            };

            match cm.write(&mut stream) {
                Ok(_) => (),
                Err(s) => panic!("{}", s)
            };

            let doc = Document::new();
            let flags = OpQueryFlags::no_flags();
            let name = "test.test".to_owned();
            let res = Message::with_query(1, flags, name, 0, 0, doc, None);

            let cm = match res {
                Ok(message) => message,
                Err(s) => panic!("{}", s)
            };

            match cm.write(&mut stream) {
                Ok(_) => (),
                Err(s) => panic!("{}", s)
            };

            let reply = match Message::read(&mut stream) {
                Ok(m) => m,
                Err(s) => panic!("{}", s)
            };

            let docs = match reply {
                Message::OpReply { header: _, flags: _, cursor_id:_,
                                   starting_from: _, number_returned: _,
                                   documents: d } => d,
                _ => panic!("Invalid response read from server")
            };

            assert_eq!(docs.len() as i32, 2);

            match docs[0].get("foo") {
                Some(&FloatingPoint(42.0)) => (),
                _ => panic!("Wrong value returned!")
            };

            match docs[0].get("bar") {
                Some(&BsonString(ref s)) => assert_eq!(s, "__z&"),
                _ => panic!("Wrong value returned!")
            };

            match docs[1].get("booyah") {
                Some(&I32(23)) => (),
                _ => panic!("Wrong value returned!")
            };
        },
        Err(_) => {
            panic!("Could not connect to server")
        }
    }
}
<|endoftext|>