<commit_before>#![feature(std_misc, path, libc)]

extern crate libc;
extern crate sdl;

use std::ffi::CString;
use libc::{c_int};

use sdl::audio::{AudioFormat, Channels};
use sdl::video::ll::SDL_RWFromFile; // XXX refactoring
use sdl::get_error;

// Setup linking for all targets.
#[cfg(any(not(target_os = "macos"), not(mac_framework)))]
#[link(name = "SDL_mixer")]
extern {}

#[cfg(all(target_os = "macos", mac_framework))]
#[link(name = "SDL_mixer", kind = "framework")]
extern {}

pub mod ll {
    #![allow(non_camel_case_types)]

    use sdl::video::ll::SDL_RWops; // XXX refactoring

    use libc::c_int;

    #[repr(C)]
    #[derive(Copy)]
    pub struct Mix_Chunk {
        pub allocated: c_int,
        pub abuf: *mut u8,
        pub alen: u32,
        pub volume: u8,
    }

    extern "C" {
        pub fn Mix_OpenAudio(frequency: c_int, format: u16, channels: c_int, chunksize: c_int)
              -> c_int;
        pub fn Mix_QuerySpec(frequency: *mut c_int, format: *mut u16, channels: *mut c_int)
              -> c_int;
        pub fn Mix_LoadWAV_RW(src: *mut SDL_RWops, freesrc: c_int) -> *mut Mix_Chunk;
        pub fn Mix_FreeChunk(chunk: *mut Mix_Chunk);
        pub fn Mix_AllocateChannels(numchans: c_int) -> c_int;
        pub fn Mix_Playing(channel: c_int) -> c_int;
        pub fn Mix_PlayChannelTimed(channel: c_int, chunk: *mut Mix_Chunk, loops: c_int, ticks: c_int)
              -> c_int;
        pub fn Mix_GetChunk(channel: c_int) -> *mut Mix_Chunk;
        pub fn Mix_CloseAudio();
        pub fn Mix_Volume(channel: c_int, volume: c_int) -> c_int;
        pub fn Mix_ReserveChannels(num: c_int) -> c_int;
        pub fn Mix_GroupChannel(which: c_int, tag: c_int) -> c_int;
        pub fn Mix_GroupNewer(tag: c_int) -> c_int;
        pub fn Mix_HaltChannel(channel: c_int) -> c_int;
    }
}

pub struct Chunk {
    data: ChunkData
}

enum ChunkData {
    Borrowed(*mut ll::Mix_Chunk),
    Allocated(*mut ll::Mix_Chunk),
    OwnedBuffer(ChunkAndBuffer)
}

struct ChunkAndBuffer {
    pub buffer: Vec<u8>,
    pub ll_chunk: ll::Mix_Chunk
}

unsafe fn check_if_not_playing(ll_chunk_addr: *mut ll::Mix_Chunk) {
    // Verify that the chunk is not currently playing.
    //
    // TODO: I can't prove to myself that this is not racy, although I believe it is not
    // as long as all SDL calls are happening from the same thread. Somebody with better
    // knowledge of how SDL_mixer works internally should double check this, though.

    let mut frequency = 0;
    let mut format = 0;
    let mut channels = 0;
    if ll::Mix_QuerySpec(&mut frequency, &mut format, &mut channels) == 0 {
        channels = 0;
    }

    for ch in range(0, (channels as usize)) {
        if ll::Mix_GetChunk(ch as i32) == ll_chunk_addr {
            panic!("attempt to free a channel that's playing!")
        }
    }
}

impl Drop for Chunk {
    fn drop(&mut self) {
        unsafe {
            match self.data {
                ChunkData::Borrowed(_) => (),
                ChunkData::Allocated(ll_chunk) => {
                    check_if_not_playing(ll_chunk);
                    ll::Mix_FreeChunk(ll_chunk);
                },
                ChunkData::OwnedBuffer(ref mut chunk) => {
                    check_if_not_playing(&mut chunk.ll_chunk);
                }
            }
        }
    }
}

impl Chunk {
    pub fn new(mut buffer: Vec<u8>, volume: u8) -> Chunk {
        let buffer_addr: *mut u8 = buffer.as_mut_ptr();
        let buffer_len = buffer.len() as u32;
        Chunk {
            data: ChunkData::OwnedBuffer(
                ChunkAndBuffer {
                    buffer: buffer,
                    ll_chunk: ll::Mix_Chunk {
                        allocated: 0,
                        abuf: buffer_addr,
                        alen: buffer_len,
                        volume: volume
                    }
                }
            )
        }
    }

    pub fn from_wav(path: &Path) -> Result<Chunk, String> {
        let cpath = CString::from_slice(path.as_vec());
        let mode = CString::from_slice("rb".as_bytes());
        let raw = unsafe {
            ll::Mix_LoadWAV_RW(SDL_RWFromFile(cpath.as_ptr(), mode.as_ptr()), 1)
        };

        if raw.is_null() { Err(get_error()) }
        else { Ok(Chunk { data: ChunkData::Allocated(raw) }) }
    }

    pub fn to_ll_chunk(&self) -> *const ll::Mix_Chunk {
        match self.data {
            ChunkData::Borrowed(ll_chunk) => ll_chunk as *const _,
            ChunkData::Allocated(ll_chunk) => ll_chunk as *const _,
            ChunkData::OwnedBuffer(ref chunk) => {
                let ll_chunk: *const ll::Mix_Chunk = &chunk.ll_chunk;
                ll_chunk
            }
        }
    }

    pub fn to_mut_ll_chunk(&mut self) -> *mut ll::Mix_Chunk {
        match self.data {
            ChunkData::Borrowed(ll_chunk) => ll_chunk,
            ChunkData::Allocated(ll_chunk) => ll_chunk,
            ChunkData::OwnedBuffer(ref mut chunk) => {
                let ll_chunk: *mut ll::Mix_Chunk = &mut chunk.ll_chunk;
                ll_chunk
            }
        }
    }

    pub fn volume(&self) -> u8 {
        let ll_chunk: *const ll::Mix_Chunk = self.to_ll_chunk();
        unsafe { (*ll_chunk).volume }
    }

    pub fn play_timed(&mut self, channel: Option<c_int>, loops: c_int, ticks: c_int) -> c_int {
        unsafe {
            let ll_channel = match channel {
                None => -1,
                Some(channel) => channel,
            };
            ll::Mix_PlayChannelTimed(ll_channel, self.to_mut_ll_chunk(), loops, ticks)
        }
    }

    pub fn play(&mut self, channel: Option<c_int>, loops: c_int) -> c_int {
        self.play_timed(channel, loops, -1)
    }
}

pub fn open(frequency: c_int, format: AudioFormat, channels: Channels, chunksize: c_int)
         -> Result<(),()> {
    unsafe {
        if ll::Mix_OpenAudio(frequency, format.to_ll_format(), channels.count(), chunksize) == 0 {
            Ok(())
        } else {
            Err(())
        }
    }
}

pub fn close() {
    unsafe {
        ll::Mix_CloseAudio()
    }
}

#[derive(Copy)]
pub struct Query {
    pub frequency: c_int,
    pub format: AudioFormat,
    pub channels: Channels,
}

pub fn query() -> Option<Query> {
    unsafe {
        let mut frequency = 0;
        let mut ll_format = 0;
        let mut ll_channels = 0;
        if ll::Mix_QuerySpec(&mut frequency, &mut ll_format, &mut ll_channels) == 0 {
            return None;
        }
        Some(Query {
            frequency: frequency,
            format: AudioFormat::from_ll_format(ll_format),
            channels: if ll_channels == 1 { Channels::Mono } else { Channels::Stereo }
        })
    }
}

pub fn allocate_channels(numchans: c_int) -> c_int {
    unsafe {
        ll::Mix_AllocateChannels(numchans)
    }
}

pub fn playing(channel: Option<c_int>) -> bool {
    unsafe {
        match channel {
            Some(channel) => ll::Mix_Playing(channel) == 0,
            None => ll::Mix_Playing(-1) == 0
        }
    }
}

pub fn num_playing(channel: Option<c_int>) -> c_int {
    unsafe {
        match channel {
            Some(channel) => ll::Mix_Playing(channel),
            None => ll::Mix_Playing(-1)
        }
    }
}

pub fn get_channel_volume(channel: Option<c_int>) -> c_int {
    unsafe {
        let ll_channel = channel.unwrap_or(-1);
        ll::Mix_Volume(ll_channel, -1)
    }
}

pub fn set_channel_volume(channel: Option<c_int>, volume: c_int) {
    unsafe {
        let ll_channel = channel.unwrap_or(-1);
        ll::Mix_Volume(ll_channel, volume);
    }
}

pub fn reserve_channels(num: c_int) -> c_int {
    unsafe { ll::Mix_ReserveChannels(num) }
}

pub fn group_channel(which: Option<c_int>, tag: Option<c_int>) -> bool {
    unsafe {
        let ll_which = which.unwrap_or(-1);
        let ll_tag = tag.unwrap_or(-1);
        ll::Mix_GroupChannel(ll_which, ll_tag) != 0
    }
}

pub fn newest_in_group(tag: Option<c_int>) -> Option<c_int> {
    unsafe {
        let ll_tag = tag.unwrap_or(-1);
        let channel = ll::Mix_GroupNewer(ll_tag);
        if channel == -1 {None} else {Some(channel)}
    }
}

pub fn halt_channel(channel: c_int) -> c_int {
    unsafe {
        ll::Mix_HaltChannel(channel)
    }
}
<commit_msg>Added allow tags in mixer lib to remove warnings, also updated range notation.<commit_after>#![feature(std_misc, path, libc)]

extern crate libc;
extern crate sdl;

use std::ffi::CString;
use libc::{c_int};

use sdl::audio::{AudioFormat, Channels};
use sdl::video::ll::SDL_RWFromFile; // XXX refactoring
use sdl::get_error;

// Setup linking for all targets.
#[cfg(any(not(target_os = "macos"), not(mac_framework)))]
#[link(name = "SDL_mixer")]
extern {}

#[cfg(all(target_os = "macos", mac_framework))]
#[link(name = "SDL_mixer", kind = "framework")]
extern {}

pub mod ll {
    #![allow(non_camel_case_types)]

    use sdl::video::ll::SDL_RWops; // XXX refactoring

    use libc::c_int;

    #[allow(raw_pointer_derive)]
    #[repr(C)]
    #[derive(Copy)]
    pub struct Mix_Chunk {
        pub allocated: c_int,
        pub abuf: *mut u8,
        pub alen: u32,
        pub volume: u8,
    }

    extern "C" {
        pub fn Mix_OpenAudio(frequency: c_int, format: u16, channels: c_int, chunksize: c_int)
              -> c_int;
        pub fn Mix_QuerySpec(frequency: *mut c_int, format: *mut u16, channels: *mut c_int)
              -> c_int;
        pub fn Mix_LoadWAV_RW(src: *mut SDL_RWops, freesrc: c_int) -> *mut Mix_Chunk;
        pub fn Mix_FreeChunk(chunk: *mut Mix_Chunk);
        pub fn Mix_AllocateChannels(numchans: c_int) -> c_int;
        pub fn Mix_Playing(channel: c_int) -> c_int;
        pub fn Mix_PlayChannelTimed(channel: c_int, chunk: *mut Mix_Chunk, loops: c_int, ticks: c_int)
              -> c_int;
        pub fn Mix_GetChunk(channel: c_int) -> *mut Mix_Chunk;
        pub fn Mix_CloseAudio();
        pub fn Mix_Volume(channel: c_int, volume: c_int) -> c_int;
        pub fn Mix_ReserveChannels(num: c_int) -> c_int;
        pub fn Mix_GroupChannel(which: c_int, tag: c_int) -> c_int;
        pub fn Mix_GroupNewer(tag: c_int) -> c_int;
        pub fn Mix_HaltChannel(channel: c_int) -> c_int;
    }
}

pub struct Chunk {
    data: ChunkData
}

#[allow(unused)]
enum ChunkData {
    Borrowed(*mut ll::Mix_Chunk),
    Allocated(*mut ll::Mix_Chunk),
    OwnedBuffer(ChunkAndBuffer)
}

struct ChunkAndBuffer {
    pub buffer: Vec<u8>,
    pub ll_chunk: ll::Mix_Chunk
}

unsafe fn check_if_not_playing(ll_chunk_addr: *mut ll::Mix_Chunk) {
    // Verify that the chunk is not currently playing.
    //
    // TODO: I can't prove to myself that this is not racy, although I believe it is not
    // as long as all SDL calls are happening from the same thread. Somebody with better
    // knowledge of how SDL_mixer works internally should double check this, though.

    let mut frequency = 0;
    let mut format = 0;
    let mut channels = 0;
    if ll::Mix_QuerySpec(&mut frequency, &mut format, &mut channels) == 0 {
        channels = 0;
    }

    for ch in 0 .. (channels as usize) {
        if ll::Mix_GetChunk(ch as i32) == ll_chunk_addr {
            panic!("attempt to free a channel that's playing!")
        }
    }
}

impl Drop for Chunk {
    fn drop(&mut self) {
        unsafe {
            match self.data {
                ChunkData::Borrowed(_) => (),
                ChunkData::Allocated(ll_chunk) => {
                    check_if_not_playing(ll_chunk);
                    ll::Mix_FreeChunk(ll_chunk);
                },
                ChunkData::OwnedBuffer(ref mut chunk) => {
                    check_if_not_playing(&mut chunk.ll_chunk);
                }
            }
        }
    }
}

impl Chunk {
    pub fn new(mut buffer: Vec<u8>, volume: u8) -> Chunk {
        let buffer_addr: *mut u8 = buffer.as_mut_ptr();
        let buffer_len = buffer.len() as u32;
        Chunk {
            data: ChunkData::OwnedBuffer(
                ChunkAndBuffer {
                    buffer: buffer,
                    ll_chunk: ll::Mix_Chunk {
                        allocated: 0,
                        abuf: buffer_addr,
                        alen: buffer_len,
                        volume: volume
                    }
                }
            )
        }
    }

    pub fn from_wav(path: &Path) -> Result<Chunk, String> {
        let cpath = CString::from_slice(path.as_vec());
        let mode = CString::from_slice("rb".as_bytes());
        let raw = unsafe {
            ll::Mix_LoadWAV_RW(SDL_RWFromFile(cpath.as_ptr(), mode.as_ptr()), 1)
        };

        if raw.is_null() { Err(get_error()) }
        else { Ok(Chunk { data: ChunkData::Allocated(raw) }) }
    }

    pub fn to_ll_chunk(&self) -> *const ll::Mix_Chunk {
        match self.data {
            ChunkData::Borrowed(ll_chunk) => ll_chunk as *const _,
            ChunkData::Allocated(ll_chunk) => ll_chunk as *const _,
            ChunkData::OwnedBuffer(ref chunk) => {
                let ll_chunk: *const ll::Mix_Chunk = &chunk.ll_chunk;
                ll_chunk
            }
        }
    }

    pub fn to_mut_ll_chunk(&mut self) -> *mut ll::Mix_Chunk {
        match self.data {
            ChunkData::Borrowed(ll_chunk) => ll_chunk,
            ChunkData::Allocated(ll_chunk) => ll_chunk,
            ChunkData::OwnedBuffer(ref mut chunk) => {
                let ll_chunk: *mut ll::Mix_Chunk = &mut chunk.ll_chunk;
                ll_chunk
            }
        }
    }

    pub fn volume(&self) -> u8 {
        let ll_chunk: *const ll::Mix_Chunk = self.to_ll_chunk();
        unsafe { (*ll_chunk).volume }
    }

    pub fn play_timed(&mut self, channel: Option<c_int>, loops: c_int, ticks: c_int) -> c_int {
        unsafe {
            let ll_channel = match channel {
                None => -1,
                Some(channel) => channel,
            };
            ll::Mix_PlayChannelTimed(ll_channel, self.to_mut_ll_chunk(), loops, ticks)
        }
    }

    pub fn play(&mut self, channel: Option<c_int>, loops: c_int) -> c_int {
        self.play_timed(channel, loops, -1)
    }
}

pub fn open(frequency: c_int, format: AudioFormat, channels: Channels, chunksize: c_int)
         -> Result<(),()> {
    unsafe {
        if ll::Mix_OpenAudio(frequency, format.to_ll_format(), channels.count(), chunksize) == 0 {
            Ok(())
        } else {
            Err(())
        }
    }
}

pub fn close() {
    unsafe {
        ll::Mix_CloseAudio()
    }
}

#[derive(Copy)]
pub struct Query {
    pub frequency: c_int,
    pub format: AudioFormat,
    pub channels: Channels,
}

pub fn query() -> Option<Query> {
    unsafe {
        let mut frequency = 0;
        let mut ll_format = 0;
        let mut ll_channels = 0;
        if ll::Mix_QuerySpec(&mut frequency, &mut ll_format, &mut ll_channels) == 0 {
            return None;
        }
        Some(Query {
            frequency: frequency,
            format: AudioFormat::from_ll_format(ll_format),
            channels: if ll_channels == 1 { Channels::Mono } else { Channels::Stereo }
        })
    }
}

pub fn allocate_channels(numchans: c_int) -> c_int {
    unsafe {
        ll::Mix_AllocateChannels(numchans)
    }
}

pub fn playing(channel: Option<c_int>) -> bool {
    unsafe {
        match channel {
            Some(channel) => ll::Mix_Playing(channel) == 0,
            None => ll::Mix_Playing(-1) == 0
        }
    }
}

pub fn num_playing(channel: Option<c_int>) -> c_int {
    unsafe {
        match channel {
            Some(channel) => ll::Mix_Playing(channel),
            None => ll::Mix_Playing(-1)
        }
    }
}

pub fn get_channel_volume(channel: Option<c_int>) -> c_int {
    unsafe {
        let ll_channel = channel.unwrap_or(-1);
        ll::Mix_Volume(ll_channel, -1)
    }
}

pub fn set_channel_volume(channel: Option<c_int>, volume: c_int) {
    unsafe {
        let ll_channel = channel.unwrap_or(-1);
        ll::Mix_Volume(ll_channel, volume);
    }
}

pub fn reserve_channels(num: c_int) -> c_int {
    unsafe { ll::Mix_ReserveChannels(num) }
}

pub fn group_channel(which: Option<c_int>, tag: Option<c_int>) -> bool {
    unsafe {
        let ll_which = which.unwrap_or(-1);
        let ll_tag = tag.unwrap_or(-1);
        ll::Mix_GroupChannel(ll_which, ll_tag) != 0
    }
}

pub fn newest_in_group(tag: Option<c_int>) -> Option<c_int> {
    unsafe {
        let ll_tag = tag.unwrap_or(-1);
        let channel = ll::Mix_GroupNewer(ll_tag);
        if channel == -1 {None} else {Some(channel)}
    }
}

pub fn halt_channel(channel: c_int) -> c_int {
    unsafe {
        ll::Mix_HaltChannel(channel)
    }
}
<|endoftext|>


<commit_before><commit_msg>Add example docs  + Added example documentation for Stack  + Renamed `seax-svm` -> `seax_svm` because the dash character breaks imports sometimes<commit_after>#![crate_name = "seax_svm"]
#![crate_type = "lib"]
#![feature(box_syntax)]

/// Contains the Seax Virtual Machine (SVM) and miscellaneous
/// support code.
pub mod svm {
    use svm::slist::List;
    use svm::slist::Stack;
    use std::iter::IteratorExt;
    use std::fmt;

    /// Singly-linked list and stack implementations.
    ///
    /// `List<T>` is a singly-linked cons list with boxed items. `Stack<T>` is
    ///  defined as a trait providing stack operations(`push()`, `pop()`, and
    ///  `peek()`), and an implementation for `List`.
    pub mod slist {

        use svm::slist::List::{Cons,Nil};
        use std::fmt;
        use std::ops::Index;

        /// Common functions for an immutable Stack abstract data type.
        pub trait Stack<T> {

            /// Push an item to the top of the stack, returning a new stack
            fn push(self, item : T) -> Self;

            /// Pop the top element of the stack. Returns an Option on a T and
            /// a new Stack<T> to replace this.
            fn pop(self)            -> Option<(T, Self)>;

            /// Peek at the top item of the stack.
            ///
            /// Returns Some<T> if there is an item on top of the stack,
            /// and None if the stack is empty.
            fn peek(&self)          -> Option<&T>;

            /// Returns an empty stack.
            fn empty()              -> Self;
        }

        /// Stack implementation using a cons list
        impl<T> Stack<T> for List<T> {

            /// Push an item to the top of the stack, returning a new stack.
            ///
            /// # Examples:
            /// ```
            /// use seax_svm::svm::slist::{List,Stack};
            ///
            /// let mut s: List<isize> = Stack::empty();
            /// assert_eq!(s.peek(), None);
            /// s = s.push(1);
            /// assert_eq!(s.peek(), Some(&1));
            /// s = s.push(6);
            /// assert_eq!(s.peek(), Some(&6));
            /// ```
            fn push(self, item: T) -> List<T> {
                Cons(item, box self)
            }

            /// Pop the top element of the stack.
            ///
            /// Pop the top element of the stack. Returns an
            /// `Option<(T,List<T>)>` containing the top element and a new
            /// `List<T>` with that item removed, or `None` if the stack is
            /// empty.
            ///
            /// # Examples:
            /// ```
            /// use seax_svm::svm::slist::{List,Stack};
            ///
            /// let mut s: List<isize> = Stack::empty();
            /// s = s.push(2);
            /// s = s.push(1);
            /// let pop_result = s.pop().unwrap();
            /// s = pop_result.1;
            /// assert_eq!(s.peek(), Some(&2));
            /// assert_eq!(pop_result.0, 1);
            /// ```
            fn pop(self) -> Option<(T,List<T>)> {
                match self {
                    Cons(item, new_self)    => Some((item, *new_self)),
                    Nil                     => None
                }
            }

            fn empty() -> List<T> {
                Nil
            }

            /// Peek at the top element of the stack.
            ///
            /// Peek at the top element of the stack. Returns an `Option<&T>`
            /// with a borrowed pointer to the top element, or `None` if the
            /// stack is empty.
            ///
            /// # Examples:
            /// ```
            /// use seax_svm::svm::slist::{List,Stack};
            ///
            /// let mut s: List<isize> = Stack::empty();
            /// s = s.push(2);
            /// s = s.push(1);
            /// let pop_result = s.pop().unwrap();
            /// s = pop_result.1;
            /// assert_eq!(s.peek(), Some(&2));
            /// assert_eq!(pop_result.0, 1);
            /// ```
            fn peek(&self) -> Option<&T> {
                match self {
                    &Nil => None,
                    &Cons(ref it,_) => Some(it)
                }
            }

        }

        /// Singly-linked cons list.
        ///
        /// This is used internally to represent list primitives in the
        /// machine.
        #[derive(PartialEq,Clone,Debug)]
        pub enum List<T> {
            /// Cons cell containing a `T` and a link to the tail
            Cons(T, Box<List<T>>),
            /// The empty list.
            Nil,
        }

        /// Public implementation for List.
        impl<T> List<T> {

            /// Creates a new empty list
            pub fn new() -> List<T> {
                Nil
            }

            /// Prepends the given item to the list.
            ///
            /// Returns the list containing the new  head item.
            /// This is an O(1) operation.
            pub fn prepend(self, it: T) -> List<T> {
                Cons(it, box self)
            }

            /// Appends an item to the end of the list.
            ///
            /// This is an O(n) operation.
            pub fn append(self, it: T) {
                unimplemented!()
            }

            /// Returns the length of the list.
            pub fn length (&self) -> usize {
                match *self {
                    Cons(_, ref tail) => 1 + tail.length(),
                    Nil => 0
                }
            }

            /// Provide a forward iterator
            #[inline]
            pub fn iter<'a>(&'a self) -> ListIterator<'a, T> {
                ListIterator{current: self}
            }
        }

        impl<'a, T> fmt::Display for List<T> where T: fmt::Display{

            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                // TODO: replace toString with this
                match *self {
                    Cons(ref head, ref tail) => write!(f, "({}, {})", head, tail),
                    Nil => write!(f,"nil")
                }
            }
        }

        /// Wraps a List<T> to allow it to be used as an Iterator<T>
        pub struct ListIterator<'a, T:'a> {
            current: &'a List<T>
        }

        /// Implementation of Iterator for List. This allows iteration by
        /// link hopping.
        impl<'a, T> Iterator for ListIterator<'a, T> {
            type Item = &'a T;

            /// Get the next element from the list. Returns a Some<T>, or Nil
            /// if at the end of the list.
            fn next(&mut self) -> Option<&'a T> {
                match self.current {
                    &Cons(ref head, box ref tail) => { self.current = tail; Some(head) },
                    &Nil => None
                }
            }
        }

        impl<'a, T> ExactSizeIterator for ListIterator<'a, T> {
            fn len(&self) -> usize {
                self.current.length()
            }
        }

        impl<T> Index<usize> for List<T> {
            type Output = T;

            fn index<'a>(&'a self, _index: &usize) -> &'a T {
                let mut it = self.iter();
                for _ in 0..*_index-1 {
                    it.next();
                }
                it.next().unwrap()
            }
        }

        /// Convenience macro for making lists.
        ///
        /// # Example:
        ///
        /// ```
        /// use svm::slist;
        ///
        /// assert_eq!(
        ///     list!(1i32, 2i32, 3i32),
        ///     Cons(1i32, Box::new(Cons(2i32, Box::new(Cons(3i32, Box::new(Nil))))))
        ///     );
        /// ```
        macro_rules! list(
            ( $e:expr, $($rest:expr),+ ) => ( Cons($e, Box::new(list!( $( $rest ),+ )) ));
            ( $e:expr ) => ( Cons($e, Box::new(Nil)) );
            () => ( @Empty )
        );

        #[cfg(test)]
        mod tests {
            use super::{List, Stack};
            use super::List::{Cons,Nil};

            #[test]
            fn test_list_length() {
                let full_list: List<i32> = list!(1i32, 2i32, 3i32);
                let empty_list: List<i32> = List::new();
                assert_eq!(full_list.length(), 3);
                assert_eq!(empty_list.length(), 0);
            }

            #[test]
            fn test_list_to_string() {
                let l: List<i32> = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
                assert_eq!(l.to_string(), "(1, (2, (3, nil)))");
            }

            #[test]
            fn test_stack_length() {
                let full_stack: List<i32> = list!(1i32, 2i32, 3i32);
                let empty_stack: List<i32> = Stack::empty();
                assert_eq!(full_stack.length(), 3);
                assert_eq!(empty_stack.length(), 0);
            }

            #[test]
            fn test_stack_peek() {
                let full_stack: List<i32> = list!(1i32, 2i32, 3i32);
                let empty_stack: List<i32> = Stack::empty();
                assert_eq!(full_stack.peek(), Some(&1));
                assert_eq!(empty_stack.peek(), None);
            }

            #[test]
            fn test_stack_push() {
                let mut s: List<i32> = Stack::empty();
                assert_eq!(s.peek(), None);
                s = s.push(1);
                assert_eq!(s.peek(), Some(&1));
                s = s.push(6);
                assert_eq!(s.peek(), Some(&6));
            }

            #[test]
            fn test_stack_pop() {
                let mut s: List<i32> = Stack::empty();
                assert_eq!(s.peek(), None);
                s = s.push(1);
                assert_eq!(s.peek(), Some(&1));
                s = s.push(6);
                assert_eq!(s.peek(), Some(&6));
                let pop_result = s.pop().unwrap(); // should not break
                s = pop_result.1;
                assert_eq!(s.peek(), Some(&1));
                assert_eq!(pop_result.0, 6);
            }

            #[test]
            fn test_list_macro() {
                let l: List<i32> = list!(1i32, 2i32, 3i32);
                assert_eq!(l.to_string(), "(1, (2, (3, nil)))")
            }

            #[test]
            fn test_list_iter() {
                let l: List<isize> = list!(1,2,3,4,5,6);
                let mut string = String::new();
                for item in l.iter() {
                    string.push_str((item.to_string() + ", ").as_slice());
                }
                assert_eq!(string.as_slice(), "1, 2, 3, 4, 5, 6, ")
            }

        }
    }

    /// SVM cell types.
    ///
    /// A cell in the VM can be either an atom (single item, either unsigned
    /// int, signed int, float, or string) or a pointer to a list cell.

    #[derive(PartialEq,Clone,Debug)]
    pub enum SVMCell {
        AtomCell(Atom),
        ListCell(Box<List<SVMCell>>)
    }

    impl fmt::Display for SVMCell {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            write!(f, "[{}]", self)
        }
    }

    /// SVM atom types.
    ///
    /// A VM atom can be either an unsigned int, signed int, float,
    /// char, or string.
    ///
    /// TODO: Strings could be implemented as char lists rather than
    /// Rust strings.
    #[derive(PartialEq,Clone,Debug)]
    pub enum Atom {
        UInt(usize),
        SInt(isize),
        Float(f64),
        Char(char),
        Str(String),
    }

    impl fmt::Display for Atom {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            match self {
                &Atom::UInt(value) => write!(f, "{}us", value),
                &Atom::SInt(value) => write!(f, "{}is", value),
                &Atom::Float(value) => write!(f, "{}f64", value),
                &Atom::Char(value) => write!(f, "'{}'", value),
                &Atom::Str(ref value) => write!(f, "\"{}\"", value)
            }
        }
    }

    /// SVM instruction types
    pub enum SVMInstruction {
        /// `nil`
        ///
        /// Pushes an empty list (nil) onto the stack
        InstNIL,
        /// `ldc`: `L`oa`d` `C`onstant. Loads a constant (atom)
        InstLDC(Atom),
        /// `ld`: `L`oa`d`. Pushes a variable onto the stack.
        ///
        /// The variable is indicated by the argument, a pair.
        /// The pair's `car` specifies the level, the `cdr` the position.
        /// So `(1 . 3)` gives the current function's (level 1) third
        /// parameter.
        InstLD,
        /// `ldf`: `L`oa`d` `F`unction.
        ///
        ///  Takes one list argument representing a function and constructs
        ///  a closure (a pair containing the function and the current
        ///  environment) and pushes that onto the stack.
        InstLDF,
        /// `join`
        ///
        /// Pops a list reference from the dump and makes this the new value
        /// of `C`. This instruction occurs at the end of both alternatives of
        ///  a `sel`.
        InstJOIN,
        /// `ap`: `Ap`ply.
        ///
        /// Pops a closure and a list of parameter values from the stack.
        /// The closure is applied to the parameters by installing its
        /// environment as the current one, pushing the parameter list
        /// in front of that, clearing the stack, and setting `C` to the
        /// closure's function pointer. The previous values of `S`, `E`,
        ///  and the next value of `C` are saved on the dump.
        InstAP,
        /// `ret`: `Ret`urn.
        ///
        /// Pops one return value from the stack, restores
        /// `S`, `E`, and `C` from the dump, and pushes
        /// the return value onto the now-current stack.
        InstRET,
        /// `dum`: `Dum`my.
        ///
        /// Pops a dummy environment (an empty list) onto the `E` stack.
        InstDUM,
        /// `rap`: `R`ecursive `Ap`ply.
        /// Works like `ap`, only that it replaces an occurrence of a
        /// dummy environment with the current one, thus making recursive
        ///  functions possible.
        InstRAP,
        /// `sel`: `Sel`ect
        ///
        /// Expects two list arguments, and pops a value from the stack.
        /// The first list is executed if the popped value was non-nil,
        /// the second list otherwise. Before one of these list pointers
        ///  is made the new `C`, a pointer to the instruction following
        ///  `sel` is saved on the dump.
        InstSEL,
        /// `add`
        ///
        /// Pops two numbers off of the stack and adds them, pushing the
        /// result onto the stack. This will up-convert integers to floating
        /// point if necessary.
        ///
        /// TODO: figure out what happens when you try to add things that aren't
        /// numbers (maybe the compiler won't let this happen?).
        InstADD,
        /// `sub`: `Sub`tract
        ///
        /// Pops two numbers off of the stack and subtracts the first from the
        /// second, pushing the result onto the stack. This will up-convert
        /// integers to floating point if necessary.
        ///
        /// TODO: figure out what happens when you try to subtract things that
        /// aren't numbers (maybe the compiler won't let this happen?).
        InstSUB,
        /// `mul`: `Mul`tiply
        ///
        /// Pops two numbers off of the stack and multiplies them, pushing the
        /// result onto the stack. This will up-convert integers to floating
        /// point if necessary.
        ///
        /// TODO: figure out what happens when you try to multiply things that
        /// aren't numbers (maybe the compiler won't let this happen?).
        InstMUL,
        /// `div`: `Div`ide
        ///
        /// Pops two numbers off of the stack and divides the first by the second,
        /// pushing the result onto the stack. This performs integer division.
        ///
        /// TODO: figure out what happens when you try to divide things that
        /// aren't numbers (maybe the compiler won't let this happen?).
        InstDIV,
        /// `fdiv`: `F`loating-point `div`ide
        ///
        /// Pops two numbers off of the stack and divides the first by the second,
        /// pushing the result onto the stack. This performs float division.
        ///
        /// TODO: figure out what happens when you try to divide things that
        /// aren't numbers (maybe the compiler won't let this happen?).
        ///
        /// TODO: Not sure if there should be separate float and int divide words
        /// I guess the compiler can figure this out
        InstFDIV,
        /// `mod`: `Mod`ulo
        ///
        /// Pops two numbers off of the stack and divides the first by the second,
        /// pushing the remainder onto the stack.
        ///
        /// TODO: figure out what happens when you try to modulo things that
        /// aren't numbers (maybe the compiler won't let this happen?).
        InstMOD
        // TODO: add some hardcoded I/O instructions here so that you can
        //  do I/O without farming everything out to `stdio`
        // TODO: add `cons` and `cdr` words
    }

    /// Represents a SVM machine state
    pub struct State {
        stack:  List<SVMCell>,
        env:  List<SVMCell>,
        control:  List<SVMCell>,
        dump:  List<SVMCell>
    }

    impl State {

        /// Creates a new empty state
        fn new() -> State {
            State {
                stack: Stack::empty(),
                env: Stack::empty(),
                control: Stack::empty(),
                dump: Stack::empty()
            }
        }

        /// Evaluates an instruction.
        ///
        /// Evaluates an instruction against a state, returning a new state.
        pub fn eval(self, inst: SVMInstruction) -> State {
            match inst {
                SVMInstruction::InstNIL => {
                    State {
                        stack: self.stack.push(SVMCell::ListCell(box List::new())),
                        env: self.env,
                        control: self.control,
                        dump: self.dump
                    }
                }
                SVMInstruction::InstLDC(atom) => {
                    State {
                        stack: self.stack.push(SVMCell::AtomCell(atom)),
                        env: self.env,
                        control: self.control,
                        dump: self.dump
                    }
                },
                _ => { unimplemented!() }
            }
        }
    }

    /*
    /// Evaluates a program.
    ///
    /// Evaluates a program represented as an `Iterator` of `SVMInstruction`s.
    /// Returns the final machine state at the end of execution

    pub fn evalProgram(insts: Iterator<Item=SVMInstruction>) -> State {
        insts.fold(State::new(), |last_state: State, inst: SVMInstruction| last_state.eval(inst));
    }*/

    #[cfg(test)]
    mod tests {
        use super::slist::Stack;
        use super::State;
        use super::{SVMInstruction, SVMCell, Atom};
        use super::slist::List::Nil;

        #[test]
        fn test_empty_state() {
            let state = State::new();
            assert_eq!(state.stack.length(), 0);
            assert_eq!(state.env.length(), 0);
            assert_eq!(state.control.length(), 0);
            assert_eq!(state.dump.length(), 0);
        }

        #[test]
        fn test_eval_nil () {
            let mut state = State::new();
            assert_eq!(state.stack.peek(), None);
            state = state.eval(SVMInstruction::InstNIL);
            assert_eq!(state.stack.peek(), Some(&SVMCell::ListCell(box Nil)));
        }

        #[test]
        fn test_eval_ldc () {
            let mut state = State::new();
            assert_eq!(state.stack.peek(), None);

            state = state.eval(SVMInstruction::InstLDC(Atom::SInt(1)));
            assert_eq!(state.stack.peek(), Some(&SVMCell::AtomCell(Atom::SInt(1))));

            state = state.eval(SVMInstruction::InstLDC(Atom::Char('a')));
            assert_eq!(state.stack.peek(), Some(&SVMCell::AtomCell(Atom::Char('a'))));

            state = state.eval(SVMInstruction::InstLDC(Atom::Float(1.0f64)));
            assert_eq!(state.stack.peek(), Some(&SVMCell::AtomCell(Atom::Float(1.0f64))));
        }

        #[test]
        fn test_atom_show () {
            let mut a: Atom;

            a = Atom::Char('a');
            assert_eq!(format!("{}", a), "'a'");

            a = Atom::UInt(1us);
            assert_eq!(format!("{}", a), "1us");

            a = Atom::SInt(42is);
            assert_eq!(format!("{}", a), "42is");

            a = Atom::Float(5.55f64);
            assert_eq!(format!("{}", a), "5.55f64");

            a = Atom::Str(String::from_str("help I'm trapped in a SECD virtual machine!"));
            assert_eq!(format!("{}", a), "\"help I'm trapped in a SECD virtual machine!\"");
        }
    }

}
<|endoftext|>


<commit_before><commit_msg>Add a test for untagged unions<commit_after>// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![feature(unsized_tuple_coercion)]

fn main() {
    let x : &(i32, i32, [i32]) = &(0, 1, [2, 3]);
    let y : &(i32, i32, [i32]) = &(0, 1, [2, 3, 4]);
    let mut a = [y, x];
    a.sort();
    assert_eq!(a, [x, y]);

    assert_eq!(&format!("{:?}", a), "[(0, 1, [2, 3]), (0, 1, [2, 3, 4])]");
}
<|endoftext|>


<commit_before><commit_msg>remove invalid crate name<commit_after><|endoftext|>


<commit_before><commit_msg>refactor(Pane): Use an idiomatic match<commit_after><|endoftext|>


<commit_before><commit_msg>docopen: Add docopen subcommand<commit_after>use std::process;
use std::process::Command;

fn main () {
    #[cfg(target_os = "macos")]
    fn inner() -> &'static str {
        "open"
    }

    let command = inner();
    let arg = "http://groonga.org/docs/";
    let err = match Command::new(command)
        .args(&[arg])
        // .stdout(Stdio::inherit())
        // .stderr(Stdio::inherit())
        .spawn() {
        Ok(_) => return (),
        Err(e) => e,
        };
    println!("Failed to execute docopen subcommand. reason: {:?}", err);
    process::exit(1);

}
<|endoftext|>


<commit_before><commit_msg>thread not shared<commit_after>use std::thread;

fn main() {
    let mut health = 12;
    for i in 2..5 {
        thread::spawn(move || {
            health *= i;
        });
    }
    thread::sleep_ms(2000);
    println!("{:?}", health);
}<|endoftext|>


<commit_before><commit_msg>Rom::from_bytes: Copy slice instead of taking ownership of boxed slice<commit_after><|endoftext|>


<commit_before>//! This module defines a series of convenience modifiers for changing
//! Responses.
//!
//! Modifiers can be used to edit `Response`s through the owning method `set`
//! or the mutating `set_mut`, both of which are defined in the `Set` trait.
//!
//! For Iron, the `Modifier` interface offers extensible and ergonomic response
//! creation while avoiding the introduction of many highly specific `Response`
//! constructors.
//!
//! The simplest case of a modifier is probably the one used to change the
//! return status code:
//!
//! ```
//! # use iron::prelude::*;
//! # use iron::status;
//! let r = Response::with(status::NotFound);
//! assert_eq!(r.status.unwrap().to_u16(), 404);
//! ```
//!
//! You can also pass in a tuple of modifiers, they will all be applied. Here's
//! an example of a modifier 2-tuple that will change the status code and the
//! body message:
//!
//! ```
//! # use iron::prelude::*;
//! # use iron::status;
//! Response::with((status::ImATeapot, "I am a tea pot!"));
//! ```
//!
//! There is also a `Redirect` modifier:
//!
//! ```
//! # use iron::prelude::*;
//! # use iron::status;
//! # use iron::modifiers;
//! # use iron::Url;
//! let url = Url::parse("http://doc.rust-lang.org").unwrap();
//! Response::with((status::Found, modifiers::Redirect(url)));
//! ```
//!
//! The modifiers are applied depending on their type. Currently the easiest
//! way to see how different types are used as modifiers, take a look at [the
//! source code](https://github.com/iron/iron/blob/master/src/modifiers.rs).
//!
//! For more information about the modifier system, see
//! [rust-modifier](https://github.com/reem/rust-modifier).

use std::fs::File;
use std::io;
use std::path::{Path, PathBuf};

use modifier::Modifier;

use hyper::mime::Mime;

use {status, headers, Request, Response, Set, Url};

use mime_types;
use response::{WriteBody, BodyReader};

lazy_static! {
    static ref MIME_TYPES: mime_types::Types = mime_types::Types::new().unwrap();
}

impl Modifier<Response> for Mime {
    #[inline]
    fn modify(self, res: &mut Response) {
        res.headers.set(headers::ContentType(self))
    }
}

impl Modifier<Response> for Box<WriteBody> {
    #[inline]
    fn modify(self, res: &mut Response) {
        res.body = Some(self);
    }
}

impl <R: io::Read + Send + 'static> Modifier<Response> for BodyReader<R> {
    #[inline]
    fn modify(self, res: &mut Response) {
        res.body = Some(Box::new(self));
    }
}

impl Modifier<Response> for String {
    #[inline]
    fn modify(self, res: &mut Response) {
        self.into_bytes().modify(res);
    }
}

impl Modifier<Response> for Vec<u8> {
    #[inline]
    fn modify(self, res: &mut Response) {
        res.headers.set(headers::ContentLength(self.len() as u64));
        res.body = Some(Box::new(self));
    }
}

impl<'a> Modifier<Response> for &'a str {
    #[inline]
    fn modify(self, res: &mut Response) {
        self.to_owned().modify(res);
    }
}

impl<'a> Modifier<Response> for &'a [u8] {
    #[inline]
    fn modify(self, res: &mut Response) {
        self.to_vec().modify(res);
    }
}

impl Modifier<Response> for File {
    fn modify(self, res: &mut Response) {
        // Set the content type based on the file extension if a path is available.
        if let Ok(metadata) = self.metadata() {
            res.headers.set(headers::ContentLength(metadata.len()));
        }

        res.body = Some(Box::new(self));
    }
}

impl<'a> Modifier<Response> for &'a Path {
    /// Set the body to the contents of the File at this path.
    ///
    /// ## Panics
    ///
    /// Panics if there is no file at the passed-in Path.
    fn modify(self, res: &mut Response) {
        File::open(self)
            .expect(&format!("No such file: {}", self.display()))
            .modify(res);

        let mime_str = MIME_TYPES.mime_for_path(self);
        let _ = mime_str.parse().map(|mime: Mime| res.set_mut(mime));
    }
}

impl Modifier<Response> for PathBuf {
    /// Set the body to the contents of the File at this path.
    ///
    /// ## Panics
    ///
    /// Panics if there is no file at the passed-in Path.
    fn modify(self, res: &mut Response) {
        File::open(&self)
            .expect(&format!("No such file: {}", self.display()))
            .modify(res);
    }
}

impl Modifier<Response> for status::Status {
    fn modify(self, res: &mut Response) {
        res.status = Some(self);
    }
}

/// A modifier for changing headers on requests and responses.
pub struct Header<H: headers::Header + headers::HeaderFormat>(pub H);

impl<H> Modifier<Response> for Header<H>
where H: headers::Header + headers::HeaderFormat {
    fn modify(self, res: &mut Response) {
        res.headers.set(self.0);
    }
}

impl<'a, 'b, H> Modifier<Request<'a, 'b>> for Header<H>
where H: headers::Header + headers::HeaderFormat {
    fn modify(self, res: &mut Request) {
        res.headers.set(self.0);
    }
}

/// A modifier for creating redirect responses.
pub struct Redirect(pub Url);

impl Modifier<Response> for Redirect {
    fn modify(self, res: &mut Response) {
        let Redirect(url) = self;
        res.headers.set(headers::Location(url.to_string()));
    }
}

/// A modifier for creating redirect responses.
pub struct RedirectRaw(pub String);

impl Modifier<Response> for RedirectRaw {
    fn modify(self, res: &mut Response) {
        let RedirectRaw(path) = self;
        res.headers.set(headers::Location(path));
    }
}
<commit_msg>Derive clone<commit_after>//! This module defines a series of convenience modifiers for changing
//! Responses.
//!
//! Modifiers can be used to edit `Response`s through the owning method `set`
//! or the mutating `set_mut`, both of which are defined in the `Set` trait.
//!
//! For Iron, the `Modifier` interface offers extensible and ergonomic response
//! creation while avoiding the introduction of many highly specific `Response`
//! constructors.
//!
//! The simplest case of a modifier is probably the one used to change the
//! return status code:
//!
//! ```
//! # use iron::prelude::*;
//! # use iron::status;
//! let r = Response::with(status::NotFound);
//! assert_eq!(r.status.unwrap().to_u16(), 404);
//! ```
//!
//! You can also pass in a tuple of modifiers, they will all be applied. Here's
//! an example of a modifier 2-tuple that will change the status code and the
//! body message:
//!
//! ```
//! # use iron::prelude::*;
//! # use iron::status;
//! Response::with((status::ImATeapot, "I am a tea pot!"));
//! ```
//!
//! There is also a `Redirect` modifier:
//!
//! ```
//! # use iron::prelude::*;
//! # use iron::status;
//! # use iron::modifiers;
//! # use iron::Url;
//! let url = Url::parse("http://doc.rust-lang.org").unwrap();
//! Response::with((status::Found, modifiers::Redirect(url)));
//! ```
//!
//! The modifiers are applied depending on their type. Currently the easiest
//! way to see how different types are used as modifiers, take a look at [the
//! source code](https://github.com/iron/iron/blob/master/src/modifiers.rs).
//!
//! For more information about the modifier system, see
//! [rust-modifier](https://github.com/reem/rust-modifier).

use std::fs::File;
use std::io;
use std::path::{Path, PathBuf};

use modifier::Modifier;

use hyper::mime::Mime;

use {status, headers, Request, Response, Set, Url};

use mime_types;
use response::{WriteBody, BodyReader};

lazy_static! {
    static ref MIME_TYPES: mime_types::Types = mime_types::Types::new().unwrap();
}

impl Modifier<Response> for Mime {
    #[inline]
    fn modify(self, res: &mut Response) {
        res.headers.set(headers::ContentType(self))
    }
}

impl Modifier<Response> for Box<WriteBody> {
    #[inline]
    fn modify(self, res: &mut Response) {
        res.body = Some(self);
    }
}

impl <R: io::Read + Send + 'static> Modifier<Response> for BodyReader<R> {
    #[inline]
    fn modify(self, res: &mut Response) {
        res.body = Some(Box::new(self));
    }
}

impl Modifier<Response> for String {
    #[inline]
    fn modify(self, res: &mut Response) {
        self.into_bytes().modify(res);
    }
}

impl Modifier<Response> for Vec<u8> {
    #[inline]
    fn modify(self, res: &mut Response) {
        res.headers.set(headers::ContentLength(self.len() as u64));
        res.body = Some(Box::new(self));
    }
}

impl<'a> Modifier<Response> for &'a str {
    #[inline]
    fn modify(self, res: &mut Response) {
        self.to_owned().modify(res);
    }
}

impl<'a> Modifier<Response> for &'a [u8] {
    #[inline]
    fn modify(self, res: &mut Response) {
        self.to_vec().modify(res);
    }
}

impl Modifier<Response> for File {
    fn modify(self, res: &mut Response) {
        // Set the content type based on the file extension if a path is available.
        if let Ok(metadata) = self.metadata() {
            res.headers.set(headers::ContentLength(metadata.len()));
        }

        res.body = Some(Box::new(self));
    }
}

impl<'a> Modifier<Response> for &'a Path {
    /// Set the body to the contents of the File at this path.
    ///
    /// ## Panics
    ///
    /// Panics if there is no file at the passed-in Path.
    fn modify(self, res: &mut Response) {
        File::open(self)
            .expect(&format!("No such file: {}", self.display()))
            .modify(res);

        let mime_str = MIME_TYPES.mime_for_path(self);
        let _ = mime_str.parse().map(|mime: Mime| res.set_mut(mime));
    }
}

impl Modifier<Response> for PathBuf {
    /// Set the body to the contents of the File at this path.
    ///
    /// ## Panics
    ///
    /// Panics if there is no file at the passed-in Path.
    fn modify(self, res: &mut Response) {
        File::open(&self)
            .expect(&format!("No such file: {}", self.display()))
            .modify(res);
    }
}

impl Modifier<Response> for status::Status {
    fn modify(self, res: &mut Response) {
        res.status = Some(self);
    }
}

/// A modifier for changing headers on requests and responses.
#[derive(Clone)]
pub struct Header<H: headers::Header + headers::HeaderFormat>(pub H);

impl<H> Modifier<Response> for Header<H>
where H: headers::Header + headers::HeaderFormat {
    fn modify(self, res: &mut Response) {
        res.headers.set(self.0);
    }
}

impl<'a, 'b, H> Modifier<Request<'a, 'b>> for Header<H>
where H: headers::Header + headers::HeaderFormat {
    fn modify(self, res: &mut Request) {
        res.headers.set(self.0);
    }
}

/// A modifier for creating redirect responses.
pub struct Redirect(pub Url);

impl Modifier<Response> for Redirect {
    fn modify(self, res: &mut Response) {
        let Redirect(url) = self;
        res.headers.set(headers::Location(url.to_string()));
    }
}

/// A modifier for creating redirect responses.
pub struct RedirectRaw(pub String);

impl Modifier<Response> for RedirectRaw {
    fn modify(self, res: &mut Response) {
        let RedirectRaw(path) = self;
        res.headers.set(headers::Location(path));
    }
}
<|endoftext|>


<commit_before>// The MIT License (MIT)
//
// Copyright (c) 2013 Jeremy Letang (letang.jeremy@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

/*!
# Rust-PortAudio

__Portaudio__ bindings for Rust

PortAudio provides a uniform application programming interface (API) across all
supported platforms.  You can think of the PortAudio library as a wrapper that
converts calls to the PortAudio API into calls to platform-specific native audio
APIs. Operating systems often offer more than one native audio API and some APIs
(such as JACK) may be available on multiple target operating systems.
PortAudio supports all the major native audio APIs on each supported platform.

# Installation

You must install on your computer the Portaudio libraries who is used for
the binding.

Portaudio is available with package management tools on Linux, or brew on Mac OS.

You can download it directly from the website :
[portaudio](http://www.portaudio.com/download.html)

Then clone the repo and build the library with the following command at the root
of the __rust-portaudio__ repository.

__rust-portaudio__ is build with the rustpkg tool :

```Shell
> rustpkg build portaudio
```

*/

#![crate_name = "portaudio"]

#![comment = "Portaudio binding for Rust"]
#![license = "MIT"]
#![crate_type = "dylib"]
#![crate_type = "rlib"]

#![feature(globs)]
#![warn(missing_doc)]
#![allow(dead_code)]

extern crate libc;

#[cfg(any(target_os="macos", target_os="linux", target_os="win32"))]
mod c_library {
    #[link(name = "portaudio")]
    extern {}
}

pub mod types;
pub mod pa;

//#[doc(hidden)]
//pub mod user_traits;
//#[doc(hidden)]
//#[cfg(target_os="macos")]
//pub mod mac_core;
//pub mod asio;
#[doc(hidden)]
mod ffi;
<commit_msg>Fixing "warning: lint missing_doc has been renamed to missing_docs"<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2013 Jeremy Letang (letang.jeremy@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

/*!
# Rust-PortAudio

__Portaudio__ bindings for Rust

PortAudio provides a uniform application programming interface (API) across all
supported platforms.  You can think of the PortAudio library as a wrapper that
converts calls to the PortAudio API into calls to platform-specific native audio
APIs. Operating systems often offer more than one native audio API and some APIs
(such as JACK) may be available on multiple target operating systems.
PortAudio supports all the major native audio APIs on each supported platform.

# Installation

You must install on your computer the Portaudio libraries who is used for
the binding.

Portaudio is available with package management tools on Linux, or brew on Mac OS.

You can download it directly from the website :
[portaudio](http://www.portaudio.com/download.html)

Then clone the repo and build the library with the following command at the root
of the __rust-portaudio__ repository.

__rust-portaudio__ is build with the rustpkg tool :

```Shell
> rustpkg build portaudio
```

*/

#![crate_name = "portaudio"]

#![comment = "Portaudio binding for Rust"]
#![license = "MIT"]
#![crate_type = "dylib"]
#![crate_type = "rlib"]

#![feature(globs)]
#![warn(missing_docs)]
#![allow(dead_code)]

extern crate libc;

#[cfg(any(target_os="macos", target_os="linux", target_os="win32"))]
mod c_library {
    #[link(name = "portaudio")]
    extern {}
}

pub mod types;
pub mod pa;

//#[doc(hidden)]
//pub mod user_traits;
//#[doc(hidden)]
//#[cfg(target_os="macos")]
//pub mod mac_core;
//pub mod asio;
#[doc(hidden)]
mod ffi;
<|endoftext|>


<commit_before><commit_msg>Second tranche of SPIR-V reflection -- read the binding points for opaque uniforms and for uniform blocks<commit_after><|endoftext|>


<commit_before><commit_msg>add basic test for proc macro<commit_after>use actix_http::HttpService;
use actix_http_test::TestServer;
use actix_web::{get, App, HttpResponse, Responder};

#[get("/test")]
fn test() -> impl Responder {
    HttpResponse::Ok()
}

#[test]
fn test_body() {
    let mut srv = TestServer::new(|| HttpService::new(App::new().service(test)));

    let request = srv.get().uri(srv.url("/test")).finish().unwrap();
    let response = srv.send_request(request).unwrap();
    assert!(response.status().is_success());
}
<|endoftext|>


<commit_before>// Copyright 2015 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::os::raw::c_void;

use device_gl::{Device, Factory, Resources as Res, create as gl_create, create_main_targets_raw};
use glutin::{HeadlessContext};

use core::format::{Format, DepthFormat, RenderFormat};
use core::handle::{DepthStencilView, RawDepthStencilView, RawRenderTargetView, RenderTargetView};
use core::memory::Typed;
use core::texture::Dimensions;

/// Initializes device and factory from a headless context.
/// This is useful for testing as it does not require a
/// X server, thus runs on CI.
///
/// Only compiled with `headless` feature.
///
/// # Example
///
/// ```rust
/// extern crate gfx_core;
/// extern crate gfx_window_glutin;
/// extern crate glutin;
///
/// use gfx_core::format::{DepthStencil, Rgba8};
/// use gfx_core::texture::AaMode;
/// use gfx_window_glutin::init_headless;
/// use glutin::HeadlessRendererBuilder;
///
/// # fn main() {
/// let dim = (256, 256, 8, AaMode::Multi(4));
///
/// let context = HeadlessRendererBuilder::new(dim.0 as u32, dim.1 as u32)
///     .build()
///     .expect("Failed to build headless context");
///
/// let (mut device, _, _, _) = init_headless::<Rgba8, DepthStencil>(&context, dim);
/// # }
/// ```
pub fn init_headless<Cf, Df>(context: &HeadlessContext, dim: Dimensions)
                             -> (Device, Factory,
                                 RenderTargetView<Res, Cf>, DepthStencilView<Res, Df>)
    where
        Cf: RenderFormat,
        Df: DepthFormat,
{
    let (device, factory, color_view, ds_view) = init_headless_raw(context, dim,
                                                                   Cf::get_format(),
                                                                   Df::get_format());
    (device, factory, Typed::new(color_view), Typed::new(ds_view))
}

/// Raw version of [`init_headless`].
///
/// [`init_headless`]: fn.init_headless.html
pub fn init_headless_raw(context: &HeadlessContext, dim: Dimensions, color: Format, depth: Format)
                         -> (Device, Factory,
                             RawRenderTargetView<Res>, RawDepthStencilView<Res>)
{
    unsafe { context.make_current().unwrap() };

    let (device, factory) = gl_create(|s|
        context.get_proc_address(s) as *const c_void);

    // create the main color/depth targets
    let (color_view, ds_view) = create_main_targets_raw(dim, color.0, depth.0);

    // done
    (device, factory, color_view, ds_view)
}

#[cfg(test)]
mod tests {
    use super::*;

    use core::format::{DepthStencil, Rgba8};
    use core::texture::AaMode;
    use core::Device;

    #[test]
    fn test_headless() {
        use glutin::{HeadlessRendererBuilder};

        let dim = (256, 256, 8, AaMode::Multi(4));

        let context: HeadlessContext = HeadlessRendererBuilder::new(dim.0 as u32, dim.1 as u32)
            .build()
            .expect("Failed to build headless context");

        let (mut device, _, _, _) = init_headless::<Rgba8, DepthStencil>(&context, dim);

        device.cleanup();
    }
}
<commit_msg>Fix glutin headless GlContext compile issue<commit_after>// Copyright 2015 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::os::raw::c_void;

use device_gl::{Device, Factory, Resources as Res, create as gl_create, create_main_targets_raw};
use glutin::{GlContext, HeadlessContext};

use core::format::{Format, DepthFormat, RenderFormat};
use core::handle::{DepthStencilView, RawDepthStencilView, RawRenderTargetView, RenderTargetView};
use core::memory::Typed;
use core::texture::Dimensions;

/// Initializes device and factory from a headless context.
/// This is useful for testing as it does not require a
/// X server, thus runs on CI.
///
/// Only compiled with `headless` feature.
///
/// # Example
///
/// ```rust
/// extern crate gfx_core;
/// extern crate gfx_window_glutin;
/// extern crate glutin;
///
/// use gfx_core::format::{DepthStencil, Rgba8};
/// use gfx_core::texture::AaMode;
/// use gfx_window_glutin::init_headless;
/// use glutin::HeadlessRendererBuilder;
///
/// # fn main() {
/// let dim = (256, 256, 8, AaMode::Multi(4));
///
/// let context = HeadlessRendererBuilder::new(dim.0 as u32, dim.1 as u32)
///     .build()
///     .expect("Failed to build headless context");
///
/// let (mut device, _, _, _) = init_headless::<Rgba8, DepthStencil>(&context, dim);
/// # }
/// ```
pub fn init_headless<Cf, Df>(context: &HeadlessContext, dim: Dimensions)
                             -> (Device, Factory,
                                 RenderTargetView<Res, Cf>, DepthStencilView<Res, Df>)
    where
        Cf: RenderFormat,
        Df: DepthFormat,
{
    let (device, factory, color_view, ds_view) = init_headless_raw(context, dim,
                                                                   Cf::get_format(),
                                                                   Df::get_format());
    (device, factory, Typed::new(color_view), Typed::new(ds_view))
}

/// Raw version of [`init_headless`].
///
/// [`init_headless`]: fn.init_headless.html
pub fn init_headless_raw(context: &HeadlessContext, dim: Dimensions, color: Format, depth: Format)
                         -> (Device, Factory,
                             RawRenderTargetView<Res>, RawDepthStencilView<Res>)
{
    unsafe { context.make_current().unwrap() };

    let (device, factory) = gl_create(|s|
        context.get_proc_address(s) as *const c_void);

    // create the main color/depth targets
    let (color_view, ds_view) = create_main_targets_raw(dim, color.0, depth.0);

    // done
    (device, factory, color_view, ds_view)
}

#[cfg(test)]
mod tests {
    use super::*;

    use core::format::{DepthStencil, Rgba8};
    use core::texture::AaMode;
    use core::Device;

    #[test]
    fn test_headless() {
        use glutin::{HeadlessRendererBuilder};

        let dim = (256, 256, 8, AaMode::Multi(4));

        let context: HeadlessContext = HeadlessRendererBuilder::new(dim.0 as u32, dim.1 as u32)
            .build()
            .expect("Failed to build headless context");

        let (mut device, _, _, _) = init_headless::<Rgba8, DepthStencil>(&context, dim);

        device.cleanup();
    }
}
<|endoftext|>


<commit_before><commit_msg>Rewrite a loop to be more readable<commit_after><|endoftext|>


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


<commit_before><commit_msg>[Rust] Order of Pair<commit_after>macro_rules! test {
    ($t:expr) => { println!("{}: {:?}", stringify!($t), $t); }
}

fn main() {
    test!((1, 2).cmp(&(1, 1)));
    test!((1, 2).cmp(&(1, 2)));
    test!((1, 2).cmp(&(1, 3)));
    test!((1, 2).cmp(&(0, 2)));
    test!((1, 2).cmp(&(1, 2)));
    test!((1, 2).cmp(&(2, 2)));
    test!((1, 2).cmp(&(0, 3)));
    test!((1, 2).cmp(&(2, 1)));
}
<|endoftext|>


<commit_before><commit_msg>Added config file for configuration values.<commit_after>#[allow(non_camel_case_types)]
pub mod net {

    pub static MDNS_SERVICE_NAME: &str = "_http._tcp"; // "_tcp.local"
    pub static MDNS_REGISTER_NAME: &str = "adbf";
    pub static MDNS_PORT : u16 = 80;
    pub static MDNS_TIMEOUT_SEC : u16 = 3;

    pub static SSH_CLIENT_KEY_FILE : &str = "/home/pe/.ssh/id_ed25519_pkcs8";
    pub static SSH_CLIENT_USERNAME : & str = "pe";
    pub static SSH_CLIENT_AND_PORT : & str = "0.0.0.0:2222";
    pub static SSH_HOST_AND_PORT : & str = "127.0.0.1:2222";

    pub struct changeable {

    }
}
<|endoftext|>


<commit_before><commit_msg>Fix missing iovcnt variable<commit_after><|endoftext|>


<commit_before><commit_msg>FilterFlags<commit_after><|endoftext|>


<commit_before><commit_msg>arp: add _.src and _.dst<commit_after><|endoftext|>


<commit_before><commit_msg>Add test using early-bound lifetimes in trait generic parameters.<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// Tests that you can use an early-bound lifetime parameter as
// on of the generic parameters in a trait.

trait Trait<'a> {
    fn long(&'a self) -> int;
    fn short<'b>(&'b self) -> int;
}

fn poly_invoke<'c, T: Trait<'c>>(x: &'c T) -> (int, int) {
    let l = x.long();
    let s = x.short();
    (l,s)
}

fn object_invoke1<'d>(x: &'d Trait<'d>) -> (int, int) {
    let l = x.long();
    let s = x.short();
    (l,s)
}

struct Struct1<'e> {
    f: &'e Trait<'e>
}

fn field_invoke1<'f, 'g>(x: &'g Struct1<'f>) -> (int,int) {
    let l = x.f.long();
    let s = x.f.short();
    (l,s)
}

struct Struct2<'h, 'i> {
    f: &'h Trait<'i>
}

fn object_invoke2<'j, 'k>(x: &'k Trait<'j>) -> int {
    x.short()
}

fn field_invoke2<'l, 'm, 'n>(x: &'n Struct2<'l,'m>) -> int {
    x.f.short()
}

trait MakerTrait<'o> {
    fn mk() -> Self;
}

fn make_val<'p, T:MakerTrait<'p>>() -> T {
    MakerTrait::mk()
}

trait RefMakerTrait<'q> {
    fn mk(Self) -> &'q Self;
}

fn make_ref<'r, T:RefMakerTrait<'r>>(t:T) -> &'r T {
    RefMakerTrait::mk(t)
}

impl<'s> Trait<'s> for (int,int) {
    fn long(&'s self) -> int {
        let &(x,_) = self;
        x
    }
    fn short<'b>(&'b self) -> int {
        let &(_,y) = self;
        y
    }
}

impl<'t> MakerTrait<'t> for ~Trait<'t> {
    fn mk() -> ~Trait<'t> { ~(4,5) as ~Trait }
}

enum List<'l> {
    Cons(int, &'l List<'l>),
    Null
}

impl<'l> List<'l> {
    fn car<'m>(&'m self) -> int {
        match self {
            &Cons(car, _) => car,
            &Null => fail!(),
        }
    }
    fn cdr<'n>(&'n self) -> &'l List<'l> {
        match self {
            &Cons(_, cdr) => cdr,
            &Null => fail!(),
        }
    }
}

impl<'t> RefMakerTrait<'t> for List<'t> {
    fn mk(l:List<'t>) -> &'t List<'t> {
        l.cdr()
    }
}

pub fn main() {
    let t = (2,3);
    let o = &t as &Trait;
    let s1 = Struct1 { f: o };
    let s2 = Struct2 { f: o };
    assert_eq!(poly_invoke(&t), (2,3));
    assert_eq!(object_invoke1(&t), (2,3));
    assert_eq!(field_invoke1(&s1), (2,3));
    assert_eq!(object_invoke2(&t), 3);
    assert_eq!(field_invoke2(&s2), 3);

    let m : ~Trait = make_val();
    assert_eq!(object_invoke1(m), (4,5));
    assert_eq!(object_invoke2(m), 5);

    // The RefMakerTrait above is pretty strange (i.e. it is strange
    // to consume a value of type T and return a &T).  Easiest thing
    // that came to my mind: consume a cell of a linked list and
    // return a reference to the list it points to.
    let l0 = Null;
    let l1 = Cons(1, &l0);
    let l2 = Cons(2, &l1);
    let rl1 = &l1;
    let r  = make_ref(l2);
    assert_eq!(rl1.car(), r.car());
}
<|endoftext|>


<commit_before><commit_msg>Increase the surface colour frequencies to get some texture at the smaller scale<commit_after><|endoftext|>


<commit_before><commit_msg>Use RollValue to represent numeric result<commit_after><|endoftext|>


<commit_before><commit_msg>add shader class<commit_after>use glium::Program;
use glium::backend::glutin_backend::GlutinFacade;

pub struct Shader {
    pub data: Program,
    pub uniform_keys: Vec<String>,
}

impl Shader {
    pub fn new(facade: &GlutinFacade, vertex_shader: &str, fragment_shader: &str) -> Result<Shader, String> {
        let data = match Program::from_source(facade, vertex_shader, fragment_shader, None) {
            Ok(v) => v,
            Err(e) => return Err(format!("Error create shaders: {}", e))
        };

        let mut uniform_keys = Vec::<String>::new();
        for (name, _) in data.uniforms() {
            uniform_keys.push(name.clone());
        }

        Ok(Shader {
            data: data,
            uniform_keys: uniform_keys,
        })
    }
}
<|endoftext|>


<commit_before><commit_msg>Implement LTEq for type-level nat<commit_after><|endoftext|>


<commit_before><commit_msg>Run the SPIR-V validator spirv-val before and after optimisation<commit_after><|endoftext|>


<commit_before><commit_msg>Fix the checks on the SPIR-V validator result, which were using the results from previous commands<commit_after><|endoftext|>


<commit_before><commit_msg>languages/rust/rust-book/3-chapter/24-code.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Write test (not passed)<commit_after>
extern crate ndarray;
extern crate ndarray_linalg as linalg;

use ndarray::prelude::*;
use linalg::Matrix;

fn assert_almost_eq(a: f64, b: f64) {
    let rel_dev = (a - b).abs() / (a.abs() + b.abs());
    if rel_dev > 1.0e-7 {
        panic!("a={:?}, b={:?} are not almost equal", a, b);
    }
}

#[test]
fn test_matrix_norm_3x4() {
    let a = arr2(&[[3.0, 1.0, 1.0, 1.0], [1.0, 3.0, 1.0, 1.0], [1.0, 1.0, 3.0, 1.0]]);
    assert_almost_eq(a.norm_1(), 5.0);
    assert_almost_eq(a.norm_i(), 6.0);
}

#[test]
fn test_matrix_norm_3x4_t() {
    let a = arr2(&[[3.0, 1.0, 1.0, 1.0], [1.0, 3.0, 1.0, 1.0], [1.0, 1.0, 3.0, 1.0]])
        .reversed_axes();
    assert_almost_eq(a.norm_1(), 6.0);
    assert_almost_eq(a.norm_i(), 5.0);
}

#[test]
fn test_matrix_norm_4x3() {
    let a = arr2(&[[3.0, 1.0, 1.0], [1.0, 3.0, 1.0], [1.0, 1.0, 3.0], [1.0, 1.0, 1.0]]);
    assert_almost_eq(a.norm_1(), 6.0);
    assert_almost_eq(a.norm_i(), 5.0);
}

#[test]
fn test_matrix_norm_4x3_t() {
    let a = arr2(&[[3.0, 1.0, 1.0], [1.0, 3.0, 1.0], [1.0, 1.0, 3.0], [1.0, 1.0, 1.0]])
        .reversed_axes();
    assert_almost_eq(a.norm_1(), 5.0);
    assert_almost_eq(a.norm_i(), 6.0);
}
<|endoftext|>


<commit_before><commit_msg>Add missing file<commit_after>// Copyright Dan Schatzberg, 2015. This file is part of Genesis.

// Genesis is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Genesis is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.

// You should have received a copy of the GNU Affero General Public License
// along with Genesis.  If not, see <http://www.gnu.org/licenses/>.
use core::fmt;

#[derive(Copy, Clone, Debug)]
pub struct PAddr(u64);

#[derive(Copy, Clone, Debug)]
pub struct VAddr(usize);

impl PAddr {
    pub fn as_u64(&self) -> u64 {
        self.0
    }
}

impl fmt::Binary for PAddr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl fmt::Display for PAddr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl fmt::LowerHex for PAddr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl fmt::Octal for PAddr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl fmt::UpperHex for PAddr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl fmt::Binary for VAddr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl fmt::Display for VAddr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl fmt::LowerHex for VAddr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl fmt::Octal for VAddr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl fmt::UpperHex for VAddr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}
<|endoftext|>


<commit_before><commit_msg>Fix Colossal build<commit_after><|endoftext|>


<commit_before><commit_msg>Fold the evaluate CLI tool back into xpath<commit_after>extern crate document;
extern crate xpath;

use std::cmp::min;
use std::collections::hashmap::HashMap;
use std::io::File;

use document::ToAny;
use document::parser::Parser;

use xpath::{XPathEvaluationContext,XPathFactory};
use xpath::expression::XPathExpression;

fn pretty_error(xml: &str, position: uint) -> &str {
    let s = xml.slice_from(position);
    let l = s.char_len();
    s.slice_chars(0, min(l, 15))
}

fn main() {
    let mut args = std::os::args();

    let filename = args.remove(1).expect("File required");
    let xpath_str = args.remove(1).expect("XPath required");

    let factory = XPathFactory::new();

    let expr = match factory.build(xpath_str.as_slice()) {
        Err(x) => fail!("Unable to compile XPath: {}", x),
        Ok(None) => fail!("Unable to compile XPath"),
        Ok(Some(x)) => x,
    };

    let p = Parser::new();

    let path = Path::new(filename);
    let mut file = File::open(&path);

    let data = match file.read_to_end() {
        Ok(x) => x,
        Err(x) => fail!("Can't read: {}", x),
    };

    let data = match String::from_utf8(data) {
        Ok(x) => x,
        Err(x) => fail!("Unable to convert to UTF-8: {}", x),
    };

    let d = match p.parse(data.as_slice()) {
        Ok(d) => d,
        Err(point) => fail!("Unable to parse: {}", pretty_error(data.as_slice(), point)),
    };

    let mut functions = HashMap::new();
    xpath::function::register_core_functions(& mut functions);
    let variables = HashMap::new();
    let mut context = XPathEvaluationContext::new(d.root().to_any(),
                                                  &functions,
                                                  &variables);
    context.next(d.root().to_any());

    let res = expr.evaluate(&context);

    println!("{}", res);
}
<|endoftext|>


<commit_before><commit_msg>Add uppercase first char C lang vi-VN<commit_after><|endoftext|>


<commit_before><commit_msg>Rename frame_renderer to video_renderer<commit_after><|endoftext|>


<commit_before><commit_msg>Fix kindck to consider inherited bounds<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// Test that Copy bounds inherited by trait are checked.

use std::any::Any;
use std::any::AnyRefExt;

trait Foo : Copy {
}

impl<T:Copy> Foo for T {
}

fn take_param<T:Foo>(foo: &T) { }

fn main() {
    let x = box 3i;
    take_param(&x); //~ ERROR does not fulfill `Copy`

    let y = &x;
    let z = &x as &Foo; //~ ERROR does not fulfill `Copy`
}
<|endoftext|>


<commit_before><commit_msg>Regression test added for an async ICE.<commit_after>// This issue reproduces an ICE on compile (E.g. fails on 2018-12-19 nightly).
// run-pass
// edition:2018
#![feature(async_await,futures_api,await_macro,generators)]

pub struct Foo;

impl Foo {
    async fn with<'a, F, R>(&'a self, f: F) -> R
    where F: Fn() -> R + 'a,
    {
        loop {
            match f() {
                _ => yield,
            }
        }
    }

    pub async fn run<'a>(&'a self, data: &'a [u8])
    {
        await!(self.with(move || {
            println!("{:p}", data);
        }))
    }
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>arg position<commit_after>// run-pass
#![allow(unused_must_use)]
fn bug(_: impl Iterator<Item = [(); { |x: u32| { x }; 4 }]>) {}

fn main() {
    bug(std::iter::empty());
}
<|endoftext|>