<commit_before>use time;
use std::io::timer::sleep;

use GameWindow;
use keyboard;
use mouse;
use event;

/// Render argument.
pub struct RenderArgs<'a> {
    /// Extrapolated time in seconds, used to do smooth animation.
    pub ext_dt: f64,
    /// The width of rendered area.
    pub width: u32,
    /// The height of rendered area.
    pub height: u32,
}

/// Update argument.
pub struct UpdateArgs {
    /// Delta time in seconds.
    pub dt: f64,
}

/// Key press arguments.
pub struct KeyPressArgs {
    /// Keyboard key.
    pub key: keyboard::Key,
}

/// Key release arguments.
pub struct KeyReleaseArgs {
    /// Keyboard key.
    pub key: keyboard::Key,
}

/// Mouse press arguments.
pub struct MousePressArgs {
    /// Mouse button.
    pub button: mouse::Button,
}

/// Mouse release arguments.
pub struct MouseReleaseArgs {
    /// Mouse button.
    pub button: mouse::Button,
}

/// Mouse move arguments.
pub struct MouseMoveArgs {
    /// x.
    pub x: f64,
    /// y.
    pub y: f64,
}

/// Mouse relative move arguments.
pub struct MouseRelativeMoveArgs {
    /// Delta x.
    pub dx: f64,
    /// Delta y.
    pub dy: f64,
}

/// Mouse scroll arguments.
pub struct MouseScrollArgs {
    /// x.
    pub x: f64,
    /// y.
    pub y: f64,
}

/// Contains the different game events.
pub enum GameEvent<'a> {
    /// Render graphics.
    Render(RenderArgs<'a>),
    /// Update physical state of the game.
    Update(UpdateArgs),
    /// Pressed a keyboard key.
    KeyPress(KeyPressArgs),
    /// Released a keyboard key.
    KeyRelease(KeyReleaseArgs),
    /// Pressed a mouse button.
    MousePress(MousePressArgs),
    /// Released a mouse button.
    MouseRelease(MouseReleaseArgs),
    /// Moved mouse cursor.
    MouseMove(MouseMoveArgs),
    /// Moved mouse relative, not bounded by cursor.
    MouseRelativeMove(MouseRelativeMoveArgs),
    /// Scrolled mouse.
    MouseScroll(MouseScrollArgs)
}

impl<'a> GameEvent<'a> {
    /// Maps event to something that can be sent between tasks if possible.
    ///
    /// Render events are not sendable between tasks.
    pub fn to_sendable(&'a self) -> Option<GameEvent<'static>> {
        match *self {
            Render(_) => None,
            Update(args) => Some(Update(args)),
            KeyPress(args) => Some(KeyPress(args)),
            KeyRelease(args) => Some(KeyRelease(args)),
            MousePress(args) => Some(MousePress(args)),
            MouseRelease(args) => Some(MouseRelease(args)),
            MouseMove(args) => Some(MouseMove(args)),
            MouseRelativeMove(args) => Some(MouseRelativeMove(args)),
            MouseScroll(args) => Some(MouseScroll(args)),
        }
    }
}

enum GameIteratorState {
    RenderState,
    SwapBuffersState,
    PrepareUpdateLoopState,
    UpdateLoopState,
    HandleEventsState,
    MouseRelativeMoveState(f64, f64),
    UpdateState,
}

/// Settings for the game loop behavior.
pub struct GameIteratorSettings {
    /// The number of updates per second (UPS).
    pub updates_per_second: u64,
    /// The maximum number of frames per second (FPS target).
    pub max_frames_per_second: u64,
}

/// A game loop iterator.
///
/// Example:
///
/// ```Rust
/// let game_iter_settings = GameIteratorSettings {
///     updates_per_second: 120,
///     max_frames_per_second: 60,
/// };
/// let mut game_iter = GameIterator::new(&mut window, &game_iter_settings);
/// loop {
///     match game_iter.next() {
///         None => break,
///         Some(mut e) => match e {
///             Render(ref mut args) => {
///                 // Create graphics context with absolute coordinates.
///                 let c = Context::abs(args.width as f64, args.height as f64);
///                 // Do rendering here.
///             },
///             _ => {},
///         },
///     }
/// }
/// ```
pub struct GameIterator<'a, W> {
    game_window: &'a mut W,
    state: GameIteratorState,
    last_update: u64,
    update_time_in_ns: u64,
    dt: f64,
    min_updates_per_frame: u64,
    min_ns_per_frame: u64,
    start_render: u64,
    next_render: u64,
    updated: u64,
}

static billion: u64 = 1_000_000_000;

impl<'a, W: GameWindow> GameIterator<'a, W> {
    /// Creates a new game iterator.
    pub fn new(
        game_window: &'a mut W,
        settings: &GameIteratorSettings
    ) -> GameIterator<'a, W> {
        let updates_per_second: u64 = settings.updates_per_second;
        let max_frames_per_second: u64 = settings.max_frames_per_second;

        let start = time::precise_time_ns();
        GameIterator {
            game_window: game_window,
            state: RenderState,
            last_update: start,
            update_time_in_ns: billion / updates_per_second,
            dt: 1.0 / updates_per_second as f64,
            // You can make this lower if needed.
            min_updates_per_frame: updates_per_second / max_frames_per_second,
            min_ns_per_frame: billion / max_frames_per_second,
            start_render: start,
            next_render: start,
            updated: 0,
        }
    }

    /// Returns the next game event.
    pub fn next<'a>(&'a mut self) -> Option<GameEvent<'a>> {
        match self.state {
            RenderState => {
                if self.game_window.should_close() { return None; }

                self.start_render = time::precise_time_ns();
                // Rendering code
                let (w, h) = self.game_window.get_size();
                if w != 0 && h != 0 {
                    // Swap buffers next time.
                    self.state = SwapBuffersState;
                    return Some(Render(RenderArgs {
                            // Extrapolate time forward to allow smooth motion.
                            // 'start_render' is always bigger than 'last_update'.
                            ext_dt: (self.start_render - self.last_update) as f64 / billion as f64,
                            width: w,
                            height: h,
                        }
                    ));
                }

                self.state = PrepareUpdateLoopState;
                return self.next();
            },
            SwapBuffersState => {
                self.game_window.swap_buffers();
                self.state = PrepareUpdateLoopState;
                return self.next();
            },
            PrepareUpdateLoopState => {
                self.updated = 0;
                self.next_render = self.start_render + self.min_ns_per_frame;
                self.state = UpdateLoopState;
                return self.next();
            },
            UpdateLoopState => {
                let got_min_updates = self.updated < self.min_updates_per_frame;
                let got_time_to_update = time::precise_time_ns() < self.next_render;
                let before_next_frame = self.last_update + self.update_time_in_ns < self.next_render;

                if ( got_time_to_update || got_min_updates ) && before_next_frame {
                    self.state = HandleEventsState;
                    return self.next();
                }

                // Wait if possible.
                // Convert to ms because that is what the sleep function takes.
                let t = (self.next_render - time::precise_time_ns() ) / 1_000_000;
                if t > 1 && t < 1000000 { // The second half just checks if it overflowed,
                                          // which tells us that t should have been negative
                                          // and we are running slow and shouldn't sleep.
                    sleep( t );
                }
                self.state = RenderState;
                return self.next();
            },
            HandleEventsState => {
                // Handle all events before updating.
                return match self.game_window.poll_event() {
                    event::KeyPressed(key) => {
                        Some(KeyPress(KeyPressArgs {
                            key: key,
                        }))
                    },
                    event::KeyReleased(key) => {
                        Some(KeyRelease(KeyReleaseArgs {
                            key: key,
                        }))
                    },
                    event::MouseButtonPressed(mouse_button) => {
                        Some(MousePress(MousePressArgs {
                            button: mouse_button,
                        }))
                    },
                    event::MouseButtonReleased(mouse_button) => {
                        Some(MouseRelease(MouseReleaseArgs {
                            button: mouse_button,
                        }))
                    },
                    event::MouseMoved(x, y, relative_move) => {
                        match relative_move {
                            Some((dx, dy)) =>
                                self.state = MouseRelativeMoveState(dx, dy),
                            None => {},
                        };
                        Some(MouseMove(MouseMoveArgs {
                            x: x,
                            y: y,
                        }))
                    },
                    event::MouseScrolled(x, y) => {
                        Some(MouseScroll(MouseScrollArgs {
                            x: x,
                            y: y
                        }))
                    },
                    event::NoEvent => {
                        self.state = UpdateState;
                        self.next()
                    },
                }
            },
            MouseRelativeMoveState(dx, dy) => {
                self.state = HandleEventsState;
                return Some(MouseRelativeMove(MouseRelativeMoveArgs {
                    dx: dx,
                    dy: dy,
                }));
            },
            UpdateState => {
                self.updated += 1;
                self.state = UpdateLoopState;
                self.last_update += self.update_time_in_ns;
                return Some(Update(UpdateArgs{
                    dt: self.dt,
                }));
            },
        };

        /*
        // copied.

        while !self.should_close(game_window) {

            let start_render = time::precise_time_ns();

            // Rendering code
            let (w, h) = game_window.get_size();
            if w != 0 && h != 0 {
                self.viewport(game_window);
                let mut gl = Gl::new(&mut gl_data, asset_store);
                bg.clear(&mut gl);
                // Extrapolate time forward to allow smooth motion.
                // 'now' is always bigger than 'last_update'.
                let ext_dt = (start_render - last_update) as f64 / billion as f64;
                self.render(
                    ext_dt,
                    &context
                        .trans(-1.0, 1.0)
                        .scale(2.0 / w as f64, -2.0 / h as f64)
                        .store_view(),
                    &mut gl
                        );
                self.swap_buffers(game_window);
            }

            let next_render = start_render + min_ns_per_frame;

            // Update gamestate
            let mut updated = 0;

            while // If we haven't reached the required number of updates yet
                  ( updated < min_updates_per_frame ||
                    // Or we have the time to update further
                    time::precise_time_ns() < next_render ) &&
                  //And we haven't already progressed time to far
                  last_update + update_time_in_ns < next_render {

                self.handle_events(game_window, asset_store);
                self.update(dt, asset_store);

                updated += 1;
                last_update += update_time_in_ns;
            }

            // Wait if possible

            let t = (next_render - time::precise_time_ns() ) / 1_000_000;
            if t > 1 && t < 1000000 { // The second half just checks if it overflowed,
                                      // which tells us that t should have been negative
                                      // and we are running slow and shouldn't sleep.
                sleep( t );
            }

        }
        */
    }
}

<commit_msg>Removed lifetime on `GameEvent`<commit_after>use time;
use std::io::timer::sleep;

use GameWindow;
use keyboard;
use mouse;
use event;

/// Render argument.
pub struct RenderArgs {
    /// Extrapolated time in seconds, used to do smooth animation.
    pub ext_dt: f64,
    /// The width of rendered area.
    pub width: u32,
    /// The height of rendered area.
    pub height: u32,
}

/// Update argument.
pub struct UpdateArgs {
    /// Delta time in seconds.
    pub dt: f64,
}

/// Key press arguments.
pub struct KeyPressArgs {
    /// Keyboard key.
    pub key: keyboard::Key,
}

/// Key release arguments.
pub struct KeyReleaseArgs {
    /// Keyboard key.
    pub key: keyboard::Key,
}

/// Mouse press arguments.
pub struct MousePressArgs {
    /// Mouse button.
    pub button: mouse::Button,
}

/// Mouse release arguments.
pub struct MouseReleaseArgs {
    /// Mouse button.
    pub button: mouse::Button,
}

/// Mouse move arguments.
pub struct MouseMoveArgs {
    /// x.
    pub x: f64,
    /// y.
    pub y: f64,
}

/// Mouse relative move arguments.
pub struct MouseRelativeMoveArgs {
    /// Delta x.
    pub dx: f64,
    /// Delta y.
    pub dy: f64,
}

/// Mouse scroll arguments.
pub struct MouseScrollArgs {
    /// x.
    pub x: f64,
    /// y.
    pub y: f64,
}

/// Contains the different game events.
pub enum GameEvent {
    /// Render graphics.
    Render(RenderArgs),
    /// Update physical state of the game.
    Update(UpdateArgs),
    /// Pressed a keyboard key.
    KeyPress(KeyPressArgs),
    /// Released a keyboard key.
    KeyRelease(KeyReleaseArgs),
    /// Pressed a mouse button.
    MousePress(MousePressArgs),
    /// Released a mouse button.
    MouseRelease(MouseReleaseArgs),
    /// Moved mouse cursor.
    MouseMove(MouseMoveArgs),
    /// Moved mouse relative, not bounded by cursor.
    MouseRelativeMove(MouseRelativeMoveArgs),
    /// Scrolled mouse.
    MouseScroll(MouseScrollArgs)
}

impl GameEvent {
    /// Maps event to something that can be sent between tasks if possible.
    ///
    /// Render events are not sendable between tasks.
    pub fn to_sendable(&self) -> Option<GameEvent> {
        match *self {
            Render(_) => None,
            Update(args) => Some(Update(args)),
            KeyPress(args) => Some(KeyPress(args)),
            KeyRelease(args) => Some(KeyRelease(args)),
            MousePress(args) => Some(MousePress(args)),
            MouseRelease(args) => Some(MouseRelease(args)),
            MouseMove(args) => Some(MouseMove(args)),
            MouseRelativeMove(args) => Some(MouseRelativeMove(args)),
            MouseScroll(args) => Some(MouseScroll(args)),
        }
    }
}

enum GameIteratorState {
    RenderState,
    SwapBuffersState,
    PrepareUpdateLoopState,
    UpdateLoopState,
    HandleEventsState,
    MouseRelativeMoveState(f64, f64),
    UpdateState,
}

/// Settings for the game loop behavior.
pub struct GameIteratorSettings {
    /// The number of updates per second (UPS).
    pub updates_per_second: u64,
    /// The maximum number of frames per second (FPS target).
    pub max_frames_per_second: u64,
}

/// A game loop iterator.
///
/// Example:
///
/// ```Rust
/// let game_iter_settings = GameIteratorSettings {
///     updates_per_second: 120,
///     max_frames_per_second: 60,
/// };
/// let mut game_iter = GameIterator::new(&mut window, &game_iter_settings);
/// loop {
///     match game_iter.next() {
///         None => break,
///         Some(mut e) => match e {
///             Render(ref mut args) => {
///                 // Create graphics context with absolute coordinates.
///                 let c = Context::abs(args.width as f64, args.height as f64);
///                 // Do rendering here.
///             },
///             _ => {},
///         },
///     }
/// }
/// ```
pub struct GameIterator<'a, W> {
    game_window: &'a mut W,
    state: GameIteratorState,
    last_update: u64,
    update_time_in_ns: u64,
    dt: f64,
    min_updates_per_frame: u64,
    min_ns_per_frame: u64,
    start_render: u64,
    next_render: u64,
    updated: u64,
}

static billion: u64 = 1_000_000_000;

impl<'a, W: GameWindow> GameIterator<'a, W> {
    /// Creates a new game iterator.
    pub fn new(
        game_window: &'a mut W,
        settings: &GameIteratorSettings
    ) -> GameIterator<'a, W> {
        let updates_per_second: u64 = settings.updates_per_second;
        let max_frames_per_second: u64 = settings.max_frames_per_second;

        let start = time::precise_time_ns();
        GameIterator {
            game_window: game_window,
            state: RenderState,
            last_update: start,
            update_time_in_ns: billion / updates_per_second,
            dt: 1.0 / updates_per_second as f64,
            // You can make this lower if needed.
            min_updates_per_frame: updates_per_second / max_frames_per_second,
            min_ns_per_frame: billion / max_frames_per_second,
            start_render: start,
            next_render: start,
            updated: 0,
        }
    }

    /// Returns the next game event.
    pub fn next(&mut self) -> Option<GameEvent> {
        match self.state {
            RenderState => {
                if self.game_window.should_close() { return None; }

                self.start_render = time::precise_time_ns();
                // Rendering code
                let (w, h) = self.game_window.get_size();
                if w != 0 && h != 0 {
                    // Swap buffers next time.
                    self.state = SwapBuffersState;
                    return Some(Render(RenderArgs {
                            // Extrapolate time forward to allow smooth motion.
                            // 'start_render' is always bigger than 'last_update'.
                            ext_dt: (self.start_render - self.last_update) as f64 / billion as f64,
                            width: w,
                            height: h,
                        }
                    ));
                }

                self.state = PrepareUpdateLoopState;
                return self.next();
            },
            SwapBuffersState => {
                self.game_window.swap_buffers();
                self.state = PrepareUpdateLoopState;
                return self.next();
            },
            PrepareUpdateLoopState => {
                self.updated = 0;
                self.next_render = self.start_render + self.min_ns_per_frame;
                self.state = UpdateLoopState;
                return self.next();
            },
            UpdateLoopState => {
                let got_min_updates = self.updated < self.min_updates_per_frame;
                let got_time_to_update = time::precise_time_ns() < self.next_render;
                let before_next_frame = self.last_update + self.update_time_in_ns < self.next_render;

                if ( got_time_to_update || got_min_updates ) && before_next_frame {
                    self.state = HandleEventsState;
                    return self.next();
                }

                // Wait if possible.
                // Convert to ms because that is what the sleep function takes.
                let t = (self.next_render - time::precise_time_ns() ) / 1_000_000;
                if t > 1 && t < 1000000 { // The second half just checks if it overflowed,
                                          // which tells us that t should have been negative
                                          // and we are running slow and shouldn't sleep.
                    sleep( t );
                }
                self.state = RenderState;
                return self.next();
            },
            HandleEventsState => {
                // Handle all events before updating.
                return match self.game_window.poll_event() {
                    event::KeyPressed(key) => {
                        Some(KeyPress(KeyPressArgs {
                            key: key,
                        }))
                    },
                    event::KeyReleased(key) => {
                        Some(KeyRelease(KeyReleaseArgs {
                            key: key,
                        }))
                    },
                    event::MouseButtonPressed(mouse_button) => {
                        Some(MousePress(MousePressArgs {
                            button: mouse_button,
                        }))
                    },
                    event::MouseButtonReleased(mouse_button) => {
                        Some(MouseRelease(MouseReleaseArgs {
                            button: mouse_button,
                        }))
                    },
                    event::MouseMoved(x, y, relative_move) => {
                        match relative_move {
                            Some((dx, dy)) =>
                                self.state = MouseRelativeMoveState(dx, dy),
                            None => {},
                        };
                        Some(MouseMove(MouseMoveArgs {
                            x: x,
                            y: y,
                        }))
                    },
                    event::MouseScrolled(x, y) => {
                        Some(MouseScroll(MouseScrollArgs {
                            x: x,
                            y: y
                        }))
                    },
                    event::NoEvent => {
                        self.state = UpdateState;
                        self.next()
                    },
                }
            },
            MouseRelativeMoveState(dx, dy) => {
                self.state = HandleEventsState;
                return Some(MouseRelativeMove(MouseRelativeMoveArgs {
                    dx: dx,
                    dy: dy,
                }));
            },
            UpdateState => {
                self.updated += 1;
                self.state = UpdateLoopState;
                self.last_update += self.update_time_in_ns;
                return Some(Update(UpdateArgs{
                    dt: self.dt,
                }));
            },
        };

        /*
        // copied.

        while !self.should_close(game_window) {

            let start_render = time::precise_time_ns();

            // Rendering code
            let (w, h) = game_window.get_size();
            if w != 0 && h != 0 {
                self.viewport(game_window);
                let mut gl = Gl::new(&mut gl_data, asset_store);
                bg.clear(&mut gl);
                // Extrapolate time forward to allow smooth motion.
                // 'now' is always bigger than 'last_update'.
                let ext_dt = (start_render - last_update) as f64 / billion as f64;
                self.render(
                    ext_dt,
                    &context
                        .trans(-1.0, 1.0)
                        .scale(2.0 / w as f64, -2.0 / h as f64)
                        .store_view(),
                    &mut gl
                        );
                self.swap_buffers(game_window);
            }

            let next_render = start_render + min_ns_per_frame;

            // Update gamestate
            let mut updated = 0;

            while // If we haven't reached the required number of updates yet
                  ( updated < min_updates_per_frame ||
                    // Or we have the time to update further
                    time::precise_time_ns() < next_render ) &&
                  //And we haven't already progressed time to far
                  last_update + update_time_in_ns < next_render {

                self.handle_events(game_window, asset_store);
                self.update(dt, asset_store);

                updated += 1;
                last_update += update_time_in_ns;
            }

            // Wait if possible

            let t = (next_render - time::precise_time_ns() ) / 1_000_000;
            if t > 1 && t < 1000000 { // The second half just checks if it overflowed,
                                      // which tells us that t should have been negative
                                      // and we are running slow and shouldn't sleep.
                sleep( t );
            }

        }
        */
    }
}

<|endoftext|>


<commit_before><commit_msg>toying with rust<commit_after>fn main() {
  print!("Hello, world!\n");
}
<|endoftext|>


<commit_before><commit_msg>Make dispatch_messages take ownership of messages<commit_after><|endoftext|>


<commit_before><commit_msg>crab example<commit_after>
extern crate rainbowcoat;
use std::io::{self, Write};

fn run() -> io::Result<()> {
    write!(
        &mut rainbowcoat::Colors::configure(io::stdout(), 2.0, 0.4, 0.0),
        r#"            ,        ,
            /(_,    ,_)\
            \ _/    \_ /
            //        \\
            \\ (@)(@) //
             \'="=="='/
         ,===/        \===,
        ",===\        /===,"
        " ,==='------'===, "
         "                "
"#
    )?;
    Ok(())
}

fn main() {
    run().unwrap()
}
<|endoftext|>


<commit_before><commit_msg>rust-rub work<commit_after><|endoftext|>


<commit_before><commit_msg>added CpuState struct and a stub for DecodeInfo<commit_after>pub struct DecodeInfo {
    stub:bool,
}

pub struct CpuState {
    pc:u16,
    sp: u8,
    a:  u8,
    x:  u8,
    y:  u8,

    // flags
    C: bool, // carry
    Z: bool, // zero
    I: bool, // interrupt
    D: bool, // decimal
    B: bool, // break
             // bit 5 is not used by the nes and is always 1
    V: bool, // overflow
    S: bool, // sign/negative

    // these are not strictly 6502 registers, but are useful for modeling the cpu
    instruction_register: u16,
    decode_register:DecodeInfo,
}

<|endoftext|>


<commit_before><commit_msg>Add binding generated by `rust-bindgen`<commit_after>// automatically generated by rust-bindgen

use std::os::raw::{c_char, c_int};

#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u32)]
pub enum Enum_SoundIoError {
    SoundIoErrorNone = 0,
    SoundIoErrorNoMem = 1,
    SoundIoErrorInitAudioBackend = 2,
    SoundIoErrorSystemResources = 3,
    SoundIoErrorOpeningDevice = 4,
    SoundIoErrorNoSuchDevice = 5,
    SoundIoErrorInvalid = 6,
    SoundIoErrorBackendUnavailable = 7,
    SoundIoErrorStreaming = 8,
    SoundIoErrorIncompatibleDevice = 9,
    SoundIoErrorNoSuchClient = 10,
    SoundIoErrorIncompatibleBackend = 11,
    SoundIoErrorBackendDisconnected = 12,
    SoundIoErrorInterrupted = 13,
    SoundIoErrorUnderflow = 14,
    SoundIoErrorEncodingString = 15,
}

#[derive(Clone, Copy)]
#[repr(u32)]
pub enum Enum_SoundIoChannelId {
    SoundIoChannelIdInvalid = 0,
    SoundIoChannelIdFrontLeft = 1,
    SoundIoChannelIdFrontRight = 2,
    SoundIoChannelIdFrontCenter = 3,
    SoundIoChannelIdLfe = 4,
    SoundIoChannelIdBackLeft = 5,
    SoundIoChannelIdBackRight = 6,
    SoundIoChannelIdFrontLeftCenter = 7,
    SoundIoChannelIdFrontRightCenter = 8,
    SoundIoChannelIdBackCenter = 9,
    SoundIoChannelIdSideLeft = 10,
    SoundIoChannelIdSideRight = 11,
    SoundIoChannelIdTopCenter = 12,
    SoundIoChannelIdTopFrontLeft = 13,
    SoundIoChannelIdTopFrontCenter = 14,
    SoundIoChannelIdTopFrontRight = 15,
    SoundIoChannelIdTopBackLeft = 16,
    SoundIoChannelIdTopBackCenter = 17,
    SoundIoChannelIdTopBackRight = 18,
    SoundIoChannelIdBackLeftCenter = 19,
    SoundIoChannelIdBackRightCenter = 20,
    SoundIoChannelIdFrontLeftWide = 21,
    SoundIoChannelIdFrontRightWide = 22,
    SoundIoChannelIdFrontLeftHigh = 23,
    SoundIoChannelIdFrontCenterHigh = 24,
    SoundIoChannelIdFrontRightHigh = 25,
    SoundIoChannelIdTopFrontLeftCenter = 26,
    SoundIoChannelIdTopFrontRightCenter = 27,
    SoundIoChannelIdTopSideLeft = 28,
    SoundIoChannelIdTopSideRight = 29,
    SoundIoChannelIdLeftLfe = 30,
    SoundIoChannelIdRightLfe = 31,
    SoundIoChannelIdLfe2 = 32,
    SoundIoChannelIdBottomCenter = 33,
    SoundIoChannelIdBottomLeftCenter = 34,
    SoundIoChannelIdBottomRightCenter = 35,
    SoundIoChannelIdMsMid = 36,
    SoundIoChannelIdMsSide = 37,
    SoundIoChannelIdAmbisonicW = 38,
    SoundIoChannelIdAmbisonicX = 39,
    SoundIoChannelIdAmbisonicY = 40,
    SoundIoChannelIdAmbisonicZ = 41,
    SoundIoChannelIdXyX = 42,
    SoundIoChannelIdXyY = 43,
    SoundIoChannelIdHeadphonesLeft = 44,
    SoundIoChannelIdHeadphonesRight = 45,
    SoundIoChannelIdClickTrack = 46,
    SoundIoChannelIdForeignLanguage = 47,
    SoundIoChannelIdHearingImpaired = 48,
    SoundIoChannelIdNarration = 49,
    SoundIoChannelIdHaptic = 50,
    SoundIoChannelIdDialogCentricMix = 51,
    SoundIoChannelIdAux = 52,
    SoundIoChannelIdAux0 = 53,
    SoundIoChannelIdAux1 = 54,
    SoundIoChannelIdAux2 = 55,
    SoundIoChannelIdAux3 = 56,
    SoundIoChannelIdAux4 = 57,
    SoundIoChannelIdAux5 = 58,
    SoundIoChannelIdAux6 = 59,
    SoundIoChannelIdAux7 = 60,
    SoundIoChannelIdAux8 = 61,
    SoundIoChannelIdAux9 = 62,
    SoundIoChannelIdAux10 = 63,
    SoundIoChannelIdAux11 = 64,
    SoundIoChannelIdAux12 = 65,
    SoundIoChannelIdAux13 = 66,
    SoundIoChannelIdAux14 = 67,
    SoundIoChannelIdAux15 = 68,
}
#[derive(Clone, Copy)]
#[repr(u32)]
pub enum Enum_SoundIoChannelLayoutId {
    SoundIoChannelLayoutIdMono = 0,
    SoundIoChannelLayoutIdStereo = 1,
    SoundIoChannelLayoutId2Point1 = 2,
    SoundIoChannelLayoutId3Point0 = 3,
    SoundIoChannelLayoutId3Point0Back = 4,
    SoundIoChannelLayoutId3Point1 = 5,
    SoundIoChannelLayoutId4Point0 = 6,
    SoundIoChannelLayoutIdQuad = 7,
    SoundIoChannelLayoutIdQuadSide = 8,
    SoundIoChannelLayoutId4Point1 = 9,
    SoundIoChannelLayoutId5Point0Back = 10,
    SoundIoChannelLayoutId5Point0Side = 11,
    SoundIoChannelLayoutId5Point1 = 12,
    SoundIoChannelLayoutId5Point1Back = 13,
    SoundIoChannelLayoutId6Point0Side = 14,
    SoundIoChannelLayoutId6Point0Front = 15,
    SoundIoChannelLayoutIdHexagonal = 16,
    SoundIoChannelLayoutId6Point1 = 17,
    SoundIoChannelLayoutId6Point1Back = 18,
    SoundIoChannelLayoutId6Point1Front = 19,
    SoundIoChannelLayoutId7Point0 = 20,
    SoundIoChannelLayoutId7Point0Front = 21,
    SoundIoChannelLayoutId7Point1 = 22,
    SoundIoChannelLayoutId7Point1Wide = 23,
    SoundIoChannelLayoutId7Point1WideBack = 24,
    SoundIoChannelLayoutIdOctagonal = 25,
}
#[derive(Clone, Copy)]
#[repr(u32)]
pub enum Enum_SoundIoBackend {
    SoundIoBackendNone = 0,
    SoundIoBackendJack = 1,
    SoundIoBackendPulseAudio = 2,
    SoundIoBackendAlsa = 3,
    SoundIoBackendCoreAudio = 4,
    SoundIoBackendWasapi = 5,
    SoundIoBackendDummy = 6,
}
#[derive(Clone, Copy)]
#[repr(u32)]
pub enum Enum_SoundIoDeviceAim {
    SoundIoDeviceAimInput = 0,
    SoundIoDeviceAimOutput = 1,
}
#[derive(Clone, Copy)]
#[repr(u32)]
pub enum Enum_SoundIoFormat {
    SoundIoFormatInvalid = 0,
    SoundIoFormatS8 = 1,
    SoundIoFormatU8 = 2,
    SoundIoFormatS16LE = 3,
    SoundIoFormatS16BE = 4,
    SoundIoFormatU16LE = 5,
    SoundIoFormatU16BE = 6,
    SoundIoFormatS24LE = 7,
    SoundIoFormatS24BE = 8,
    SoundIoFormatU24LE = 9,
    SoundIoFormatU24BE = 10,
    SoundIoFormatS32LE = 11,
    SoundIoFormatS32BE = 12,
    SoundIoFormatU32LE = 13,
    SoundIoFormatU32BE = 14,
    SoundIoFormatFloat32LE = 15,
    SoundIoFormatFloat32BE = 16,
    SoundIoFormatFloat64LE = 17,
    SoundIoFormatFloat64BE = 18,
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_SoundIoChannelLayout {
    pub name: *const c_char,
    pub channel_count: c_int,
    pub channels: [Enum_SoundIoChannelId; 24usize],
}
impl ::std::clone::Clone for Struct_SoundIoChannelLayout {
    fn clone(&self) -> Self {
        *self
    }
}
impl ::std::default::Default for Struct_SoundIoChannelLayout {
    fn default() -> Self {
        unsafe { ::std::mem::zeroed() }
    }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_SoundIoSampleRateRange {
    pub min: c_int,
    pub max: c_int,
}
impl ::std::clone::Clone for Struct_SoundIoSampleRateRange {
    fn clone(&self) -> Self {
        *self
    }
}
impl ::std::default::Default for Struct_SoundIoSampleRateRange {
    fn default() -> Self {
        unsafe { ::std::mem::zeroed() }
    }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_SoundIoChannelArea {
    pub ptr: *mut c_char,
    pub step: c_int,
}
impl ::std::clone::Clone for Struct_SoundIoChannelArea {
    fn clone(&self) -> Self {
        *self
    }
}
impl ::std::default::Default for Struct_SoundIoChannelArea {
    fn default() -> Self {
        unsafe { ::std::mem::zeroed() }
    }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_SoundIo {
    pub userdata: *mut ::std::os::raw::c_void,
    pub on_devices_change: ::std::option::Option<unsafe extern "C" fn(arg1:
                                                                          *mut Struct_SoundIo)>,
    pub on_backend_disconnect: ::std::option::Option<unsafe extern "C" fn(arg1:
                                                                              *mut Struct_SoundIo,
                                                                          err:
                                                                              c_int)>,
    pub on_events_signal: ::std::option::Option<unsafe extern "C" fn(arg1:
                                                                         *mut Struct_SoundIo)>,
    pub current_backend: Enum_SoundIoBackend,
    pub app_name: *const c_char,
    pub emit_rtprio_warning: ::std::option::Option<extern "C" fn()>,
    pub jack_info_callback: ::std::option::Option<unsafe extern "C" fn(msg:
                                                                           *const c_char)>,
    pub jack_error_callback: ::std::option::Option<unsafe extern "C" fn(msg:
                                                                            *const c_char)>,
}
impl ::std::clone::Clone for Struct_SoundIo {
    fn clone(&self) -> Self {
        *self
    }
}
impl ::std::default::Default for Struct_SoundIo {
    fn default() -> Self {
        unsafe { ::std::mem::zeroed() }
    }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_SoundIoDevice {
    pub soundio: *mut Struct_SoundIo,
    pub id: *mut c_char,
    pub name: *mut c_char,
    pub aim: Enum_SoundIoDeviceAim,
    pub layouts: *mut Struct_SoundIoChannelLayout,
    pub layout_count: c_int,
    pub current_layout: Struct_SoundIoChannelLayout,
    pub formats: *mut Enum_SoundIoFormat,
    pub format_count: c_int,
    pub current_format: Enum_SoundIoFormat,
    pub sample_rates: *mut Struct_SoundIoSampleRateRange,
    pub sample_rate_count: c_int,
    pub sample_rate_current: c_int,
    pub software_latency_min: ::std::os::raw::c_double,
    pub software_latency_max: ::std::os::raw::c_double,
    pub software_latency_current: ::std::os::raw::c_double,
    pub is_raw: u8,
    pub ref_count: c_int,
    pub probe_error: c_int,
}
impl ::std::clone::Clone for Struct_SoundIoDevice {
    fn clone(&self) -> Self {
        *self
    }
}
impl ::std::default::Default for Struct_SoundIoDevice {
    fn default() -> Self {
        unsafe { ::std::mem::zeroed() }
    }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_SoundIoOutStream {
    pub device: *mut Struct_SoundIoDevice,
    pub format: Enum_SoundIoFormat,
    pub sample_rate: c_int,
    pub layout: Struct_SoundIoChannelLayout,
    pub software_latency: ::std::os::raw::c_double,
    pub userdata: *mut ::std::os::raw::c_void,
    pub write_callback: ::std::option::Option<unsafe extern "C" fn(arg1:
                                                                       *mut Struct_SoundIoOutStream,
                                                                   frame_count_min:
                                                                       c_int,
                                                                   frame_count_max:
                                                                       c_int)>,
    pub underflow_callback: ::std::option::Option<unsafe extern "C" fn(arg1:
                                                                           *mut Struct_SoundIoOutStream)>,
    pub error_callback: ::std::option::Option<unsafe extern "C" fn(arg1:
                                                                       *mut Struct_SoundIoOutStream,
                                                                   err:
                                                                       c_int)>,
    pub name: *const c_char,
    pub non_terminal_hint: u8,
    pub bytes_per_frame: c_int,
    pub bytes_per_sample: c_int,
    pub layout_error: c_int,
}
impl ::std::clone::Clone for Struct_SoundIoOutStream {
    fn clone(&self) -> Self {
        *self
    }
}
impl ::std::default::Default for Struct_SoundIoOutStream {
    fn default() -> Self {
        unsafe { ::std::mem::zeroed() }
    }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_SoundIoInStream {
    pub device: *mut Struct_SoundIoDevice,
    pub format: Enum_SoundIoFormat,
    pub sample_rate: c_int,
    pub layout: Struct_SoundIoChannelLayout,
    pub software_latency: ::std::os::raw::c_double,
    pub userdata: *mut ::std::os::raw::c_void,
    pub read_callback: ::std::option::Option<unsafe extern "C" fn(arg1:
                                                                      *mut Struct_SoundIoInStream,
                                                                  frame_count_min:
                                                                      c_int,
                                                                  frame_count_max:
                                                                      c_int)>,
    pub overflow_callback: ::std::option::Option<unsafe extern "C" fn(arg1:
                                                                          *mut Struct_SoundIoInStream)>,
    pub error_callback: ::std::option::Option<unsafe extern "C" fn(arg1:
                                                                       *mut Struct_SoundIoInStream,
                                                                   err:
                                                                       c_int)>,
    pub name: *const c_char,
    pub non_terminal_hint: u8,
    pub bytes_per_frame: c_int,
    pub bytes_per_sample: c_int,
    pub layout_error: c_int,
}
impl ::std::clone::Clone for Struct_SoundIoInStream {
    fn clone(&self) -> Self {
        *self
    }
}
impl ::std::default::Default for Struct_SoundIoInStream {
    fn default() -> Self {
        unsafe { ::std::mem::zeroed() }
    }
}
pub enum Struct_SoundIoRingBuffer { }

#[link(name = "soundio")]
extern "C" {
    pub fn soundio_create() -> *mut Struct_SoundIo;
    pub fn soundio_destroy(soundio: *mut Struct_SoundIo);
    pub fn soundio_connect(soundio: *mut Struct_SoundIo) -> Enum_SoundIoError;
    pub fn soundio_connect_backend(soundio: *mut Struct_SoundIo,
                                   backend: Enum_SoundIoBackend)
                                   -> Enum_SoundIoError;
    pub fn soundio_disconnect(soundio: *mut Struct_SoundIo);
    pub fn soundio_strerror(error: Enum_SoundIoError) -> *const c_char;
    pub fn soundio_backend_name(backend: Enum_SoundIoBackend) -> *const c_char;
    pub fn soundio_backend_count(soundio: *mut Struct_SoundIo) -> c_int;
    pub fn soundio_get_backend(soundio: *mut Struct_SoundIo, index: c_int) -> Enum_SoundIoBackend;
    pub fn soundio_have_backend(backend: Enum_SoundIoBackend) -> u8;
    pub fn soundio_flush_events(soundio: *mut Struct_SoundIo);
    pub fn soundio_wait_events(soundio: *mut Struct_SoundIo);
    pub fn soundio_wakeup(soundio: *mut Struct_SoundIo);
    pub fn soundio_force_device_scan(soundio: *mut Struct_SoundIo);
    pub fn soundio_channel_layout_equal(a: *const Struct_SoundIoChannelLayout,
                                        b: *const Struct_SoundIoChannelLayout)
                                        -> u8;
    pub fn soundio_get_channel_name(id: Enum_SoundIoChannelId) -> *const c_char;
    pub fn soundio_parse_channel_id(str: *const c_char, str_len: c_int) -> Enum_SoundIoChannelId;
    pub fn soundio_channel_layout_builtin_count() -> c_int;
    pub fn soundio_channel_layout_get_builtin(index: c_int) -> *const Struct_SoundIoChannelLayout;
    pub fn soundio_channel_layout_get_default(channel_count: c_int)
                                              -> *const Struct_SoundIoChannelLayout;
    pub fn soundio_channel_layout_find_channel(layout: *const Struct_SoundIoChannelLayout,
                                               channel: Enum_SoundIoChannelId)
                                               -> c_int;
    pub fn soundio_channel_layout_detect_builtin(layout: *mut Struct_SoundIoChannelLayout) -> u8;
    pub fn soundio_best_matching_channel_layout(preferred_layouts:
                                                    *const Struct_SoundIoChannelLayout,
                                                preferred_layout_count:
                                                    c_int,
                                                available_layouts:
                                                    *const Struct_SoundIoChannelLayout,
                                                available_layout_count:
                                                    c_int)
     -> *const Struct_SoundIoChannelLayout;
    pub fn soundio_sort_channel_layouts(layouts: *mut Struct_SoundIoChannelLayout,
                                        layout_count: c_int);
    pub fn soundio_get_bytes_per_sample(format: Enum_SoundIoFormat) -> c_int;
    pub fn soundio_format_string(format: Enum_SoundIoFormat) -> *const c_char;
    pub fn soundio_input_device_count(soundio: *mut Struct_SoundIo) -> c_int;
    pub fn soundio_output_device_count(soundio: *mut Struct_SoundIo) -> c_int;
    pub fn soundio_get_input_device(soundio: *mut Struct_SoundIo,
                                    index: c_int)
                                    -> *mut Struct_SoundIoDevice;
    pub fn soundio_get_output_device(soundio: *mut Struct_SoundIo,
                                     index: c_int)
                                     -> *mut Struct_SoundIoDevice;
    pub fn soundio_default_input_device_index(soundio: *mut Struct_SoundIo) -> c_int;
    pub fn soundio_default_output_device_index(soundio: *mut Struct_SoundIo) -> c_int;
    pub fn soundio_device_ref(device: *mut Struct_SoundIoDevice);
    pub fn soundio_device_unref(device: *mut Struct_SoundIoDevice);
    pub fn soundio_device_equal(a: *const Struct_SoundIoDevice,
                                b: *const Struct_SoundIoDevice)
                                -> u8;
    pub fn soundio_device_sort_channel_layouts(device: *mut Struct_SoundIoDevice);
    pub fn soundio_device_supports_format(device: *mut Struct_SoundIoDevice,
                                          format: Enum_SoundIoFormat)
                                          -> u8;
    pub fn soundio_device_supports_layout(device: *mut Struct_SoundIoDevice,
                                          layout: *const Struct_SoundIoChannelLayout)
                                          -> u8;
    pub fn soundio_device_supports_sample_rate(device: *mut Struct_SoundIoDevice,
                                               sample_rate: c_int)
                                               -> u8;
    pub fn soundio_device_nearest_sample_rate(device: *mut Struct_SoundIoDevice,
                                              sample_rate: c_int)
                                              -> c_int;
    pub fn soundio_outstream_create(device: *mut Struct_SoundIoDevice)
                                    -> *mut Struct_SoundIoOutStream;
    pub fn soundio_outstream_destroy(outstream: *mut Struct_SoundIoOutStream);
    pub fn soundio_outstream_open(outstream: *mut Struct_SoundIoOutStream) -> c_int;
    pub fn soundio_outstream_start(outstream: *mut Struct_SoundIoOutStream) -> c_int;
    pub fn soundio_outstream_begin_write(outstream: *mut Struct_SoundIoOutStream,
                                         areas: *mut *mut Struct_SoundIoChannelArea,
                                         frame_count: *mut c_int)
                                         -> c_int;
    pub fn soundio_outstream_end_write(outstream: *mut Struct_SoundIoOutStream) -> c_int;
    pub fn soundio_outstream_clear_buffer(outstream: *mut Struct_SoundIoOutStream) -> c_int;
    pub fn soundio_outstream_pause(outstream: *mut Struct_SoundIoOutStream, pause: u8) -> c_int;
    pub fn soundio_outstream_get_latency(outstream: *mut Struct_SoundIoOutStream,
                                         out_latency: *mut ::std::os::raw::c_double)
                                         -> c_int;
    pub fn soundio_instream_create(device: *mut Struct_SoundIoDevice) -> *mut Struct_SoundIoInStream;
    pub fn soundio_instream_destroy(instream: *mut Struct_SoundIoInStream);
    pub fn soundio_instream_open(instream: *mut Struct_SoundIoInStream) -> c_int;
    pub fn soundio_instream_start(instream: *mut Struct_SoundIoInStream) -> c_int;
    pub fn soundio_instream_begin_read(instream: *mut Struct_SoundIoInStream,
                                       areas: *mut *mut Struct_SoundIoChannelArea,
                                       frame_count: *mut c_int)
                                       -> c_int;
    pub fn soundio_instream_end_read(instream: *mut Struct_SoundIoInStream) -> c_int;
    pub fn soundio_instream_pause(instream: *mut Struct_SoundIoInStream, pause: u8) -> c_int;
    pub fn soundio_instream_get_latency(instream: *mut Struct_SoundIoInStream,
                                        out_latency: *mut ::std::os::raw::c_double)
                                        -> c_int;
    pub fn soundio_ring_buffer_create(soundio: *mut Struct_SoundIo,
                                      requested_capacity: c_int)
                                      -> *mut Struct_SoundIoRingBuffer;
    pub fn soundio_ring_buffer_destroy(ring_buffer: *mut Struct_SoundIoRingBuffer);
    pub fn soundio_ring_buffer_capacity(ring_buffer: *mut Struct_SoundIoRingBuffer) -> c_int;
    pub fn soundio_ring_buffer_write_ptr(ring_buffer: *mut Struct_SoundIoRingBuffer) -> *mut c_char;
    pub fn soundio_ring_buffer_advance_write_ptr(ring_buffer: *mut Struct_SoundIoRingBuffer,
                                                 count: c_int);
    pub fn soundio_ring_buffer_read_ptr(ring_buffer: *mut Struct_SoundIoRingBuffer) -> *mut c_char;
    pub fn soundio_ring_buffer_advance_read_ptr(ring_buffer: *mut Struct_SoundIoRingBuffer,
                                                count: c_int);
    pub fn soundio_ring_buffer_fill_count(ring_buffer: *mut Struct_SoundIoRingBuffer) -> c_int;
    pub fn soundio_ring_buffer_free_count(ring_buffer: *mut Struct_SoundIoRingBuffer) -> c_int;
    pub fn soundio_ring_buffer_clear(ring_buffer: *mut Struct_SoundIoRingBuffer);
}
<|endoftext|>


<commit_before><commit_msg>added check for line already in history file<commit_after><|endoftext|>


<commit_before><commit_msg>Added frame count<commit_after><|endoftext|>


<commit_before><commit_msg>add_history_persist<commit_after><|endoftext|>


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


<commit_before><commit_msg>Auto merge of #228 - servo:doc-examples, r=SimonSapin<commit_after><|endoftext|>


<commit_before><commit_msg>Make whatwg_scheme_type_mapper() public.<commit_after><|endoftext|>


<commit_before><commit_msg>Simplify encode_digest.<commit_after><|endoftext|>


<commit_before><commit_msg>start exploring implementation possibilities<commit_after>#![crate_name = "tcc"]
#![crate_type = "lib"]

#[test]
fn it_works() {
}

struct Date {
    year: i64,
    month: i8,
    day: i8,
    hour: i8,
    minute: i8,
    second: i8,
    nano_second: i32,
    year_base: u64,
    mod_quarter: i64,
    mod_month: i64,
    mod_week: i64,
    mod_day: i64,
    mod_hour: i64,
    mod_minute: i64,
    mod_second: i64,
}
<|endoftext|>


<commit_before><commit_msg>Rename Entry and EntryTable to EntryInfo and EntryInfoTable respectively<commit_after><|endoftext|>


<commit_before><commit_msg>Avoid re-parsing in Url::from_file_path<commit_after><|endoftext|>


<commit_before><commit_msg>Exit safely<commit_after><|endoftext|>


<commit_before><commit_msg>WIP: server<commit_after><|endoftext|>


<commit_before><commit_msg>examples: add raw_atomic_drm<commit_after>#![warn(rust_2018_idioms)]

#[macro_use]
extern crate slog;

use slog::Drain;
use smithay::{
    backend::drm::{
        atomic::{AtomicDrmDevice, AtomicDrmSurface},
        common::Error,
        device_bind, Device, DeviceHandler, RawSurface, Surface,
    },
    reexports::{
        calloop::EventLoop,
        drm::{
            buffer::format::PixelFormat,
            control::{
                connector::State as ConnectorState, crtc, dumbbuffer::DumbBuffer, framebuffer, property,
                Device as ControlDevice, ResourceHandle,
            },
        },
    },
};
use std::{
    fs::{File, OpenOptions},
    io::Error as IoError,
    rc::Rc,
    sync::Mutex,
};

fn get_property_by_name<'a, D: ControlDevice, T: ResourceHandle>(
    dev: &'a D,
    handle: T,
    name: &'static str,
) -> Option<(property::ValueType, property::RawValue)> {
    let props = dev.get_properties(handle).expect("Could not get props");
    let (ids, vals) = props.as_props_and_values();
    for (&id, &val) in ids.iter().zip(vals.iter()) {
        let info = dev.get_property(id).unwrap();
        if info.name().to_str().map(|x| x == name).unwrap_or(false) {
            let val_ty = info.value_type();
            return Some((val_ty, val));
        }
    }
    None
}

fn main() {
    let log = slog::Logger::root(Mutex::new(slog_term::term_full().fuse()).fuse(), o!());

    /*
     * Initialize the drm backend
     */

    // "Find" a suitable drm device
    let mut options = OpenOptions::new();
    options.read(true);
    options.write(true);
    let mut device = AtomicDrmDevice::new(options.open("/dev/dri/card0").unwrap(), log.clone()).unwrap();

    // Get a set of all modesetting resource handles (excluding planes):
    let res_handles = Device::resource_handles(&device).unwrap();

    // Use first connected connector
    let connector_info = res_handles
        .connectors()
        .iter()
        .map(|conn| device.get_connector_info(*conn).unwrap())
        .find(|conn| conn.state() == ConnectorState::Connected)
        .unwrap();

    // use the connected crtc if any
    let (val_ty, raw) = get_property_by_name(&device, connector_info.handle(), "CRTC_ID").unwrap();
    let crtc = match val_ty.convert_value(raw) {
        property::Value::CRTC(Some(handle)) => handle,
        property::Value::CRTC(None) => {
            // Use the first encoder
            let encoder = connector_info
                .encoders()
                .iter()
                .filter_map(|&e| e)
                .next()
                .unwrap();
            let encoder_info = device.get_encoder_info(encoder).unwrap();

            *res_handles
                .filter_crtcs(encoder_info.possible_crtcs())
                .iter()
                .next()
                .unwrap()
        }
        _ => unreachable!("CRTC_ID does not return another property type"),
    };

    // Assuming we found a good connector and loaded the info into `connector_info`
    let mode = connector_info.modes()[0]; // Use first mode (usually highest resoltion, but in reality you should filter and sort and check and match with other connectors, if you use more then one.)

    // Initialize the hardware backend
    let surface = Rc::new(device.create_surface(crtc).unwrap());
    surface.set_connectors(&[connector_info.handle()]).unwrap();
    surface.use_mode(Some(mode)).unwrap();

    for conn in surface.current_connectors().into_iter() {
        if conn != connector_info.handle() {
            surface.remove_connector(conn).unwrap();
        }
    }
    surface.add_connector(connector_info.handle()).unwrap();

    /*
     * Lets create buffers and framebuffers.
     * We use drm-rs DumbBuffers, because they always work and require little to no setup.
     * But they are very slow, this is just for demonstration purposes.
     */
    let (w, h) = mode.size();
    let front_buffer = device
        .create_dumb_buffer((w as u32, h as u32), PixelFormat::XRGB8888)
        .unwrap();
    let front_framebuffer = device.add_framebuffer(&front_buffer).unwrap();
    let back_buffer = device
        .create_dumb_buffer((w as u32, h as u32), PixelFormat::XRGB8888)
        .unwrap();
    let back_framebuffer = device.add_framebuffer(&back_buffer).unwrap();

    device.set_handler(DrmHandlerImpl {
        current: front_framebuffer,
        front: (front_buffer, front_framebuffer),
        back: (back_buffer, back_framebuffer),
        surface: surface.clone(),
    });

    /*
     * Register the DrmDevice on the EventLoop
     */
    let mut event_loop = EventLoop::<()>::new().unwrap();
    let _source = device_bind(&event_loop.handle(), device)
        .map_err(|err| -> IoError { err.into() })
        .unwrap();

    // Start rendering
    if surface.commit_pending() {
        surface.commit(front_framebuffer).unwrap();
    }

    // Run
    event_loop.run(None, &mut (), |_| {}).unwrap();
}

pub struct DrmHandlerImpl {
    front: (DumbBuffer, framebuffer::Handle),
    back: (DumbBuffer, framebuffer::Handle),
    current: framebuffer::Handle,
    surface: Rc<AtomicDrmSurface<File>>,
}

impl DeviceHandler for DrmHandlerImpl {
    type Device = AtomicDrmDevice<File>;

    fn vblank(&mut self, _crtc: crtc::Handle) {
        {
            // Swap and map buffer
            let mut mapping = if self.current == self.front.1 {
                self.current = self.back.1;
                self.surface.map_dumb_buffer(&mut self.back.0).unwrap()
            } else {
                self.current = self.front.1;
                self.surface.map_dumb_buffer(&mut self.front.0).unwrap()
            };

            // now we could render to the mapping via software rendering.
            // this example just sets some grey color

            for x in mapping.as_mut() {
                *x = 128;
            }
        }
        RawSurface::page_flip(&*self.surface, self.current).unwrap();
    }

    fn error(&mut self, error: Error) {
        panic!("{:?}", error);
    }
}
<|endoftext|>


<commit_before><commit_msg>rustfmt.<commit_after><|endoftext|>


<commit_before><commit_msg>Add an example<commit_after>extern crate blip_buf;

use blip_buf::BlipBuf;

const CLOCK_RATE : f64 = 1000000.0;
const SAMPLE_RATE : u32 = 48000;

fn main() {
    let mut blip = BlipBuf::new(SAMPLE_RATE as i32 / 10);
    blip.set_rates(CLOCK_RATE, SAMPLE_RATE as f64 );

    let mut time  = 0;      // number of clocks until next wave delta
    let mut delta = 10000;  // amplitude of next delta
    let mut period = 400;   // clocks between deltas

    for _n in 0..60 {
        // Slowly lower pitch every frame
        period = period + 3;

        // Generate 1/60 second of input clocks. We could generate
        // any number of clocks here, all the way down to 1.
        let clocks = CLOCK_RATE as i32 / 60;
        while time < clocks
        {
            blip.add_delta( time as u32, delta );
            delta = -delta; // square wave deltas alternate sign
            time = time + period;
        }

        // Add those clocks to buffer and adjust time for next frame
        time = time - clocks;
        blip.end_frame( clocks as u32 );

        // Read and play any output samples now available
        while blip.samples_avail() > 0
        {
            let mut temp = &mut [0i16; 1024];
            let count = blip.read_samples( temp, false );
            play_samples( &temp[..(count as usize)] );
        }
    }

    // wait until the sound finishes
    std::thread::sleep_ms(1000);
}

fn play_samples(_buf: &[i16]) {
    // play contents of _buf
}
<|endoftext|>


<commit_before><commit_msg>Frame Check Sequence (FCS)<commit_after>//! Frame Check Sequence
//!
//! The FCS is a sequence of 16 bits used for checking the integrity of a
//! received frame.
//!
//! Derived from [casebeer/afsk](https://github.com/casebeer/afsk)
//!
//! Copyright (c) 2013 Christopher H. Casebeer. All rights reserved.

use byteorder::{ByteOrder, LittleEndian};
use bit_vec::BitVec;

pub struct FCS {
    fcs: u16,
}

impl FCS {
    pub fn new() -> FCS {
        FCS {
            fcs: 0xFFFF
        }
    }
    pub fn update_bit(&mut self, bit: bool) {
        let check: bool = self.fcs & 0x1 == 1;
        self.fcs = self.fcs >> 1;
        if check != bit {
            self.fcs = self.fcs ^ 0x8408_u16;
        }
    }
    pub fn update_bytes(&mut self, bytes: &[u8]) {
        for byte in bytes {
            for i in (0..8).rev() {
                // pass each bit of u8 from left->right (true/false)
                self.update_bit(((byte >> i) & 0x01_u8) == 1_u8);
            }
        }
    }
    pub fn digest(&self) -> Vec<u8> {
        // Two bytes (u16), little endian
        let mut ret: Vec<u8> = Vec::new();
        LittleEndian::write_u16(&mut ret, !self.fcs % ::std::u16::MAX);
        ret
    }
}

pub fn fcs(bits: Vec<bool>) -> Vec<bool> {
    let mut fcs_sum: Vec<bool> = Vec::new();
    let mut fcs = FCS::new();
    for bit in &bits {
        fcs.update_bit(*bit);
    }
    fcs_sum.extend(&bits);

    // little-bit-endian in addition to little-byte-endian
    let mut bit_vec: Vec<u8> = Vec::new();
    for byte in fcs.digest().iter() {
        bit_vec.push(reverse_bits(*byte));
    }
    fcs_sum.extend(BitVec::from_bytes(&bit_vec));

    fcs_sum
}

pub fn fcs_validate(bits: Vec<bool>) -> Result<bool, String> {
    let mut buffer: Vec<bool> = Vec::new();
    let mut fcs = FCS::new();

    for bit in bits {
        buffer.push(bit);
        if buffer.len() > 16 {
            buffer = {
                let (first, seq) = buffer.split_at(1);
                fcs.update_bit(first[0]);
                seq.to_vec()
            };
        }
    }
    let mut _buffer: BitVec = BitVec::new();
    _buffer.extend(buffer.into_iter());

    if fcs.digest() != _buffer.to_bytes() {
        return Err(String::from("Invalid FCS"));
    }
    return Ok(true);
}

fn reverse_bits(bits: u8) -> u8 {
    // From https://graphics.stanford.edu/~seander/bithacks.html#BitReverseObvious
    let mut r: u8 = bits; // reversed bits of v; first get LSB of bits
    let mut s: u8 = 7;    // shift amount at end
    for i in 1..8 {
        let v: u8 = bits >> i;
        if v != 0 {
            r = r << 1;
            r = r | (v & 1);
            s = s - 1;
        }
    }
    r << s                // shift when bits' highest bits are 0
}
<|endoftext|>


<commit_before>use redox::Vec;

pub struct AvlNode<T> {
    value: T,
    left: Option<AvlNodeId>, // ID for left node
    right: Option<AvlNodeId>, // ID for right node
}

#[derive(Copy, Clone)]
pub struct AvlNodeId {
    index: usize,
    time_stamp: u64,
}

impl AvlNodeId {
    pub fn get<'a, T>(&self, avl: &'a Avl<T>) -> Option<&'a AvlNode<T>> {
        avl.nodes
           .get(self.index)
           .and_then(|slot| {
               if slot.time_stamp == self.time_stamp {
                   slot.node.as_ref()
               } else {
                   None
               }
           })
    }

    pub fn get_mut<'a, T>(&self, avl: &'a mut Avl<T>) -> Option<&'a mut AvlNode<T>> {
        avl.nodes
           .get_mut(self.index)
           .and_then(|slot| {
               if slot.time_stamp == self.time_stamp {
                   slot.node.as_mut()
               } else {
                   None
               }
           })
    }
}

pub struct Avl<T> {
    root: usize, // Index of the root node
    nodes: Vec<AvlSlot<T>>,
    free_list: Vec<usize>,
}

impl<T> Avl<T> {
    pub fn new() -> Self {
        Avl {
            root: 0,
            nodes: Vec::new(),
            free_list: Vec::new(),
        }
    }

    pub fn insert(&mut self, value: T) -> AvlNodeId {
        // TODO this is just a placeholder, we need to deal with all the fancy rotation stuff that
        // AVL trees do
        self.allocate_node(value)
    }

    // Performs a left rotation on a tree/subtree.
    // Returns the replace the specified node with
    fn rotate_left(&mut self, node: AvlNodeId) -> AvlNodeId {
        // Keep track of the original node positions
        // For a rotate left, the right child node must exist
        let r = node.get(self).unwrap().right.unwrap();
        let rl = r.get(self).unwrap().left;

        let ret = r;
        node.get_mut(self).unwrap().right = rl;
        ret.get_mut(self).unwrap().left = Some(node);

        ret
    }

    // Performs a right rotation on a tree/subtree.
    // Returns the replace the specified node with
    fn rotate_right(&mut self, node: AvlNodeId) -> AvlNodeId {
        // Keep track of the original node positions
        // For a rotate right, the left child node must exist
        let l = node.get(self).unwrap().left.unwrap();
        let lr = l.get(self).unwrap().right;

        let ret = l;
        node.get_mut(self).unwrap().left = lr;
        ret.get_mut(self).unwrap().right = Some(node);

        ret
    }

    // performs a left-right double rotation on a tree/subtree.
    fn rotate_leftright(&mut self, node: AvlNodeId) -> AvlNodeId {
        let l = node.get(self).unwrap().left.unwrap();
        let new_l = self.rotate_left(l); // Left node needs to exist
        node.get_mut(self).unwrap().left = Some(new_l);
        self.rotate_right(node)
    }

    // performs a right-left double rotation on a tree/subtree.
    fn rotate_rightleft(&mut self, node: AvlNodeId) -> AvlNodeId {
        let r = node.get(self).unwrap().right.unwrap();
        let new_r = self.rotate_right(r); // Right node needs to exist
        node.get_mut(self).unwrap().right = Some(new_r);
        self.rotate_left(node)
    }

    // _ins is the implementation of the binary tree insert function. Lesser values will be stored on
    // the left, while greater values will be stored on the right. No duplicates are allowed.
    /*fn _ins(&mut self, node_index: Option<AvlNodeId>, value: T) -> AvlNodeId {
        let node =
            match node_index {
                Some(node) => {
                    // Node exists, check which way to branch.
                    if n == node->val {
                        return node;
                    else if (n < node->val)
                        _ins(n, node->left);
                    else if (n > node->val)
                        _ins(n, node->right);
                },
                None => {
                    // The node doesn't exist, create it here.
                    self.allocate_node(value)
                },
            };

        rebalance(node);
    }*/

    // _rebalance rebalances the provided node
    /*fn rebalance(Node*& node) {
        if (!node)
        {
            return;
        }

        int balance = _height(node->left) - _height(node->right);
        if (balance == 2) // left
        {
            int lbalance = _height(node->left->left) - _height(node->left->right);
            if (lbalance == 0 || lbalance == 1) // left left - need to rotate right
            {
                rotate_right(node);
            }
            else if (lbalance == -1) // left right
            {
                rotate_leftright(node); // function name is just a coincidence
            }
        }
        else if (balance == -2) // right
        {
            int rbalance = _height(node->right->left) - _height(node->right->right);
            if (rbalance == 1) // right left
            {
                rotate_rightleft(node); // function name is just a coincidence
            }
            else if (rbalance == 0 || rbalance == -1) // right right - need to rotate left
            {
                rotate_left(node);
            }
        }
    }*/

    // height gets the height of a tree or subtree
    fn height(&self, node: Option<AvlNodeId>) -> i64 {
        match node {
            Some(node) => {
                let left_height = self.height(node.get(self).unwrap().left);
                let right_height = self.height(node.get(self).unwrap().right);

                if left_height > right_height {
                    left_height+1
                } else {
                    right_height+1
                }
            },
            None => { -1 },
        }
    }

    fn allocate_node(&mut self, value: T) -> AvlNodeId {
        match self.free_list.pop() {
            Some(index) => {
                AvlNodeId { time_stamp: self.nodes[index].time_stamp+1, index: index }
            },
            None => {
                // No free slots, create a new one
                let id = AvlNodeId { index: self.nodes.len(), time_stamp: 0 };
                self.nodes.push(AvlSlot { time_stamp: 0,
                                          node: Some(AvlNode { value: value, left: None, right: None }) });
                id
            },
        }
    }

    fn free_node(&mut self, id: AvlNodeId) -> AvlNode<T> {
        self.free_list.push(id.index);

        // NOTE: We unwrap here, because we trust that `id` points to a valid node, because
        // only we can create and free AvlNodes and their AvlNodeIds
        self.nodes[id.index].node.take().unwrap()
    }
}

struct AvlSlot<T> {
    time_stamp: u64,
    node: Option<AvlNode<T>>,
}
<commit_msg>AvlNodeId::get and AvlNodeId::try_get and mut<commit_after>use redox::Vec;

pub struct AvlNode<T> {
    value: T,
    left: Option<AvlNodeId>, // ID for left node
    right: Option<AvlNodeId>, // ID for right node
}

#[derive(Copy, Clone)]
pub struct AvlNodeId {
    index: usize,
    time_stamp: u64,
}

impl AvlNodeId {
    pub fn get<'a, T>(&self, avl: &'a Avl<T>) -> &'a AvlNode<T> {
        let ref slot = avl.nodes[self.index];
        if slot.time_stamp == self.time_stamp {
            slot.node.as_ref().unwrap()
        } else {
            panic!("AvlNodeId had invalid time_stamp");
        }
    }

    pub fn try_get<'a, T>(&self, avl: &'a Avl<T>) -> Option<&'a AvlNode<T>> {
        avl.nodes
           .get(self.index)
           .and_then(|slot| {
               if slot.time_stamp == self.time_stamp {
                   slot.node.as_ref()
               } else {
                   None
               }
           })
    }

    pub fn get_mut<'a, T>(&self, avl: &'a mut Avl<T>) -> &'a mut AvlNode<T> {
        let ref mut slot = avl.nodes[self.index];
        if slot.time_stamp == self.time_stamp {
            slot.node.as_mut().unwrap()
        } else {
            panic!("AvlNodeId had invalid time_stamp");
        }
    }

    pub fn try_get_mut<'a, T>(&self, avl: &'a mut Avl<T>) -> Option<&'a mut AvlNode<T>> {
        avl.nodes
           .get_mut(self.index)
           .and_then(|slot| {
               if slot.time_stamp == self.time_stamp {
                   slot.node.as_mut()
               } else {
                   None
               }
           })
    }
}

pub struct Avl<T> {
    root: usize, // Index of the root node
    nodes: Vec<AvlSlot<T>>,
    free_list: Vec<usize>,
}

impl<T> Avl<T> {
    pub fn new() -> Self {
        Avl {
            root: 0,
            nodes: Vec::new(),
            free_list: Vec::new(),
        }
    }

    pub fn insert(&mut self, value: T) -> AvlNodeId {
        // TODO this is just a placeholder, we need to deal with all the fancy rotation stuff that
        // AVL trees do
        self.allocate_node(value)
    }

    // Performs a left rotation on a tree/subtree.
    // Returns the replace the specified node with
    fn rotate_left(&mut self, node: AvlNodeId) -> AvlNodeId {
        // Keep track of the original node positions
        // For a rotate left, the right child node must exist
        let r = node.get(self).right.unwrap();
        let rl = r.get(self).left;

        let ret = r;
        node.get_mut(self).right = rl;
        ret.get_mut(self).left = Some(node);

        ret
    }

    // Performs a right rotation on a tree/subtree.
    // Returns the replace the specified node with
    fn rotate_right(&mut self, node: AvlNodeId) -> AvlNodeId {
        // Keep track of the original node positions
        // For a rotate right, the left child node must exist
        let l = node.get(self).left.unwrap();
        let lr = l.get(self).right;

        let ret = l;
        node.get_mut(self).left = lr;
        ret.get_mut(self).right = Some(node);

        ret
    }

    // performs a left-right double rotation on a tree/subtree.
    fn rotate_leftright(&mut self, node: AvlNodeId) -> AvlNodeId {
        let l = node.get(self).left.unwrap();
        let new_l = self.rotate_left(l); // Left node needs to exist
        node.get_mut(self).left = Some(new_l);
        self.rotate_right(node)
    }

    // performs a right-left double rotation on a tree/subtree.
    fn rotate_rightleft(&mut self, node: AvlNodeId) -> AvlNodeId {
        let r = node.get(self).right.unwrap();
        let new_r = self.rotate_right(r); // Right node needs to exist
        node.get_mut(self).right = Some(new_r);
        self.rotate_left(node)
    }

    // _ins is the implementation of the binary tree insert function. Lesser values will be stored on
    // the left, while greater values will be stored on the right. No duplicates are allowed.
    /*fn _ins(&mut self, node_index: Option<AvlNodeId>, value: T) -> AvlNodeId {
        let node =
            match node_index {
                Some(node) => {
                    // Node exists, check which way to branch.
                    if n == node->val {
                        return node;
                    else if (n < node->val)
                        _ins(n, node->left);
                    else if (n > node->val)
                        _ins(n, node->right);
                },
                None => {
                    // The node doesn't exist, create it here.
                    self.allocate_node(value)
                },
            };

        rebalance(node);
    }*/

    // _rebalance rebalances the provided node
    /*fn rebalance(node: AvlNodeId) {
        if !node {
            return;
        }

        let balance = self.height(node.get(self).left) - self.height(node.right);
        if balance == 2 { // left
            let lbalance = self.height(node.left.left) - self.height(node.left.right);
            if lbalance == 0 || lbalance == 1 { // left left - need to rotate right
                rotate_right(node);
            } else if lbalance == -1 { // left right
                rotate_leftright(node); // function name is just a coincidence
            }
        }
        else if balance == -2 { // right
            let rbalance = _height(node->right->left) - _height(node->right->right);
            if rbalance == 1 { // right left
                rotate_rightleft(node); // function name is just a coincidence
            } else if (rbalance == 0 || rbalance == -1) { // right right - need to rotate left
                rotate_left(node);
            }
        }
    }*/

    // height gets the height of a tree or subtree
    fn height(&self, node: Option<AvlNodeId>) -> i64 {
        match node {
            Some(node) => {
                let left_height = self.height(node.get(self).left);
                let right_height = self.height(node.get(self).right);

                if left_height > right_height {
                    left_height+1
                } else {
                    right_height+1
                }
            },
            None => { -1 },
        }
    }

    fn allocate_node(&mut self, value: T) -> AvlNodeId {
        match self.free_list.pop() {
            Some(index) => {
                AvlNodeId { time_stamp: self.nodes[index].time_stamp+1, index: index }
            },
            None => {
                // No free slots, create a new one
                let id = AvlNodeId { index: self.nodes.len(), time_stamp: 0 };
                self.nodes.push(AvlSlot { time_stamp: 0,
                                          node: Some(AvlNode { value: value, left: None, right: None }) });
                id
            },
        }
    }

    fn free_node(&mut self, id: AvlNodeId) -> AvlNode<T> {
        self.free_list.push(id.index);

        // NOTE: We unwrap here, because we trust that `id` points to a valid node, because
        // only we can create and free AvlNodes and their AvlNodeIds
        self.nodes[id.index].node.take().unwrap()
    }
}

struct AvlSlot<T> {
    time_stamp: u64,
    node: Option<AvlNode<T>>,
}
<|endoftext|>


<commit_before>// Interior vector utility functions.

import option::{some, none};
import uint::next_power_of_two;
import ptr::addr_of;

native "rust-intrinsic" mod rusti {
    fn vec_len<T>(v: [T]) -> uint;
}

native "rust" mod rustrt {
    fn vec_reserve_shared<T>(&v: [mutable? T], n: uint);
    fn vec_from_buf_shared<T>(ptr: *T, count: uint) -> [T];
}

/// Reserves space for `n` elements in the given vector.
fn reserve<@T>(&v: [mutable? T], n: uint) {
    rustrt::vec_reserve_shared(v, n);
}

fn len<T>(v: [mutable? T]) -> uint { ret rusti::vec_len(v); }

type init_op<T> = fn(uint) -> T;

fn init_fn<@T>(op: init_op<T>, n_elts: uint) -> [T] {
    let v = [];
    reserve(v, n_elts);
    let i: uint = 0u;
    while i < n_elts { v += [op(i)]; i += 1u; }
    ret v;
}

// TODO: Remove me once we have slots.
fn init_fn_mut<@T>(op: init_op<T>, n_elts: uint) -> [mutable T] {
    let v = [mutable];
    reserve(v, n_elts);
    let i: uint = 0u;
    while i < n_elts { v += [mutable op(i)]; i += 1u; }
    ret v;
}

fn init_elt<@T>(t: T, n_elts: uint) -> [T] {
    let v = [];
    reserve(v, n_elts);
    let i: uint = 0u;
    while i < n_elts { v += [t]; i += 1u; }
    ret v;
}

// TODO: Remove me once we have slots.
fn init_elt_mut<@T>(t: T, n_elts: uint) -> [mutable T] {
    let v = [mutable];
    reserve(v, n_elts);
    let i: uint = 0u;
    while i < n_elts { v += [mutable t]; i += 1u; }
    ret v;
}

// FIXME: Possible typestate postcondition:
// len(result) == len(v) (needs issue #586)
fn to_mut<@T>(v: [T]) -> [mutable T] {
    let vres = [mutable];
    for t: T in v { vres += [mutable t]; }
    ret vres;
}

// Same comment as from_mut
fn from_mut<@T>(v: [mutable T]) -> [T] {
    let vres = [];
    for t: T in v { vres += [t]; }
    ret vres;
}

// Predicates
pure fn is_empty<T>(v: [mutable? T]) -> bool {
    // FIXME: This would be easier if we could just call len
    for t: T in v { ret false; }
    ret true;
}

pure fn is_not_empty<T>(v: [mutable? T]) -> bool { ret !is_empty(v); }

// Accessors

/// Returns the first element of a vector
fn head<@T>(v: [mutable? T]) : is_not_empty(v) -> T { ret v[0]; }

/// Returns all but the first element of a vector
fn tail<@T>(v: [mutable? T]) : is_not_empty(v) -> [mutable? T] {
    ret slice(v, 1u, len(v));
}

/// Returns the last element of `v`.
fn last<@T>(v: [mutable? T]) -> option::t<T> {
    if len(v) == 0u { ret none; }
    ret some(v[len(v) - 1u]);
}

/// Returns the last element of a non-empty vector `v`.
fn last_total<@T>(v: [mutable? T]) : is_not_empty(v) -> T {
    ret v[len(v) - 1u];
}

/// Returns a copy of the elements from [`start`..`end`) from `v`.
fn slice<@T>(v: [mutable? T], start: uint, end: uint) -> [T] {
    assert (start <= end);
    assert (end <= len(v));
    let result = [];
    reserve(result, end - start);
    let i = start;
    while i < end { result += [v[i]]; i += 1u; }
    ret result;
}

// TODO: Remove me once we have slots.
fn slice_mut<@T>(v: [mutable? T], start: uint, end: uint) -> [mutable T] {
    assert (start <= end);
    assert (end <= len(v));
    let result = [mutable];
    reserve(result, end - start);
    let i = start;
    while i < end { result += [mutable v[i]]; i += 1u; }
    ret result;
}

// Mutators

fn shift<@T>(&v: [mutable? T]) -> T {
    let ln = len::<T>(v);
    assert (ln > 0u);
    let e = v[0];
    v = slice::<T>(v, 1u, ln);
    ret e;
}

// TODO: Write this, unsafely, in a way that's not O(n).
fn pop<@T>(&v: [mutable? T]) -> T {
    let ln = len(v);
    assert (ln > 0u);
    ln -= 1u;
    let e = v[ln];
    v = slice(v, 0u, ln);
    ret e;
}

// TODO: More.

// Appending

/// Expands the given vector in-place by appending `n` copies of `initval`.
fn grow<@T>(&v: [T], n: uint, initval: T) {
    reserve(v, next_power_of_two(len(v) + n));
    let i: uint = 0u;
    while i < n { v += [initval]; i += 1u; }
}

// TODO: Remove me once we have slots.
fn grow_mut<@T>(&v: [mutable T], n: uint, initval: T) {
    reserve(v, next_power_of_two(len(v) + n));
    let i: uint = 0u;
    while i < n { v += [mutable initval]; i += 1u; }
}

/// Calls `f` `n` times and appends the results of these calls to the given
/// vector.
fn grow_fn<@T>(&v: [T], n: uint, init_fn: fn(uint) -> T) {
    reserve(v, next_power_of_two(len(v) + n));
    let i: uint = 0u;
    while i < n { v += [init_fn(i)]; i += 1u; }
}

/// Sets the element at position `index` to `val`. If `index` is past the end
/// of the vector, expands the vector by replicating `initval` to fill the
/// intervening space.
fn grow_set<@T>(&v: [mutable T], index: uint, initval: T, val: T) {
    if index >= len(v) { grow_mut(v, index - len(v) + 1u, initval); }
    v[index] = val;
}

// Functional utilities

fn map<@T, @U>(f: block(T) -> U, v: [mutable? T]) -> [U] {
    let result = [];
    reserve(result, len(v));
    for elem: T in v {
        let elem2 = elem; // satisfies alias checker
        result += [f(elem2)];
    }
    ret result;
}

fn map2<@T, @U, @V>(f: block(T, U) -> V, v0: [T], v1: [U]) -> [V] {
    let v0_len = len::<T>(v0);
    if v0_len != len::<U>(v1) { fail; }
    let u: [V] = [];
    let i = 0u;
    while i < v0_len { u += [f({ v0[i] }, { v1[i] })]; i += 1u; }
    ret u;
}

fn filter_map<@T, @U>(f: block(T) -> option::t<U>, v: [mutable? T]) -> [U] {
    let result = [];
    for elem: T in v {
        let elem2 = elem; // satisfies alias checker
        alt f(elem2) {
          none. {/* no-op */ }
          some(result_elem) { result += [result_elem]; }
        }
    }
    ret result;
}

fn filter<@T>(f: block(T) -> bool, v: [mutable? T]) -> [T] {
    let result = [];
    for elem: T in v {
        let elem2 = elem; // satisfies alias checker
        if f(elem2) {
            result += [elem2];
        }
    }
    ret result;
}

fn foldl<@T, @U>(p: block(U, T) -> U, z: U, v: [mutable? T]) -> U {
    let sz = len(v);
    if sz == 0u { ret z; }
    let first = v[0];
    let rest = slice(v, 1u, sz);
    ret p(foldl(p, z, rest), first);
}

fn any<T>(f: block(T) -> bool, v: [T]) -> bool {
    for elem: T in v { if f(elem) { ret true; } }
    ret false;
}

fn all<T>(f: block(T) -> bool, v: [T]) -> bool {
    for elem: T in v { if !f(elem) { ret false; } }
    ret true;
}

fn member<T>(x: T, v: [T]) -> bool {
    for elt: T in v { if x == elt { ret true; } }
    ret false;
}

fn count<T>(x: T, v: [mutable? T]) -> uint {
    let cnt = 0u;
    for elt: T in v { if x == elt { cnt += 1u; } }
    ret cnt;
}

fn find<@T>(f: block(T) -> bool, v: [T]) -> option::t<T> {
    for elt: T in v { if f(elt) { ret some(elt); } }
    ret none;
}

fn position<@T>(x: T, v: [T]) -> option::t<uint> {
    let i: uint = 0u;
    while i < len(v) { if x == v[i] { ret some::<uint>(i); } i += 1u; }
    ret none;
}

fn position_pred<T>(f: fn(T) -> bool, v: [T]) -> option::t<uint> {
    let i: uint = 0u;
    while i < len(v) { if f(v[i]) { ret some::<uint>(i); } i += 1u; }
    ret none;
}

pure fn same_length<T, U>(xs: [T], ys: [U]) -> bool {
    let xlen = unchecked{ vec::len(xs) };
    let ylen = unchecked{ vec::len(ys) };
    xlen == ylen
}

// FIXME: if issue #586 gets implemented, could have a postcondition
// saying the two result lists have the same length -- or, could
// return a nominal record with a constraint saying that, instead of
// returning a tuple (contingent on issue #869)
fn unzip<@T, @U>(v: [(T, U)]) -> ([T], [U]) {
    let as = [], bs = [];
    for (a, b) in v { as += [a]; bs += [b]; }
    ret (as, bs);
}

fn zip<@T, @U>(v: [T], u: [U]) : same_length(v, u) -> [(T, U)] {
    let zipped = [];
    let sz = len(v), i = 0u;
    assert (sz == len(u));
    while i < sz { zipped += [(v[i], u[i])]; i += 1u; }
    ret zipped;
}

// Swaps two elements in a vector
fn swap<@T>(v: [mutable T], a: uint, b: uint) {
    let t: T = v[a];
    v[a] = v[b];
    v[b] = t;
}

// In place vector reversal
fn reverse<@T>(v: [mutable T]) {
    let i: uint = 0u;
    let ln = len::<T>(v);
    while i < ln / 2u { swap(v, i, ln - i - 1u); i += 1u; }
}

// Functional vector reversal. Returns a reversed copy of v.
fn reversed<@T>(v: [T]) -> [T] {
    let rs: [T] = [];
    let i = len::<T>(v);
    if i == 0u { ret rs; } else { i -= 1u; }
    while i != 0u { rs += [v[i]]; i -= 1u; }
    rs += [v[0]];
    ret rs;
}

// Generating vecs.
fn enum_chars(start: u8, end: u8) : u8::le(start, end) -> [char] {
    let i = start;
    let r = [];
    while i <= end { r += [i as char]; i += 1u as u8; }
    ret r;
}

fn enum_uints(start: uint, end: uint) : uint::le(start, end) -> [uint] {
    let i = start;
    let r = [];
    while i <= end { r += [i]; i += 1u; }
    ret r;
}

// Iterate over a list with with the indexes
iter iter2<@T>(v: [T]) -> (uint, T) {
    let i = 0u;
    for x in v { put (i, x); i += 1u; }
}

mod unsafe {
    type vec_repr = {mutable fill: uint, mutable alloc: uint, data: u8};

    fn from_buf<@T>(ptr: *T, elts: uint) -> [T] {
        ret rustrt::vec_from_buf_shared(ptr, elts);
    }

    fn set_len<T>(&v: [T], new_len: uint) {
        let repr: **vec_repr = ::unsafe::reinterpret_cast(addr_of(v));
        (**repr).fill = new_len * sys::size_of::<T>();
    }

    fn to_ptr<T>(v: [T]) -> *T {
        let repr: **vec_repr = ::unsafe::reinterpret_cast(addr_of(v));
        ret ::unsafe::reinterpret_cast(addr_of((**repr).data));
    }
}

fn to_ptr<T>(v: [T]) -> *T { ret unsafe::to_ptr(v); }

// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<commit_msg>Mark vec::len as pure<commit_after>// Interior vector utility functions.

import option::{some, none};
import uint::next_power_of_two;
import ptr::addr_of;

native "rust-intrinsic" mod rusti {
    fn vec_len<T>(v: [T]) -> uint;
}

native "rust" mod rustrt {
    fn vec_reserve_shared<T>(&v: [mutable? T], n: uint);
    fn vec_from_buf_shared<T>(ptr: *T, count: uint) -> [T];
}

/// Reserves space for `n` elements in the given vector.
fn reserve<@T>(&v: [mutable? T], n: uint) {
    rustrt::vec_reserve_shared(v, n);
}

pure fn len<T>(v: [mutable? T]) -> uint { unchecked { rusti::vec_len(v) } }

type init_op<T> = fn(uint) -> T;

fn init_fn<@T>(op: init_op<T>, n_elts: uint) -> [T] {
    let v = [];
    reserve(v, n_elts);
    let i: uint = 0u;
    while i < n_elts { v += [op(i)]; i += 1u; }
    ret v;
}

// TODO: Remove me once we have slots.
fn init_fn_mut<@T>(op: init_op<T>, n_elts: uint) -> [mutable T] {
    let v = [mutable];
    reserve(v, n_elts);
    let i: uint = 0u;
    while i < n_elts { v += [mutable op(i)]; i += 1u; }
    ret v;
}

fn init_elt<@T>(t: T, n_elts: uint) -> [T] {
    let v = [];
    reserve(v, n_elts);
    let i: uint = 0u;
    while i < n_elts { v += [t]; i += 1u; }
    ret v;
}

// TODO: Remove me once we have slots.
fn init_elt_mut<@T>(t: T, n_elts: uint) -> [mutable T] {
    let v = [mutable];
    reserve(v, n_elts);
    let i: uint = 0u;
    while i < n_elts { v += [mutable t]; i += 1u; }
    ret v;
}

// FIXME: Possible typestate postcondition:
// len(result) == len(v) (needs issue #586)
fn to_mut<@T>(v: [T]) -> [mutable T] {
    let vres = [mutable];
    for t: T in v { vres += [mutable t]; }
    ret vres;
}

// Same comment as from_mut
fn from_mut<@T>(v: [mutable T]) -> [T] {
    let vres = [];
    for t: T in v { vres += [t]; }
    ret vres;
}

// Predicates
pure fn is_empty<T>(v: [mutable? T]) -> bool {
    // FIXME: This would be easier if we could just call len
    for t: T in v { ret false; }
    ret true;
}

pure fn is_not_empty<T>(v: [mutable? T]) -> bool { ret !is_empty(v); }

// Accessors

/// Returns the first element of a vector
fn head<@T>(v: [mutable? T]) : is_not_empty(v) -> T { ret v[0]; }

/// Returns all but the first element of a vector
fn tail<@T>(v: [mutable? T]) : is_not_empty(v) -> [mutable? T] {
    ret slice(v, 1u, len(v));
}

/// Returns the last element of `v`.
fn last<@T>(v: [mutable? T]) -> option::t<T> {
    if len(v) == 0u { ret none; }
    ret some(v[len(v) - 1u]);
}

/// Returns the last element of a non-empty vector `v`.
fn last_total<@T>(v: [mutable? T]) : is_not_empty(v) -> T {
    ret v[len(v) - 1u];
}

/// Returns a copy of the elements from [`start`..`end`) from `v`.
fn slice<@T>(v: [mutable? T], start: uint, end: uint) -> [T] {
    assert (start <= end);
    assert (end <= len(v));
    let result = [];
    reserve(result, end - start);
    let i = start;
    while i < end { result += [v[i]]; i += 1u; }
    ret result;
}

// TODO: Remove me once we have slots.
fn slice_mut<@T>(v: [mutable? T], start: uint, end: uint) -> [mutable T] {
    assert (start <= end);
    assert (end <= len(v));
    let result = [mutable];
    reserve(result, end - start);
    let i = start;
    while i < end { result += [mutable v[i]]; i += 1u; }
    ret result;
}

// Mutators

fn shift<@T>(&v: [mutable? T]) -> T {
    let ln = len::<T>(v);
    assert (ln > 0u);
    let e = v[0];
    v = slice::<T>(v, 1u, ln);
    ret e;
}

// TODO: Write this, unsafely, in a way that's not O(n).
fn pop<@T>(&v: [mutable? T]) -> T {
    let ln = len(v);
    assert (ln > 0u);
    ln -= 1u;
    let e = v[ln];
    v = slice(v, 0u, ln);
    ret e;
}

// TODO: More.

// Appending

/// Expands the given vector in-place by appending `n` copies of `initval`.
fn grow<@T>(&v: [T], n: uint, initval: T) {
    reserve(v, next_power_of_two(len(v) + n));
    let i: uint = 0u;
    while i < n { v += [initval]; i += 1u; }
}

// TODO: Remove me once we have slots.
fn grow_mut<@T>(&v: [mutable T], n: uint, initval: T) {
    reserve(v, next_power_of_two(len(v) + n));
    let i: uint = 0u;
    while i < n { v += [mutable initval]; i += 1u; }
}

/// Calls `f` `n` times and appends the results of these calls to the given
/// vector.
fn grow_fn<@T>(&v: [T], n: uint, init_fn: fn(uint) -> T) {
    reserve(v, next_power_of_two(len(v) + n));
    let i: uint = 0u;
    while i < n { v += [init_fn(i)]; i += 1u; }
}

/// Sets the element at position `index` to `val`. If `index` is past the end
/// of the vector, expands the vector by replicating `initval` to fill the
/// intervening space.
fn grow_set<@T>(&v: [mutable T], index: uint, initval: T, val: T) {
    if index >= len(v) { grow_mut(v, index - len(v) + 1u, initval); }
    v[index] = val;
}

// Functional utilities

fn map<@T, @U>(f: block(T) -> U, v: [mutable? T]) -> [U] {
    let result = [];
    reserve(result, len(v));
    for elem: T in v {
        let elem2 = elem; // satisfies alias checker
        result += [f(elem2)];
    }
    ret result;
}

fn map2<@T, @U, @V>(f: block(T, U) -> V, v0: [T], v1: [U]) -> [V] {
    let v0_len = len::<T>(v0);
    if v0_len != len::<U>(v1) { fail; }
    let u: [V] = [];
    let i = 0u;
    while i < v0_len { u += [f({ v0[i] }, { v1[i] })]; i += 1u; }
    ret u;
}

fn filter_map<@T, @U>(f: block(T) -> option::t<U>, v: [mutable? T]) -> [U] {
    let result = [];
    for elem: T in v {
        let elem2 = elem; // satisfies alias checker
        alt f(elem2) {
          none. {/* no-op */ }
          some(result_elem) { result += [result_elem]; }
        }
    }
    ret result;
}

fn filter<@T>(f: block(T) -> bool, v: [mutable? T]) -> [T] {
    let result = [];
    for elem: T in v {
        let elem2 = elem; // satisfies alias checker
        if f(elem2) {
            result += [elem2];
        }
    }
    ret result;
}

fn foldl<@T, @U>(p: block(U, T) -> U, z: U, v: [mutable? T]) -> U {
    let sz = len(v);
    if sz == 0u { ret z; }
    let first = v[0];
    let rest = slice(v, 1u, sz);
    ret p(foldl(p, z, rest), first);
}

fn any<T>(f: block(T) -> bool, v: [T]) -> bool {
    for elem: T in v { if f(elem) { ret true; } }
    ret false;
}

fn all<T>(f: block(T) -> bool, v: [T]) -> bool {
    for elem: T in v { if !f(elem) { ret false; } }
    ret true;
}

fn member<T>(x: T, v: [T]) -> bool {
    for elt: T in v { if x == elt { ret true; } }
    ret false;
}

fn count<T>(x: T, v: [mutable? T]) -> uint {
    let cnt = 0u;
    for elt: T in v { if x == elt { cnt += 1u; } }
    ret cnt;
}

fn find<@T>(f: block(T) -> bool, v: [T]) -> option::t<T> {
    for elt: T in v { if f(elt) { ret some(elt); } }
    ret none;
}

fn position<@T>(x: T, v: [T]) -> option::t<uint> {
    let i: uint = 0u;
    while i < len(v) { if x == v[i] { ret some::<uint>(i); } i += 1u; }
    ret none;
}

fn position_pred<T>(f: fn(T) -> bool, v: [T]) -> option::t<uint> {
    let i: uint = 0u;
    while i < len(v) { if f(v[i]) { ret some::<uint>(i); } i += 1u; }
    ret none;
}

pure fn same_length<T, U>(xs: [T], ys: [U]) -> bool {
    vec::len(xs) == vec::len(ys)
}

// FIXME: if issue #586 gets implemented, could have a postcondition
// saying the two result lists have the same length -- or, could
// return a nominal record with a constraint saying that, instead of
// returning a tuple (contingent on issue #869)
fn unzip<@T, @U>(v: [(T, U)]) -> ([T], [U]) {
    let as = [], bs = [];
    for (a, b) in v { as += [a]; bs += [b]; }
    ret (as, bs);
}

fn zip<@T, @U>(v: [T], u: [U]) : same_length(v, u) -> [(T, U)] {
    let zipped = [];
    let sz = len(v), i = 0u;
    assert (sz == len(u));
    while i < sz { zipped += [(v[i], u[i])]; i += 1u; }
    ret zipped;
}

// Swaps two elements in a vector
fn swap<@T>(v: [mutable T], a: uint, b: uint) {
    let t: T = v[a];
    v[a] = v[b];
    v[b] = t;
}

// In place vector reversal
fn reverse<@T>(v: [mutable T]) {
    let i: uint = 0u;
    let ln = len::<T>(v);
    while i < ln / 2u { swap(v, i, ln - i - 1u); i += 1u; }
}

// Functional vector reversal. Returns a reversed copy of v.
fn reversed<@T>(v: [T]) -> [T] {
    let rs: [T] = [];
    let i = len::<T>(v);
    if i == 0u { ret rs; } else { i -= 1u; }
    while i != 0u { rs += [v[i]]; i -= 1u; }
    rs += [v[0]];
    ret rs;
}

// Generating vecs.
fn enum_chars(start: u8, end: u8) : u8::le(start, end) -> [char] {
    let i = start;
    let r = [];
    while i <= end { r += [i as char]; i += 1u as u8; }
    ret r;
}

fn enum_uints(start: uint, end: uint) : uint::le(start, end) -> [uint] {
    let i = start;
    let r = [];
    while i <= end { r += [i]; i += 1u; }
    ret r;
}

// Iterate over a list with with the indexes
iter iter2<@T>(v: [T]) -> (uint, T) {
    let i = 0u;
    for x in v { put (i, x); i += 1u; }
}

mod unsafe {
    type vec_repr = {mutable fill: uint, mutable alloc: uint, data: u8};

    fn from_buf<@T>(ptr: *T, elts: uint) -> [T] {
        ret rustrt::vec_from_buf_shared(ptr, elts);
    }

    fn set_len<T>(&v: [T], new_len: uint) {
        let repr: **vec_repr = ::unsafe::reinterpret_cast(addr_of(v));
        (**repr).fill = new_len * sys::size_of::<T>();
    }

    fn to_ptr<T>(v: [T]) -> *T {
        let repr: **vec_repr = ::unsafe::reinterpret_cast(addr_of(v));
        ret ::unsafe::reinterpret_cast(addr_of((**repr).data));
    }
}

fn to_ptr<T>(v: [T]) -> *T { ret unsafe::to_ptr(v); }

// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<|endoftext|>


<commit_before><commit_msg>playground/oses/pure-rust-os/rust_os/src/main.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Add a test for the pipe_in operation<commit_after>extern crate desync;
extern crate futures;

use desync::*;
use futures::stream;

use std::sync::*;
use std::thread;
use std::time::Duration;

#[test]
fn pipe_in_simple_stream() {
    // Create a stream
    let stream  = vec![1, 2, 3];
    let stream  = stream::iter_ok(stream);

    // Create an object for the stream to be piped into
    let obj     = Arc::new(Desync::new(vec![]));

    // Pipe the stream into the object
    pipe_in(Arc::clone(&obj), stream, |core: &mut Vec<Result<i32, ()>>, item| core.push(item));

    // Once the stream is drained, the core should contain Ok(1), Ok(2), Ok(3)
    thread::sleep(Duration::from_millis(100));
    assert!(obj.sync(|core| core.clone()) == vec![Ok(1), Ok(2), Ok(3)])
}
<|endoftext|>


<commit_before><commit_msg>added context support<commit_after>use super::data_store::DataStore;

pub struct Context<'a> {

    store: &'a DataStore

}
<|endoftext|>


<commit_before><commit_msg>Huge changes.<commit_after><|endoftext|>


<commit_before><commit_msg>Web init<commit_after>
// web interface of crates.fyi
//
// Database layout:
//
// Crate:
// * id
// * name
// * latest-version
// * authors
// * licence
// * repository
// * documentation
// * homepage
// * description
// * github stars
// * github forks
// * badges (travis etc)
// * keywords
// * issues
//
// Releases:
// * id
// * crate_id
// * version
// * dependencies
// * yanked
// * rustdoc_status
// * test_status
//
//-------------------------------------------------------------------------
// TODO:
// * I need to get name, versions, deps, yanked from crates.io-index
// * Rest of the fields must be taken from crates Cargo.toml
// * Need to write a parser to parse eiter
//   lib.rs, main.rs to get long description of crate.
//   If long description is not available, need to get long description
//   from README.md.
// * Need to write a parser to get travis and other (?) badges.
// * Need to write a github client to get stars, forks and issues.
//
// Dev steps are basically follows:
// * Read and understand iron and how to use it with postresql.
// * Crate a postgresql database.
// * Start working on database module.
<|endoftext|>


<commit_before><commit_msg>New example<commit_after>extern crate powerline;

use powerline::segments::*;
use powerline::part::*;

fn main() {

    let mut prompt = powerline::Powerline::new(powerline::theme::DEFAULT_THEME);

    prompt.add_segments(cwd::Cwd::new("~").get_segments().expect("Failed seg: Cwd"));
    prompt.add_segments(git::GitInfo::new().get_segments().expect("Failed seg: Git"));
    prompt.add_segments(readonly::ReadOnly::new("").get_segments().expect("Failed seg: ReadOnly"));
    prompt.add_segments(cmd::Cmd::new("$", "#").get_segments().expect("Failed seg: Cmd"));
    println!("{}", prompt);
}
<|endoftext|>


<commit_before><commit_msg>Added gpu.rs and first draft of emulate<commit_after>
pub struct GPU {
    mode: Mode,
    line: u32,
    cycles: u32,
}

impl GPU {
    pub fn new() -> GPU {
        GPU {
            mode: Mode::HBlank,
            line: 0,
            cycles: 0,
        }
    }

    /// Emulates the GPU.
    /// This function should be called after an instruction is executed by the CPU,
    /// `delta` is the number of cycles passed from the last instruction.
    pub fn emulate(&mut self, delta: u32) {

        self.cycles += delta;

        match self.mode {
            Mode::OAMRead => {
                if self.cycles >= 80 {
                    self.cycles = 0;
                    self.mode = Mode::VRAMRead;
                }
            }
            Mode::VRAMRead => {
                if self.cycles >= 172 {
                    self.cycles = 0;
                    self.mode = Mode::HBlank;

                    // TODO: scanline is done, write it to framebuffer
                }
            }
            Mode::HBlank => {
                if self.cycles >= 204 {
                    self.cycles = 0;
                    self.line += 1;

                    self.mode = if self.line == 143 {
                        Mode::VBlank
                    } else {
                        Mode::OAMRead
                    };
                }
            }
            Mode::VBlank => {
                if self.cycles >= 456 {
                    self.mode = Mode::HBlank;
                    self.line += 1;

                    if self.line > 153 {
                        self.mode = Mode::OAMRead;
                        self.line = 0;
                    }
                }
            }
        }
    }
}

enum Mode {
    OAMRead,
    VRAMRead,
    HBlank,
    VBlank,
}

/// The memory owned by the GPU
struct VideoMemory {
    data: [u8; 8192],
    oam: [u8; 160],
}<|endoftext|>