<commit_before>#![feature(box_syntax)]
#![allow(dead_code)]

pub mod svm {

    use svm::slist::List;

    mod slist {

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

        pub struct Stack<T> {
            head: Box<List<T>>
        }

        impl<T> Stack<T> {
            fn push(self, it: T) -> Stack<T> {
                Stack { head: Box::new(self.head.prepend(it)) }
            }

            fn peek(&self) -> Option<&T> {
                match *self.head {
                    Nil => None,
                    Cons(ref it,_) => Some(it)
                }
            }

            fn empty() -> Stack<T> {
                Stack { head: box Nil }
            }

            fn new(l: List<T>) -> Stack<T> {
                Stack { head: box l }
            }
        }

        /// Singly-linked cons list.
        ///
        /// This is used internally to represent list primitives in the machine.
        pub enum List<T> {
            Cons(T, Box<List<T>>),
            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
            pub fn prepend(self, it: T) -> List<T> {
                Cons(it, box self)
            }

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

        impl<T> List<T> where T: Show {
            /// Return a string representation of the list
            fn to_string(&self) -> String {
                match *self {
                    Cons(ref head, ref tail) => format!("({:?}, {})", head, tail.to_string()),
                    Nil => format!("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 l: List<i32> = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
                assert_eq!(l.length(), 3);
            }

            #[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(), "(1i32, (2i32, (3i32, nil)))");
            }

            #[test]
            fn test_stack_peek() {
                let s: Stack<i32> = Stack::new(Cons(1, Box::new(Cons(2, Box::new(Nil)))));
                assert_eq!(s.peek(), Some(&1));
            }

            #[test]
            fn test_stack_push() {
                let mut s: Stack<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: Stack<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_list_macro() {
                let l: List<i32> = list!(1i32, 2i32, 3i32);
                assert_eq!(l.to_string(), "(1i32, (2i32, (3i32, nil)))")
            }
        }
    }

    enum Exp {
        Number(i32)
    }

    struct Engine {
        stack: List<Exp>
    }
}
<commit_msg>Add RustDoc, finish machine state struct<commit_after>#![crate_id = "seax-svm"]
#![crate_type="lib"]

//! Contains the Seax Virtual Machine (SVM) and miscellaneous
//! support code.

#![feature(box_syntax)]
#![allow(dead_code)]

pub mod svm {

    use svm::slist::List;
    use svm::slist::Stack;

    /// Singly-linked list and stack implementations.
    mod slist {

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

        /// A stack implementation wrapping a List<T>
        pub struct Stack<T> {
            /// The head item of the list.
            head: Box<List<T>>
        }

        impl<T> Stack<T> {
            /// Push an item to the top of the stack, returning a new stack
            fn push(self, it: T) -> Stack<T> {
                Stack { head: Box::new(self.head.prepend(it)) }
            }

            /// Peak 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> {
                match *self.head {
                    Nil => None,
                    Cons(ref it,_) => Some(it)
                }
            }

            /// Returns an empty stack.
            fn empty() -> Stack<T> {
                Stack { head: box Nil }
            }

            /// Wraps a list into a stack.
            fn new(l: List<T>) -> Stack<T> {
                Stack { head: box l }
            }
        }

        /// Singly-linked cons list.
        ///
        /// This is used internally to represent list primitives in the machine.
        pub enum List<T> {
            Cons(T, Box<List<T>>),
            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
            pub fn prepend(self, it: T) -> List<T> {
                Cons(it, box self)
            }

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

        impl<T> List<T> where T: Show {
            /// Return a string representation of the list
            fn to_string(&self) -> String {
                match *self {
                    Cons(ref head, ref tail) => format!("({:?}, {})", head, tail.to_string()),
                    Nil => format!("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 l: List<i32> = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
                assert_eq!(l.length(), 3);
            }

            #[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(), "(1i32, (2i32, (3i32, nil)))");
            }

            #[test]
            fn test_stack_peek() {
                let s: Stack<i32> = Stack::new(Cons(1, Box::new(Cons(2, Box::new(Nil)))));
                assert_eq!(s.peek(), Some(&1));
            }

            #[test]
            fn test_stack_push() {
                let mut s: Stack<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: Stack<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_list_macro() {
                let l: List<i32> = list!(1i32, 2i32, 3i32);
                assert_eq!(l.to_string(), "(1i32, (2i32, (3i32, nil)))")
            }
        }
    }

    /// SVM item types
    enum Exp {
        Number(i32)
    }

    /// Represents a SVM machine state
    struct State {
        stack: Stack<Exp>,
        env: Stack<Exp>,
        control: Stack<Exp>,
        dump: Stack<Exp>
    }
}
<|endoftext|>


<commit_before>// main.rs
// Main entry point for a guessing game
//
// taken from the rust-lang tutorial:
// http://doc.rust-lang.org/stable/book/guessing-game.html
//

use std::io;

fn main() {
    println!("Guess the number!");

    println!("Please input your guess.");

    let mut guess = String::new();

    io::stdin().read_line(&mut guess)
        .ok()
        .expect("Failed to read line");

    println!("You guessed: {}", guess);
}

<commit_msg>+ finish guessing_game tutorial<commit_after>// main.rs
// Main entry point for a guessing game
//
// taken from the rust-lang tutorial:
// http://doc.rust-lang.org/stable/book/guessing-game.html
//
// vim: ft=rust sw=4 ts=4

extern crate rand;

use std::io;
use std::cmp::Ordering;
use rand::Rng;

fn main() {
	println!("Guess the number!");

	let secret_number = rand::thread_rng().gen_range(1, 101);

	//println!("The secret number is: {}", secret_number);

	loop {
		println!("Please input your guess.");

		let mut guess = String::new();

		io::stdin().read_line(&mut guess)
			.ok()
			.expect("Failed to read line");

		// convert to number
		let guess: u32 = match guess.trim().parse() {
			Ok(num)	=> num,
			Err(_)	=> continue
		};

		println!("You guessed: {}", guess);

		match guess.cmp(&secret_number) {
			Ordering::Less		=> println!("Too small!"),
			Ordering::Greater	=> println!("Too big!"),
			Ordering::Equal		=> {
				println!("You win!");
				break;
			}
		}
	}
}

<|endoftext|>


<commit_before>#[macro_use]
extern crate nom;

extern crate serde;
#[macro_use]
extern crate serde_derive;

pub use self::arithmetic::{ArithmeticBase, ArithmeticExpression, ArithmeticOperator};
pub use self::common::{FieldExpression, Literal, Operator, SqlType, TableKey};
pub use self::column::{Column, ColumnConstraint, ColumnSpecification, FunctionExpression};
pub use self::condition::{ConditionBase, ConditionExpression, ConditionTree};
pub use self::create::CreateTableStatement;
pub use self::delete::DeleteStatement;
pub use self::insert::InsertStatement;
pub use self::join::{JoinConstraint, JoinOperator, JoinRightSide};
pub use self::parser::*;
pub use self::compound_select::{CompoundSelectOperator, CompoundSelectStatement};
pub use self::select::{GroupByClause, JoinClause, LimitClause, SelectStatement};
pub use self::order::{OrderClause, OrderType};
pub use self::table::Table;
pub use self::set::SetStatement;
pub use self::update::UpdateStatement;

pub mod parser;

#[macro_use]
mod keywords;
mod arithmetic;
mod column;
mod common;
mod condition;
mod create;
mod insert;
mod join;
mod select;
mod compound_select;
mod table;
mod delete;
mod drop;
mod update;
mod set;
mod order;
<commit_msg>Make Real public<commit_after>#[macro_use]
extern crate nom;

extern crate serde;
#[macro_use]
extern crate serde_derive;

pub use self::arithmetic::{ArithmeticBase, ArithmeticExpression, ArithmeticOperator};
pub use self::common::{FieldExpression, Literal, Operator, Real, SqlType, TableKey};
pub use self::column::{Column, ColumnConstraint, ColumnSpecification, FunctionExpression};
pub use self::condition::{ConditionBase, ConditionExpression, ConditionTree};
pub use self::create::CreateTableStatement;
pub use self::delete::DeleteStatement;
pub use self::insert::InsertStatement;
pub use self::join::{JoinConstraint, JoinOperator, JoinRightSide};
pub use self::parser::*;
pub use self::compound_select::{CompoundSelectOperator, CompoundSelectStatement};
pub use self::select::{GroupByClause, JoinClause, LimitClause, SelectStatement};
pub use self::order::{OrderClause, OrderType};
pub use self::table::Table;
pub use self::set::SetStatement;
pub use self::update::UpdateStatement;

pub mod parser;

#[macro_use]
mod keywords;
mod arithmetic;
mod column;
mod common;
mod condition;
mod create;
mod insert;
mod join;
mod select;
mod compound_select;
mod table;
mod delete;
mod drop;
mod update;
mod set;
mod order;
<|endoftext|>


<commit_before>
extern crate bytes;
extern crate futures;
extern crate kcp;
extern crate mio;
#[macro_use]
extern crate tokio_core;
extern crate tokio_io;
extern crate rand;
extern crate time;

use std::cell::RefCell;
use std::collections::HashMap;
use std::io::{self, Read, Write};
use std::net::SocketAddr;
use std::rc::Rc;
use std::time::{Duration, Instant};

use bytes::BytesMut;
use bytes::buf::FromBuf;
use futures::{Poll, Async, Future};
use futures::stream::Stream;
use kcp::prelude::*;
use mio::{Ready, Registration, PollOpt, Token, SetReadiness};
use mio::event::Evented;
use tokio_core::net::UdpSocket;
use tokio_core::reactor::{Handle, PollEvented, Timeout};
use tokio_io::{AsyncRead, AsyncWrite};

#[inline]
fn current() -> u32 {
    let timespec = time::get_time();
    (timespec.sec * 1000 + timespec.nsec as i64 / 1000 / 1000) as u32
}

pub struct KcpOutput {
    udp: Rc<UdpSocket>,
    peer: SocketAddr,
}

impl Write for KcpOutput {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.udp.send_to(buf, &self.peer)
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

struct KcpTimer {
    kcp: Rc<RefCell<Kcp<KcpOutput>>>,
    timer: Rc<RefCell<Timeout>>,
}

impl Stream for KcpTimer {
    type Item = ();
    type Error = io::Error;

    fn poll(&mut self) -> Poll<Option<()>, io::Error> {
        let mut timer = self.timer.borrow_mut();
        match timer.poll() {
            Ok(Async::Ready(())) => {
                let mut kcp = self.kcp.borrow_mut();
                kcp.update(current())?;
                let dur = kcp.check(current());
                let next = Instant::now() + Duration::from_millis(dur as u64);
                timer.reset(next);
                Ok(Async::Ready(Some(())))
            }
            Ok(Async::NotReady) => Ok(Async::NotReady),
            Err(e) => Err(e),
        }
    }
}

struct KcpIo {
    kcp: Rc<RefCell<Kcp<KcpOutput>>>,
    registration: Registration,
    set_readiness: SetReadiness,
}

impl Read for KcpIo {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.kcp.borrow_mut().recv(buf)
    }
}

impl Write for KcpIo {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let mut kcp = self.kcp.borrow_mut();
        kcp.send(&mut BytesMut::from_buf(buf)).and_then(|n| {
            kcp.flush().map(|_| n)
        })
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

impl Evented for KcpIo {
    fn register(
        &self,
        poll: &mio::Poll,
        token: Token,
        interest: Ready,
        opts: PollOpt,
    ) -> io::Result<()> {
        self.registration.register(poll, token, interest, opts)
    }

    fn reregister(
        &self,
        poll: &mio::Poll,
        token: Token,
        interest: Ready,
        opts: PollOpt,
    ) -> io::Result<()> {
        self.registration.reregister(poll, token, interest, opts)
    }

    fn deregister(&self, poll: &mio::Poll) -> io::Result<()> {
        <Registration as Evented>::deregister(&self.registration, poll)
    }
}

pub struct KcpClientStream {
    udp: Rc<UdpSocket>,
    io: PollEvented<KcpIo>,
}

impl Read for KcpClientStream {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if let Ok((n, _)) = self.udp.recv_from(buf) {
            self.io.get_ref().kcp.borrow_mut().input(
                &mut BytesMut::from_buf(
                    &buf[..n],
                ),
            )?;
            self.io.get_ref().set_readiness.set_readiness(
                mio::Ready::readable(),
            )?;
        }
        self.io.read(buf)
    }
}

impl AsyncRead for KcpClientStream {}

impl AsyncWrite for KcpClientStream {
    fn shutdown(&mut self) -> Poll<(), io::Error> {
        Ok(().into())
    }
}

impl Write for KcpClientStream {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.io.get_ref().set_readiness.set_readiness(
            mio::Ready::writable(),
        )?;
        self.io.write(buf)
    }
    fn flush(&mut self) -> io::Result<()> {
        self.io.flush()
    }
}

pub struct KcpStreamNew {
    inner: Option<KcpClientStream>,
}

impl Future for KcpStreamNew {
    type Item = KcpClientStream;
    type Error = io::Error;

    fn poll(&mut self) -> Poll<KcpClientStream, io::Error> {
        Ok(Async::Ready(self.inner.take().unwrap()))
    }
}

pub struct KcpStream {
    io: PollEvented<KcpIo>,
}

impl KcpStream {
    pub fn connect(addr: &SocketAddr, handle: &Handle) -> KcpStreamNew {
        let local: SocketAddr = "0.0.0.0:0".parse().unwrap();
        let udp = Rc::new(UdpSocket::bind(&local, handle).unwrap());
        let kcp = Kcp::new(
            rand::random::<u32>(),
            KcpOutput {
                udp: udp.clone(),
                peer: *addr,
            },
        );
        let kcp = Rc::new(RefCell::new(kcp));
        let (registration, set_readiness) = Registration::new2();
        let timer = Rc::new(RefCell::new(
            Timeout::new_at(Instant::now(), handle).unwrap(),
        ));
        let io = KcpIo {
            kcp: kcp.clone(),
            registration: registration,
            set_readiness: set_readiness.clone(),
        };

        let interval = KcpTimer {
            kcp: kcp.clone(),
            timer: timer.clone(),
        };
        handle.spawn(interval.for_each(|_| Ok(())).then(|_| Ok(())));
        let io = PollEvented::new(io, handle).unwrap();
        let inner = KcpClientStream { udp: udp, io: io };
        KcpStreamNew { inner: Some(inner) }
    }
}

impl Read for KcpStream {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.io.read(buf)
    }
}

impl Write for KcpStream {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.io.get_ref().set_readiness.set_readiness(
            mio::Ready::writable(),
        )?;
        self.io.write(buf)
    }
    fn flush(&mut self) -> io::Result<()> {
        self.io.flush()
    }
}

impl AsyncRead for KcpStream {}

impl AsyncWrite for KcpStream {
    fn shutdown(&mut self) -> Poll<(), io::Error> {
        Ok(().into())
    }
}

struct KcpSession {
    kcp: Rc<RefCell<Kcp<KcpOutput>>>,
    set_readiness: SetReadiness,
}

pub struct KcpListener {
    udp: Rc<UdpSocket>,
    sessions: HashMap<SocketAddr, KcpSession>,
    handle: Handle,
}

pub struct Incoming {
    inner: KcpListener,
}

impl Stream for Incoming {
    type Item = (KcpStream, SocketAddr);
    type Error = io::Error;

    fn poll(&mut self) -> Poll<Option<Self::Item>, io::Error> {
        Ok(Async::Ready(Some(try_nb!(self.inner.accept()))))
    }
}

impl KcpListener {
    pub fn bind(addr: &SocketAddr, handle: &Handle) -> io::Result<KcpListener> {
        UdpSocket::bind(addr, handle).map(|udp| {
            KcpListener {
                udp: Rc::new(udp),
                sessions: HashMap::new(),
                handle: handle.clone(),
            }
        })
    }

    pub fn accept(&mut self) -> io::Result<(KcpStream, SocketAddr)> {
        let mut buf = [0; 1500];

        loop {
            let (size, addr) = self.udp.recv_from(&mut buf)?;

            if let Some(session) = self.sessions.get(&addr) {
                session.kcp.borrow_mut().input(&mut BytesMut::from_buf(
                    &buf[..size],
                ))?;
                session.set_readiness.set_readiness(mio::Ready::readable())?;
                continue;
            }

            let kcp = Kcp::new(
                get_conv(&buf),
                KcpOutput {
                    udp: self.udp.clone(),
                    peer: addr,
                },
            );
            let kcp = Rc::new(RefCell::new(kcp));
            let (registration, set_readiness) = Registration::new2();
            let timer = Rc::new(RefCell::new(Timeout::new_at(Instant::now(), &self.handle)?));
            let io = KcpIo {
                kcp: kcp.clone(),
                registration: registration,
                set_readiness: set_readiness.clone(),
            };
            let interval = KcpTimer {
                kcp: kcp.clone(),
                timer: timer.clone(),
            };
            self.handle.spawn(
                interval.for_each(|_| Ok(())).then(|_| Ok(())),
            );
            let io = PollEvented::new(io, &self.handle).unwrap();
            let stream = KcpStream { io: io };
            stream.io.get_ref().kcp.borrow_mut().input(
                &mut BytesMut::from_buf(&buf[..size]),
            )?;

            stream.io.get_ref().set_readiness.set_readiness(
                mio::Ready::readable(),
            )?;

            let session = KcpSession {
                kcp: kcp.clone(),
                set_readiness: set_readiness.clone(),
            };
            self.sessions.insert(addr, session);
            return Ok((stream, addr));
        }
    }

    pub fn incoming(self) -> Incoming {
        Incoming { inner: self }
    }
}
<commit_msg>refactor KcpStram's connect<commit_after>
extern crate bytes;
extern crate futures;
extern crate kcp;
extern crate mio;
#[macro_use]
extern crate tokio_core;
extern crate tokio_io;
extern crate rand;
extern crate time;

use std::cell::RefCell;
use std::collections::HashMap;
use std::io::{self, Read, Write};
use std::net::SocketAddr;
use std::rc::Rc;
use std::time::{Duration, Instant};

use bytes::BytesMut;
use bytes::buf::FromBuf;
use futures::{Poll, Async, Future};
use futures::stream::Stream;
use kcp::prelude::*;
use mio::{Ready, Registration, PollOpt, Token, SetReadiness};
use mio::event::Evented;
use tokio_core::net::UdpSocket;
use tokio_core::reactor::{Handle, PollEvented, Timeout};
use tokio_io::{AsyncRead, AsyncWrite};

#[inline]
fn current() -> u32 {
    let timespec = time::get_time();
    (timespec.sec * 1000 + timespec.nsec as i64 / 1000 / 1000) as u32
}

pub struct KcpOutput {
    udp: Rc<UdpSocket>,
    peer: SocketAddr,
}

impl Write for KcpOutput {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.udp.send_to(buf, &self.peer)
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

struct KcpTimer {
    kcp: Rc<RefCell<Kcp<KcpOutput>>>,
    timer: Rc<RefCell<Timeout>>,
}

impl Stream for KcpTimer {
    type Item = ();
    type Error = io::Error;

    fn poll(&mut self) -> Poll<Option<()>, io::Error> {
        let mut timer = self.timer.borrow_mut();
        match timer.poll() {
            Ok(Async::Ready(())) => {
                let mut kcp = self.kcp.borrow_mut();
                kcp.update(current())?;
                let dur = kcp.check(current());
                let next = Instant::now() + Duration::from_millis(dur as u64);
                timer.reset(next);
                Ok(Async::Ready(Some(())))
            }
            Ok(Async::NotReady) => Ok(Async::NotReady),
            Err(e) => Err(e),
        }
    }
}

struct KcpIo {
    kcp: Rc<RefCell<Kcp<KcpOutput>>>,
    registration: Registration,
    set_readiness: SetReadiness,
}

impl Read for KcpIo {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.kcp.borrow_mut().recv(buf)
    }
}

impl Write for KcpIo {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let mut kcp = self.kcp.borrow_mut();
        kcp.send(&mut BytesMut::from_buf(buf)).and_then(|n| {
            kcp.flush().map(|_| n)
        })
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

impl Evented for KcpIo {
    fn register(
        &self,
        poll: &mio::Poll,
        token: Token,
        interest: Ready,
        opts: PollOpt,
    ) -> io::Result<()> {
        self.registration.register(poll, token, interest, opts)
    }

    fn reregister(
        &self,
        poll: &mio::Poll,
        token: Token,
        interest: Ready,
        opts: PollOpt,
    ) -> io::Result<()> {
        self.registration.reregister(poll, token, interest, opts)
    }

    fn deregister(&self, poll: &mio::Poll) -> io::Result<()> {
        <Registration as Evented>::deregister(&self.registration, poll)
    }
}

pub struct KcpClientStream {
    udp: Rc<UdpSocket>,
    io: PollEvented<KcpIo>,
}

impl Read for KcpClientStream {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if let Ok((n, _)) = self.udp.recv_from(buf) {
            self.io.get_ref().kcp.borrow_mut().input(
                &mut BytesMut::from_buf(
                    &buf[..n],
                ),
            )?;
            self.io.get_ref().set_readiness.set_readiness(
                mio::Ready::readable(),
            )?;
        }
        self.io.read(buf)
    }
}

impl AsyncRead for KcpClientStream {}

impl AsyncWrite for KcpClientStream {
    fn shutdown(&mut self) -> Poll<(), io::Error> {
        Ok(().into())
    }
}

impl Write for KcpClientStream {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.io.get_ref().set_readiness.set_readiness(
            mio::Ready::writable(),
        )?;
        self.io.write(buf)
    }
    fn flush(&mut self) -> io::Result<()> {
        self.io.flush()
    }
}

pub struct KcpStreamNew {
    inner: Option<KcpClientStream>,
}

impl Future for KcpStreamNew {
    type Item = KcpClientStream;
    type Error = io::Error;

    fn poll(&mut self) -> Poll<KcpClientStream, io::Error> {
        Ok(Async::Ready(self.inner.take().unwrap()))
    }
}

pub struct KcpStream {
    io: PollEvented<KcpIo>,
}

impl KcpStream {
    pub fn connect(addr: &SocketAddr, handle: &Handle) -> KcpStreamNew {
        let local: SocketAddr = "0.0.0.0:0".parse().unwrap();

        let (registration, set_readiness) = Registration::new2();

        let timer = match Timeout::new_at(Instant::now(), handle) {
            Ok(timeout) => Rc::new(RefCell::new(timeout)),
            _ => return KcpStreamNew { inner: None },
        };

        let udp = match UdpSocket::bind(&local, handle) {
            Ok(udp) => Rc::new(udp),
            _ => return KcpStreamNew { inner: None },
        };

        let kcp = Rc::new(RefCell::new(Kcp::new(
            rand::random::<u32>(),
            KcpOutput {
                udp: udp.clone(),
                peer: *addr,
            },
        )));

        let io = KcpIo {
            kcp: kcp.clone(),
            registration: registration,
            set_readiness: set_readiness.clone(),
        };

        let io = match PollEvented::new(io, handle) {
            Ok(evented) => evented,
            _ => return KcpStreamNew { inner: None },
        };

        let interval = KcpTimer {
            kcp: kcp.clone(),
            timer: timer.clone(),
        };

        handle.spawn(interval.for_each(|_| Ok(())).then(|_| Ok(())));

        KcpStreamNew { inner: Some(KcpClientStream { udp: udp, io: io }) }
    }
}

impl Read for KcpStream {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.io.read(buf)
    }
}

impl Write for KcpStream {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.io.get_ref().set_readiness.set_readiness(
            mio::Ready::writable(),
        )?;
        self.io.write(buf)
    }
    fn flush(&mut self) -> io::Result<()> {
        self.io.flush()
    }
}

impl AsyncRead for KcpStream {}

impl AsyncWrite for KcpStream {
    fn shutdown(&mut self) -> Poll<(), io::Error> {
        Ok(().into())
    }
}

struct KcpSession {
    kcp: Rc<RefCell<Kcp<KcpOutput>>>,
    set_readiness: SetReadiness,
}

pub struct KcpListener {
    udp: Rc<UdpSocket>,
    sessions: HashMap<SocketAddr, KcpSession>,
    handle: Handle,
}

pub struct Incoming {
    inner: KcpListener,
}

impl Stream for Incoming {
    type Item = (KcpStream, SocketAddr);
    type Error = io::Error;

    fn poll(&mut self) -> Poll<Option<Self::Item>, io::Error> {
        Ok(Async::Ready(Some(try_nb!(self.inner.accept()))))
    }
}

impl KcpListener {
    pub fn bind(addr: &SocketAddr, handle: &Handle) -> io::Result<KcpListener> {
        UdpSocket::bind(addr, handle).map(|udp| {
            KcpListener {
                udp: Rc::new(udp),
                sessions: HashMap::new(),
                handle: handle.clone(),
            }
        })
    }

    pub fn accept(&mut self) -> io::Result<(KcpStream, SocketAddr)> {
        let mut buf = [0; 1500];

        loop {
            let (size, addr) = self.udp.recv_from(&mut buf)?;

            if let Some(session) = self.sessions.get(&addr) {
                session.kcp.borrow_mut().input(&mut BytesMut::from_buf(
                    &buf[..size],
                ))?;
                session.set_readiness.set_readiness(mio::Ready::readable())?;
                continue;
            }

            let kcp = Kcp::new(
                get_conv(&buf),
                KcpOutput {
                    udp: self.udp.clone(),
                    peer: addr,
                },
            );
            let kcp = Rc::new(RefCell::new(kcp));
            let (registration, set_readiness) = Registration::new2();
            let timer = Rc::new(RefCell::new(Timeout::new_at(Instant::now(), &self.handle)?));
            let io = KcpIo {
                kcp: kcp.clone(),
                registration: registration,
                set_readiness: set_readiness.clone(),
            };
            let interval = KcpTimer {
                kcp: kcp.clone(),
                timer: timer.clone(),
            };
            self.handle.spawn(
                interval.for_each(|_| Ok(())).then(|_| Ok(())),
            );
            let io = PollEvented::new(io, &self.handle).unwrap();
            let stream = KcpStream { io: io };
            stream.io.get_ref().kcp.borrow_mut().input(
                &mut BytesMut::from_buf(&buf[..size]),
            )?;

            stream.io.get_ref().set_readiness.set_readiness(
                mio::Ready::readable(),
            )?;

            let session = KcpSession {
                kcp: kcp.clone(),
                set_readiness: set_readiness.clone(),
            };
            self.sessions.insert(addr, session);
            return Ok((stream, addr));
        }
    }

    pub fn incoming(self) -> Incoming {
        Incoming { inner: self }
    }
}
<|endoftext|>


<commit_before>
extern crate websocket;

use std::thread;
use std::sync::{Arc, Mutex};
use std::fs::File;
use std::path::Path;
use std::io::Read;
use std::io::Write;
use std::io::{Error,ErrorKind};
use std::string::*;

use websocket::{Server, Message, Sender, Receiver};
use websocket::header::WebSocketProtocol;
use websocket::message::Type;

extern crate iron;

use iron::prelude::*;
use iron::status;
use iron::mime::Mime;

#[macro_use]
mod tryopt;
mod stringerror;
mod controls;
mod broadcaster;
mod string_defaults;
pub mod control_updates;

extern crate serde_json;
use serde_json::Value;

fn load_string(file_name: &str) -> Result<String, Box<std::error::Error> >
{
  let path = &Path::new(&file_name);
  let mut inf = try!(File::open(path));
  let mut result = String::new();
  try!(inf.read_to_string(&mut result));
  Ok(result)
}

fn write_string(text: &str, file_name: &str) -> Result<(), Box<std::error::Error> >
{
  let path = &Path::new(&file_name);
  let mut inf = try!(File::create(path));
  match inf.write(text.as_bytes()) {
    Ok(_) => Ok(()),
    Err(e) => Err(Box::new(e)),
    }
}

pub struct ControlInfo {
  cm: controls::ControlMap,
  cnm: controls::ControlNameMap,
  guijson: String,
}

pub struct ControlServer<'a> {
  ci: Arc<Mutex<ControlInfo>>,
  bc: broadcaster::Broadcaster,
  on_update_received: &'a ControlUpdateProcessor,
}

pub trait ControlUpdateProcessor {
  fn on_update_received(&self, &control_updates::UpdateMsg) -> ();
}

impl<'a> ControlServer<'a> {
  fn get_cid_by_name(&self, name: &str) -> Option<Vec<i32> > {
    let guard = match self.ci.lock() {
      Ok(guard) => guard,
      Err(poisoned) => poisoned.into_inner(),
    };

    match guard.cnm.get(name) {
      Some(cid) => Some(cid.clone()),
      _ => None,
    }
  }

  pub fn get_osc_name(&self, id: &Vec<i32>) -> Option<String>
  {
    let ci = match self.ci.lock() {
      Ok(guard) => guard,
      Err(poisoned) => poisoned.into_inner(),
    };

    match ci.cm.get(id) {
      Some(ctrl) => Some(String::from(ctrl.oscname())),
      _ => None,
    }

  }

  pub fn make_update_msg(&self, name: &str) -> Option<control_updates::UpdateMsg> {
    let guard = match self.ci.lock() {
      Ok(guard) => guard,
      Err(poisoned) => poisoned.into_inner(),
    };

    match guard.cnm.get(name) {
      Some(cid) =>
        match guard.cm.get(cid) {
          Some(ctrl) => ctrl.empty_update(),
          None => None,
        },
      _ => None,
    }
  }
  pub fn update(&self, updmsg: &control_updates::UpdateMsg) {
    let mut ci = match self.ci.lock() {
      Ok(guard) => guard,
      Err(poisoned) => poisoned.into_inner(),
    };

    match ci.cm.get_mut(controls::get_um_id(&updmsg)) {
    Some(ctl) => {
      (*ctl).update(&updmsg);
      let val = controls::encode_update_message(&updmsg);
      match serde_json::ser::to_string(&val) {
        Ok(s) => self.bc.broadcast(Message::text(s)),
        Err(_) => ()
        }
      }
    None => (),
    }
  }
  pub fn load_gui_string(&self, guistring: &str) -> Result<(), Box<std::error::Error> >
  {
    match serde_json::from_str(guistring) {
      Ok(guival) => {
        match controls::deserialize_root(&guival) {
          Ok(controltree) => {
            println!("new control layout recieved!");

            println!("title: {} count: {} ",
              controltree.title, controltree.root_control.control_type());
            println!("controls: {:?}", controltree.root_control);

            // from control tree, make a map of ids->controls.
            // let mapp = controls::make_control_map(&*controltree.root_control);
            // let cnm = controls::control_map_to_name_map(&mapp);
  /*
            sci.cm = mapp;
            sci.guijson = guistring.to_string();
            bc.broadcast(Message::text(guistring.to_string()));

  pub struct ControlInfo {
    cm: controls::ControlMap,
    cnm: controls::ControlNameMap,
    guijson: String,
  }

  */
            let mut guard = match self.ci.lock() {
                Ok(guard) => guard,
                Err(poisoned) => poisoned.into_inner(),
            };

            (*guard).cm = controls::make_control_map(&*controltree.root_control);
            (*guard).cnm = controls::control_map_to_name_map(&(*guard).cm);
            (*guard).guijson = guistring.to_string();

            // send the updated gui string to all clients.
            self.bc.broadcast(Message::text(guistring.to_string()));

            Ok(())
          },
          Err(e) => {
            println!("error reading guiconfig from json: {:?}", e);
            let s = format!("error reading guiconfig json: {:?}", e);
            Err(Box::new(Error::new(ErrorKind::Other, s))) },
        }
      },
      Err(e) => {
        // println!("error reading guiconfig json: {:?}", e);
        let s = format!("error reading guiconfig json: {:?}", e);
        Err(Box::new(Error::new(ErrorKind::Other, s))) },
    }
  }

}

//  iron-server-canceler: ???
//  websocket-thread-canceler: ???
//  fn lookup_control(name) -> index
//  fn modify_control(index, ftn) -> result   <-- will this work with types??  have to cast.
//  load_guistring

//  how about ftns like the ones for faust, for building the gui tree?
//  addbutton
//  addslider
//  addlabel
//  startsizer
//  endsizer

pub fn startserver<'a>(guistring: &str,
    on_update_received: &'a ControlUpdateProcessor,
    ip: &str,
    http_port: &str,
    websockets_port: &str,
    htmltemplatefile: Option<&str> ) -> Result<ControlServer<'a>, Box<std::error::Error> >
{
    let mut http_ip = String::from(ip);
    http_ip.push_str(":");
    http_ip.push_str(&http_port);

    let mut websockets_ip = String::from(ip);
    websockets_ip.push_str(":");
    websockets_ip.push_str(&websockets_port);

    let htmltemplate = {
      match htmltemplatefile {
        Some(fname) => {
          try!(load_string(fname))
        }
        None => string_defaults::MAIN_HTML.to_string()
      }
    };

    let htmlstring = htmltemplate.replace("<websockets-port>", &websockets_port);

    // println!("{}", htmlstring);

    // let guistring = try!(load_string(&guifilename[..]));
    // let guival: Value = try!(serde_json::from_str(&guistring[..]));
    let guival: Value = try!(serde_json::from_str(guistring));

    let blah = try!(controls::deserialize_root(&guival));

    println!("title: {} rootcontroltype: {} ",
      blah.title, blah.root_control.control_type());
    println!("controls: {:?}", blah.root_control);

    // from control tree, make a map of ids->controls.
    let mapp = controls::make_control_map(&*blah.root_control);
    let cnm = controls::control_map_to_name_map(&mapp);
    // let guijson = guistring.clone();

    let ci = ControlInfo { cm: mapp, cnm: cnm, guijson: String::new() + guistring };

    let cmshare = Arc::new(Mutex::new(ci));
    let wscmshare = cmshare.clone();
    // let oscsocket = try!(UdpSocket::bind(&oscrecvip[..]));
    // for sending, bind to this.  if we bind to localhost, we can't
    // send messages to other machines.
    // let oscsendsocket = try!(UdpSocket::bind("0.0.0.0:0"));
    let bc = broadcaster::Broadcaster::new();
    // let wsos = try!(oscsendsocket.try_clone());
    let wsbc = bc.clone();
    // let wsoscsendip = oscsendip.clone();

    let cs_ret = ControlServer { ci: cmshare,
                                 bc: bc,
                                 on_update_received: on_update_received,
                               };

    /*
    thread::spawn(move || {
      match oscmain(oscsocket, bc, cmshare) {
        Err(e) => println!("oscmain exited with error: {:?}", e),
        Ok(_) => (),
      }
      });
    */

    // Spawn a thread for the websockets handler.
    thread::spawn(move || {
      match websockets_main(websockets_ip, wscmshare, wsbc, on_update_received) {
        Ok(_) => (),
        Err(e) => println!("error in websockets_main: {:?}", e),
      }
    });

    thread::spawn(move || {
      // use this thread for the web server.
      Iron::new(move | _: &mut Request| {
          let content_type = "text/html".parse::<Mime>().unwrap();
          Ok(Response::with((content_type, status::Ok, &*htmlstring)))
      }).http(&http_ip[..]);
      // return when the web server dies, if it ever does.
      });

    Ok(cs_ret)

}

// need to lock the control structs and stuff, refresh them, then send out the
// updates.

// TODO: refactor to return a (rx/sx) pair for sending, recieving messages.
// library users start the websockets_main and get that pair of things.
// then, can send the various control structs and receive the messages.
fn websockets_main<'a>( ipaddr: String,
                    ci: Arc<Mutex<ControlInfo>>,
                    broadcaster: broadcaster::Broadcaster,
                    on_update_received: &'a ControlUpdateProcessor,
                    )
                  -> Result<(), Box<std::error::Error> >
{
	let server = try!(Server::bind(&ipaddr[..]));

	for connection in server {

    println!("new websockets connection!");
		// Spawn a new thread for each connection.

    let sci = ci.clone();
//    let osock = try!(oscsocket.try_clone());
 //   let osend = oscsendip.clone();
    let broadcaster = broadcaster.clone();

    let conn = try!(connection);
    thread::spawn(move || {
      match websockets_client(conn,
                            sci,
                            broadcaster,
                            on_update_received) {
        Ok(_) => (),
        Err(e) => {
          println!("error in websockets thread: {:?}", e);
          ()
        },
      }
    });
  }

  Ok(())
}

fn websockets_client(connection: websocket::server::Connection<websocket::stream::WebSocketStream, websocket::stream::WebSocketStream>,
                    ci: Arc<Mutex<ControlInfo>>,
                    mut broadcaster: broadcaster::Broadcaster,
                    on_update_received: fn(&control_updates::UpdateMsg) -> (),
                    ) -> Result<(), Box<std::error::Error> >
{
  // Get the request
  let request = try!(connection.read_request());
  // Keep the headers so we can check them
  let headers = request.headers.clone();

  try!(request.validate()); // Validate the request

  let mut response = request.accept(); // Form a response

  if let Some(&WebSocketProtocol(ref protocols)) = headers.get() {
    if protocols.contains(&("rust-websocket".to_string())) {
      // We have a protocol we want to use
      response.headers.set(WebSocketProtocol(vec!["rust-websocket".to_string()]));
    }
  }

  let mut client = try!(response.send()); // Send the response

  let ip = try!(client.get_mut_sender()
                  .get_mut()
                  .peer_addr());

  println!("Websocket connection from {}", ip);

  // send up the json of the current controls.
  {
    let sci = ci.lock().unwrap();

    let updarray = controls::cm_to_update_array(&sci.cm);

    // build json message containing both guijson and the updarray.
    // let updvals = updarray.into_iter().map(|x|{controls::encode_update_message(&x)}).collect();

    let mut updvals = Vec::new();

    for upd in updarray {
      let um = controls::encode_update_message(&upd);
      updvals.push(um);
    }

    let mut guival: Value = try!(serde_json::from_str(&sci.guijson[..]));

    match guival.as_object_mut() {
      Some(obj) => {
        obj.insert("state".to_string(), Value::Array(updvals));
        ()
      },
      None => (),
    }

    let guistring = try!(serde_json::ser::to_string(&guival));
    let message = Message::text(guistring);
    try!(client.send_message(&message));
  }

  let (sender, mut receiver) = client.split();

  let sendmeh = Arc::new(Mutex::new(sender));

  broadcaster.register(sendmeh.clone());

  for msg in receiver.incoming_messages() {
    let message: Message = try!(msg);
    // println!("message: {:?}", message);

    match message.opcode {
      Type::Close => {
        let message = Message::close();
        // let mut sender = try!(sendmeh.lock());
        let mut sender = sendmeh.lock().unwrap();
        try!(sender.send_message(&message));
        println!("Client {} disconnected", ip);
        return Ok(());
      }
      Type::Ping => {
        println!("Message::Ping(data)");
        let message = Message::pong(message.payload);
        let mut sender = sendmeh.lock().unwrap();
        try!(sender.send_message(&message));
      }
      Type::Text => {
        let u8 = message.payload.to_owned();
        let str = try!(std::str::from_utf8(&*u8));
        let jsonval: Value = try!(serde_json::from_str(str));
        let s_um = controls::decode_update_message(&jsonval);
        match s_um {
          Some(updmsg) => {
            let mut sci  = ci.lock().unwrap();
            let mbcntrl = sci.cm.get_mut(controls::get_um_id(&updmsg));
            match mbcntrl {
              Some(cntrl) => {
                (*cntrl).update(&updmsg);
                broadcaster.broadcast_others(&ip, Message::text(str));

                // TODO: callback ftn??
                /*
                match ctrl_update_to_osc(&updmsg, &**cntrl) {
                  Ok(v) => match oscsocket.send_to(&v, &oscsendip[..]) {
                    Ok(_) => (),
                    Err(e) =>
                      println!("error sending osc message: {:?}", e),
                    },
                  Err(e) =>
                    println!("error building osc message: {:?}", e),
                };
                */

                on_update_received(&updmsg);

                println!("websockets control update recieved: {:?}", updmsg);
                ()
              },
              None => println!("none"),
            }
          },
          _ => println!("decode_update_message failed on websockets msg: {:?}", message),
        }
      },
      _ => {
        println!("unknown websockets msg: {:?}", message);
      }
    }
  }

  Ok(())
}

<commit_msg>compiles and seems to work<commit_after>
extern crate websocket;

use std::thread;
use std::sync::{Arc, Mutex};
use std::fs::File;
use std::path::Path;
use std::io::Read;
use std::io::Write;
use std::io::{Error,ErrorKind};
use std::string::*;

use websocket::{Server, Message, Sender, Receiver};
use websocket::header::WebSocketProtocol;
use websocket::message::Type;

extern crate iron;

use iron::prelude::*;
use iron::status;
use iron::mime::Mime;

#[macro_use]
mod tryopt;
mod stringerror;
mod controls;
mod broadcaster;
mod string_defaults;
pub mod control_updates;

extern crate serde_json;
use serde_json::Value;

fn load_string(file_name: &str) -> Result<String, Box<std::error::Error> >
{
  let path = &Path::new(&file_name);
  let mut inf = try!(File::open(path));
  let mut result = String::new();
  try!(inf.read_to_string(&mut result));
  Ok(result)
}

fn write_string(text: &str, file_name: &str) -> Result<(), Box<std::error::Error> >
{
  let path = &Path::new(&file_name);
  let mut inf = try!(File::create(path));
  match inf.write(text.as_bytes()) {
    Ok(_) => Ok(()),
    Err(e) => Err(Box::new(e)),
    }
}

pub trait ControlUpdateProcessor: Send {
  fn on_update_received(&mut self, &control_updates::UpdateMsg) -> ();
}

pub struct ControlInfo {
  cm: controls::ControlMap,
  cnm: controls::ControlNameMap,
  guijson: String,
  cup: Box<ControlUpdateProcessor>,
}

pub struct ControlServer {
  ci: Arc<Mutex<ControlInfo>>,
  bc: broadcaster::Broadcaster,
}

impl ControlServer {
  fn get_cid_by_name(&self, name: &str) -> Option<Vec<i32> > {
    let guard = match self.ci.lock() {
      Ok(guard) => guard,
      Err(poisoned) => poisoned.into_inner(),
    };

    match guard.cnm.get(name) {
      Some(cid) => Some(cid.clone()),
      _ => None,
    }
  }

  pub fn get_osc_name(&self, id: &Vec<i32>) -> Option<String>
  {
    let ci = match self.ci.lock() {
      Ok(guard) => guard,
      Err(poisoned) => poisoned.into_inner(),
    };

    match ci.cm.get(id) {
      Some(ctrl) => Some(String::from(ctrl.oscname())),
      _ => None,
    }

  }

  pub fn make_update_msg(&self, name: &str) -> Option<control_updates::UpdateMsg> {
    let guard = match self.ci.lock() {
      Ok(guard) => guard,
      Err(poisoned) => poisoned.into_inner(),
    };

    match guard.cnm.get(name) {
      Some(cid) =>
        match guard.cm.get(cid) {
          Some(ctrl) => ctrl.empty_update(),
          None => None,
        },
      _ => None,
    }
  }
  pub fn update(&self, updmsg: &control_updates::UpdateMsg) {
    let mut ci = match self.ci.lock() {
      Ok(guard) => guard,
      Err(poisoned) => poisoned.into_inner(),
    };

    match ci.cm.get_mut(controls::get_um_id(&updmsg)) {
    Some(ctl) => {
      (*ctl).update(&updmsg);
      let val = controls::encode_update_message(&updmsg);
      match serde_json::ser::to_string(&val) {
        Ok(s) => self.bc.broadcast(Message::text(s)),
        Err(_) => ()
        }
      }
    None => (),
    }
  }
  pub fn load_gui_string(&self, guistring: &str) -> Result<(), Box<std::error::Error> >
  {
    match serde_json::from_str(guistring) {
      Ok(guival) => {
        match controls::deserialize_root(&guival) {
          Ok(controltree) => {
            println!("new control layout recieved!");

            println!("title: {} count: {} ",
              controltree.title, controltree.root_control.control_type());
            println!("controls: {:?}", controltree.root_control);

            // from control tree, make a map of ids->controls.
            // let mapp = controls::make_control_map(&*controltree.root_control);
            // let cnm = controls::control_map_to_name_map(&mapp);
  /*
            sci.cm = mapp;
            sci.guijson = guistring.to_string();
            bc.broadcast(Message::text(guistring.to_string()));

  pub struct ControlInfo {
    cm: controls::ControlMap,
    cnm: controls::ControlNameMap,
    guijson: String,
  }

  */
            let mut guard = match self.ci.lock() {
                Ok(guard) => guard,
                Err(poisoned) => poisoned.into_inner(),
            };

            (*guard).cm = controls::make_control_map(&*controltree.root_control);
            (*guard).cnm = controls::control_map_to_name_map(&(*guard).cm);
            (*guard).guijson = guistring.to_string();

            // send the updated gui string to all clients.
            self.bc.broadcast(Message::text(guistring.to_string()));

            Ok(())
          },
          Err(e) => {
            println!("error reading guiconfig from json: {:?}", e);
            let s = format!("error reading guiconfig json: {:?}", e);
            Err(Box::new(Error::new(ErrorKind::Other, s))) },
        }
      },
      Err(e) => {
        // println!("error reading guiconfig json: {:?}", e);
        let s = format!("error reading guiconfig json: {:?}", e);
        Err(Box::new(Error::new(ErrorKind::Other, s))) },
    }
  }

}

//  iron-server-canceler: ???
//  websocket-thread-canceler: ???
//  fn lookup_control(name) -> index
//  fn modify_control(index, ftn) -> result   <-- will this work with types??  have to cast.
//  load_guistring

//  how about ftns like the ones for faust, for building the gui tree?
//  addbutton
//  addslider
//  addlabel
//  startsizer
//  endsizer

pub fn startserver<'a>(guistring: &str,
    cup: Box<ControlUpdateProcessor>,
    ip: &str,
    http_port: &str,
    websockets_port: &str,
    htmltemplatefile: Option<&str> ) -> Result<ControlServer, Box<std::error::Error> >
{
    let mut http_ip = String::from(ip);
    http_ip.push_str(":");
    http_ip.push_str(&http_port);

    let mut websockets_ip = String::from(ip);
    websockets_ip.push_str(":");
    websockets_ip.push_str(&websockets_port);

    let htmltemplate = {
      match htmltemplatefile {
        Some(fname) => {
          try!(load_string(fname))
        }
        None => string_defaults::MAIN_HTML.to_string()
      }
    };

    let htmlstring = htmltemplate.replace("<websockets-port>", &websockets_port);

    // println!("{}", htmlstring);

    // let guistring = try!(load_string(&guifilename[..]));
    // let guival: Value = try!(serde_json::from_str(&guistring[..]));
    let guival: Value = try!(serde_json::from_str(guistring));

    let blah = try!(controls::deserialize_root(&guival));

    println!("title: {} rootcontroltype: {} ",
      blah.title, blah.root_control.control_type());
    println!("controls: {:?}", blah.root_control);

    // from control tree, make a map of ids->controls.
    let mapp = controls::make_control_map(&*blah.root_control);
    let cnm = controls::control_map_to_name_map(&mapp);
    // let guijson = guistring.clone();

    let ci = ControlInfo { cm: mapp,
                           cnm: cnm,
                           guijson: String::new() + guistring,
                           cup: cup,
                           };

    let cmshare = Arc::new(Mutex::new(ci));
    let wscmshare = cmshare.clone();
    // let oscsocket = try!(UdpSocket::bind(&oscrecvip[..]));
    // for sending, bind to this.  if we bind to localhost, we can't
    // send messages to other machines.
    // let oscsendsocket = try!(UdpSocket::bind("0.0.0.0:0"));
    let bc = broadcaster::Broadcaster::new();
    // let wsos = try!(oscsendsocket.try_clone());
    let wsbc = bc.clone();
    // let wsoscsendip = oscsendip.clone();

    let cs_ret = ControlServer { ci: cmshare,
                                 bc: bc,
                                 // on_update_received: on_update_received,
                               };

    /*
    thread::spawn(move || {
      match oscmain(oscsocket, bc, cmshare) {
        Err(e) => println!("oscmain exited with error: {:?}", e),
        Ok(_) => (),
      }
      });
    */

    // Spawn a thread for the websockets handler.
    thread::spawn(move || {
      match websockets_main(websockets_ip, wscmshare, wsbc) {
        Ok(_) => (),
        Err(e) => println!("error in websockets_main: {:?}", e),
      }
    });

    thread::spawn(move || {
      // use this thread for the web server.
      Iron::new(move | _: &mut Request| {
          let content_type = "text/html".parse::<Mime>().unwrap();
          Ok(Response::with((content_type, status::Ok, &*htmlstring)))
      }).http(&http_ip[..]);
      // return when the web server dies, if it ever does.
      });

    Ok(cs_ret)

}

// need to lock the control structs and stuff, refresh them, then send out the
// updates.

// TODO: refactor to return a (rx/sx) pair for sending, recieving messages.
// library users start the websockets_main and get that pair of things.
// then, can send the various control structs and receive the messages.
fn websockets_main( ipaddr: String,
                    ci: Arc<Mutex<ControlInfo>>,
                    broadcaster: broadcaster::Broadcaster,
//                    on_update_received: &ControlUpdateProcessor,
                    )
                  -> Result<(), Box<std::error::Error> >
{
	let server = try!(Server::bind(&ipaddr[..]));

	for connection in server {

    println!("new websockets connection!");
		// Spawn a new thread for each connection.

    let sci = ci.clone();
//    let osock = try!(oscsocket.try_clone());
 //   let osend = oscsendip.clone();
    let broadcaster = broadcaster.clone();
//    let our = on_update_received.clone();   // a different one for each connection?

    let conn = try!(connection);
    thread::spawn(move || {
      match websockets_client(conn,
                            sci,
                            broadcaster,
                           // &our
                            ) {
        Ok(_) => (),
        Err(e) => {
          println!("error in websockets thread: {:?}", e);
          ()
        },
      }
    });
  }

  Ok(())
}

fn websockets_client(connection: websocket::server::Connection<websocket::stream::WebSocketStream,
                    websocket::stream::WebSocketStream>,
                    ci: Arc<Mutex<ControlInfo>>,
                    mut broadcaster: broadcaster::Broadcaster,
   //                 on_update_received: &ControlUpdateProcessor,
                    ) -> Result<(), Box<std::error::Error> >
{
  // Get the request
  let request = try!(connection.read_request());
  // Keep the headers so we can check them
  let headers = request.headers.clone();

  try!(request.validate()); // Validate the request

  let mut response = request.accept(); // Form a response

  if let Some(&WebSocketProtocol(ref protocols)) = headers.get() {
    if protocols.contains(&("rust-websocket".to_string())) {
      // We have a protocol we want to use
      response.headers.set(WebSocketProtocol(vec!["rust-websocket".to_string()]));
    }
  }

  let mut client = try!(response.send()); // Send the response

  let ip = try!(client.get_mut_sender()
                  .get_mut()
                  .peer_addr());

  println!("Websocket connection from {}", ip);

  // send up the json of the current controls.
  {
    let sci = ci.lock().unwrap();

    let updarray = controls::cm_to_update_array(&sci.cm);

    // build json message containing both guijson and the updarray.
    // let updvals = updarray.into_iter().map(|x|{controls::encode_update_message(&x)}).collect();

    let mut updvals = Vec::new();

    for upd in updarray {
      let um = controls::encode_update_message(&upd);
      updvals.push(um);
    }

    let mut guival: Value = try!(serde_json::from_str(&sci.guijson[..]));

    match guival.as_object_mut() {
      Some(obj) => {
        obj.insert("state".to_string(), Value::Array(updvals));
        ()
      },
      None => (),
    }

    let guistring = try!(serde_json::ser::to_string(&guival));
    let message = Message::text(guistring);
    try!(client.send_message(&message));
  }

  let (sender, mut receiver) = client.split();

  let sendmeh = Arc::new(Mutex::new(sender));

  broadcaster.register(sendmeh.clone());

  for msg in receiver.incoming_messages() {
    let message: Message = try!(msg);
    // println!("message: {:?}", message);

    match message.opcode {
      Type::Close => {
        let message = Message::close();
        // let mut sender = try!(sendmeh.lock());
        let mut sender = sendmeh.lock().unwrap();
        try!(sender.send_message(&message));
        println!("Client {} disconnected", ip);
        return Ok(());
      }
      Type::Ping => {
        println!("Message::Ping(data)");
        let message = Message::pong(message.payload);
        let mut sender = sendmeh.lock().unwrap();
        try!(sender.send_message(&message));
      }
      Type::Text => {
        let u8 = message.payload.to_owned();
        let str = try!(std::str::from_utf8(&*u8));
        let jsonval: Value = try!(serde_json::from_str(str));
        let s_um = controls::decode_update_message(&jsonval);
        match s_um {
          Some(updmsg) => {
            let mut sci  = ci.lock().unwrap();
            {
            let mbcntrl = sci.cm.get_mut(controls::get_um_id(&updmsg));
            match mbcntrl {
              Some(cntrl) => {
                (*cntrl).update(&updmsg);
                broadcaster.broadcast_others(&ip, Message::text(str));

                // TODO: callback ftn??
                /*
                match ctrl_update_to_osc(&updmsg, &**cntrl) {
                  Ok(v) => match oscsocket.send_to(&v, &oscsendip[..]) {
                    Ok(_) => (),
                    Err(e) =>
                      println!("error sending osc message: {:?}", e),
                    },
                  Err(e) =>
                    println!("error building osc message: {:?}", e),
                };
                */

                println!("websockets control update recieved: {:?}", updmsg);
                ()
              },
              None => println!("none"),
            }
            }

            sci.cup.on_update_received(&updmsg);
          },
          _ => println!("decode_update_message failed on websockets msg: {:?}", message),
        }
      },
      _ => {
        println!("unknown websockets msg: {:?}", message);
      }
    }
  }

  Ok(())
}

<|endoftext|>


<commit_before>use std::collections::BTreeMap;
use std::io::prelude::*;
use std::fs::File;

enum DomainOrIPAddressLiteral<'a> {
    ADomain(Domain<'a>),
    IPAddressLiteral(&'a str),
}

// TODO: Better type:
type Domain<'a> = &'a str;

type Postmaster = String;
fn postmaster() {
    "Postmaster";
}

enum AddressOrPostmaster<'a> {
    AnAddress(Address<'a>),
    Postmaster,
}

struct Address<'a> {
    local_part: &'a str, // TODO: own type
    domain: Domain<'a>,
}

enum OneOrMore<T> {
    One(T),
    More(T,Box<OneOrMore<T>>),
}

enum ProtocolExtension {
    EightBitMIME,
}

struct Envelope<'a> {
    originator: Address<'a>,
    recipients: OneOrMore<Address<'a>>,
    protocol_extensions: Vec<ProtocolExtension>
}

struct Header<'a> {
    fields: BTreeMap<&'a str, &'a str> // Case-insensitivity
}

struct Content<'a> {
    header: Header<'a>,
    body: &'a str, // TODO: own type
}

struct MailObject<'a> {
    envelope: Envelope<'a>,
    content: Content<'a>,
}

type ReversePath = String;
type MailParameter = String;
type RecipientParameter = String;

enum SMTPCommand<'a> {
    Hello(Domain<'a>),
    ExtendedHello(DomainOrIPAddressLiteral<'a>),
    Mail(ReversePath, Vec<MailParameter>),
    Recipient(Vec<AddressOrPostmaster<'a>>, Vec<RecipientParameter>),
    Data,
    Reset,
    Verify(String),
    Expand(String),
    Help(Option<String>),
    NoOp(Option<String>),
    Quit,
}

fn helo(stream: Write) -> std::io::Result<usize> {
  let mut helo_string = "HELO";
  stream.write(helo_string);
}

type ExtendedHelloGreet = String;

type ExtendedHelloLine = String;

enum SMTPResponse<'a> {
    ExtendedHelloOkResponse(Domain<'a>, Option<ExtendedHelloGreet>, Vec<ExtendedHelloLine>),
}

#[test]
fn it_works() {
    let mail_object = MailObject {
        envelope: Envelope {
            originator: Address {
                local_part: "kyle.marek.spartz",
                domain: "gmail.com",
            },
            recipients: OneOrMore::More(Address {
                    local_part: "zeckalpha",
                    domain: "gmail.com",
                }, Box::new(OneOrMore::One(Address {
                    local_part: "kyle",
                    domain: "marek-spartz.org",
                }))
            ),
            protocol_extensions: vec![
                ProtocolExtension::EightBitMIME,
            ]
        },
        content: Content {
            header: Header {
                fields: {
                    let mut fields = BTreeMap::new();
                    fields.insert("orig-date", "...");
                    fields.insert("from", "kyle.marek.spartz@gmail.com");
                    fields
                }
            },
            body: "LOL"
        }
    };
    assert_eq!("LOL", mail_object.content.body);
}

#[test]
fn helo_writes() {
    let mut stream = try!(File::create("helo_output"));
    let mut content = String::new();
    helo(stream);
    stream.read_to_string(&mut content);
    assert_eq!("HELO", content);
}
<commit_msg>Make the tests pass<commit_after>use std::collections::BTreeMap;
use std::io::prelude::*;

enum DomainOrIPAddressLiteral<'a> {
    ADomain(Domain<'a>),
    IPAddressLiteral(&'a str),
}

// TODO: Better type:
type Domain<'a> = &'a str;

type Postmaster = String;
fn postmaster() {
    "Postmaster";
}

enum AddressOrPostmaster<'a> {
    AnAddress(Address<'a>),
    Postmaster,
}

struct Address<'a> {
    local_part: &'a str, // TODO: own type
    domain: Domain<'a>,
}

enum OneOrMore<T> {
    One(T),
    More(T,Box<OneOrMore<T>>),
}

enum ProtocolExtension {
    EightBitMIME,
}

struct Envelope<'a> {
    originator: Address<'a>,
    recipients: OneOrMore<Address<'a>>,
    protocol_extensions: Vec<ProtocolExtension>
}

struct Header<'a> {
    fields: BTreeMap<&'a str, &'a str> // Case-insensitivity
}

struct Content<'a> {
    header: Header<'a>,
    body: &'a str, // TODO: own type
}

struct MailObject<'a> {
    envelope: Envelope<'a>,
    content: Content<'a>,
}

type ReversePath = String;
type MailParameter = String;
type RecipientParameter = String;

enum SMTPCommand<'a> {
    Hello(Domain<'a>),
    ExtendedHello(DomainOrIPAddressLiteral<'a>),
    Mail(ReversePath, Vec<MailParameter>),
    Recipient(Vec<AddressOrPostmaster<'a>>, Vec<RecipientParameter>),
    Data,
    Reset,
    Verify(String),
    Expand(String),
    Help(Option<String>),
    NoOp(Option<String>),
    Quit,
}

fn helo(stream: &mut Write) -> std::io::Result<usize> {
  stream.write("HELO".as_bytes())
}

type ExtendedHelloGreet = String;

type ExtendedHelloLine = String;

enum SMTPResponse<'a> {
    ExtendedHelloOkResponse(Domain<'a>, Option<ExtendedHelloGreet>, Vec<ExtendedHelloLine>),
}

#[test]
fn it_works() {
    let mail_object = MailObject {
        envelope: Envelope {
            originator: Address {
                local_part: "kyle.marek.spartz",
                domain: "gmail.com",
            },
            recipients: OneOrMore::More(Address {
                    local_part: "zeckalpha",
                    domain: "gmail.com",
                }, Box::new(OneOrMore::One(Address {
                    local_part: "kyle",
                    domain: "marek-spartz.org",
                }))
            ),
            protocol_extensions: vec![
                ProtocolExtension::EightBitMIME,
            ]
        },
        content: Content {
            header: Header {
                fields: {
                    let mut fields = BTreeMap::new();
                    fields.insert("orig-date", "...");
                    fields.insert("from", "kyle.marek.spartz@gmail.com");
                    fields
                }
            },
            body: "LOL"
        }
    };
    assert_eq!("LOL", mail_object.content.body);
}

#[test]
fn helo_writes() {
    use std::fs::File;

    let mut write_stream = File::create("helo_output").ok().unwrap();
    let mut content = String::new();
    assert_eq!(4, helo(&mut write_stream).ok().unwrap());
    write_stream.flush();
    let mut read_stream = File::open("helo_output").ok().unwrap();
    assert_eq!(4, read_stream.read_to_string(&mut content).ok().unwrap());
    assert_eq!("HELO", content);
}
<|endoftext|>


<commit_before>extern crate serial;
#[macro_use] extern crate serde_derive;
extern crate serde;

use serde::ser::{Serializer, Serialize};
use serde::de::{self, Deserializer, Deserialize};

pub use serial::Error;

mod enttec;

pub use enttec::{available_enttec_ports, EnttecDmxPort, ENTTEC_NAMESPACE};

/// Trait for the general notion of a DMX port.
/// This enables creation of an "offline" port to slot into place if an API requires an output.
pub trait DmxPort {
    /// Write a DMX frame out to the port.  If the frame is smaller than the minimum universe size,
    /// it will be padded with zeros.  If the frame is larger than the maximum universe size, the
    /// values beyond the max size will be ignored.
    fn write(&mut self, frame: &[u8]) -> Result<(), Error>;

    /// Return the name of this port.  Should only be used for display purposes.
    fn port_name(&self) -> &str;

    /// Return a SerializablePort to be used to try to reopen a port
    /// after deserialization of a saved show or after application restart.
    fn serializable(&self) -> SerializablePort;
}

pub struct OfflineDmxPort {}

const OFFLINE_NAMESPACE: &'static str = "offline";
const OFFLINE_ID: &'static str = "offline";

impl DmxPort for OfflineDmxPort {
    fn write(&mut self, _: &[u8]) -> Result<(), Error> {
        Ok(())
    }
    fn port_name(&self) -> &str {
        OFFLINE_ID
    }
    fn serializable(&self) -> SerializablePort {
        SerializablePort::new(OFFLINE_NAMESPACE, OFFLINE_ID)
    }
}

#[derive(PartialEq, Eq, Serialize, Deserialize)]
/// A serializable data structure for persisting a record of a port to disk, also providing
/// for attempted reopening of a port.
pub struct SerializablePort<'a> {
    namespace: &'a str,
    id: &'a str,
}

impl<'a> SerializablePort<'a> {
    fn new(namespace: &'a str, id: &'a str) -> Self {
        SerializablePort { namespace: namespace, id: id }
    }
    /// Based on the namespace and id, try to reopen this DMX port.
    /// If we don't know the namespace or the port isn't available, return an offline port.
    fn reopen(self) -> Box<DmxPort> {
        fn offline() -> Box<DmxPort> {
            Box::new(OfflineDmxPort{})
        }
        match self.namespace {
            OFFLINE_NAMESPACE => offline(),
            ENTTEC_NAMESPACE =>
                match EnttecDmxPort::new(self.id) {
                    Ok(port) => Box::new(port),
                    Err(_) => offline()
                },
            _ => offline()
        }
    }
}

// Helper functions to use when serializing and deserializing DmxPort trait objects contained in
// other structs.  This can be done using the serde with attribute.
pub fn serialize<S>(port: &Box<DmxPort>, serializer: S) -> Result<S::Ok, S::Error>
    where S: Serializer
{
    port.serializable().serialize(serializer)
}

pub fn deserialize<'de, D>(deserializer: D) -> Result<Box<DmxPort>, D::Error>
    where D: Deserializer<'de>
{
    SerializablePort::deserialize(deserializer).map(SerializablePort::reopen)
}<commit_msg>ENH: serializable port impls debug<commit_after>extern crate serial;
#[macro_use] extern crate serde_derive;
extern crate serde;

use serde::ser::{Serializer, Serialize};
use serde::de::{self, Deserializer, Deserialize};

pub use serial::Error;

mod enttec;

pub use enttec::{available_enttec_ports, EnttecDmxPort, ENTTEC_NAMESPACE};

/// Trait for the general notion of a DMX port.
/// This enables creation of an "offline" port to slot into place if an API requires an output.
pub trait DmxPort {
    /// Write a DMX frame out to the port.  If the frame is smaller than the minimum universe size,
    /// it will be padded with zeros.  If the frame is larger than the maximum universe size, the
    /// values beyond the max size will be ignored.
    fn write(&mut self, frame: &[u8]) -> Result<(), Error>;

    /// Return the name of this port.  Should only be used for display purposes.
    fn port_name(&self) -> &str;

    /// Return a SerializablePort to be used to try to reopen a port
    /// after deserialization of a saved show or after application restart.
    fn serializable(&self) -> SerializablePort;
}

pub struct OfflineDmxPort {}

const OFFLINE_NAMESPACE: &'static str = "offline";
const OFFLINE_ID: &'static str = "offline";

impl DmxPort for OfflineDmxPort {
    fn write(&mut self, _: &[u8]) -> Result<(), Error> {
        Ok(())
    }
    fn port_name(&self) -> &str {
        OFFLINE_ID
    }
    fn serializable(&self) -> SerializablePort {
        SerializablePort::new(OFFLINE_NAMESPACE, OFFLINE_ID)
    }
}

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
/// A serializable data structure for persisting a record of a port to disk, also providing
/// for attempted reopening of a port.
pub struct SerializablePort<'a> {
    namespace: &'a str,
    id: &'a str,
}

impl<'a> SerializablePort<'a> {
    fn new(namespace: &'a str, id: &'a str) -> Self {
        SerializablePort { namespace: namespace, id: id }
    }
    /// Based on the namespace and id, try to reopen this DMX port.
    /// If we don't know the namespace or the port isn't available, return an offline port.
    fn reopen(self) -> Box<DmxPort> {
        fn offline() -> Box<DmxPort> {
            Box::new(OfflineDmxPort{})
        }
        match self.namespace {
            OFFLINE_NAMESPACE => offline(),
            ENTTEC_NAMESPACE =>
                match EnttecDmxPort::new(self.id) {
                    Ok(port) => Box::new(port),
                    Err(_) => offline()
                },
            _ => offline()
        }
    }
}

// Helper functions to use when serializing and deserializing DmxPort trait objects contained in
// other structs.  This can be done using the serde with attribute.
pub fn serialize<S>(port: &Box<DmxPort>, serializer: S) -> Result<S::Ok, S::Error>
    where S: Serializer
{
    port.serializable().serialize(serializer)
}

pub fn deserialize<'de, D>(deserializer: D) -> Result<Box<DmxPort>, D::Error>
    where D: Deserializer<'de>
{
    SerializablePort::deserialize(deserializer).map(SerializablePort::reopen)
}<|endoftext|>


<commit_before>extern crate libc;
use libc::{c_int, c_double};

extern "C" {
    fn __mvwrap_MOD_mvndist(n: *const c_int,
                            covrnc: *const c_double,
                            nu: *const c_int,
                            m: *const c_int,
                            lower: *const c_double,
                            constr: *const c_double,
                            upper: *const c_double,
                            infin: *const c_int,
                            delta: *const c_double,
                            maxpts: *const c_int,
                            abseps: *const c_double,
                            releps: *const c_double,
                            error: *mut c_double,
                            value: *mut c_double,
                            nevals: *mut c_int,
                            inform: *mut c_int);
}

fn arr<T: Sized>(s: &[T]) -> *const T {
    s.as_ptr()
}

fn flatten<T: Sized + Clone>(m: &[Vec<T>]) -> Vec<T> {
    let mut res = vec![];
    for &ref v in m {
        res.append(&mut v.clone());
    }
    res
}

pub fn mvdist(n: i32,
              covrnc: &[Vec<f64>],
              nu: i32,
              m: i32,
              lower: &[f64],
              constr: &[Vec<f64>],
              upper: &[f64],
              infin: &[i32],
              delta: &[f64],
              maxpts: i32,
              abseps: f64,
              releps: f64)
              -> (f64, f64, i32, i32) {
    let mut error = 0f64;
    let mut value = 0f64;
    let mut nevals = 0i32;
    let mut inform = 0i32;
    unsafe {
        __mvwrap_MOD_mvndist(&n,
                             flatten(covrnc).as_ptr(),
                             &nu,
                             &m,
                             arr(lower),
                             flatten(constr).as_ptr(),
                             arr(upper),
                             arr(infin),
                             arr(delta),
                             &maxpts,
                             &abseps,
                             &releps,
                             &mut error,
                             &mut value,
                             &mut nevals,
                             &mut inform);
    }
    (error, value, nevals, inform)
}

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

    #[test]
    fn mvtst_a() {
        let n = 4;
        let m = 5;
        let nu = 8i32;
        let mx = 100000i32;
        let abseps = 1e-5f64;
        let mut cov = Vec::with_capacity(n);
        let mut cns = Vec::with_capacity(n);
        let delta = vec![0f64; m];
        let infin = vec![2i32; m];
        let lower = vec![0f64; m];
        let upper = vec![1f64; m];
        for i in 0..n {
            {
                let mut col = vec![0.0; n];
                col[i] = 1.0;
                cov.push(col);
            }
            {

                let mut col = vec![0f64; m];
                col[i] = 1f64;
                col[n] = 1f64;
                cns.push(col);
            }
        }

        let (error, value, nevals, inform) = mvdist(n as i32,
                                                    &cov,
                                                    nu,
                                                    m as i32,
                                                    &lower,
                                                    &cns,
                                                    &upper,
                                                    &infin,
                                                    &delta,
                                                    mx,
                                                    abseps,
                                                    0f64);

        assert!(inform == 0);
        assert!(nevals > 0);
        assert!((value - 0.001).abs() < 0.0001);
        assert!(error <= abseps);
    }
}
<commit_msg>Changed mvdist to accept a slice instead of slice of vecs<commit_after>extern crate libc;
use libc::{c_int, c_double};

extern "C" {
    fn __mvwrap_MOD_mvndist(n: *const c_int,
                            covrnc: *const c_double,
                            nu: *const c_int,
                            m: *const c_int,
                            lower: *const c_double,
                            constr: *const c_double,
                            upper: *const c_double,
                            infin: *const c_int,
                            delta: *const c_double,
                            maxpts: *const c_int,
                            abseps: *const c_double,
                            releps: *const c_double,
                            error: *mut c_double,
                            value: *mut c_double,
                            nevals: *mut c_int,
                            inform: *mut c_int);
}

fn arr<T: Sized>(s: &[T]) -> *const T {
    s.as_ptr()
}

pub fn mvdist(n: i32,
              covrnc: &[f64],
              nu: i32,
              m: i32,
              lower: &[f64],
              constr: &[f64],
              upper: &[f64],
              infin: &[i32],
              delta: &[f64],
              maxpts: i32,
              abseps: f64,
              releps: f64)
              -> (f64, f64, i32, i32) {
    let mut error = 0f64;
    let mut value = 0f64;
    let mut nevals = 0i32;
    let mut inform = 0i32;
    unsafe {
        __mvwrap_MOD_mvndist(&n,
                             arr(covrnc),
                             &nu,
                             &m,
                             arr(lower),
                             arr(constr),
                             arr(upper),
                             arr(infin),
                             arr(delta),
                             &maxpts,
                             &abseps,
                             &releps,
                             &mut error,
                             &mut value,
                             &mut nevals,
                             &mut inform);
    }
    (error, value, nevals, inform)
}

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

    fn flatten<T: Sized + Clone>(m: &[Vec<T>]) -> Vec<T> {
        let mut res = vec![];
        for &ref v in m {
            res.append(&mut v.clone());
        }
        res
    }

    #[test]
    fn mvtst_a() {
        let n = 4;
        let m = 5;
        let nu = 8i32;
        let mx = 100000i32;
        let abseps = 1e-5f64;
        let mut cov = Vec::with_capacity(n);
        let mut cns = Vec::with_capacity(n);
        let delta = vec![0f64; m];
        let infin = vec![2i32; m];
        let lower = vec![0f64; m];
        let upper = vec![1f64; m];
        for i in 0..n {
            {
                let mut col = vec![0.0; n];
                col[i] = 1.0;
                cov.push(col);
            }
            {

                let mut col = vec![0f64; m];
                col[i] = 1f64;
                col[n] = 1f64;
                cns.push(col);
            }
        }

        let (error, value, nevals, inform) = mvdist(n as i32,
                                                    &flatten(&cov),
                                                    nu,
                                                    m as i32,
                                                    &lower,
                                                    &flatten(&cns),
                                                    &upper,
                                                    &infin,
                                                    &delta,
                                                    mx,
                                                    abseps,
                                                    0f64);

        assert!(inform == 0);
        assert!(nevals > 0);
        assert!((value - 0.001).abs() < 0.0001);
        assert!(error <= abseps);
    }
}
<|endoftext|>


<commit_before>// Copyright 2014-2016 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.

//! A collection of numeric types and traits for Rust.
//!
//! This includes new types for big integers, rationals, and complex numbers,
//! new traits for generic programming on numeric properties like `Integer`,
//! and generic range iterators.
//!
//! ## Example
//!
//! This example uses the BigRational type and [Newton's method][newt] to
//! approximate a square root to arbitrary precision:
//!
//! ```
//! extern crate num;
//! # #[cfg(all(feature = "bigint", feature="rational"))]
//! # mod test {
//!
//! use num::FromPrimitive;
//! use num::bigint::BigInt;
//! use num::rational::{Ratio, BigRational};
//!
//! # pub
//! fn approx_sqrt(number: u64, iterations: usize) -> BigRational {
//!     let start: Ratio<BigInt> = Ratio::from_integer(FromPrimitive::from_u64(number).unwrap());
//!     let mut approx = start.clone();
//!
//!     for _ in 0..iterations {
//!         approx = (&approx + (&start / &approx)) /
//!             Ratio::from_integer(FromPrimitive::from_u64(2).unwrap());
//!     }
//!
//!     approx
//! }
//! # }
//! # #[cfg(not(all(feature = "bigint", feature="rational")))]
//! # mod test { pub fn approx_sqrt(n: u64, _: usize) -> u64 { n } }
//! # use test::approx_sqrt;
//!
//! fn main() {
//!     println!("{}", approx_sqrt(10, 4)); // prints 4057691201/1283082416
//! }
//!
//! ```
//!
//! [newt]: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
#![doc(html_logo_url = "https://rust-num.github.io/num/rust-logo-128x128-blk-v2.png",
       html_favicon_url = "https://rust-num.github.io/num/favicon.ico",
       html_root_url = "https://rust-num.github.io/num/",
       html_playground_url = "http://play.integer32.com/")]

extern crate num_traits;
extern crate num_integer;
extern crate num_iter;
#[cfg(feature = "num-complex")]
extern crate num_complex;
#[cfg(feature = "num-bigint")]
extern crate num_bigint;
#[cfg(feature = "num-rational")]
extern crate num_rational;

#[cfg(feature = "num-bigint")]
pub use num_bigint::{BigInt, BigUint};
#[cfg(feature = "num-rational")]
pub use num_rational::Rational;
#[cfg(all(feature = "num-rational", feature="num-bigint"))]
pub use num_rational::BigRational;
#[cfg(feature = "num-complex")]
pub use num_complex::Complex;
pub use num_integer::Integer;
pub use num_iter::{range, range_inclusive, range_step, range_step_inclusive};
pub use num_traits::{Num, Zero, One, Signed, Unsigned, Bounded,
                     one, zero, abs, abs_sub, signum,
                     Saturating, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv,
                     PrimInt, Float, ToPrimitive, FromPrimitive, NumCast, cast,
                     pow, checked_pow};

#[cfg(feature = "num-bigint")]
pub mod bigint {
    pub use num_bigint::*;
}

#[cfg(feature = "num-complex")]
pub mod complex {
    pub use num_complex::*;
}

pub mod integer {
    pub use num_integer::*;
}

pub mod iter {
    pub use num_iter::*;
}

pub mod traits {
    pub use num_traits::*;
}

#[cfg(feature = "num-rational")]
pub mod rational {
    pub use num_rational::*;
}

pub fn clamp<T: PartialOrd + Copy>(input: T, min: T, max: T) -> T {
    debug_assert!(min < max, "min must be less than max");
    if input <= min {min}
    else if input >= max {max}
    else {input}
}
<commit_msg>Adding documentation comments<commit_after>// Copyright 2014-2016 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.

//! A collection of numeric types and traits for Rust.
//!
//! This includes new types for big integers, rationals, and complex numbers,
//! new traits for generic programming on numeric properties like `Integer`,
//! and generic range iterators.
//!
//! ## Example
//!
//! This example uses the BigRational type and [Newton's method][newt] to
//! approximate a square root to arbitrary precision:
//!
//! ```
//! extern crate num;
//! # #[cfg(all(feature = "bigint", feature="rational"))]
//! # mod test {
//!
//! use num::FromPrimitive;
//! use num::bigint::BigInt;
//! use num::rational::{Ratio, BigRational};
//!
//! # pub
//! fn approx_sqrt(number: u64, iterations: usize) -> BigRational {
//!     let start: Ratio<BigInt> = Ratio::from_integer(FromPrimitive::from_u64(number).unwrap());
//!     let mut approx = start.clone();
//!
//!     for _ in 0..iterations {
//!         approx = (&approx + (&start / &approx)) /
//!             Ratio::from_integer(FromPrimitive::from_u64(2).unwrap());
//!     }
//!
//!     approx
//! }
//! # }
//! # #[cfg(not(all(feature = "bigint", feature="rational")))]
//! # mod test { pub fn approx_sqrt(n: u64, _: usize) -> u64 { n } }
//! # use test::approx_sqrt;
//!
//! fn main() {
//!     println!("{}", approx_sqrt(10, 4)); // prints 4057691201/1283082416
//! }
//!
//! ```
//!
//! [newt]: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
#![doc(html_logo_url = "https://rust-num.github.io/num/rust-logo-128x128-blk-v2.png",
       html_favicon_url = "https://rust-num.github.io/num/favicon.ico",
       html_root_url = "https://rust-num.github.io/num/",
       html_playground_url = "http://play.integer32.com/")]

extern crate num_traits;
extern crate num_integer;
extern crate num_iter;
#[cfg(feature = "num-complex")]
extern crate num_complex;
#[cfg(feature = "num-bigint")]
extern crate num_bigint;
#[cfg(feature = "num-rational")]
extern crate num_rational;

#[cfg(feature = "num-bigint")]
pub use num_bigint::{BigInt, BigUint};
#[cfg(feature = "num-rational")]
pub use num_rational::Rational;
#[cfg(all(feature = "num-rational", feature="num-bigint"))]
pub use num_rational::BigRational;
#[cfg(feature = "num-complex")]
pub use num_complex::Complex;
pub use num_integer::Integer;
pub use num_iter::{range, range_inclusive, range_step, range_step_inclusive};
pub use num_traits::{Num, Zero, One, Signed, Unsigned, Bounded,
                     one, zero, abs, abs_sub, signum,
                     Saturating, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv,
                     PrimInt, Float, ToPrimitive, FromPrimitive, NumCast, cast,
                     pow, checked_pow};

#[cfg(feature = "num-bigint")]
pub mod bigint {
    pub use num_bigint::*;
}

#[cfg(feature = "num-complex")]
pub mod complex {
    pub use num_complex::*;
}

pub mod integer {
    pub use num_integer::*;
}

pub mod iter {
    pub use num_iter::*;
}

pub mod traits {
    pub use num_traits::*;
}

#[cfg(feature = "num-rational")]
pub mod rational {
    pub use num_rational::*;
}
/// A value bounded by a minimum and a maximum
///
/// If input is less than min then min is returned, if input is greater than max then max is
/// returned.  Otherwise input is returned.
pub fn clamp<T: PartialOrd + Copy>(input: T, min: T, max: T) -> T {
    debug_assert!(min < max, "min must be less than max");
    if input <= min {min}
    else if input >= max {max}
    else {input}
}
<|endoftext|>


<commit_before>//! A safe wrapper for the [`c-ares`](http://c-ares.haxx.se) library.
//!
//! Usage is as follows:
//!
//! -  Create a `Channel`.
//!
//! -  Make queries on the `Channel`.  Queries all take callbacks, which will
//!    be called when the query completes.
//!
//! -  Have `c-ares` tell you what file descriptors to listen on for read and /
//!    or write events.  You can do this either by providing a callback, which
//!    is called whenever the set of interesting file descriptors changes, or
//!    by querying the `Channel` directly with `get_sock()`.
//!
//! -  Do as `c-ares` asks.  That is, listen for the events that it requests,
//!    on the file descriptors that it cares about.
//!
//! -  When a file descriptor becomes readable or writable, call `process_fd()`
//!    on the `Channel` to tell `c-ares` what has happened.
//!
//! -  If you have queries pending and don't see events happening, you still
//!    need to call `process_fd()` at some point anyway - to give `c-ares` an
//!    opportunity to process any requests that have timed out.
//!
//! Complete examples showing how to use the library can be found
//! [here](https://github.com/dimbleby/rust-c-ares/tree/master/examples).
#[macro_use] extern crate bitflags;

mod a;
mod aaaa;
mod channel;
mod cname;
mod ctypes;
mod error;
pub mod flags;
mod host;
mod hostent;
mod mx;
mod nameinfo;
mod naptr;
pub mod ni_flags;
mod ns;
mod ptr;
mod query;
mod srv;
mod types;
mod txt;
mod soa;
mod utils;

// Re-export public interfaces.
pub use a::AResults;
pub use aaaa::AAAAResults;
pub use channel::{
    Channel,
    GetSock,
    Options,
};
pub use cname::CNameResults;
pub use error::AresError;
pub use host::HostResults;
pub use hostent::{
    HostAddressResult,
    HostAliasResult,
};
pub use mx::{
    MXResult,
    MXResults,
};
pub use nameinfo::NameInfoResult;
pub use naptr::{
    NAPTRResult,
    NAPTRResults,
};
pub use ns::NSResults;
pub use ptr::PTRResults;
pub use soa::SOAResult;
pub use srv::{
    SRVResult,
    SRVResults,
};
pub use txt::{
    TXTResult,
    TXTResults,
};
pub use types::{
    AddressFamily,
    IpAddr,
    Socket,
    SOCKET_BAD,
};
<commit_msg>Export fd_set<commit_after>//! A safe wrapper for the [`c-ares`](http://c-ares.haxx.se) library.
//!
//! Usage is as follows:
//!
//! -  Create a `Channel`.
//!
//! -  Make queries on the `Channel`.  Queries all take callbacks, which will
//!    be called when the query completes.
//!
//! -  Have `c-ares` tell you what file descriptors to listen on for read and /
//!    or write events.  You can do this either by providing a callback, which
//!    is called whenever the set of interesting file descriptors changes, or
//!    by querying the `Channel` directly with `get_sock()`.
//!
//! -  Do as `c-ares` asks.  That is, listen for the events that it requests,
//!    on the file descriptors that it cares about.
//!
//! -  When a file descriptor becomes readable or writable, call `process_fd()`
//!    on the `Channel` to tell `c-ares` what has happened.
//!
//! -  If you have queries pending and don't see events happening, you still
//!    need to call `process_fd()` at some point anyway - to give `c-ares` an
//!    opportunity to process any requests that have timed out.
//!
//! Complete examples showing how to use the library can be found
//! [here](https://github.com/dimbleby/rust-c-ares/tree/master/examples).
#[macro_use] extern crate bitflags;

mod a;
mod aaaa;
mod channel;
mod cname;
mod ctypes;
mod error;
pub mod flags;
mod host;
mod hostent;
mod mx;
mod nameinfo;
mod naptr;
pub mod ni_flags;
mod ns;
mod ptr;
mod query;
mod srv;
mod types;
mod txt;
mod soa;
mod utils;

// Re-export public interfaces.
pub use a::AResults;
pub use aaaa::AAAAResults;
pub use channel::{
    Channel,
    GetSock,
    Options,
};
pub use cname::CNameResults;
pub use ctypes::fd_set;
pub use error::AresError;
pub use host::HostResults;
pub use hostent::{
    HostAddressResult,
    HostAliasResult,
};
pub use mx::{
    MXResult,
    MXResults,
};
pub use nameinfo::NameInfoResult;
pub use naptr::{
    NAPTRResult,
    NAPTRResults,
};
pub use ns::NSResults;
pub use ptr::PTRResults;
pub use soa::SOAResult;
pub use srv::{
    SRVResult,
    SRVResults,
};
pub use txt::{
    TXTResult,
    TXTResults,
};
pub use types::{
    AddressFamily,
    IpAddr,
    Socket,
    SOCKET_BAD,
};
<|endoftext|>


<commit_before>pub mod ffi;
mod base;
mod stream;

pub use base::*;
pub use stream::*;
<commit_msg>Update example<commit_after>//! [libsoundio](http://libsound.io) bindings for Rust.
//!
//! # Example
//!
//! ```
//! extern crate rsoundio;
//!
//! // create new context
//! let sio = rsoundio::SoundIo::new();
//! // connect to default audio backend
//! sio.connect().unwrap();
//! sio.flush_events();
//! let dev = sio.default_output_device().unwrap();
//! let mut out = dev.create_outstream().unwrap();
//! // register write_callback
//! out.register_write_callback(Box::new(|out: rsoundio::OutStream, min_frame_count: i32,
//! max_frame_count: i32| {
//!     let frames = vec![vec![], vec![]];
//!     // frames should contain audio data for each channel
//!     out.write_stream_f32(min_frame_count, &frames).unwrap();
//! }));
//! out.open().unwrap();
//! // start the audio stream and wait for events
//! // out.start().unwrap();
//! // loop { sio.wait_events(); }
//! out.destroy();
//! ```

pub mod ffi;
mod base;
mod stream;

pub use base::*;
pub use stream::*;
<|endoftext|>


<commit_before>//! Tools for concurrent programming.
//!
//! ## Atomics
//!
//! * [`AtomicCell`], a thread-safe mutable memory location.
//! * [`AtomicConsume`], for reading from primitive atomic types with "consume" ordering.
//!
//! ## Data structures
//!
//! * [`deque`], work-stealing deques for building task schedulers.
//! * [`ArrayQueue`], a bounded MPMC queue that allocates a fixed-capacity buffer on construction.
//! * [`SegQueue`], an unbounded MPMC queue that allocates small buffers, segments, on demand.
//!
//! ## Memory management
//!
//! * [`epoch`], an epoch-based garbage collector.
//!
//! ## Thread synchronization
//!
//! * [`channel`], multi-producer multi-consumer channels for message passing.
//! * [`Parker`], a thread parking primitive.
//! * [`ShardedLock`], a sharded reader-writer lock with fast concurrent reads.
//! * [`WaitGroup`], for synchronizing the beginning or end of some computation.
//!
//! ## Utilities
//!
//! * [`Backoff`], for exponential backoff in spin loops.
//! * [`CachePadded`], for padding and aligning a value to the length of a cache line.
//! * [`scope`], for spawning threads that borrow local variables from the stack.
//!
//! [`AtomicCell`]: atomic/struct.AtomicCell.html
//! [`AtomicConsume`]: atomic/trait.AtomicConsume.html
//! [`deque`]: deque/index.html
//! [`ArrayQueue`]: queue/struct.ArrayQueue.html
//! [`SegQueue`]: queue/struct.SegQueue.html
//! [`channel`]: channel/index.html
//! [`Parker`]: sync/struct.Parker.html
//! [`ShardedLock`]: sync/struct.ShardedLock.html
//! [`WaitGroup`]: sync/struct.WaitGroup.html
//! [`epoch`]: epoch/index.html
//! [`Backoff`]: utils/struct.Backoff.html
//! [`CachePadded`]: utils/struct.CachePadded.html
//! [`scope`]: fn.scope.html

#![warn(missing_docs)]
#![warn(missing_debug_implementations)]
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(feature = "nightly", feature(cfg_target_has_atomic))]

#[macro_use]
extern crate cfg_if;
#[cfg(feature = "std")]
extern crate core;

cfg_if! {
    if #[cfg(feature = "alloc")] {
        extern crate alloc;
    } else if #[cfg(feature = "std")] {
        extern crate std as alloc;
    }
}

mod _epoch {
    pub extern crate crossbeam_epoch;
}
#[doc(inline)]
pub use _epoch::crossbeam_epoch as epoch;

extern crate crossbeam_utils;

#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "ptr"))]
pub use crossbeam_utils::atomic;

/// Miscellaneous utilities.
pub mod utils {
    pub use crossbeam_utils::Backoff;
    pub use crossbeam_utils::CachePadded;
}

cfg_if! {
    if #[cfg(any(feature = "std", feature = "alloc"))] {
        mod _queue {
            pub extern crate crossbeam_queue;
        }
        #[doc(inline)]
        pub use _queue::crossbeam_queue as queue;
    }
}

cfg_if! {
    if #[cfg(feature = "std")] {
        mod _deque {
            pub extern crate crossbeam_deque;
        }
        #[doc(inline)]
        pub use _deque::crossbeam_deque as deque;

        mod _channel {
            pub extern crate crossbeam_channel;
            pub use self::crossbeam_channel::*;
        }
        #[doc(inline)]
        pub use _channel::crossbeam_channel as channel;

        // HACK(stjepang): This is the only way to reexport `select!` in Rust older than 1.30.0
        #[doc(hidden)]
        pub use _channel::*;

        pub use crossbeam_utils::sync;
        pub use crossbeam_utils::thread;
        pub use crossbeam_utils::thread::scope;
    }
}
<commit_msg>Fix compilation for thumv6m<commit_after>//! Tools for concurrent programming.
//!
//! ## Atomics
//!
//! * [`AtomicCell`], a thread-safe mutable memory location.
//! * [`AtomicConsume`], for reading from primitive atomic types with "consume" ordering.
//!
//! ## Data structures
//!
//! * [`deque`], work-stealing deques for building task schedulers.
//! * [`ArrayQueue`], a bounded MPMC queue that allocates a fixed-capacity buffer on construction.
//! * [`SegQueue`], an unbounded MPMC queue that allocates small buffers, segments, on demand.
//!
//! ## Memory management
//!
//! * [`epoch`], an epoch-based garbage collector.
//!
//! ## Thread synchronization
//!
//! * [`channel`], multi-producer multi-consumer channels for message passing.
//! * [`Parker`], a thread parking primitive.
//! * [`ShardedLock`], a sharded reader-writer lock with fast concurrent reads.
//! * [`WaitGroup`], for synchronizing the beginning or end of some computation.
//!
//! ## Utilities
//!
//! * [`Backoff`], for exponential backoff in spin loops.
//! * [`CachePadded`], for padding and aligning a value to the length of a cache line.
//! * [`scope`], for spawning threads that borrow local variables from the stack.
//!
//! [`AtomicCell`]: atomic/struct.AtomicCell.html
//! [`AtomicConsume`]: atomic/trait.AtomicConsume.html
//! [`deque`]: deque/index.html
//! [`ArrayQueue`]: queue/struct.ArrayQueue.html
//! [`SegQueue`]: queue/struct.SegQueue.html
//! [`channel`]: channel/index.html
//! [`Parker`]: sync/struct.Parker.html
//! [`ShardedLock`]: sync/struct.ShardedLock.html
//! [`WaitGroup`]: sync/struct.WaitGroup.html
//! [`epoch`]: epoch/index.html
//! [`Backoff`]: utils/struct.Backoff.html
//! [`CachePadded`]: utils/struct.CachePadded.html
//! [`scope`]: fn.scope.html

#![warn(missing_docs)]
#![warn(missing_debug_implementations)]
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(feature = "nightly", feature(cfg_target_has_atomic))]

#[macro_use]
extern crate cfg_if;
#[cfg(feature = "std")]
extern crate core;

cfg_if! {
    if #[cfg(feature = "alloc")] {
        extern crate alloc;
    } else if #[cfg(feature = "std")] {
        extern crate std as alloc;
    }
}

mod _epoch {
    pub extern crate crossbeam_epoch;
}
#[doc(inline)]
pub use _epoch::crossbeam_epoch as epoch;

extern crate crossbeam_utils;

#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "ptr"))]
pub use crossbeam_utils::atomic;

/// Miscellaneous utilities.
pub mod utils {
    pub use crossbeam_utils::Backoff;
    pub use crossbeam_utils::CachePadded;
}

#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "ptr"))]
cfg_if! {
    if #[cfg(any(feature = "std", feature = "alloc"))] {
        mod _queue {
            pub extern crate crossbeam_queue;
        }
        #[doc(inline)]
        pub use _queue::crossbeam_queue as queue;
    }
}

cfg_if! {
    if #[cfg(feature = "std")] {
        mod _deque {
            pub extern crate crossbeam_deque;
        }
        #[doc(inline)]
        pub use _deque::crossbeam_deque as deque;

        mod _channel {
            pub extern crate crossbeam_channel;
            pub use self::crossbeam_channel::*;
        }
        #[doc(inline)]
        pub use _channel::crossbeam_channel as channel;

        // HACK(stjepang): This is the only way to reexport `select!` in Rust older than 1.30.0
        #[doc(hidden)]
        pub use _channel::*;

        pub use crossbeam_utils::sync;
        pub use crossbeam_utils::thread;
        pub use crossbeam_utils::thread::scope;
    }
}
<|endoftext|>