<commit_before>#![cfg(target_os = "windows")]

extern crate user32;
extern crate kernel32;
extern crate winapi;
extern crate gdi32;

use Scale;
use Vsync;
use Key;

use std::ffi::CString;
use std::ptr;
use std::os::windows::ffi::OsStrExt;
use std::ffi::OsStr;
use std::mem;

use self::winapi::windef::HWND;
use self::winapi::windef::HDC;
use self::winapi::winuser::WS_OVERLAPPEDWINDOW;
use self::winapi::winuser::WNDCLASSW;
use self::winapi::wingdi::BITMAPINFOHEADER;
use self::winapi::wingdi::RGBQUAD;

static mut CLOSE_APP: bool = false;

// Wrap this so we can have a proper numbef of bmiColors to write in
#[repr(C)]
struct BitmapInfo {
    pub bmi_header: BITMAPINFOHEADER,
    pub bmi_colors: [RGBQUAD; 3],
}

fn update_key_state(window: &mut Window, wparam: u32, state: bool) {
    match wparam & 0x1ff {
        0x00B => window.keys[Key::Key0 as usize] = state,
        0x002 => window.keys[Key::Key1 as usize] = state,
        0x003 => window.keys[Key::Key2 as usize] = state,
        0x004 => window.keys[Key::Key3 as usize] = state,
        0x005 => window.keys[Key::Key4 as usize] = state,
        0x006 => window.keys[Key::Key5 as usize] = state,
        0x007 => window.keys[Key::Key6 as usize] = state,
        0x008 => window.keys[Key::Key7 as usize] = state,
        0x009 => window.keys[Key::Key8 as usize] = state,
        0x00A => window.keys[Key::Key9 as usize] = state,
        0x01E => window.keys[Key::A as usize] = state,
        0x030 => window.keys[Key::B as usize] = state,
        0x02E => window.keys[Key::C as usize] = state,
        0x020 => window.keys[Key::D as usize] = state,
        0x012 => window.keys[Key::E as usize] = state,
        0x021 => window.keys[Key::F as usize] = state,
        0x022 => window.keys[Key::G as usize] = state,
        0x023 => window.keys[Key::H as usize] = state,
        0x017 => window.keys[Key::I as usize] = state,
        0x024 => window.keys[Key::J as usize] = state,
        0x025 => window.keys[Key::K as usize] = state,
        0x026 => window.keys[Key::L as usize] = state,
        0x032 => window.keys[Key::M as usize] = state,
        0x031 => window.keys[Key::N as usize] = state,
        0x018 => window.keys[Key::O as usize] = state,
        0x019 => window.keys[Key::P as usize] = state,
        0x010 => window.keys[Key::Q as usize] = state,
        0x013 => window.keys[Key::R as usize] = state,
        0x01F => window.keys[Key::S as usize] = state,
        0x014 => window.keys[Key::T as usize] = state,
        0x016 => window.keys[Key::U as usize] = state,
        0x02F => window.keys[Key::V as usize] = state,
        0x011 => window.keys[Key::W as usize] = state,
        0x02D => window.keys[Key::X as usize] = state,
        0x015 => window.keys[Key::Y as usize] = state,
        0x02C => window.keys[Key::Z as usize] = state,
        0x03B => window.keys[Key::F1 as usize] = state,
        0x03C => window.keys[Key::F2 as usize] = state,
        0x03D => window.keys[Key::F3 as usize] = state,
        0x03E => window.keys[Key::F4 as usize] = state,
        0x03F => window.keys[Key::F5 as usize] = state,
        0x040 => window.keys[Key::F6 as usize] = state,
        0x041 => window.keys[Key::F7 as usize] = state,
        0x042 => window.keys[Key::F8 as usize] = state,
        0x043 => window.keys[Key::F9 as usize] = state,
        0x044 => window.keys[Key::F10 as usize] = state,
        0x057 => window.keys[Key::F11 as usize] = state,
        0x058 => window.keys[Key::F12 as usize] = state,
        0x150 => window.keys[Key::Down as usize] = state,
        0x14B => window.keys[Key::Left as usize] = state,
        0x14D => window.keys[Key::Right as usize] = state,
        0x148 => window.keys[Key::Up as usize] = state,
        0x028 => window.keys[Key::Apostrophe as usize] = state,
        0x02B => window.keys[Key::Backslash as usize] = state,
        0x033 => window.keys[Key::Comma as usize] = state,
        0x00D => window.keys[Key::Equal as usize] = state,
        0x01A => window.keys[Key::LeftBracket as usize] = state,
        0x00C => window.keys[Key::Minus as usize] = state,
        0x034 => window.keys[Key::Period as usize] = state,
        0x01B => window.keys[Key::RightBracket as usize] = state,
        0x027 => window.keys[Key::Semicolon as usize] = state,
        0x035 => window.keys[Key::Slash as usize] = state,
        0x00E => window.keys[Key::Backspace as usize] = state,
        0x153 => window.keys[Key::Delete as usize] = state,
        0x14F => window.keys[Key::End as usize] = state,
        0x01C => window.keys[Key::Enter as usize] = state,
        0x001 => window.keys[Key::Escape as usize] = state,
        0x147 => window.keys[Key::Home as usize] = state,
        0x152 => window.keys[Key::Insert as usize] = state,
        0x15D => window.keys[Key::Menu as usize] = state,
        0x151 => window.keys[Key::PageDown as usize] = state,
        0x149 => window.keys[Key::PageUp as usize] = state,
        0x045 => window.keys[Key::Pause as usize] = state,
        0x039 => window.keys[Key::Space as usize] = state,
        0x00F => window.keys[Key::Tab as usize] = state,
        0x03A => window.keys[Key::CapsLock as usize] = state,
        _ => (),
    }
}

unsafe extern "system" fn wnd_proc(window: winapi::HWND,
                                   msg: winapi::UINT,
                                   wparam: winapi::WPARAM,
                                   lparam: winapi::LPARAM)
                                   -> winapi::LRESULT {
    // This make sure we actually don't do anything before the user data has been setup for the
    // window

    let user_data = user32::GetWindowLongPtrW(window, winapi::winuser::GWLP_USERDATA);

    if user_data == 0 {
        return user32::DefWindowProcW(window, msg, wparam, lparam);
    }

    let mut wnd: &mut Window = mem::transmute(user_data);

    match msg {
        winapi::winuser::WM_KEYDOWN => {
            update_key_state(wnd, (lparam as u32) >> 16, true);
            if (wparam & 0x1ff) == 27 {
                CLOSE_APP = true;
            }
        }

        winapi::winuser::WM_KEYUP => {
            update_key_state(wnd, (lparam as u32) >> 16, false);
        }

        winapi::winuser::WM_PAINT => {
            let mut rect: winapi::RECT = mem::uninitialized();

            user32::GetClientRect(window, &mut rect);

            let mut bitmap_info: BitmapInfo = mem::zeroed();
            let width = rect.right - rect.left;
            let height = rect.bottom - rect.top;

            bitmap_info.bmi_header.biSize = mem::size_of::<BITMAPINFOHEADER>() as u32;
            bitmap_info.bmi_header.biPlanes = 1;
            bitmap_info.bmi_header.biBitCount = 32;
            bitmap_info.bmi_header.biCompression = winapi::wingdi::BI_BITFIELDS;
            bitmap_info.bmi_header.biWidth = width;
            bitmap_info.bmi_header.biHeight = -height;
            bitmap_info.bmi_colors[0].rgbRed = 0xff;
            bitmap_info.bmi_colors[1].rgbGreen = 0xff;
            bitmap_info.bmi_colors[2].rgbBlue = 0xff;

            gdi32::StretchDIBits(wnd.dc.unwrap(),
                                 0,
                                 0,
                                 width,
                                 height,
                                 0,
                                 0,
                                 width,
                                 height,
                                 mem::transmute(wnd.buffer.as_ptr()),
                                 mem::transmute(&bitmap_info),
                                 winapi::wingdi::DIB_RGB_COLORS,
                                 winapi::wingdi::SRCCOPY);

            user32::ValidateRect(window, ptr::null_mut());
        }

        _ => (),
    }

    return user32::DefWindowProcW(window, msg, wparam, lparam);
}

pub enum MinifbError {
    UnableToCreateWindow,
}

fn to_wstring(str: &str) -> *const u16 {
    let v: Vec<u16> = OsStr::new(str).encode_wide().chain(Some(0).into_iter()).collect();
    v.as_ptr()
}

pub struct Window {
    dc: Option<HDC>,
    window: Option<HWND>,
    keys: [bool; 512],
    buffer: Vec<u32>,
}

impl Window {
    fn open_window(name: &str, width: usize, height: usize, _: Scale, _: Vsync) -> HWND {
        unsafe {
            let class_name = to_wstring("minifb_window");
            let s = CString::new(name).unwrap();

            let class = WNDCLASSW {
                style: winapi::CS_HREDRAW | winapi::CS_VREDRAW | winapi::CS_OWNDC,
                lpfnWndProc: Some(wnd_proc),
                cbClsExtra: 0,
                cbWndExtra: 0,
                hInstance: kernel32::GetModuleHandleA(ptr::null()),
                hIcon: ptr::null_mut(),
                hCursor: ptr::null_mut(),
                hbrBackground: ptr::null_mut(),
                lpszMenuName: ptr::null(),
                lpszClassName: class_name,
            };

            user32::RegisterClassW(&class);

            let mut rect = winapi::RECT {
                left: 0,
                right: width as winapi::LONG,
                top: 0,
                bottom: height as winapi::LONG,
            };

            user32::AdjustWindowRect(&mut rect,
                                     winapi::WS_POPUP | winapi::WS_SYSMENU | winapi::WS_CAPTION,
                                     0);

            rect.right -= rect.left;
            rect.bottom -= rect.top;

            let handle = user32::CreateWindowExA(0,
                                                 "minifb_window".as_ptr() as *mut _,
                                                 s.as_ptr(),
                                                 winapi::WS_OVERLAPPEDWINDOW &
                                                 !winapi::WS_MAXIMIZEBOX &
                                                 !winapi::WS_THICKFRAME,
                                                 winapi::CW_USEDEFAULT,
                                                 winapi::CW_USEDEFAULT,
                                                 rect.right,
                                                 rect.bottom,
                                                 ptr::null_mut(),
                                                 ptr::null_mut(),
                                                 ptr::null_mut(),
                                                 ptr::null_mut());

            if !handle.is_null() {
                user32::ShowWindow(handle, winapi::SW_NORMAL);
            }

            return handle;
        }
    }

    pub fn new(name: &str,
               width: usize,
               height: usize,
               scale: Scale,
               vsync: Vsync)
               -> Result<Window, &str> {
        unsafe {
            let handle = Self::open_window(name, width, height, scale, vsync);

            if handle.is_null() {
                return Err("Unable to create Window");
            }

            let window = Window {
                dc: Some(user32::GetDC(handle)),
                window: Some(handle),
                keys: [false; 512],
                buffer: Vec::new(),
            };

            Ok(window)
        }
    }

    pub fn get_keys(&self) -> Vec<Key> {
        let mut index: u8 = 0;
        let mut keys: Vec<Key> = Vec::new();

        for i in self.keys.iter() {
            if *i {
                unsafe {
                    keys.push(mem::transmute(index));
                }
            }

            index += 1;
        }

        keys
    }

    pub fn update(&mut self, buffer: &[u32]) -> bool {
        unsafe {
            let mut msg = mem::uninitialized();
            let window = self.window.unwrap();

            // TODO: Optimize

            self.buffer = buffer.iter().cloned().collect();

            user32::SetWindowLongPtrW(window, winapi::winuser::GWLP_USERDATA, mem::transmute(self));
            user32::InvalidateRect(window, ptr::null_mut(), winapi::TRUE);

            while user32::PeekMessageW(&mut msg, window, 0, 0, winapi::winuser::PM_REMOVE) != 0 {
                user32::TranslateMessage(&mut msg);
                user32::DispatchMessageW(&mut msg);
            }
        }

        unsafe {
            return !CLOSE_APP;
        }
    }
}

impl Drop for Window {
    fn drop(&mut self) {
        unsafe {
            if self.dc.is_some() {
                user32::ReleaseDC(self.window.unwrap(), self.dc.unwrap());
            }

            if self.window.is_some() {
                user32::CloseWindow(self.window.unwrap());
            }
        }
    }
}
<commit_msg>Fixed overflow on windows<commit_after>#![cfg(target_os = "windows")]

extern crate user32;
extern crate kernel32;
extern crate winapi;
extern crate gdi32;

use Scale;
use Vsync;
use Key;

use std::ffi::CString;
use std::ptr;
use std::os::windows::ffi::OsStrExt;
use std::ffi::OsStr;
use std::mem;

use self::winapi::windef::HWND;
use self::winapi::windef::HDC;
use self::winapi::winuser::WS_OVERLAPPEDWINDOW;
use self::winapi::winuser::WNDCLASSW;
use self::winapi::wingdi::BITMAPINFOHEADER;
use self::winapi::wingdi::RGBQUAD;

static mut CLOSE_APP: bool = false;

// Wrap this so we can have a proper numbef of bmiColors to write in
#[repr(C)]
struct BitmapInfo {
    pub bmi_header: BITMAPINFOHEADER,
    pub bmi_colors: [RGBQUAD; 3],
}

fn update_key_state(window: &mut Window, wparam: u32, state: bool) {
    match wparam & 0x1ff {
        0x00B => window.keys[Key::Key0 as usize] = state,
        0x002 => window.keys[Key::Key1 as usize] = state,
        0x003 => window.keys[Key::Key2 as usize] = state,
        0x004 => window.keys[Key::Key3 as usize] = state,
        0x005 => window.keys[Key::Key4 as usize] = state,
        0x006 => window.keys[Key::Key5 as usize] = state,
        0x007 => window.keys[Key::Key6 as usize] = state,
        0x008 => window.keys[Key::Key7 as usize] = state,
        0x009 => window.keys[Key::Key8 as usize] = state,
        0x00A => window.keys[Key::Key9 as usize] = state,
        0x01E => window.keys[Key::A as usize] = state,
        0x030 => window.keys[Key::B as usize] = state,
        0x02E => window.keys[Key::C as usize] = state,
        0x020 => window.keys[Key::D as usize] = state,
        0x012 => window.keys[Key::E as usize] = state,
        0x021 => window.keys[Key::F as usize] = state,
        0x022 => window.keys[Key::G as usize] = state,
        0x023 => window.keys[Key::H as usize] = state,
        0x017 => window.keys[Key::I as usize] = state,
        0x024 => window.keys[Key::J as usize] = state,
        0x025 => window.keys[Key::K as usize] = state,
        0x026 => window.keys[Key::L as usize] = state,
        0x032 => window.keys[Key::M as usize] = state,
        0x031 => window.keys[Key::N as usize] = state,
        0x018 => window.keys[Key::O as usize] = state,
        0x019 => window.keys[Key::P as usize] = state,
        0x010 => window.keys[Key::Q as usize] = state,
        0x013 => window.keys[Key::R as usize] = state,
        0x01F => window.keys[Key::S as usize] = state,
        0x014 => window.keys[Key::T as usize] = state,
        0x016 => window.keys[Key::U as usize] = state,
        0x02F => window.keys[Key::V as usize] = state,
        0x011 => window.keys[Key::W as usize] = state,
        0x02D => window.keys[Key::X as usize] = state,
        0x015 => window.keys[Key::Y as usize] = state,
        0x02C => window.keys[Key::Z as usize] = state,
        0x03B => window.keys[Key::F1 as usize] = state,
        0x03C => window.keys[Key::F2 as usize] = state,
        0x03D => window.keys[Key::F3 as usize] = state,
        0x03E => window.keys[Key::F4 as usize] = state,
        0x03F => window.keys[Key::F5 as usize] = state,
        0x040 => window.keys[Key::F6 as usize] = state,
        0x041 => window.keys[Key::F7 as usize] = state,
        0x042 => window.keys[Key::F8 as usize] = state,
        0x043 => window.keys[Key::F9 as usize] = state,
        0x044 => window.keys[Key::F10 as usize] = state,
        0x057 => window.keys[Key::F11 as usize] = state,
        0x058 => window.keys[Key::F12 as usize] = state,
        0x150 => window.keys[Key::Down as usize] = state,
        0x14B => window.keys[Key::Left as usize] = state,
        0x14D => window.keys[Key::Right as usize] = state,
        0x148 => window.keys[Key::Up as usize] = state,
        0x028 => window.keys[Key::Apostrophe as usize] = state,
        0x02B => window.keys[Key::Backslash as usize] = state,
        0x033 => window.keys[Key::Comma as usize] = state,
        0x00D => window.keys[Key::Equal as usize] = state,
        0x01A => window.keys[Key::LeftBracket as usize] = state,
        0x00C => window.keys[Key::Minus as usize] = state,
        0x034 => window.keys[Key::Period as usize] = state,
        0x01B => window.keys[Key::RightBracket as usize] = state,
        0x027 => window.keys[Key::Semicolon as usize] = state,
        0x035 => window.keys[Key::Slash as usize] = state,
        0x00E => window.keys[Key::Backspace as usize] = state,
        0x153 => window.keys[Key::Delete as usize] = state,
        0x14F => window.keys[Key::End as usize] = state,
        0x01C => window.keys[Key::Enter as usize] = state,
        0x001 => window.keys[Key::Escape as usize] = state,
        0x147 => window.keys[Key::Home as usize] = state,
        0x152 => window.keys[Key::Insert as usize] = state,
        0x15D => window.keys[Key::Menu as usize] = state,
        0x151 => window.keys[Key::PageDown as usize] = state,
        0x149 => window.keys[Key::PageUp as usize] = state,
        0x045 => window.keys[Key::Pause as usize] = state,
        0x039 => window.keys[Key::Space as usize] = state,
        0x00F => window.keys[Key::Tab as usize] = state,
        0x03A => window.keys[Key::CapsLock as usize] = state,
        _ => (),
    }
}

unsafe extern "system" fn wnd_proc(window: winapi::HWND,
                                   msg: winapi::UINT,
                                   wparam: winapi::WPARAM,
                                   lparam: winapi::LPARAM)
                                   -> winapi::LRESULT {
    // This make sure we actually don't do anything before the user data has been setup for the
    // window

    let user_data = user32::GetWindowLongPtrW(window, winapi::winuser::GWLP_USERDATA);

    if user_data == 0 {
        return user32::DefWindowProcW(window, msg, wparam, lparam);
    }

    let mut wnd: &mut Window = mem::transmute(user_data);

    match msg {
        winapi::winuser::WM_KEYDOWN => {
            update_key_state(wnd, (lparam as u32) >> 16, true);
            if (wparam & 0x1ff) == 27 {
                CLOSE_APP = true;
            }
        }

        winapi::winuser::WM_KEYUP => {
            update_key_state(wnd, (lparam as u32) >> 16, false);
        }

        winapi::winuser::WM_PAINT => {
            let mut rect: winapi::RECT = mem::uninitialized();

            user32::GetClientRect(window, &mut rect);

            let mut bitmap_info: BitmapInfo = mem::zeroed();
            let width = rect.right - rect.left;
            let height = rect.bottom - rect.top;

            bitmap_info.bmi_header.biSize = mem::size_of::<BITMAPINFOHEADER>() as u32;
            bitmap_info.bmi_header.biPlanes = 1;
            bitmap_info.bmi_header.biBitCount = 32;
            bitmap_info.bmi_header.biCompression = winapi::wingdi::BI_BITFIELDS;
            bitmap_info.bmi_header.biWidth = width;
            bitmap_info.bmi_header.biHeight = -height;
            bitmap_info.bmi_colors[0].rgbRed = 0xff;
            bitmap_info.bmi_colors[1].rgbGreen = 0xff;
            bitmap_info.bmi_colors[2].rgbBlue = 0xff;

            gdi32::StretchDIBits(wnd.dc.unwrap(),
                                 0,
                                 0,
                                 width,
                                 height,
                                 0,
                                 0,
                                 width,
                                 height,
                                 mem::transmute(wnd.buffer.as_ptr()),
                                 mem::transmute(&bitmap_info),
                                 winapi::wingdi::DIB_RGB_COLORS,
                                 winapi::wingdi::SRCCOPY);

            user32::ValidateRect(window, ptr::null_mut());
        }

        _ => (),
    }

    return user32::DefWindowProcW(window, msg, wparam, lparam);
}

pub enum MinifbError {
    UnableToCreateWindow,
}

fn to_wstring(str: &str) -> *const u16 {
    let v: Vec<u16> = OsStr::new(str).encode_wide().chain(Some(0).into_iter()).collect();
    v.as_ptr()
}

pub struct Window {
    dc: Option<HDC>,
    window: Option<HWND>,
    keys: [bool; 512],
    buffer: Vec<u32>,
}

impl Window {
    fn open_window(name: &str, width: usize, height: usize, _: Scale, _: Vsync) -> HWND {
        unsafe {
            let class_name = to_wstring("minifb_window");
            let s = CString::new(name).unwrap();

            let class = WNDCLASSW {
                style: winapi::CS_HREDRAW | winapi::CS_VREDRAW | winapi::CS_OWNDC,
                lpfnWndProc: Some(wnd_proc),
                cbClsExtra: 0,
                cbWndExtra: 0,
                hInstance: kernel32::GetModuleHandleA(ptr::null()),
                hIcon: ptr::null_mut(),
                hCursor: ptr::null_mut(),
                hbrBackground: ptr::null_mut(),
                lpszMenuName: ptr::null(),
                lpszClassName: class_name,
            };

            user32::RegisterClassW(&class);

            let mut rect = winapi::RECT {
                left: 0,
                right: width as winapi::LONG,
                top: 0,
                bottom: height as winapi::LONG,
            };

            user32::AdjustWindowRect(&mut rect,
                                     winapi::WS_POPUP | winapi::WS_SYSMENU | winapi::WS_CAPTION,
                                     0);

            rect.right -= rect.left;
            rect.bottom -= rect.top;

            let handle = user32::CreateWindowExA(0,
                                                 "minifb_window".as_ptr() as *mut _,
                                                 s.as_ptr(),
                                                 winapi::WS_OVERLAPPEDWINDOW &
                                                 !winapi::WS_MAXIMIZEBOX &
                                                 !winapi::WS_THICKFRAME,
                                                 winapi::CW_USEDEFAULT,
                                                 winapi::CW_USEDEFAULT,
                                                 rect.right,
                                                 rect.bottom,
                                                 ptr::null_mut(),
                                                 ptr::null_mut(),
                                                 ptr::null_mut(),
                                                 ptr::null_mut());

            if !handle.is_null() {
                user32::ShowWindow(handle, winapi::SW_NORMAL);
            }

            return handle;
        }
    }

    pub fn new(name: &str,
               width: usize,
               height: usize,
               scale: Scale,
               vsync: Vsync)
               -> Result<Window, &str> {
        unsafe {
            let handle = Self::open_window(name, width, height, scale, vsync);

            if handle.is_null() {
                return Err("Unable to create Window");
            }

            let window = Window {
                dc: Some(user32::GetDC(handle)),
                window: Some(handle),
                keys: [false; 512],
                buffer: Vec::new(),
            };

            Ok(window)
        }
    }

    pub fn get_keys(&self) -> Vec<Key> {
        let mut index: u16 = 0;
        let mut keys: Vec<Key> = Vec::new();

        for i in self.keys.iter() {
            if *i {
                unsafe {
                    keys.push(mem::transmute(index as u8));
                }
            }

            index += 1;
        }

        keys
    }

    pub fn update(&mut self, buffer: &[u32]) -> bool {
        unsafe {
            let mut msg = mem::uninitialized();
            let window = self.window.unwrap();

            // TODO: Optimize

            self.buffer = buffer.iter().cloned().collect();

            user32::SetWindowLongPtrW(window, winapi::winuser::GWLP_USERDATA, mem::transmute(self));
            user32::InvalidateRect(window, ptr::null_mut(), winapi::TRUE);

            while user32::PeekMessageW(&mut msg, window, 0, 0, winapi::winuser::PM_REMOVE) != 0 {
                user32::TranslateMessage(&mut msg);
                user32::DispatchMessageW(&mut msg);
            }
        }

        unsafe {
            return !CLOSE_APP;
        }
    }
}

impl Drop for Window {
    fn drop(&mut self) {
        unsafe {
            if self.dc.is_some() {
                user32::ReleaseDC(self.window.unwrap(), self.dc.unwrap());
            }

            if self.window.is_some() {
                user32::CloseWindow(self.window.unwrap());
            }
        }
    }
}
<|endoftext|>


<commit_before>use super::super::*;
use sixty_four::*;

pub use v256::{
    f64x4, bool64fx4, u64x4, i64x4, bool64ix4,
    f32x8, bool32fx8, u32x8, i32x8, bool32ix8,
    u16x16, i16x16, bool16ix16,
    u8x32, i8x32, bool8ix32,
};

#[allow(dead_code)]
extern "platform-intrinsic" {
    fn x86_mm256_addsub_ps(x: f32x8, y: f32x8) -> f32x8;
    fn x86_mm256_addsub_pd(x: f64x4, y: f64x4) -> f64x4;
    fn x86_mm256_dp_ps(x: f32x8, y: f32x8, z: i32) -> f32x8;
    fn x86_mm256_hadd_ps(x: f32x8, y: f32x8) -> f32x8;
    fn x86_mm256_hadd_pd(x: f64x4, y: f64x4) -> f64x4;
    fn x86_mm256_hsub_ps(x: f32x8, y: f32x8) -> f32x8;
    fn x86_mm256_hsub_pd(x: f64x4, y: f64x4) -> f64x4;
    fn x86_mm256_max_ps(x: f32x8, y: f32x8) -> f32x8;
    fn x86_mm256_max_pd(x: f64x4, y: f64x4) -> f64x4;
    fn x86_mm256_min_ps(x: f32x8, y: f32x8) -> f32x8;
    fn x86_mm256_min_pd(x: f64x4, y: f64x4) -> f64x4;
    fn x86_mm256_movemask_ps(x: f32x8) -> i32;
    fn x86_mm256_movemask_pd(x: f64x4) -> i32;
    fn x86_mm_permutevar_ps(x: f32x4, y: i32x4) -> f32x4;
    fn x86_mm_permutevar_pd(x: f64x2, y: i64x2) -> f64x2;
    fn x86_mm256_permutevar_ps(x: f32x8, y: i32x8) -> f32x8;
    fn x86_mm256_permutevar_pd(x: f64x4, y: i64x4) -> f64x4;
    fn x86_mm256_rcp_ps(x: f32x8) -> f32x8;
    fn x86_mm256_rsqrt_ps(x: f32x8) -> f32x8;
    fn x86_mm256_sqrt_ps(x: f32x8) -> f32x8;
    fn x86_mm256_sqrt_pd(x: f64x4) -> f64x4;
    fn x86_mm_testc_ps(x: f32x4, y: f32x4) -> i32;
    fn x86_mm256_testc_ps(x: f32x8, y: f32x8) -> i32;
    fn x86_mm_testc_pd(x: f64x2, y: f64x2) -> i32;
    fn x86_mm256_testc_pd(x: f64x4, y: f64x4) -> i32;
    fn x86_mm256_testc_si256(x: u64x4, y: u64x4) -> i32;
    fn x86_mm_testnzc_ps(x: f32x4, y: f32x4) -> i32;
    fn x86_mm256_testnzc_ps(x: f32x8, y: f32x8) -> i32;
    fn x86_mm_testnzc_pd(x: f64x2, y: f64x2) -> i32;
    fn x86_mm256_testnzc_pd(x: f64x4, y: f64x4) -> i32;
    fn x86_mm256_testnzc_si256(x: u64x4, y: u64x4) -> i32;
    fn x86_mm_testz_ps(x: f32x4, y: f32x4) -> i32;
    fn x86_mm256_testz_ps(x: f32x8, y: f32x8) -> i32;
    fn x86_mm_testz_pd(x: f64x2, y: f64x2) -> i32;
    fn x86_mm256_testz_pd(x: f64x4, y: f64x4) -> i32;
    fn x86_mm256_testz_si256(x: u64x4, y: u64x4) -> i32;
}
<commit_msg>Expose most 128-bit AVX operations via traits.<commit_after>use super::super::*;
use sixty_four::*;

pub use v256::{
    f64x4, bool64fx4, u64x4, i64x4, bool64ix4,
    f32x8, bool32fx8, u32x8, i32x8, bool32ix8,
    u16x16, i16x16, bool16ix16,
    u8x32, i8x32, bool8ix32,
};

#[allow(dead_code)]
extern "platform-intrinsic" {
    fn x86_mm256_addsub_ps(x: f32x8, y: f32x8) -> f32x8;
    fn x86_mm256_addsub_pd(x: f64x4, y: f64x4) -> f64x4;
    fn x86_mm256_dp_ps(x: f32x8, y: f32x8, z: i32) -> f32x8;
    fn x86_mm256_hadd_ps(x: f32x8, y: f32x8) -> f32x8;
    fn x86_mm256_hadd_pd(x: f64x4, y: f64x4) -> f64x4;
    fn x86_mm256_hsub_ps(x: f32x8, y: f32x8) -> f32x8;
    fn x86_mm256_hsub_pd(x: f64x4, y: f64x4) -> f64x4;
    fn x86_mm256_max_ps(x: f32x8, y: f32x8) -> f32x8;
    fn x86_mm256_max_pd(x: f64x4, y: f64x4) -> f64x4;
    fn x86_mm256_min_ps(x: f32x8, y: f32x8) -> f32x8;
    fn x86_mm256_min_pd(x: f64x4, y: f64x4) -> f64x4;
    fn x86_mm256_movemask_ps(x: f32x8) -> i32;
    fn x86_mm256_movemask_pd(x: f64x4) -> i32;
    fn x86_mm_permutevar_ps(x: f32x4, y: i32x4) -> f32x4;
    fn x86_mm_permutevar_pd(x: f64x2, y: i64x2) -> f64x2;
    fn x86_mm256_permutevar_ps(x: f32x8, y: i32x8) -> f32x8;
    fn x86_mm256_permutevar_pd(x: f64x4, y: i64x4) -> f64x4;
    fn x86_mm256_rcp_ps(x: f32x8) -> f32x8;
    fn x86_mm256_rsqrt_ps(x: f32x8) -> f32x8;
    fn x86_mm256_sqrt_ps(x: f32x8) -> f32x8;
    fn x86_mm256_sqrt_pd(x: f64x4) -> f64x4;
    fn x86_mm_testc_ps(x: f32x4, y: f32x4) -> i32;
    fn x86_mm256_testc_ps(x: f32x8, y: f32x8) -> i32;
    fn x86_mm_testc_pd(x: f64x2, y: f64x2) -> i32;
    fn x86_mm256_testc_pd(x: f64x4, y: f64x4) -> i32;
    fn x86_mm256_testc_si256(x: u64x4, y: u64x4) -> i32;
    fn x86_mm_testnzc_ps(x: f32x4, y: f32x4) -> i32;
    fn x86_mm256_testnzc_ps(x: f32x8, y: f32x8) -> i32;
    fn x86_mm_testnzc_pd(x: f64x2, y: f64x2) -> i32;
    fn x86_mm256_testnzc_pd(x: f64x4, y: f64x4) -> i32;
    fn x86_mm256_testnzc_si256(x: u64x4, y: u64x4) -> i32;
    fn x86_mm_testz_ps(x: f32x4, y: f32x4) -> i32;
    fn x86_mm256_testz_ps(x: f32x8, y: f32x8) -> i32;
    fn x86_mm_testz_pd(x: f64x2, y: f64x2) -> i32;
    fn x86_mm256_testz_pd(x: f64x4, y: f64x4) -> i32;
    fn x86_mm256_testz_si256(x: u64x4, y: u64x4) -> i32;
}

// 128-bit vectors:

// 32 bit floats

pub trait AvxF32x4 {
    fn permutevar(self, other: i32x4) -> f32x4;
}
impl AvxF32x4 for f32x4 {
    fn permutevar(self, other: i32x4) -> f32x4 {
        unsafe { x86_mm_permutevar_ps(self, other) }
    }
}

pub trait AvxBool32fx4 {}
impl AvxBool32fx4 for bool32fx4 {}

// 64 bit floats

pub trait AvxF64x2 {
    fn permutevar(self, other: i64x2) -> f64x2;
}
impl AvxF64x2 for f64x2 {
    fn permutevar(self, other: i64x2) -> f64x2 {
        unsafe { x86_mm_permutevar_pd(self, other) }
    }
}

pub trait AvxBool64fx2 {}
impl AvxBool64fx2 for bool64fx2 {}

// 64 bit integers

pub trait AvxU64x2 {}
impl AvxU64x2 for u64x2 {}
pub trait AvxI64x2 {}
impl AvxI64x2 for i64x2 {}

pub trait AvxBool64ix2 {}
impl AvxBool64ix2 for bool64ix2 {}

// 32 bit integers

pub trait AvxU32x4 {}
impl AvxU32x4 for u32x4 {}
pub trait AvxI32x4 {}
impl AvxI32x4 for i32x4 {}

pub trait AvxBool32ix4 {}
impl AvxBool32ix4 for bool32ix4 {}

// 16 bit integers

pub trait AvxU16x8 {}
impl AvxU16x8 for u16x8 {}
pub trait AvxI16x8 {}
impl AvxI16x8 for i16x8 {}

pub trait AvxBool16ix8 {}
impl AvxBool16ix8 for bool16ix8 {}

// 8 bit integers

pub trait AvxU8x16 {}
impl AvxU8x16 for u8x16 {}
pub trait AvxI8x16 {}
impl AvxI8x16 for i8x16 {}

pub trait AvxBool8ix16 {}
impl AvxBool8ix16 for bool8ix16 {}
<|endoftext|>


<commit_before>use bytecode::{Chunk, Inst};
use std::collections::HashMap;
use syntax::{Expr, ExprF, Literal};

pub struct Codegen<'str> {
  next_str_id: usize,
  strs: HashMap<usize, &'str str>,

  pub chunks: Vec<Chunk>,
}

impl<'str> Codegen<'str> {
  pub fn new() -> Self {
    Codegen{
      next_str_id: 0,
      strs: HashMap::new(),

      chunks: vec![],
    }
  }

  pub fn strs(&self) -> &HashMap<usize, &'str str> {
    &self.strs
  }

  fn codegen_func_bytecode(
    &mut self,
    locals: usize,
    captures: usize,
    insts: Vec<Inst>,
  ) -> usize {
    self.chunks.push(Chunk{
      insts: insts,
      locals: locals,
      captures: captures,
    });
    self.chunks.len() - 1
  }

  pub fn codegen_func<'expr, T>(
    &mut self,
    env: &HashMap<&str, usize>,
    captures: usize,
    body: &Expr<'str, 'expr, T>,
  ) -> usize {
    let mut insts = vec![];
    self.codegen_expr(env, body, &mut insts);
    insts.push(Inst::Return);
    self.chunks.push(Chunk{
      insts: insts,
      locals: 1 + captures,
      captures: captures,
    });
    self.chunks.len() - 1
  }

  pub fn codegen_expr<'expr, T>(
    &mut self,
    env: &HashMap<&str, usize>,
    expr: &Expr<'str, 'expr, T>,
    insts: &mut Vec<Inst>,
  ) {
    match expr.1 {
      ExprF::Lit(ref lit) =>
        self.codegen_literal(lit, insts),
      ExprF::Var("stdout#") => // TODO: Move to feldspar::builtin
        insts.push(Inst::NewI32(1)),
      ExprF::Var("to_utf8#") => { // TODO: Move to feldspar::builtin
        let chunk_id = self.codegen_func_bytecode(1, 0, vec![
          Inst::GetLocal(0),
          Inst::Return,
        ]);
        insts.push(Inst::NewFunc(chunk_id));
      },
      ExprF::Var("write#") => { // TODO: Move to feldspar::builtin
        let action_chunk_id = self.codegen_func_bytecode(3, 2, vec![
          Inst::GetLocal(1), // handle
          Inst::GetLocal(2), // bytes
          Inst::Write,
          Inst::Return,
        ]);
        let curry2_chunk_id = self.codegen_func_bytecode(2, 1, vec![
          Inst::GetLocal(0), // bytes
          Inst::GetLocal(1), // handle
          Inst::NewFunc(action_chunk_id),
          Inst::Return,
        ]);
        let curry1_chunk_id = self.codegen_func_bytecode(1, 0, vec![
          Inst::GetLocal(0), // handle
          Inst::NewFunc(curry2_chunk_id),
          Inst::Return,
        ]);
        insts.push(Inst::NewFunc(curry1_chunk_id));
      },
      ExprF::Var(name) => {
        let offset = env[name];
        insts.push(Inst::GetLocal(offset));
      },
      ExprF::Abs(param, body) => {
        let mut body_env = HashMap::new();
        body_env.insert(param, 0);
        for (i, (k, &v)) in env.iter().enumerate() {
          body_env.insert(k, i + 1);
          insts.push(Inst::GetLocal(v));
        }
        let chunk_id = self.codegen_func(&body_env, env.len(), body);
        insts.push(Inst::NewFunc(chunk_id));
      },
      ExprF::App(callee, argument) => {
        self.codegen_expr(env, callee, insts);
        self.codegen_expr(env, argument, insts);
        insts.push(Inst::Call);
      },
      ExprF::Tup(_) => panic!("NYI"),
    }
  }

  pub fn codegen_literal(
    &mut self,
    lit: &Literal<'str>,
    insts: &mut Vec<Inst>,
  ) {
    match *lit {
      Literal::Bool(value) =>
        insts.push(Inst::NewI32(value as i32)),
      Literal::Str(value) => {
        let id = self.next_str_id;
        self.next_str_id += 1;
        self.strs.insert(id, value);
        insts.push(Inst::NewStr(id));
      },
      _ => panic!("codegen_literal: NYI"),
    }
  }
}
<commit_msg>Codegen tuple expressions<commit_after>use bytecode::{Chunk, Inst};
use std::collections::HashMap;
use syntax::{Expr, ExprF, Literal};

pub struct Codegen<'str> {
  next_str_id: usize,
  strs: HashMap<usize, &'str str>,

  pub chunks: Vec<Chunk>,
}

impl<'str> Codegen<'str> {
  pub fn new() -> Self {
    Codegen{
      next_str_id: 0,
      strs: HashMap::new(),

      chunks: vec![],
    }
  }

  pub fn strs(&self) -> &HashMap<usize, &'str str> {
    &self.strs
  }

  fn codegen_func_bytecode(
    &mut self,
    locals: usize,
    captures: usize,
    insts: Vec<Inst>,
  ) -> usize {
    self.chunks.push(Chunk{
      insts: insts,
      locals: locals,
      captures: captures,
    });
    self.chunks.len() - 1
  }

  pub fn codegen_func<'expr, T>(
    &mut self,
    env: &HashMap<&str, usize>,
    captures: usize,
    body: &Expr<'str, 'expr, T>,
  ) -> usize {
    let mut insts = vec![];
    self.codegen_expr(env, body, &mut insts);
    insts.push(Inst::Return);
    self.chunks.push(Chunk{
      insts: insts,
      locals: 1 + captures,
      captures: captures,
    });
    self.chunks.len() - 1
  }

  pub fn codegen_expr<'expr, T>(
    &mut self,
    env: &HashMap<&str, usize>,
    expr: &Expr<'str, 'expr, T>,
    insts: &mut Vec<Inst>,
  ) {
    match expr.1 {
      ExprF::Lit(ref lit) =>
        self.codegen_literal(lit, insts),
      ExprF::Var("stdout#") => // TODO: Move to feldspar::builtin
        insts.push(Inst::NewI32(1)),
      ExprF::Var("to_utf8#") => { // TODO: Move to feldspar::builtin
        let chunk_id = self.codegen_func_bytecode(1, 0, vec![
          Inst::GetLocal(0),
          Inst::Return,
        ]);
        insts.push(Inst::NewFunc(chunk_id));
      },
      ExprF::Var("write#") => { // TODO: Move to feldspar::builtin
        let action_chunk_id = self.codegen_func_bytecode(3, 2, vec![
          Inst::GetLocal(1), // handle
          Inst::GetLocal(2), // bytes
          Inst::Write,
          Inst::Return,
        ]);
        let curry2_chunk_id = self.codegen_func_bytecode(2, 1, vec![
          Inst::GetLocal(0), // bytes
          Inst::GetLocal(1), // handle
          Inst::NewFunc(action_chunk_id),
          Inst::Return,
        ]);
        let curry1_chunk_id = self.codegen_func_bytecode(1, 0, vec![
          Inst::GetLocal(0), // handle
          Inst::NewFunc(curry2_chunk_id),
          Inst::Return,
        ]);
        insts.push(Inst::NewFunc(curry1_chunk_id));
      },
      ExprF::Var(name) => {
        let offset = env[name];
        insts.push(Inst::GetLocal(offset));
      },
      ExprF::Abs(param, body) => {
        let mut body_env = HashMap::new();
        body_env.insert(param, 0);
        for (i, (k, &v)) in env.iter().enumerate() {
          body_env.insert(k, i + 1);
          insts.push(Inst::GetLocal(v));
        }
        let chunk_id = self.codegen_func(&body_env, env.len(), body);
        insts.push(Inst::NewFunc(chunk_id));
      },
      ExprF::App(callee, argument) => {
        self.codegen_expr(env, callee, insts);
        self.codegen_expr(env, argument, insts);
        insts.push(Inst::Call);
      },
      ExprF::Tup(ref elems) => {
        for elem in elems {
          self.codegen_expr(env, elem, insts);
        }
        insts.push(Inst::New(elems.len(), 0));
      },
    }
  }

  pub fn codegen_literal(
    &mut self,
    lit: &Literal<'str>,
    insts: &mut Vec<Inst>,
  ) {
    match *lit {
      Literal::Bool(value) =>
        insts.push(Inst::NewI32(value as i32)),
      Literal::Str(value) => {
        let id = self.next_str_id;
        self.next_str_id += 1;
        self.strs.insert(id, value);
        insts.push(Inst::NewStr(id));
      },
      _ => panic!("codegen_literal: NYI"),
    }
  }
}
<|endoftext|>


<commit_before>use std::fs;
use std::path::Path;

pub fn initialize() {
    println!("Initialize ...");

    let dir_name = ".keepha";
    if !dir_exists(dir_name) {
        match fs::create_dir(dir_name) {
            Ok(_)    => println!("  OK: Created \"{}\" directory.", dir_name),
            Err(why) => panic!("{:?}", why),
        }
    } else {
        println!("  OK: \"{}\" directory has already exist.", dir_name);
    }
}

fn dir_exists<P: AsRef<Path>>(path: P) -> bool {
    match fs::metadata(path) {
        Ok(m)    => m.is_dir(),
        Err(why) => {
            match why.raw_os_error() {
                Some(2) => false,
                _       => panic!("{:?}", why),
            }
        }
    }
}

pub fn set_params() {
    println!("set parameters");
}

pub fn sweep() {
    println!("sweep");
}

pub fn register_with_cron() {
    println!("register");
}

pub fn unregister_cron() {
    println!("unregister");
}

pub fn destroy() {
    println!("destroy");
}
<commit_msg>Swap "if" statements<commit_after>use std::fs;
use std::path::Path;

pub fn initialize() {
    println!("Initialize ...");

    let dir_name = ".keepha";
    if dir_exists(dir_name) {
        println!("  OK: \"{}\" directory has already exist.", dir_name);
    } else {
        match fs::create_dir(dir_name) {
            Ok(_)    => println!("  OK: Created \"{}\" directory.", dir_name),
            Err(why) => panic!("{:?}", why),
        }
    }
}

fn dir_exists<P: AsRef<Path>>(path: P) -> bool {
    match fs::metadata(path) {
        Ok(m)    => m.is_dir(),
        Err(why) => {
            match why.raw_os_error() {
                Some(2) => false,
                _       => panic!("{:?}", why),
            }
        }
    }
}

pub fn set_params() {
    println!("set parameters");
}

pub fn sweep() {
    println!("sweep");
}

pub fn register_with_cron() {
    println!("register");
}

pub fn unregister_cron() {
    println!("unregister");
}

pub fn destroy() {
    println!("destroy");
}
<|endoftext|>


<commit_before>use std::fs::File;
use std::io::{Read, Seek, Cursor};
use std::io::{SeekFrom, Error, ErrorKind};
use std::convert::AsMut;

extern crate uuid;
extern crate byteorder;
use self::byteorder::{LittleEndian, ReadBytesExt, BigEndian};
use self::uuid::Uuid;
#[derive(Debug)]
pub struct Header {
    pub signature: String, // EFI PART
    pub revision: u32, // 00 00 01 00
    pub header_size_le: u32, // little endian
    pub crc32: u32,
    pub reserved: u32, // must be 0
    pub current_lba: u64,
    pub backup_lba: u64,
    pub first_usable: u64,
    pub last_usable: u64,
    pub disk_guid: uuid::Uuid,
    pub start_lba: u64,
    pub num_parts: u32,
    pub part_size: u32, // usually 128
    pub crc32_parts: u32,
}

fn parse_uuid(rdr: &mut Cursor<&[u8]>) -> Result<Uuid, Error> {
    //let mut rdr = Cursor::new(bytes);
    let d1: u32 = rdr.read_u32::<LittleEndian>()?;
    let d2: u16 = rdr.read_u16::<LittleEndian>()?;
    let d3: u16 = rdr.read_u16::<LittleEndian>()?;

    match Uuid::from_fields(d1, d2, d3, &rdr.get_ref()[8..]) {
        Ok(uuid) => Ok(uuid),
        Err(_) => Err(Error::new(ErrorKind::Other, "Invalid Disk UUID?")),
    }
}

pub fn read_header2(path: &String) -> Result<Header, Error> {
    let mut file = File::open(path)?;
    let _ = file.seek(SeekFrom::Start(512));

    let mut hdr: [u8; 92] = [0; 92];

    let _ = file.read_exact(&mut hdr);
    let mut reader = Cursor::new(&hdr[..]);

    let sigstr = reader.read_u64::<LittleEndian>()?.to_string();

    if sigstr != "EFI PART" {
        return Err(Error::new(ErrorKind::Other, "Invalid GPT Signature."));
    };

    let h = Header {
        signature: sigstr.to_string(),
        revision: reader.read_u32::<LittleEndian>()?,
        header_size_le: reader.read_u32::<LittleEndian>()?,
        crc32: reader.read_u32::<LittleEndian>()?,
        reserved: reader.read_u32::<LittleEndian>()?,
        current_lba: reader.read_u64::<LittleEndian>()?,
        backup_lba: reader.read_u64::<LittleEndian>()?,
        first_usable: reader.read_u64::<LittleEndian>()?,
        last_usable: reader.read_u64::<LittleEndian>()?,
        disk_guid: parse_uuid(&mut reader)?,
        start_lba: reader.read_u64::<LittleEndian>()?,
        num_parts: reader.read_u32::<LittleEndian>()?,
        part_size: reader.read_u32::<LittleEndian>()?,
        crc32_parts: reader.read_u32::<LittleEndian>()?,
    };

    Ok(h)
}
/*
pub fn read_header(path:&String) -> Result<Header, Error>
{
	let mut file = File::open(path)?;
	let _ = file.seek(SeekFrom::Start(512))?;

	let mut signature: [u8;8] = [0;8];
	let _ = file.read_exact(&mut signature);
	let sigstr = String::from_utf8_lossy(&signature);
	if sigstr.as_ref() != "EFI PART" { return Err(Error::new(ErrorKind::Other,
	"Invalid GPT Signature")) };

	let mut revision: [u8; 4] = [0; 4];
	let mut header_size_le: [u8;4] = [0; 4];
	let mut crc32: [u8;4] = [0; 4];
	let mut reserved: [u8;4] = [0; 4];
	let mut current_lba: [u8;8] = [0; 8];
	let mut backup_lba: [u8;8] = [0; 8];
	let mut first_usable: [u8;8] = [0; 8];
	let mut last_usable: [u8;8] = [0; 8];
	let mut disk_guid: [u8;16] = [0; 16];
	let mut start_lba: [u8; 8] = [0; 8];
	let mut num_parts: [u8; 4] = [0; 4];
	let mut part_size: [u8; 4]= [0; 4];
	let mut crc32_parts: [u8; 4] = [0; 4];

	let _ = file.read_exact(&mut revision);
	let _ = file.read_exact(&mut header_size_le);
	let _ = file.read_exact(&mut crc32);
	let _ = file.read_exact(&mut reserved);
	let _ = file.read_exact(&mut current_lba);
	let _ = file.read_exact(&mut backup_lba);
	let _ = file.read_exact(&mut first_usable);
	let _ = file.read_exact(&mut last_usable);
	let _ = file.read_exact(&mut disk_guid);
	let _ = file.read_exact(&mut start_lba);
	let _ = file.read_exact(&mut num_parts);
	let _ = file.read_exact(&mut part_size);
	let _ = file.read_exact(&mut crc32_parts);

	return Ok(Header{
		signature: signature,
		revision: revision,
		header_size_le: header_size_le,
		crc32: crc32,
		reserved: reserved,
		current_lba: current_lba,
		backup_lba: backup_lba,
		first_usable: first_usable,
		last_usable: last_usable,
		disk_guid: parse_uuid(&disk_guid)?,
		start_lba: start_lba,
		num_parts: num_parts,
		part_size: part_size,
		crc32_parts: crc32_parts
	});
}
*/
<commit_msg>Remove unused import<commit_after>use std::fs::File;
use std::io::{Read, Seek, Cursor};
use std::io::{SeekFrom, Error, ErrorKind};

extern crate uuid;
extern crate byteorder;
use self::byteorder::{LittleEndian, ReadBytesExt, BigEndian};
use self::uuid::Uuid;

#[derive(Debug)]
pub struct Header {
    pub signature: String, // EFI PART
    pub revision: u32, // 00 00 01 00
    pub header_size_le: u32, // little endian
    pub crc32: u32,
    pub reserved: u32, // must be 0
    pub current_lba: u64,
    pub backup_lba: u64,
    pub first_usable: u64,
    pub last_usable: u64,
    pub disk_guid: uuid::Uuid,
    pub start_lba: u64,
    pub num_parts: u32,
    pub part_size: u32, // usually 128
    pub crc32_parts: u32,
}

fn parse_uuid(rdr: &mut Cursor<&[u8]>) -> Result<Uuid, Error> {
    //let mut rdr = Cursor::new(bytes);
    let d1: u32 = rdr.read_u32::<LittleEndian>()?;
    let d2: u16 = rdr.read_u16::<LittleEndian>()?;
    let d3: u16 = rdr.read_u16::<LittleEndian>()?;

    match Uuid::from_fields(d1, d2, d3, &rdr.get_ref()[8..]) {
        Ok(uuid) => Ok(uuid),
        Err(_) => Err(Error::new(ErrorKind::Other, "Invalid Disk UUID?")),
    }
}

pub fn read_header2(path: &String) -> Result<Header, Error> {
    let mut file = File::open(path)?;
    let _ = file.seek(SeekFrom::Start(512));

    let mut hdr: [u8; 92] = [0; 92];

    let _ = file.read_exact(&mut hdr);
    let mut reader = Cursor::new(&hdr[..]);

    let sigstr = reader.read_u64::<LittleEndian>()?.to_string();

    if sigstr != "EFI PART" {
        return Err(Error::new(ErrorKind::Other, "Invalid GPT Signature."));
    };

    let h = Header {
        signature: sigstr.to_string(),
        revision: reader.read_u32::<LittleEndian>()?,
        header_size_le: reader.read_u32::<LittleEndian>()?,
        crc32: reader.read_u32::<LittleEndian>()?,
        reserved: reader.read_u32::<LittleEndian>()?,
        current_lba: reader.read_u64::<LittleEndian>()?,
        backup_lba: reader.read_u64::<LittleEndian>()?,
        first_usable: reader.read_u64::<LittleEndian>()?,
        last_usable: reader.read_u64::<LittleEndian>()?,
        disk_guid: parse_uuid(&mut reader)?,
        start_lba: reader.read_u64::<LittleEndian>()?,
        num_parts: reader.read_u32::<LittleEndian>()?,
        part_size: reader.read_u32::<LittleEndian>()?,
        crc32_parts: reader.read_u32::<LittleEndian>()?,
    };

    Ok(h)
}
/*
pub fn read_header(path:&String) -> Result<Header, Error>
{
	let mut file = File::open(path)?;
	let _ = file.seek(SeekFrom::Start(512))?;

	let mut signature: [u8;8] = [0;8];
	let _ = file.read_exact(&mut signature);
	let sigstr = String::from_utf8_lossy(&signature);
	if sigstr.as_ref() != "EFI PART" { return Err(Error::new(ErrorKind::Other,
	"Invalid GPT Signature")) };

	let mut revision: [u8; 4] = [0; 4];
	let mut header_size_le: [u8;4] = [0; 4];
	let mut crc32: [u8;4] = [0; 4];
	let mut reserved: [u8;4] = [0; 4];
	let mut current_lba: [u8;8] = [0; 8];
	let mut backup_lba: [u8;8] = [0; 8];
	let mut first_usable: [u8;8] = [0; 8];
	let mut last_usable: [u8;8] = [0; 8];
	let mut disk_guid: [u8;16] = [0; 16];
	let mut start_lba: [u8; 8] = [0; 8];
	let mut num_parts: [u8; 4] = [0; 4];
	let mut part_size: [u8; 4]= [0; 4];
	let mut crc32_parts: [u8; 4] = [0; 4];

	let _ = file.read_exact(&mut revision);
	let _ = file.read_exact(&mut header_size_le);
	let _ = file.read_exact(&mut crc32);
	let _ = file.read_exact(&mut reserved);
	let _ = file.read_exact(&mut current_lba);
	let _ = file.read_exact(&mut backup_lba);
	let _ = file.read_exact(&mut first_usable);
	let _ = file.read_exact(&mut last_usable);
	let _ = file.read_exact(&mut disk_guid);
	let _ = file.read_exact(&mut start_lba);
	let _ = file.read_exact(&mut num_parts);
	let _ = file.read_exact(&mut part_size);
	let _ = file.read_exact(&mut crc32_parts);

	return Ok(Header{
		signature: signature,
		revision: revision,
		header_size_le: header_size_le,
		crc32: crc32,
		reserved: reserved,
		current_lba: current_lba,
		backup_lba: backup_lba,
		first_usable: first_usable,
		last_usable: last_usable,
		disk_guid: parse_uuid(&disk_guid)?,
		start_lba: start_lba,
		num_parts: num_parts,
		part_size: part_size,
		crc32_parts: crc32_parts
	});
}
*/
<|endoftext|>


<commit_before>#[macro_export]
macro_rules! approve {
    ($actual: ident) => {
        {
            use std::fs;
            use std::fs::{File, PathExt};
            use std::io::{Read, Write};
            use std::path::Path;
            use std::process::Command;

            let mut backtrace = vec![];
            ::std::rt::backtrace::write(&mut backtrace);
            let s = String::from_utf8(backtrace).unwrap();

            let method_name = s
                .as_str()
                .lines()
                .skip(2)
                .next()
                .unwrap()
                .split("-")
                .last()
                .unwrap()
                .split(":")
                .next()
                .unwrap()
                .trim_left_matches(" "); // FIXME: Handle all results/options

            let approvals_dirname = "approvals";
            let approvals_dir = Path::new(approvals_dirname);
            if !approvals_dir.exists() {
                match fs::create_dir(approvals_dir) {
                    Err(err) => panic!("Failed to create directory for approvals data: {:?}", err),
                    _ => {}
                }
            } else if !approvals_dir.is_dir() {
                panic!("Path for approvals data is not a directory")
            }

            let expected_filename = format!("{}/{}_expected.txt", approvals_dirname, method_name);
            let expected_path = Path::new(&expected_filename);
            let expected = match File::open(expected_path) {
                Ok(mut f) => {
                    let mut data = String::with_capacity($actual.len());
                    match f.read_to_string(&mut data) {
                        Err(err) => panic!("Failed to read expected data: {:?}", err),
                        _ => {}
                    }

                    data.trim_right_matches("\n").to_string() // Removing LF in the end
                },
                Err(open_err) => {
                    match File::create(expected_path) {
                        Ok(_) => String::new(),
                        Err(create_err) => panic!("Failed to open file '{:?}'.\nOpen error: {:?}.\nCreate error: {:?}", expected_path, open_err, create_err)
                    }
                }
            };

            if $actual != expected {
                let actual_filename = format!("{}/{}_actual.txt", approvals_dirname, method_name);
                let mut actual_file = match File::create(actual_filename.clone()) {
                    Ok(f) => f,
                    Err(err) => panic!("Failed to create temp file: {:?}", err)
                };

                match actual_file.write_all($actual.as_bytes()) {
                    Err(err) => panic!("Failed to write actual data for comparing: {:?}", err),
                    _ => {}
                }

                let diff_tool = "vimdiff"; // FIXME: Configure

                let output = match
                    Command::new(diff_tool).arg(::std::ffi::OsStr::new(actual_filename.as_str()))
                    .arg(expected_path.as_os_str())
                    .spawn() {
                    Ok(p) => p.wait_with_output(),
                    Err(err) => panic!("Failed to launch diff tool '{}': {:?}", diff_tool, err)
                };

                match output {
                    Err(err) => panic!("Failed to launch diff tool '{}': {:?}", diff_tool, err),
                    _ => {}
                }

                fs::remove_file(actual_filename);

                panic!("strings are not equal")
            }
        }
    }
}
<commit_msg>Trimming LF in the end for actual and expected<commit_after>#[macro_export]
macro_rules! approve {
    ($actual: ident) => {
        {
            use std::fs;
            use std::fs::{File, PathExt};
            use std::io::{Read, Write};
            use std::path::Path;
            use std::process::Command;

            let mut backtrace = vec![];
            ::std::rt::backtrace::write(&mut backtrace);
            let s = String::from_utf8(backtrace).unwrap();

            let method_name = s
                .as_str()
                .lines()
                .skip(2)
                .next()
                .unwrap()
                .split("-")
                .last()
                .unwrap()
                .split(":")
                .next()
                .unwrap()
                .trim_left_matches(" "); // FIXME: Handle all results/options

            let approvals_dirname = "approvals";
            let approvals_dir = Path::new(approvals_dirname);
            if !approvals_dir.exists() {
                match fs::create_dir(approvals_dir) {
                    Err(err) => panic!("Failed to create directory for approvals data: {:?}", err),
                    _ => {}
                }
            } else if !approvals_dir.is_dir() {
                panic!("Path for approvals data is not a directory")
            }

            let expected_filename = format!("{}/{}_expected.txt", approvals_dirname, method_name);
            let expected_path = Path::new(&expected_filename);
            let expected = match File::open(expected_path) {
                Ok(mut f) => {
                    let mut data = String::with_capacity($actual.len());
                    match f.read_to_string(&mut data) {
                        Err(err) => panic!("Failed to read expected data: {:?}", err),
                        _ => {}
                    }

                    data
                },
                Err(open_err) => {
                    match File::create(expected_path) {
                        Ok(_) => String::new(),
                        Err(create_err) => panic!("Failed to open file '{:?}'.\nOpen error: {:?}.\nCreate error: {:?}", expected_path, open_err, create_err)
                    }
                }
            };

            if $actual.trim_right_matches("\n") != expected.trim_right_matches("\n") {
                let actual_filename = format!("{}/{}_actual.txt", approvals_dirname, method_name);
                let mut actual_file = match File::create(actual_filename.clone()) {
                    Ok(f) => f,
                    Err(err) => panic!("Failed to create temp file: {:?}", err)
                };

                match actual_file.write_all($actual.as_bytes()) {
                    Err(err) => panic!("Failed to write actual data for comparing: {:?}", err),
                    _ => {}
                }

                let diff_tool = "vimdiff"; // FIXME: Configure

                let output = match
                    Command::new(diff_tool).arg(::std::ffi::OsStr::new(actual_filename.as_str()))
                    .arg(expected_path.as_os_str())
                    .spawn() {
                    Ok(p) => p.wait_with_output(),
                    Err(err) => panic!("Failed to launch diff tool '{}': {:?}", diff_tool, err)
                };

                match output {
                    Err(err) => panic!("Failed to launch diff tool '{}': {:?}", diff_tool, err),
                    _ => {}
                }

                fs::remove_file(actual_filename);

                panic!("strings are not equal")
            }
        }
    }
}
<|endoftext|>


<commit_before>
pub mod graph {
	use std::collections::HashMap;

	struct Graph {
		elements: i64,
		vertices: HashMap<i64, Box<Vertex>>,
	}

	impl Graph {
		fn new() -> Box<Graph> {
			let vertices: HashMap<i64, Box<Vertex>> = HashMap::new();
			Box::new(Graph{elements:0, vertices:vertices})
		}
		fn add_vertex(&mut self) -> VertexProxy {
			let new_id = self.elements + 1;
			self.elements += 1;
			let v = Vertex::new(new_id);

			let ptr: *const Box<Vertex> = &v as *const Box<Vertex>;

			self .vertices.insert(new_id, v);

			// return the proxy which knows it's own id
			VertexProxy{id:new_id, v: ptr}
		}
	}

	struct Vertex {
		id: i64,
		edges: *mut Vec<Edge>,
	}

	impl Vertex {
		fn new(id: i64) -> Box<Vertex> {

			let mut edges : Vec<Edge> = Vec::new();
			let edges_ptr :    *mut Vec<Edge> = &mut edges;
			let vertex = Vertex{id:id, edges:edges_ptr};
			let mut v = Box::new(vertex);
			return v;
		}

		fn query(self) {

		}
	}

	#[derive(Debug)]
	struct VertexProxy {
		id: i64,
		v: *const Box<Vertex>,
	}

	//let i: u32 = 1;
	//// explicit cast
	//let p_imm: *const u32 = &i as *const u32;
	//let mut m: u32 = 2;
	//// implicit coercion
	//let p_mut: *mut u32 = &mut m;
	//
	//unsafe {
	//let ref_imm: &u32 = &*p_imm;
	//let ref_mut: &mut u32 = &mut *p_mut;
	//}

	impl VertexProxy {
		fn add_edge(& self, to_vertex: &VertexProxy) {
			unsafe {
				let in_vertex =  &* self .v;
				let out_vertex = &*to_vertex.v;
			}
			// create the edge
			let e = Edge{from_vertex: self.v,
			to_vertex:   to_vertex.v};

		}
	}

	struct Edge {
		from_vertex: *const Box<Vertex>,
		to_vertex: *const Box<Vertex>
	}

	#[test]
	fn test_unsafe_vertex() {
		let mut g = Graph::new();
		let mut v1 = g.add_vertex();
		assert!(v1.id == 1);

		let mut v2 = g.add_vertex();
		assert!(v2.id == 2);
	}

	#[test]
	fn test_add_edge() {
		let mut g = Graph::new();
		let mut v1 = g.add_vertex();
		let mut v2 = g.add_vertex();
		v2.add_edge(&v2);

	}

}
<commit_msg>clearing warnings<commit_after>
pub mod graph {
	use std::collections::HashMap;

	pub struct Graph {
		elements: i64,
		vertices: HashMap<i64, Box<Vertex>>,
	}

	impl Graph {
		pub fn new() -> Box<Graph> {
			let vertices: HashMap<i64, Box<Vertex>> = HashMap::new();
			Box::new(Graph{elements:0, vertices:vertices})
		}

		pub fn add_vertex(&mut self) -> VertexProxy {
			let new_id = self.elements + 1;
			self.elements += 1;
			let v = Vertex::new(new_id);

			let ptr: *const Box<Vertex> = &v as *const Box<Vertex>;

			self .vertices.insert(new_id, v);

			// return the proxy which knows it's own id
			VertexProxy{id:new_id, v: ptr}
		}
	}

	struct Vertex {
		id: i64,
		edges: *mut Vec<Edge>,
	}

	impl Vertex {
		pub fn new(id: i64) -> Box<Vertex> {

			let mut edges : Vec<Edge> = Vec::new();
			let edges_ptr :    *mut Vec<Edge> = &mut edges;
			let vertex = Vertex{id:id, edges:edges_ptr};
			let mut v = Box::new(vertex);
			return v;
		}

	}

	#[derive(Debug)]
	pub struct VertexProxy {
		id: i64,
		v: *const Box<Vertex>,
	}

	//let i: u32 = 1;
	//// explicit cast
	//let p_imm: *const u32 = &i as *const u32;
	//let mut m: u32 = 2;
	//// implicit coercion
	//let p_mut: *mut u32 = &mut m;
	//
	//unsafe {
	//let ref_imm: &u32 = &*p_imm;
	//let ref_mut: &mut u32 = &mut *p_mut;
	//}

	impl VertexProxy {
		pub fn add_edge(& self, to_vertex: &VertexProxy) {
			unsafe {
				let in_vertex =  &* self .v;
				let out_vertex = &*to_vertex.v;
			}
			// create the edge
			let e = Edge{from_vertex: self.v,
			to_vertex:   to_vertex.v};

		}
		pub fn query(self) {

		}
	}

	struct Edge {
		from_vertex: *const Box<Vertex>,
		to_vertex: *const Box<Vertex>
	}

	#[test]
	fn test_unsafe_vertex() {
		let mut g = Graph::new();
		let v1 = g.add_vertex();
		assert!(v1.id == 1);

		let v2 = g.add_vertex();
		assert!(v2.id == 2);
	}

	#[test]
	fn test_add_edge() {
		let mut g = Graph::new();
		let v1 = g.add_vertex();
		let v2 = g.add_vertex();
		v2.add_edge(&v2);

	}

}
<|endoftext|>


<commit_before>// I have no idea what I'm doing with these attributes. Are we using
// semantic versioning? Some packages include their full github URL.
// Documentation for this stuff is extremely scarce.
#[crate_id = "quickcheck#0.1.0"];
#[crate_type = "lib"];
#[license = "UNLICENSE"];
#[doc(html_root_url = "http://burntsushi.net/rustdoc/quickcheck")];

//! This crate is a port of
//! [Haskell's QuickCheck](http://hackage.haskell.org/package/QuickCheck).

extern crate collections;

pub use arbitrary::{Arbitrary, Gen, StdGen, arbitrary, default_gen, gen};
pub use shrink::{ObjIter, Shrink};
pub use tester::{Testable, TestResult, Status};

mod arbitrary;
mod shrink;

mod tester {
    use std::fmt::Show;

    use super::{Arbitrary, Gen};

    fn arby<A: Arbitrary, G: Gen>(g: &mut G) -> A { Arbitrary::arbitrary(g) }

    #[deriving(Clone, Show)]
    pub struct TestResult {
        priv status: Status,
        priv arguments: ~[~str],
    }

    #[deriving(Clone, Show)]
    pub enum Status { Pass, Fail, Discard }

    impl TestResult {
        pub fn passed() -> ~TestResult { TestResult::from_bool(true) }
        pub fn failed() -> ~TestResult { TestResult::from_bool(false) }
        pub fn discard() -> ~TestResult {
            ~TestResult { status: Discard, arguments: ~[] }
        }
        pub fn from_bool(b: bool) -> ~TestResult {
            ~TestResult { status: if b { Pass } else { Fail }, arguments: ~[] }
        }
    }

    pub trait Testable {
        fn result<G: Gen>(&self, &mut G) -> ~TestResult;
    }

    impl Testable for bool {
        fn result<G: Gen>(&self, _: &mut G) -> ~TestResult {
            TestResult::from_bool(*self)
        }
    }

    impl Testable for ~TestResult {
        fn result<G: Gen>(&self, _: &mut G) -> ~TestResult { self.clone() }
    }

    // I should really figure out how to use macros. This is painful.
    // N.B. This isn't needed in Haskell because it's currying by default!
    // Perhaps there is a way to circumvent this in Rust too (without macros),
    // but I'm not sure.

    impl<A: Testable> Testable for 'static || -> A {
        fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
            (*self)().result(g)
        }
    }

    impl<A: Arbitrary + Show, B: Testable> Testable for 'static |A| -> B {
        fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
            let a: A = Arbitrary::arbitrary(g);
            let arg: ~str = a.to_str();
            let mut r: ~TestResult = (*self)(a).result(g);
            r.arguments.unshift(arg);
            r
        }
    }

    impl<A: Arbitrary + Show, B: Arbitrary + Show, C: Testable>
        Testable for 'static |A, B| -> C {
        fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
            let (a, b): (A, B) = (arby(g), arby(g));
            let (a_arg, b_arg) = (a.to_str(), b.to_str());
            let mut r: ~TestResult = (*self)(a, b).result(g);
            r.arguments.unshift(b_arg);
            r.arguments.unshift(a_arg);
            r
        }
    }

    impl<A: Arbitrary + Show,
         B: Arbitrary + Show,
         C: Arbitrary + Show,
         D: Testable>
        Testable for 'static |A, B, C| -> D {
        fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
            let (a, b, c): (A, B, C) = (arby(g), arby(g), arby(g));
            let (a_arg, b_arg, c_arg) = (a.to_str(), b.to_str(), c.to_str());
            let mut r: ~TestResult = (*self)(a, b, c).result(g);
            r.arguments.unshift(c_arg);
            r.arguments.unshift(b_arg);
            r.arguments.unshift(a_arg);
            r
        }
    }

    impl<A: Testable> Testable for fn() -> A {
        fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
            (*self)().result(g)
        }
    }

    impl<A: Arbitrary + Show, B: Testable> Testable for fn(A) -> B {
        fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
            let a: A = Arbitrary::arbitrary(g);
            let arg: ~str = a.to_str();
            let mut r: ~TestResult = (*self)(a).result(g);
            r.arguments.unshift(arg);
            r
        }
    }

    impl<A: Arbitrary + Show, B: Arbitrary + Show, C: Testable>
        Testable for fn(A, B) -> C {
        fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
            let (a, b): (A, B) = (arby(g), arby(g));
            let (a_arg, b_arg) = (a.to_str(), b.to_str());
            let mut r: ~TestResult = (*self)(a, b).result(g);
            r.arguments.unshift(b_arg);
            r.arguments.unshift(a_arg);
            r
        }
    }

    impl<A: Arbitrary + Show,
         B: Arbitrary + Show,
         C: Arbitrary + Show,
         D: Testable>
        Testable for fn(A, B, C) -> D {
        fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
            let (a, b, c): (A, B, C) = (arby(g), arby(g), arby(g));
            let (a_arg, b_arg, c_arg) = (a.to_str(), b.to_str(), c.to_str());
            let mut r: ~TestResult = (*self)(a, b, c).result(g);
            r.arguments.unshift(c_arg);
            r.arguments.unshift(b_arg);
            r.arguments.unshift(a_arg);
            r
        }
    }
}

#[cfg(test)]
mod test {
    use std::iter;

    use super::{Testable, TestResult, default_gen};

    #[test]
    fn reverse_reverse() {
        let g = &mut default_gen();
        fn revrev(xs: ~[uint]) -> bool {
            let rev = xs.clone().move_rev_iter().to_owned_vec()
                        .move_rev_iter().to_owned_vec();
            xs == rev
        }
        for _ in iter::range(0, 10) {
            debug!("{}", (revrev).result(g));
        }
    }

    #[test]
    fn reverse_single() {
        let g = &mut default_gen();
        fn rev_single(xs: ~[uint]) -> ~TestResult {
            if xs.len() != 1 {
                return TestResult::discard()
            }
            return TestResult::from_bool(
                xs.clone().move_rev_iter().to_owned_vec()
                ==
                xs.clone().move_rev_iter().to_owned_vec()
            )
        }
        for _ in iter::range(0, 10) {
            debug!("{}", (rev_single).result(g));
        }
    }

    #[test]
    fn reverse_app() {
        let g = &mut default_gen();
        fn revapp(xs: ~[uint], ys: ~[uint]) -> bool {
            let app = ::std::vec::append(xs.clone(), ys);
            let app_rev = app.move_rev_iter().to_owned_vec();

            let rxs = xs.clone().move_rev_iter().to_owned_vec();
            let rys = ys.clone().move_rev_iter().to_owned_vec();
            let rev_app = ::std::vec::append(rys, rxs);

            app_rev == rev_app
        }
        for _ in iter::range(0, 10) {
            debug!("{}", (revapp).result(g));
        }
    }
}
<commit_msg>Hide Status type.<commit_after>// I have no idea what I'm doing with these attributes. Are we using
// semantic versioning? Some packages include their full github URL.
// Documentation for this stuff is extremely scarce.
#[crate_id = "quickcheck#0.1.0"];
#[crate_type = "lib"];
#[license = "UNLICENSE"];
#[doc(html_root_url = "http://burntsushi.net/rustdoc/quickcheck")];

//! This crate is a port of
//! [Haskell's QuickCheck](http://hackage.haskell.org/package/QuickCheck).

extern crate collections;

pub use arbitrary::{Arbitrary, Gen, StdGen, arbitrary, default_gen, gen};
pub use shrink::{ObjIter, Shrink};
pub use tester::{Testable, TestResult};

mod arbitrary;
mod shrink;

mod tester {
    use std::fmt::Show;

    use super::{Arbitrary, Gen};

    fn arby<A: Arbitrary, G: Gen>(g: &mut G) -> A { Arbitrary::arbitrary(g) }

    #[deriving(Clone, Show)]
    pub struct TestResult {
        priv status: Status,
        priv arguments: ~[~str],
    }

    #[deriving(Clone, Show)]
    priv enum Status { Pass, Fail, Discard }

    impl TestResult {
        pub fn passed() -> ~TestResult { TestResult::from_bool(true) }
        pub fn failed() -> ~TestResult { TestResult::from_bool(false) }
        pub fn discard() -> ~TestResult {
            ~TestResult { status: Discard, arguments: ~[] }
        }
        pub fn from_bool(b: bool) -> ~TestResult {
            ~TestResult { status: if b { Pass } else { Fail }, arguments: ~[] }
        }
    }

    pub trait Testable {
        fn result<G: Gen>(&self, &mut G) -> ~TestResult;
    }

    impl Testable for bool {
        fn result<G: Gen>(&self, _: &mut G) -> ~TestResult {
            TestResult::from_bool(*self)
        }
    }

    impl Testable for ~TestResult {
        fn result<G: Gen>(&self, _: &mut G) -> ~TestResult { self.clone() }
    }

    // I should really figure out how to use macros. This is painful.
    // N.B. This isn't needed in Haskell because it's currying by default!
    // Perhaps there is a way to circumvent this in Rust too (without macros),
    // but I'm not sure.

    impl<A: Testable> Testable for 'static || -> A {
        fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
            (*self)().result(g)
        }
    }

    impl<A: Arbitrary + Show, B: Testable> Testable for 'static |A| -> B {
        fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
            let a: A = Arbitrary::arbitrary(g);
            let arg: ~str = a.to_str();
            let mut r: ~TestResult = (*self)(a).result(g);
            r.arguments.unshift(arg);
            r
        }
    }

    impl<A: Arbitrary + Show, B: Arbitrary + Show, C: Testable>
        Testable for 'static |A, B| -> C {
        fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
            let (a, b): (A, B) = (arby(g), arby(g));
            let (a_arg, b_arg) = (a.to_str(), b.to_str());
            let mut r: ~TestResult = (*self)(a, b).result(g);
            r.arguments.unshift(b_arg);
            r.arguments.unshift(a_arg);
            r
        }
    }

    impl<A: Arbitrary + Show,
         B: Arbitrary + Show,
         C: Arbitrary + Show,
         D: Testable>
        Testable for 'static |A, B, C| -> D {
        fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
            let (a, b, c): (A, B, C) = (arby(g), arby(g), arby(g));
            let (a_arg, b_arg, c_arg) = (a.to_str(), b.to_str(), c.to_str());
            let mut r: ~TestResult = (*self)(a, b, c).result(g);
            r.arguments.unshift(c_arg);
            r.arguments.unshift(b_arg);
            r.arguments.unshift(a_arg);
            r
        }
    }

    impl<A: Testable> Testable for fn() -> A {
        fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
            (*self)().result(g)
        }
    }

    impl<A: Arbitrary + Show, B: Testable> Testable for fn(A) -> B {
        fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
            let a: A = Arbitrary::arbitrary(g);
            let arg: ~str = a.to_str();
            let mut r: ~TestResult = (*self)(a).result(g);
            r.arguments.unshift(arg);
            r
        }
    }

    impl<A: Arbitrary + Show, B: Arbitrary + Show, C: Testable>
        Testable for fn(A, B) -> C {
        fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
            let (a, b): (A, B) = (arby(g), arby(g));
            let (a_arg, b_arg) = (a.to_str(), b.to_str());
            let mut r: ~TestResult = (*self)(a, b).result(g);
            r.arguments.unshift(b_arg);
            r.arguments.unshift(a_arg);
            r
        }
    }

    impl<A: Arbitrary + Show,
         B: Arbitrary + Show,
         C: Arbitrary + Show,
         D: Testable>
        Testable for fn(A, B, C) -> D {
        fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
            let (a, b, c): (A, B, C) = (arby(g), arby(g), arby(g));
            let (a_arg, b_arg, c_arg) = (a.to_str(), b.to_str(), c.to_str());
            let mut r: ~TestResult = (*self)(a, b, c).result(g);
            r.arguments.unshift(c_arg);
            r.arguments.unshift(b_arg);
            r.arguments.unshift(a_arg);
            r
        }
    }
}

#[cfg(test)]
mod test {
    use std::iter;

    use super::{Testable, TestResult, default_gen};

    #[test]
    fn reverse_reverse() {
        let g = &mut default_gen();
        fn revrev(xs: ~[uint]) -> bool {
            let rev = xs.clone().move_rev_iter().to_owned_vec()
                        .move_rev_iter().to_owned_vec();
            xs == rev
        }
        for _ in iter::range(0, 10) {
            debug!("{}", (revrev).result(g));
        }
    }

    #[test]
    fn reverse_single() {
        let g = &mut default_gen();
        fn rev_single(xs: ~[uint]) -> ~TestResult {
            if xs.len() != 1 {
                return TestResult::discard()
            }
            return TestResult::from_bool(
                xs.clone().move_rev_iter().to_owned_vec()
                ==
                xs.clone().move_rev_iter().to_owned_vec()
            )
        }
        for _ in iter::range(0, 10) {
            debug!("{}", (rev_single).result(g));
        }
    }

    #[test]
    fn reverse_app() {
        let g = &mut default_gen();
        fn revapp(xs: ~[uint], ys: ~[uint]) -> bool {
            let app = ::std::vec::append(xs.clone(), ys);
            let app_rev = app.move_rev_iter().to_owned_vec();

            let rxs = xs.clone().move_rev_iter().to_owned_vec();
            let rys = ys.clone().move_rev_iter().to_owned_vec();
            let rev_app = ::std::vec::append(rys, rxs);

            app_rev == rev_app
        }
        for _ in iter::range(0, 10) {
            debug!("{}", (revapp).result(g));
        }
    }
}
<|endoftext|>


<commit_before>//! Replaces the deprecated functionality of std::os::num_cpus.
#![cfg_attr(test, deny(warnings))]
#![deny(missing_docs)]

extern crate libc;

/// Returns the number of CPUs of the current machine.
#[inline]
pub fn get() -> usize {
    get_num_cpus()
}

#[cfg(windows)]
fn get_num_cpus() -> usize {
    unsafe {
        let mut sysinfo: libc::SYSTEM_INFO = ::std::mem::uninitialized();
        libc::GetSystemInfo(&mut sysinfo);
        sysinfo.dwNumberOfProcessors as usize
    }
}

#[cfg(
    any(
        target_os = "freebsd",
        target_os = "dragonfly",
        target_os = "bitrig",
        target_os = "openbsd"
    )
)]
fn get_num_cpus() -> usize {
    use libc::{c_int, c_uint};
    use libc::funcs::bsd44::sysctl;

    //XXX: uplift to libc?
    const CTL_HW: c_int = 6;
    const HW_AVAILCPU: c_int = 25;
    const HW_NCPU: c_int = 3;

    let mut cpus: c_uint = 0;
    let mut CPUS_SIZE = ::std::mem::size_of::<c_uint>();
    let mut mib: [c_int; 4] = [CTL_HW, HW_AVAILCPU, 0, 0];

    unsafe {
        sysctl(mib.as_mut_ptr(), 2, &mut cpus, &mut CPUS_SIZE, &mut (), 0);
    }

    if cpus < 1 {
        mib[1] = HW_NCPU;
        unsafe {
            sysctl(mib.as_mut_ptr(), 2, &mut cpus, &mut CPUS_SIZE, &mut (), 0);
        }
        if cpus < 1 {
            cpus = 1;
        }
    }

    cpus as usize
}

#[cfg(target_os= "linux")]
fn get_num_cpus() -> usize {
    //to-do: replace with libc::_SC_NPROCESSORS_ONLN once available
    unsafe {
        libc::sysconf(84) as usize
    }
}
#[cfg(target_os = "nacl")]
fn get_num_cpus() -> usize {
    //to-do: replace with libc::_SC_NPROCESSORS_ONLN once available
    unsafe {
        libc::sysconf(1) as usize
    }
}

#[cfg(
    any(
        target_os = "macos",
        target_os = "ios"
    )
)]
fn get_num_cpus() -> usize {
    //to-do: replace with libc::_SC_NPROCESSORS_ONLN once available
    unsafe {
        libc::sysconf(58) as usize
    }
}

#[test]
fn lower_bound() {
    assert!(get() > 0);
}

#[test]
fn upper_bound() {
    assert!(get() < 236_451);
}
<commit_msg>Add Android version of get_num_cpus<commit_after>//! Replaces the deprecated functionality of std::os::num_cpus.
#![cfg_attr(test, deny(warnings))]
#![deny(missing_docs)]

extern crate libc;

/// Returns the number of CPUs of the current machine.
#[inline]
pub fn get() -> usize {
    get_num_cpus()
}

#[cfg(windows)]
fn get_num_cpus() -> usize {
    unsafe {
        let mut sysinfo: libc::SYSTEM_INFO = ::std::mem::uninitialized();
        libc::GetSystemInfo(&mut sysinfo);
        sysinfo.dwNumberOfProcessors as usize
    }
}

#[cfg(
    any(
        target_os = "freebsd",
        target_os = "dragonfly",
        target_os = "bitrig",
        target_os = "openbsd"
    )
)]
fn get_num_cpus() -> usize {
    use libc::{c_int, c_uint};
    use libc::funcs::bsd44::sysctl;

    //XXX: uplift to libc?
    const CTL_HW: c_int = 6;
    const HW_AVAILCPU: c_int = 25;
    const HW_NCPU: c_int = 3;

    let mut cpus: c_uint = 0;
    let mut CPUS_SIZE = ::std::mem::size_of::<c_uint>();
    let mut mib: [c_int; 4] = [CTL_HW, HW_AVAILCPU, 0, 0];

    unsafe {
        sysctl(mib.as_mut_ptr(), 2, &mut cpus, &mut CPUS_SIZE, &mut (), 0);
    }

    if cpus < 1 {
        mib[1] = HW_NCPU;
        unsafe {
            sysctl(mib.as_mut_ptr(), 2, &mut cpus, &mut CPUS_SIZE, &mut (), 0);
        }
        if cpus < 1 {
            cpus = 1;
        }
    }

    cpus as usize
}

#[cfg(target_os= "linux")]
fn get_num_cpus() -> usize {
    //to-do: replace with libc::_SC_NPROCESSORS_ONLN once available
    unsafe {
        libc::sysconf(84) as usize
    }
}

#[cfg(target_os= "android")]
fn get_num_cpus() -> usize {
    //to-do: replace with libc::_SC_NPROCESSORS_ONLN once available
    unsafe {
        libc::sysconf(97) as usize
    }
}

#[cfg(target_os = "nacl")]
fn get_num_cpus() -> usize {
    //to-do: replace with libc::_SC_NPROCESSORS_ONLN once available
    unsafe {
        libc::sysconf(1) as usize
    }
}

#[cfg(
    any(
        target_os = "macos",
        target_os = "ios"
    )
)]
fn get_num_cpus() -> usize {
    //to-do: replace with libc::_SC_NPROCESSORS_ONLN once available
    unsafe {
        libc::sysconf(58) as usize
    }
}

#[test]
fn lower_bound() {
    assert!(get() > 0);
}

#[test]
fn upper_bound() {
    assert!(get() < 236_451);
}
<|endoftext|>


<commit_before>
pub fn xor(source: &[u8], key: &[u8]) -> Vec<u8> {
    if source.len() == 0 {
        return Vec::new();
    }
    if key.len() == 0 {
        return source.to_vec();
    }
    let key_iter = InfiniteByteIterator::new(key);
    source.iter().zip(key_iter).map(|(&a, b)| a ^ b).collect()
}

struct InfiniteByteIterator {
    bytes: Vec<u8>,
    index: uint
}

impl InfiniteByteIterator {
    pub fn new(bytes: &[u8]) -> InfiniteByteIterator {
        InfiniteByteIterator {
            bytes: bytes.to_vec(),
            index: 0
        }
    }
}

impl Iterator<u8> for InfiniteByteIterator {
    fn next(&mut self) -> Option<u8> {
        let byte = self.bytes[self.index];
        self.index = next_index(self.index, self.bytes.len());
        Some(byte)
    }
}

fn next_index(current: uint, count: uint) -> uint {
    let index = current + 1;
    if index < count {
        index
    } else {
        0
    }
}

#[cfg(test)]
mod test {

    use super::xor;

    #[test]
    fn test_len() {
        let source = [0, 1, 2, 3];
        let key = [34, 52];
        assert!(xor(source, key).len() == source.len());
    }

    #[test]
    fn test_result() {
        let source = [0, 1, 2, 3];
        let key = [34, 52];
        assert!(xor(source, key) == vec![34, 53, 32, 55]);
    }

    #[test]
    fn test_with_empty_key() {
        let source = [0, 1, 2, 3];
        let key = [];
        assert!(xor(source, key) == vec![0, 1, 2, 3]);
    }

    #[test]
    fn test_with_empty_source() {
        let source = [];
        let key = [45, 32, 56];
        assert!(xor(source, key) == vec![]);
    }
}
<commit_msg>Removed unneeded test.<commit_after>
pub fn xor(source: &[u8], key: &[u8]) -> Vec<u8> {
    if source.len() == 0 {
        return Vec::new();
    }
    if key.len() == 0 {
        return source.to_vec();
    }
    let key_iter = InfiniteByteIterator::new(key);
    source.iter().zip(key_iter).map(|(&a, b)| a ^ b).collect()
}

struct InfiniteByteIterator {
    bytes: Vec<u8>,
    index: uint
}

impl InfiniteByteIterator {
    pub fn new(bytes: &[u8]) -> InfiniteByteIterator {
        InfiniteByteIterator {
            bytes: bytes.to_vec(),
            index: 0
        }
    }
}

impl Iterator<u8> for InfiniteByteIterator {
    fn next(&mut self) -> Option<u8> {
        let byte = self.bytes[self.index];
        self.index = next_index(self.index, self.bytes.len());
        Some(byte)
    }
}

fn next_index(current: uint, count: uint) -> uint {
    let index = current + 1;
    if index < count {
        index
    } else {
        0
    }
}

#[cfg(test)]
mod test {

    use super::xor;

    #[test]
    fn test_result() {
        let source = [0, 1, 2, 3];
        let key = [34, 52];
        assert!(xor(source, key) == vec![34, 53, 32, 55]);
    }

    #[test]
    fn test_with_empty_key() {
        let source = [0, 1, 2, 3];
        let key = [];
        assert!(xor(source, key) == vec![0, 1, 2, 3]);
    }

    #[test]
    fn test_with_empty_source() {
        let source = [];
        let key = [45, 32, 56];
        assert!(xor(source, key) == vec![]);
    }
}
<|endoftext|>


<commit_before>//! **cobalt** is a networking library which provides [virtual connections
//! over UDP](http://gafferongames.com/networking-for-game-programmers/udp-vs-tcp/)
//! along with a messaging layer for sending both unreliable, reliable as well
//! as ordered messages.
//!
//! It is primarily designed to be used as the basis for real-time, latency
//! bound, multi client systems.
//!
//! The library provides the underlying architecture required for handling and
//! maintaining virtual connections over UDP sockets and takes care of sending
//! reliable, raw messages over the established client-server connections with
//! minimal overhead.
//!
//! cobalt is also fully configurable and can be plugged in a variety of ways,
//! so that library users have the largest possible degree of control over
//! the behavior of their connections.
//!
//! ## Getting started
//!
//! When working with **cobalt** the most important part is implementing the so
//! called handlers. A `Handler` is a trait which acts as a event proxy for
//! both server and client events that are emitted from the underlying tick
//! loop.
//!
//! Below follows a very basic example implementation of a custom game server.
//!
//! ```
//! use std::collections::HashMap;
//! use cobalt::{Config, Connection, ConnectionID, Handler, Server};
//!
//! struct GameServer;
//! impl Handler<Server> for GameServer {
//!
//!     fn bind(&mut self, server: &mut Server) {
//!         // Since this is a runnable doc, we'll just exit right away
//!         server.shutdown();
//!     }
//!
//!     fn tick_connections(
//!         &mut self, _: &mut Server,
//!         connections: &mut HashMap<ConnectionID, Connection>
//!     ) {
//!
//!         for (_, conn) in connections.iter_mut() {
//!             // Receive player input
//!         }
//!
//!         // Advance game state
//!
//!         for (_, conn) in connections.iter_mut() {
//!             // Send state to players
//!         }
//!
//!     }
//!
//!     fn shutdown(&mut self, _: &mut Server) {
//!         // Logging and things
//!     }
//!
//!     fn connection(&mut self, _: &mut Server, _: &mut Connection) {
//!         // Create Player, send MOTD etc.
//!     }
//!
//!     fn connection_lost(&mut self, _: &mut Server, _: &mut Connection) {
//!         // Remove Player
//!     }
//!
//! }
//!
//! let mut handler = GameServer;
//! let mut server = Server::new(Config::default());
//! server.bind(&mut handler, "127.0.0.1:7156").unwrap();
//! ```
//!
//! And the client version would look almost identical except for a few methods
//! having different names.
//!
//! ```
//! use std::collections::HashMap;
//! use cobalt::{Config, Connection, Handler, Client};
//!
//! struct GameClient;
//! impl Handler<Client> for GameClient {
//!
//!     fn connect(&mut self, client: &mut Client) {
//!         // Since this is a runnable doc, we'll just exit right away
//!         client.close();
//!     }
//!
//!     fn tick_connection(&mut self, _: &mut Client, conn: &mut Connection) {
//!
//!         for msg in conn.received() {
//!             // Receive state from server
//!         }
//!
//!         // Advance game state
//!
//!         // Send input to server
//!
//!     }
//!
//!     fn close(&mut self, _: &mut Client) {
//!         // Exit game
//!     }
//!
//!     fn connection(&mut self, _: &mut Client, _: &mut Connection) {
//!         // Request map list and settings from server
//!     }
//!
//!     fn connection_failed(&mut self, client: &mut Client, _: &mut Connection) {
//!         // Failed to connect to the server
//!     }
//!
//!     fn connection_lost(&mut self, client: &mut Client, _: &mut Connection) {
//!         // Inform the user
//!     }
//!
//! }
//!
//! let mut handler = GameClient;
//! let mut client = Client::new(Config::default());
//! client.connect(&mut handler, "127.0.0.1:7156").unwrap();
//! ```
#![deny(
    missing_docs,
    missing_debug_implementations, missing_copy_implementations,
    trivial_casts, trivial_numeric_casts,
    unsafe_code,
    unstable_features,
    unused_import_braces, unused_qualifications
)]
mod client;
mod server;

mod shared {
    pub mod binary_rate_limiter;
    pub mod config;
    pub mod connection;
    pub mod message_queue;
    pub mod udp_socket;
    pub mod stats;
}

mod traits {
    pub mod handler;
    pub mod rate_limiter;
    pub mod socket;
}

#[doc(inline)]
pub use shared::config::Config;

#[doc(inline)]
pub use shared::connection::{Connection, ConnectionID, ConnectionState};

#[doc(inline)]
pub use shared::message_queue::MessageKind;

#[doc(inline)]
pub use shared::binary_rate_limiter::BinaryRateLimiter;

#[doc(inline)]
pub use shared::udp_socket::UdpSocket;

#[doc(inline)]
pub use shared::stats::Stats;

#[doc(inline)]
pub use traits::handler::Handler;

#[doc(inline)]
pub use traits::rate_limiter::RateLimiter;

#[doc(inline)]
pub use traits::socket::Socket;

#[doc(inline)]
pub use client::Client;

#[doc(inline)]
pub use client::ClientState;

#[doc(inline)]
pub use server::Server;

#[cfg(test)]
mod tests {
    mod client;
    mod connection;
    mod message_queue;
    mod server;
}

<commit_msg>Add initial top level documentation on synchronized client apis.<commit_after>//! **cobalt** is a networking library which provides [virtual connections
//! over UDP](http://gafferongames.com/networking-for-game-programmers/udp-vs-tcp/)
//! along with a messaging layer for sending both unreliable, reliable as well
//! as ordered messages.
//!
//! It is primarily designed to be used as the basis for real-time, latency
//! bound, multi client systems.
//!
//! The library provides the underlying architecture required for handling and
//! maintaining virtual connections over UDP sockets and takes care of sending
//! reliable, raw messages over the established client-server connections with
//! minimal overhead.
//!
//! cobalt is also fully configurable and can be plugged in a variety of ways,
//! so that library users have the largest possible degree of control over
//! the behavior of their connections.
//!
//! ## Getting started
//!
//! When working with **cobalt** the most important part is implementing the so
//! called handlers. A `Handler` is a trait which acts as a event proxy for
//! both server and client events that are emitted from the underlying tick
//! loop.
//!
//! Below follows a very basic example implementation of a custom game server.
//!
//! ```
//! use std::collections::HashMap;
//! use cobalt::{Config, Connection, ConnectionID, Handler, Server};
//!
//! struct GameServer;
//! impl Handler<Server> for GameServer {
//!
//!     fn bind(&mut self, server: &mut Server) {
//!         // Since this is a runnable doc, we'll just exit right away
//!         server.shutdown();
//!     }
//!
//!     fn tick_connections(
//!         &mut self, _: &mut Server,
//!         connections: &mut HashMap<ConnectionID, Connection>
//!     ) {
//!
//!         for (_, conn) in connections.iter_mut() {
//!             // Receive player input
//!         }
//!
//!         // Advance game state
//!
//!         for (_, conn) in connections.iter_mut() {
//!             // Send state to players
//!         }
//!
//!     }
//!
//!     fn shutdown(&mut self, _: &mut Server) {
//!         // Logging and things
//!     }
//!
//!     fn connection(&mut self, _: &mut Server, _: &mut Connection) {
//!         // Create Player, send MOTD etc.
//!     }
//!
//!     fn connection_lost(&mut self, _: &mut Server, _: &mut Connection) {
//!         // Remove Player
//!     }
//!
//! }
//!
//! let mut handler = GameServer;
//! let mut server = Server::new(Config::default());
//! server.bind(&mut handler, "127.0.0.1:7156").unwrap();
//! ```
//!
//! And the client version would look almost identical except for a few methods
//! having different names.
//!
//! ```
//! use std::collections::HashMap;
//! use cobalt::{Config, Connection, Handler, Client};
//!
//! struct GameClient;
//! impl Handler<Client> for GameClient {
//!
//!     fn connect(&mut self, client: &mut Client) {
//!         // Since this is a runnable doc, we'll just exit right away
//!         client.close();
//!     }
//!
//!     fn tick_connection(&mut self, _: &mut Client, conn: &mut Connection) {
//!
//!         for msg in conn.received() {
//!             // Receive state from server
//!         }
//!
//!         // Advance game state
//!
//!         // Send input to server
//!
//!     }
//!
//!     fn close(&mut self, _: &mut Client) {
//!         // Exit game
//!     }
//!
//!     fn connection(&mut self, _: &mut Client, _: &mut Connection) {
//!         // Request map list and settings from server
//!     }
//!
//!     fn connection_failed(&mut self, client: &mut Client, _: &mut Connection) {
//!         // Failed to connect to the server
//!     }
//!
//!     fn connection_lost(&mut self, client: &mut Client, _: &mut Connection) {
//!         // Inform the user
//!     }
//!
//! }
//!
//! let mut handler = GameClient;
//! let mut client = Client::new(Config::default());
//! client.connect(&mut handler, "127.0.0.1:7156").unwrap();
//! ```
//!
//! ## Integration with existing event loops
//!
//! When a client already provides its own event loop via a rendering framework
//! or game engine, a **synchronous** version of the `Client` interface is also
//! available in order to ease integration in such cases.
//!
//! In these cases it can also make sense to use a `EventQueue` like
//! implementation of the `Handler` trait.
//!
//! ```
//! use cobalt::{Client, Config, Connection, ConnectionID, Handler};
//!
//! struct SyncHandler;
//! impl Handler<Client> for SyncHandler {}
//!
//! let mut handler = SyncHandler;
//! let mut client = Client::new(Config::default());
//! let mut state = client.connect_sync(&mut handler, "127.0.0.1:7156").unwrap();
//!
//! // Receive from and tick the client connection
//! client.receive_sync(&mut handler, &mut state);
//! client.tick_sync(&mut handler, &mut state);
//!
//! // Handle received message and send new ones here
//!
//! // Send any pending messages via the connection
//! client.send_sync(&mut handler, &mut state);
//! ```
#![deny(
    missing_docs,
    missing_debug_implementations, missing_copy_implementations,
    trivial_casts, trivial_numeric_casts,
    unsafe_code,
    unstable_features,
    unused_import_braces, unused_qualifications
)]
mod client;
mod server;

mod shared {
    pub mod binary_rate_limiter;
    pub mod config;
    pub mod connection;
    pub mod message_queue;
    pub mod udp_socket;
    pub mod stats;
}

mod traits {
    pub mod handler;
    pub mod rate_limiter;
    pub mod socket;
}

#[doc(inline)]
pub use shared::config::Config;

#[doc(inline)]
pub use shared::connection::{Connection, ConnectionID, ConnectionState};

#[doc(inline)]
pub use shared::message_queue::MessageKind;

#[doc(inline)]
pub use shared::binary_rate_limiter::BinaryRateLimiter;

#[doc(inline)]
pub use shared::udp_socket::UdpSocket;

#[doc(inline)]
pub use shared::stats::Stats;

#[doc(inline)]
pub use traits::handler::Handler;

#[doc(inline)]
pub use traits::rate_limiter::RateLimiter;

#[doc(inline)]
pub use traits::socket::Socket;

#[doc(inline)]
pub use client::Client;

#[doc(inline)]
pub use client::ClientState;

#[doc(inline)]
pub use server::Server;

#[cfg(test)]
mod tests {
    mod client;
    mod connection;
    mod message_queue;
    mod server;
}

<|endoftext|>