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

//! Generic RPC handling (used for both front end and plugin communication).
//!
//! The RPC protocol is based on [JSON-RPC](http://www.jsonrpc.org/specification),
//! but with some modifications. Unlike JSON-RPC 2.0, requests and notifications
//! are allowed in both directions, rather than imposing client and server roles.
//! Further, the batch form is not supported.
//!
//! Because these changes make the protocol not fully compliant with the spec,
//! the `"jsonrpc"` member is omitted from request and response objects.

extern crate serde;
extern crate serde_json;
extern crate crossbeam;

#[macro_use]
mod macros;

use std::collections::{BTreeMap, VecDeque};
use std::io;
use std::io::{BufRead, Write};
use std::sync::{Arc, Mutex, Condvar};
use std::sync::mpsc;
use std::sync::atomic::{AtomicUsize, Ordering};
use crossbeam::scope;

use serde_json::builder::ObjectBuilder;
use serde_json::Value;

#[derive(Debug)]
pub enum Error {
    /// An IO error occurred on the underlying communication channel.
    IoError(io::Error),
    /// The peer closed its connection.
    PeerDisconnect,
    /// The remote method returned an error.
    RemoteError(Value),
    /// The peer sent a response containing the id, but was malformed according
    /// to the json-rpc spec.
    MalformedResponse,
}

/// An interface to access the other side of the RPC channel. The main purpose
/// is to send RPC requests and notifications to the peer.
///
/// The concrete type may change; if the `RpcLoop` were to start a separate
/// writer thread, as opposed to writes being synchronous, then the peer would
/// not need to take the writer type as a parameter.
pub struct RpcPeer<W: Write>(Arc<RpcState<W>>);

pub struct RpcCtx<'a, W: 'a + Write> {
    peer: &'a RpcPeer<W>,
    idle: &'a mut VecDeque<usize>,
}

pub trait Handler<W: Write> {
    fn handle_notification(&mut self, ctx: RpcCtx<W>, method: &str, params: &Value);
    fn handle_request(&mut self, ctx: RpcCtx<W>, method: &str, params: &Value) ->
        Result<Value, Value>;
    #[allow(unused_variables)]
    fn idle(&mut self, ctx: RpcCtx<W>, token: usize) {}
}

trait Callback: Send {
    fn call(self: Box<Self>, result: Result<Value, Error>);
}

impl<F:Send + FnOnce(Result<Value, Error>)> Callback for F {
    fn call(self: Box<F>, result: Result<Value, Error>) {
        (*self)(result)
    }
}

trait IdleProc: Send {
    fn call(self: Box<Self>, token: usize);
}

impl<F:Send + FnOnce(usize)> IdleProc for F {
    fn call(self: Box<F>, token: usize) {
        (*self)(token)
    }
}

enum ResponseHandler {
    Chan(mpsc::Sender<Result<Value, Error>>),
    Callback(Box<Callback>),
}

impl ResponseHandler {
    fn invoke(self, result: Result<Value, Error>) {
        match self {
            ResponseHandler::Chan(tx) => {
                let _ = tx.send(result);
            },
            ResponseHandler::Callback(f) => f.call(result)
        }
    }
}

struct RpcState<W: Write> {
    rx_queue: Mutex<VecDeque<Value>>,
    rx_cvar: Condvar,
    writer: Mutex<W>,
    id: AtomicUsize,
    pending: Mutex<BTreeMap<usize, ResponseHandler>>,
}

/// A structure holding the state of a main loop for handing RPC's.
pub struct RpcLoop<W: Write> {
    buf: String,
    peer: RpcPeer<W>,
}

fn parse_rpc_request(json: &Value) -> Option<(Option<&Value>, &str, &Value)> {
    json.as_object().and_then(|req| {
        if let (Some(method), Some(params)) =
            (dict_get_string(req, "method"), req.get("params")) {
                let id = req.get("id");
                Some((id, method, params))
            }
        else { None }
    })
}

impl<W:Write + Send> RpcLoop<W> {
    /// Creates a new `RpcLoop` with the given output stream (which is used for
    /// sending requests and notifications, as well as responses).
    pub fn new(writer: W) -> Self {
        let rpc_peer = RpcPeer(Arc::new(RpcState {
            rx_queue: Mutex::new(VecDeque::new()),
            rx_cvar: Condvar::new(),
            writer: Mutex::new(writer),
            id: AtomicUsize::new(0),
            pending: Mutex::new(BTreeMap::new()),
        }));
        RpcLoop {
            buf: String::new(),
            peer: rpc_peer,
        }
    }

    /// Gets a reference to the peer.
    pub fn get_peer(&self) -> RpcPeer<W> {
        self.peer.clone()
    }

    // Reads raw json from the input stream.
    fn read_json<R: BufRead>(&mut self, reader: &mut R)
            -> Option<serde_json::error::Result<Value>> {
        self.buf.clear();
        if reader.read_line(&mut self.buf).is_ok() {
            if self.buf.is_empty() {
                return None;
            }
            return Some(serde_json::from_str::<Value>(&self.buf));
        }
        None
    }

    /// Starts a main loop. The reader is supplied via a closure, as basically
    /// a workaround so that the reader doesn't have to be `Send`. Internally, the
    /// main loop starts a separate thread for I/O, and at startup that thread calls
    /// the given closure.
    ///
    /// Calls to the handler (the second closure) happen on the caller's thread, so
    /// that closure need not be `Send`.
    ///
    /// Calls to the handler are guaranteed to preserve the order as they appear on
    /// on the channel. At the moment, there is no way for there to be more than one
    /// incoming request to be outstanding.
    ///
    /// This method returns when the input channel is closed.
    pub fn mainloop<R: BufRead, RF: Send + FnOnce() -> R>(&mut self,
            rf: RF,
            handler: &mut Handler<W>) {
        crossbeam::scope(|scope| {
            let peer = self.get_peer();
            scope.spawn(move|| {
                let mut reader = rf();
                while let Some(json_result) = self.read_json(&mut reader) {
                    match json_result {
                        Ok(json) => {
                            let is_method = json.as_object().map_or(false, |dict|
                                dict.contains_key("method"));
                            if is_method {
                                self.peer.put_rx(json);
                            } else {
                                self.peer.handle_response(json);
                            }
                        }
                        Err(err) => print_err!("Error decoding json: {:?}", err)
                    }
                }
                self.peer.put_rx(Value::Null);
                // TODO: send disconnect error to all pending
            });
            let mut idle = VecDeque::<usize>::new();
            loop {
                let json = if !idle.is_empty() {
                    if let Some(json) = peer.try_get_rx() {
                        json
                    } else {
                        let token = idle.pop_front().unwrap();
                        let ctx = RpcCtx {
                            peer: &peer,
                            idle: &mut idle,
                        };
                        handler.idle(ctx, token);
                        continue;
                    }
                } else {
                    peer.get_rx()
                };
                if json == Value::Null {
                    break;
                }
                //print_err!("to core: {:?}", json);
                match parse_rpc_request(&json) {
                    Some((id, method, params)) => {
                        let ctx = RpcCtx {
                            peer: &peer,
                            idle: &mut idle,
                        };
                        if let Some(id) = id {
                            let result = handler.handle_request(ctx, method, params);
                            peer.respond(result, id);
                        } else {
                            handler.handle_notification(ctx, method, params);
                        }
                    }
                    None => print_err!("invalid RPC request")
                }
            }
        });
    }
}

impl<'a, W: Write> RpcCtx<'a, W> {
    pub fn get_peer(&self) -> &RpcPeer<W> {
        self.peer
    }

    /// Schedule the idle handler to be run when there are no requests pending.
    pub fn schedule_idle(&mut self, token: usize) {
        self.idle.push_back(token);
    }
}

impl<W:Write> RpcPeer<W> {
    fn send(&self, v: &Value) -> Result<(), io::Error> {
        let mut s = serde_json::to_string(v).unwrap();
        s.push('\n');
        //print_err!("from core: {}", s);
        self.0.writer.lock().unwrap().write_all(s.as_bytes())
        // Technically, maybe we should flush here, but doesn't seem to be required.
    }

    fn respond(&self, result: Result<Value, Value>, id: &Value) {
        let mut builder = ObjectBuilder::new()
            .insert("id", id);
        match result {
            Ok(result) => builder = builder.insert("result", result),
            Err(error) => builder = builder.insert("error", error),
        }
        if let Err(e) = self.send(&builder.build()) {
            print_err!("error {} sending response to RPC {:?}", e, id);
        }
    }

    /// Sends a notification (asynchronous rpc) to the peer.
    pub fn send_rpc_notification(&self, method: &str, params: &Value) {
        if let Err(e) = self.send(&ObjectBuilder::new()
            .insert("method", method)
            .insert("params", params)
            .build()) {
            print_err!("send error on send_rpc_notification method {}: {}", method, e);
        }
    }

    fn send_rpc_request_common(&self, method: &str, params: &Value, rh: ResponseHandler) {
        let id = self.0.id.fetch_add(1, Ordering::Relaxed);
        {
            let mut pending = self.0.pending.lock().unwrap();
            pending.insert(id, rh);
        }
        if let Err(e) = self.send(&ObjectBuilder::new()
                .insert("id", id)
                .insert("method", method)
                .insert("params", params)
                .build()) {
            let mut pending = self.0.pending.lock().unwrap();
            if let Some(rh) = pending.remove(&id) {
                rh.invoke(Err(Error::IoError(e)));
            }
        }
    }

    /// Sends a request asynchronously, and the supplied callback will be called when
    /// the response arrives.
    pub fn send_rpc_request_async<F>(&self, method: &str, params: &Value, f: F)
        where F: FnOnce(Result<Value, Error>) + Send + 'static {
        self.send_rpc_request_common(method, params, ResponseHandler::Callback(Box::new(f)));
    }

    /// Sends a request (synchronous rpc) to the peer, and waits for the result.
    pub fn send_rpc_request(&self, method: &str, params: &Value) -> Result<Value, Error> {
        let (tx, rx) = mpsc::channel();
        self.send_rpc_request_common(method, params, ResponseHandler::Chan(tx));
        rx.recv().unwrap_or(Err(Error::PeerDisconnect))
    }

    fn handle_response(&self, mut response: Value) {
        let mut dict = response.as_object_mut().unwrap();
        let id = dict.get("id").and_then(Value::as_u64);
        if id.is_none() {
            print_err!("id missing from response, or is not u64");
            return;
        }
        let id = id.unwrap() as usize;
        let result = dict.remove("result");
        let error = dict.remove("error");
        let result = match (result, error) {
            (Some(result), None) => Ok(result),
            (None, Some(err)) => Err(Error::RemoteError(err)),
            _ => Err(Error::MalformedResponse)
        };
        let mut pending = self.0.pending.lock().unwrap();
        match pending.remove(&id) {
            Some(responsehandler) => responsehandler.invoke(result),
            None => print_err!("id {} not found in pending", id)
        }
    }

    // Get a message from the recieve queue if available.
    fn try_get_rx(&self) -> Option<Value> {
        let mut queue = self.0.rx_queue.lock().unwrap();
        queue.pop_front()
    }

    // Get a message from the receive queue, blocking until available.
    fn get_rx(&self) -> Value {
        let mut queue = self.0.rx_queue.lock().unwrap();
        while queue.is_empty() {
            queue = self.0.rx_cvar.wait(queue).unwrap();
        }
        queue.pop_front().unwrap()
    }

    fn put_rx(&self, json: Value) {
        let mut queue = self.0.rx_queue.lock().unwrap();
        queue.push_back(json);
        self.0.rx_cvar.notify_one();
    }

    /// Determines whether an incoming request (or notification) is pending. This
    /// is intended to reduce latency for bulk operations done in the background;
    /// the handler can do this work, periodically check
    pub fn request_is_pending(&self) -> bool {
        let queue = self.0.rx_queue.lock().unwrap();
        !queue.is_empty()
    }
}

impl<W:Write> Clone for RpcPeer<W> {
    fn clone(&self) -> Self {
        RpcPeer(self.0.clone())
    }
}

// =============================================================================
//  Helper functions for value access
// =============================================================================

pub fn dict_get_u64(dict: &BTreeMap<String, Value>, key: &str) -> Option<u64> {
    dict.get(key).and_then(Value::as_u64)
}

pub fn dict_get_string<'a>(dict: &'a BTreeMap<String, Value>, key: &str) -> Option<&'a str> {
    dict.get(key).and_then(Value::as_str)
}

pub fn arr_get_u64(arr: &[Value], idx: usize) -> Option<u64> {
    arr.get(idx).and_then(Value::as_u64)
}

pub fn arr_get_i64(arr: &[Value], idx: usize) -> Option<i64> {
    arr.get(idx).and_then(Value::as_i64)
}
<commit_msg>Fix potential deadlock in async RPC response<commit_after>// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Generic RPC handling (used for both front end and plugin communication).
//!
//! The RPC protocol is based on [JSON-RPC](http://www.jsonrpc.org/specification),
//! but with some modifications. Unlike JSON-RPC 2.0, requests and notifications
//! are allowed in both directions, rather than imposing client and server roles.
//! Further, the batch form is not supported.
//!
//! Because these changes make the protocol not fully compliant with the spec,
//! the `"jsonrpc"` member is omitted from request and response objects.

extern crate serde;
extern crate serde_json;
extern crate crossbeam;

#[macro_use]
mod macros;

use std::collections::{BTreeMap, VecDeque};
use std::io;
use std::io::{BufRead, Write};
use std::sync::{Arc, Mutex, Condvar};
use std::sync::mpsc;
use std::sync::atomic::{AtomicUsize, Ordering};
use crossbeam::scope;

use serde_json::builder::ObjectBuilder;
use serde_json::Value;

#[derive(Debug)]
pub enum Error {
    /// An IO error occurred on the underlying communication channel.
    IoError(io::Error),
    /// The peer closed its connection.
    PeerDisconnect,
    /// The remote method returned an error.
    RemoteError(Value),
    /// The peer sent a response containing the id, but was malformed according
    /// to the json-rpc spec.
    MalformedResponse,
}

/// An interface to access the other side of the RPC channel. The main purpose
/// is to send RPC requests and notifications to the peer.
///
/// The concrete type may change; if the `RpcLoop` were to start a separate
/// writer thread, as opposed to writes being synchronous, then the peer would
/// not need to take the writer type as a parameter.
pub struct RpcPeer<W: Write>(Arc<RpcState<W>>);

pub struct RpcCtx<'a, W: 'a + Write> {
    peer: &'a RpcPeer<W>,
    idle: &'a mut VecDeque<usize>,
}

pub trait Handler<W: Write> {
    fn handle_notification(&mut self, ctx: RpcCtx<W>, method: &str, params: &Value);
    fn handle_request(&mut self, ctx: RpcCtx<W>, method: &str, params: &Value) ->
        Result<Value, Value>;
    #[allow(unused_variables)]
    fn idle(&mut self, ctx: RpcCtx<W>, token: usize) {}
}

trait Callback: Send {
    fn call(self: Box<Self>, result: Result<Value, Error>);
}

impl<F:Send + FnOnce(Result<Value, Error>)> Callback for F {
    fn call(self: Box<F>, result: Result<Value, Error>) {
        (*self)(result)
    }
}

trait IdleProc: Send {
    fn call(self: Box<Self>, token: usize);
}

impl<F:Send + FnOnce(usize)> IdleProc for F {
    fn call(self: Box<F>, token: usize) {
        (*self)(token)
    }
}

enum ResponseHandler {
    Chan(mpsc::Sender<Result<Value, Error>>),
    Callback(Box<Callback>),
}

impl ResponseHandler {
    fn invoke(self, result: Result<Value, Error>) {
        match self {
            ResponseHandler::Chan(tx) => {
                let _ = tx.send(result);
            },
            ResponseHandler::Callback(f) => f.call(result)
        }
    }
}

struct RpcState<W: Write> {
    rx_queue: Mutex<VecDeque<Value>>,
    rx_cvar: Condvar,
    writer: Mutex<W>,
    id: AtomicUsize,
    pending: Mutex<BTreeMap<usize, ResponseHandler>>,
}

/// A structure holding the state of a main loop for handing RPC's.
pub struct RpcLoop<W: Write> {
    buf: String,
    peer: RpcPeer<W>,
}

fn parse_rpc_request(json: &Value) -> Option<(Option<&Value>, &str, &Value)> {
    json.as_object().and_then(|req| {
        if let (Some(method), Some(params)) =
            (dict_get_string(req, "method"), req.get("params")) {
                let id = req.get("id");
                Some((id, method, params))
            }
        else { None }
    })
}

impl<W:Write + Send> RpcLoop<W> {
    /// Creates a new `RpcLoop` with the given output stream (which is used for
    /// sending requests and notifications, as well as responses).
    pub fn new(writer: W) -> Self {
        let rpc_peer = RpcPeer(Arc::new(RpcState {
            rx_queue: Mutex::new(VecDeque::new()),
            rx_cvar: Condvar::new(),
            writer: Mutex::new(writer),
            id: AtomicUsize::new(0),
            pending: Mutex::new(BTreeMap::new()),
        }));
        RpcLoop {
            buf: String::new(),
            peer: rpc_peer,
        }
    }

    /// Gets a reference to the peer.
    pub fn get_peer(&self) -> RpcPeer<W> {
        self.peer.clone()
    }

    // Reads raw json from the input stream.
    fn read_json<R: BufRead>(&mut self, reader: &mut R)
            -> Option<serde_json::error::Result<Value>> {
        self.buf.clear();
        if reader.read_line(&mut self.buf).is_ok() {
            if self.buf.is_empty() {
                return None;
            }
            return Some(serde_json::from_str::<Value>(&self.buf));
        }
        None
    }

    /// Starts a main loop. The reader is supplied via a closure, as basically
    /// a workaround so that the reader doesn't have to be `Send`. Internally, the
    /// main loop starts a separate thread for I/O, and at startup that thread calls
    /// the given closure.
    ///
    /// Calls to the handler (the second closure) happen on the caller's thread, so
    /// that closure need not be `Send`.
    ///
    /// Calls to the handler are guaranteed to preserve the order as they appear on
    /// on the channel. At the moment, there is no way for there to be more than one
    /// incoming request to be outstanding.
    ///
    /// This method returns when the input channel is closed.
    pub fn mainloop<R: BufRead, RF: Send + FnOnce() -> R>(&mut self,
            rf: RF,
            handler: &mut Handler<W>) {
        crossbeam::scope(|scope| {
            let peer = self.get_peer();
            scope.spawn(move|| {
                let mut reader = rf();
                while let Some(json_result) = self.read_json(&mut reader) {
                    match json_result {
                        Ok(json) => {
                            let is_method = json.as_object().map_or(false, |dict|
                                dict.contains_key("method"));
                            if is_method {
                                self.peer.put_rx(json);
                            } else {
                                self.peer.handle_response(json);
                            }
                        }
                        Err(err) => print_err!("Error decoding json: {:?}", err)
                    }
                }
                self.peer.put_rx(Value::Null);
                // TODO: send disconnect error to all pending
            });
            let mut idle = VecDeque::<usize>::new();
            loop {
                let json = if !idle.is_empty() {
                    if let Some(json) = peer.try_get_rx() {
                        json
                    } else {
                        let token = idle.pop_front().unwrap();
                        let ctx = RpcCtx {
                            peer: &peer,
                            idle: &mut idle,
                        };
                        handler.idle(ctx, token);
                        continue;
                    }
                } else {
                    peer.get_rx()
                };
                if json == Value::Null {
                    break;
                }
                //print_err!("to core: {:?}", json);
                match parse_rpc_request(&json) {
                    Some((id, method, params)) => {
                        let ctx = RpcCtx {
                            peer: &peer,
                            idle: &mut idle,
                        };
                        if let Some(id) = id {
                            let result = handler.handle_request(ctx, method, params);
                            peer.respond(result, id);
                        } else {
                            handler.handle_notification(ctx, method, params);
                        }
                    }
                    None => print_err!("invalid RPC request")
                }
            }
        });
    }
}

impl<'a, W: Write> RpcCtx<'a, W> {
    pub fn get_peer(&self) -> &RpcPeer<W> {
        self.peer
    }

    /// Schedule the idle handler to be run when there are no requests pending.
    pub fn schedule_idle(&mut self, token: usize) {
        self.idle.push_back(token);
    }
}

impl<W:Write> RpcPeer<W> {
    fn send(&self, v: &Value) -> Result<(), io::Error> {
        let mut s = serde_json::to_string(v).unwrap();
        s.push('\n');
        //print_err!("from core: {}", s);
        self.0.writer.lock().unwrap().write_all(s.as_bytes())
        // Technically, maybe we should flush here, but doesn't seem to be required.
    }

    fn respond(&self, result: Result<Value, Value>, id: &Value) {
        let mut builder = ObjectBuilder::new()
            .insert("id", id);
        match result {
            Ok(result) => builder = builder.insert("result", result),
            Err(error) => builder = builder.insert("error", error),
        }
        if let Err(e) = self.send(&builder.build()) {
            print_err!("error {} sending response to RPC {:?}", e, id);
        }
    }

    /// Sends a notification (asynchronous rpc) to the peer.
    pub fn send_rpc_notification(&self, method: &str, params: &Value) {
        if let Err(e) = self.send(&ObjectBuilder::new()
            .insert("method", method)
            .insert("params", params)
            .build()) {
            print_err!("send error on send_rpc_notification method {}: {}", method, e);
        }
    }

    fn send_rpc_request_common(&self, method: &str, params: &Value, rh: ResponseHandler) {
        let id = self.0.id.fetch_add(1, Ordering::Relaxed);
        {
            let mut pending = self.0.pending.lock().unwrap();
            pending.insert(id, rh);
        }
        if let Err(e) = self.send(&ObjectBuilder::new()
                .insert("id", id)
                .insert("method", method)
                .insert("params", params)
                .build()) {
            let mut pending = self.0.pending.lock().unwrap();
            if let Some(rh) = pending.remove(&id) {
                rh.invoke(Err(Error::IoError(e)));
            }
        }
    }

    /// Sends a request asynchronously, and the supplied callback will be called when
    /// the response arrives.
    pub fn send_rpc_request_async<F>(&self, method: &str, params: &Value, f: F)
        where F: FnOnce(Result<Value, Error>) + Send + 'static {
        self.send_rpc_request_common(method, params, ResponseHandler::Callback(Box::new(f)));
    }

    /// Sends a request (synchronous rpc) to the peer, and waits for the result.
    pub fn send_rpc_request(&self, method: &str, params: &Value) -> Result<Value, Error> {
        let (tx, rx) = mpsc::channel();
        self.send_rpc_request_common(method, params, ResponseHandler::Chan(tx));
        rx.recv().unwrap_or(Err(Error::PeerDisconnect))
    }

    fn handle_response(&self, mut response: Value) {
        let mut dict = response.as_object_mut().unwrap();
        let id = dict.get("id").and_then(Value::as_u64);
        if id.is_none() {
            print_err!("id missing from response, or is not u64");
            return;
        }
        let id = id.unwrap() as usize;
        let result = dict.remove("result");
        let error = dict.remove("error");
        let result = match (result, error) {
            (Some(result), None) => Ok(result),
            (None, Some(err)) => Err(Error::RemoteError(err)),
            _ => Err(Error::MalformedResponse)
        };
        let handler = {
            let mut pending = self.0.pending.lock().unwrap();
            pending.remove(&id)
        };
        match handler {
            Some(responsehandler) => responsehandler.invoke(result),
            None => print_err!("id {} not found in pending", id)
        }
    }

    // Get a message from the recieve queue if available.
    fn try_get_rx(&self) -> Option<Value> {
        let mut queue = self.0.rx_queue.lock().unwrap();
        queue.pop_front()
    }

    // Get a message from the receive queue, blocking until available.
    fn get_rx(&self) -> Value {
        let mut queue = self.0.rx_queue.lock().unwrap();
        while queue.is_empty() {
            queue = self.0.rx_cvar.wait(queue).unwrap();
        }
        queue.pop_front().unwrap()
    }

    fn put_rx(&self, json: Value) {
        let mut queue = self.0.rx_queue.lock().unwrap();
        queue.push_back(json);
        self.0.rx_cvar.notify_one();
    }

    /// Determines whether an incoming request (or notification) is pending. This
    /// is intended to reduce latency for bulk operations done in the background;
    /// the handler can do this work, periodically check
    pub fn request_is_pending(&self) -> bool {
        let queue = self.0.rx_queue.lock().unwrap();
        !queue.is_empty()
    }
}

impl<W:Write> Clone for RpcPeer<W> {
    fn clone(&self) -> Self {
        RpcPeer(self.0.clone())
    }
}

// =============================================================================
//  Helper functions for value access
// =============================================================================

pub fn dict_get_u64(dict: &BTreeMap<String, Value>, key: &str) -> Option<u64> {
    dict.get(key).and_then(Value::as_u64)
}

pub fn dict_get_string<'a>(dict: &'a BTreeMap<String, Value>, key: &str) -> Option<&'a str> {
    dict.get(key).and_then(Value::as_str)
}

pub fn arr_get_u64(arr: &[Value], idx: usize) -> Option<u64> {
    arr.get(idx).and_then(Value::as_u64)
}

pub fn arr_get_i64(arr: &[Value], idx: usize) -> Option<i64> {
    arr.get(idx).and_then(Value::as_i64)
}
<|endoftext|>


<commit_before><commit_msg>Started Rust based solution<commit_after>use std::rand;
use std::rand::Rng;

fn main() {
	println("Secret Santa");

	let names = ~["Angus", "Greg", "Lewis", "Mike", "Isabel", "Rob", "Shannon", "Allan"];

	secret_santa(names, pairs);
}

fn secret_santa(names: ~[&str], pairs: ~[(&str, &str)]) {
	let mut rng = rand::rng();
	let mut unshuffled_names = names.clone();
	let mut shuffled_names = rng.shuffle(names.clone());

	println!("Picking pairings from: {:?}", unshuffled_names);

	while shuffled_names.len() > 0 {
		let chosen = unshuffled_names.pop();
		let partner = shuffled_names.pop();

		if( chosen == partner ) {
			unshuffled_names.push(chosen);
			shuffled_names.push(partner);

			if(shuffled_names.len() == 1) {
				break;
			}
			rng.shuffle_mut(shuffled_names);
			loop;
		}

		pairs.push((chosen,partner));
	}

	if(shuffled_names.len() == 1) {
		println("Restarting - no good solution.");
		secret_santa(names.clone());
	} else {
		print_pairings(pairs);
	}

	return pairs;
}

fn print_pairings(pairings: ~[(&str, &str)]) {
	for &pair in pairings.iter() {
			println!("{:?} --- is buying for ---> {:?}", pair.first(), pair.second());
	}
}<|endoftext|>


<commit_before><commit_msg>Add anagrams<commit_after>use std::os;
fn main() {
    let args = os::args();
    if args.len() != 2 {
        println!("Please enter only one argument.");
        os::set_exit_status(1);
        return;
    }
    let word: Vec<char> = args[1].chars().collect();
    generate_permutations(word.len() - 1, word);
}

fn generate_permutations(n: uint, a: Vec<char>) {
    if n == 0 {
        println!("{}", a.into_iter().collect::<String>());
    } else {
        let mut this_word = a.clone();
        for i in range(0, n + 1) {
            generate_permutations(n - 1, this_word.clone());
            let swap_index = if n % 2 == 0 {
                i
            } else {
                0
            };

            this_word.swap(swap_index, n);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Enum example added<commit_after>enum message
{
    Quit,
    ChangeColor(i32, i32, i32),
    Move { x: i32, y: i32 },
    Write(String),
}
fn main()
{

}
<|endoftext|>


<commit_before><commit_msg>:hammer: Enable to display markdown preview<commit_after><|endoftext|>


<commit_before><commit_msg>chore: pattern match with scope<commit_after><|endoftext|>


<commit_before>// Support code for rustc's built in test runner generator. Currently,
// none of this is meant for users. It is intended to support the
// simplest interface possible for representing and running tests
// while providing a base that other test frameworks may build off of.

import generic_os::getenv;
import task::task_id;

export test_name;
export test_fn;
export test_desc;
export test_main;
export test_main_ivec;
export test_result;
export test_opts;
export tr_ok;
export tr_failed;
export tr_ignored;
export run_tests_console;
export run_tests_console_;
export run_test;
export filter_tests;
export parse_opts;
export test_to_task;
export default_test_to_task;
export configure_test_task;

native "rust" mod rustrt {
    fn hack_allow_leaks();
    fn sched_threads() -> uint;
}

// The name of a test. By convention this follows the rules for rust
// paths, i.e it should be a series of identifiers seperated by double
// colons. This way if some test runner wants to arrange the tests
// heirarchically it may.
type test_name = str;

// A function that runs a test. If the function returns successfully,
// the test succeeds; if the function fails then the test fails. We
// may need to come up with a more clever definition of test in order
// to support isolation of tests into tasks.
type test_fn = fn() ;

// The definition of a single test. A test runner will run a list of
// these.
type test_desc = {name: test_name, fn: test_fn, ignore: bool};

// The default console test runner. It accepts the command line
// arguments and a vector of test_descs (generated at compile time).
fn test_main(args: &[str], tests: &[test_desc]) {
    check (vec::is_not_empty(args));
    let opts =
        alt parse_opts(args) {
          either::left(o) { o }
          either::right(m) { fail m }
        };
    if !run_tests_console(opts, tests) { fail "Some tests failed"; }
}

type test_opts = {filter: option::t<str>, run_ignored: bool};

type opt_res = either::t<test_opts, str>;

// Parses command line arguments into test options
fn parse_opts(args: &[str]) : vec::is_not_empty(args) -> opt_res {

    // FIXME (#649): Shouldn't have to check here
    check (vec::is_not_empty(args));
    let args_ = vec::tail(args);
    let opts = ~[getopts::optflag("ignored")];
    let match =
        alt getopts::getopts(args_, opts) {
          getopts::success(m) { m }
          getopts::failure(f) { ret either::right(getopts::fail_str(f)) }
        };

    let filter =
        if vec::len(match.free) > 0u {
            option::some(match.free.(0))
        } else { option::none };

    let run_ignored = getopts::opt_present(match, "ignored");

    let test_opts = {filter: filter, run_ignored: run_ignored};

    ret either::left(test_opts);
}

tag test_result { tr_ok; tr_failed; tr_ignored; }

// To get isolation and concurrency tests have to be run in their own tasks.
// In cases where test functions and closures it is not ok to just dump them
// into a task and run them, so this transformation gives the caller a chance
// to create the test task.
type test_to_task = fn(&fn()) -> task_id ;

// A simple console test runner
fn run_tests_console(opts: &test_opts, tests: &[test_desc]) -> bool {
    run_tests_console_(opts, tests, default_test_to_task)
}

fn run_tests_console_(opts: &test_opts, tests: &[test_desc],
                      to_task: &test_to_task) -> bool {

    type test_state = @{
        out: io::writer,
        use_color: bool,
        mutable total: uint,
        mutable passed: uint,
        mutable failed: uint,
        mutable ignored: uint,
        mutable failures: [test_desc]
    };

    fn callback(event: testevent, st: test_state) {
        alt event {
          te_filtered(filtered_tests) {
            st.total = vec::len(filtered_tests);
            st.out.write_line(#fmt("\nrunning %u tests", st.total));
          }
          te_wait(test) {
            st.out.write_str(#fmt("test %s ... ", test.name));
          }
          te_result(test, result) {
            alt result {
              tr_ok. {
                st.passed += 1u;
                write_ok(st.out, st.use_color);
                st.out.write_line("");
              }
              tr_failed. {
                st.failed += 1u;
                write_failed(st.out, st.use_color);
                st.out.write_line("");
                st.failures += ~[test];
              }
              tr_ignored. {
                st.ignored += 1u;
                write_ignored(st.out, st.use_color);
                st.out.write_line("");
              }
            }
          }
        }
    }

    let st = @{
        out: io::stdout(),
        use_color: use_color(),
        mutable total: 0u,
        mutable passed: 0u,
        mutable failed: 0u,
        mutable ignored: 0u,
        mutable failures: ~[]
    };

    run_tests(opts, tests, to_task,
              bind callback(_, st));

    assert st.passed + st.failed + st.ignored == st.total;
    let success = st.failed == 0u;

    if !success {
        st.out.write_line("\nfailures:");
        for test: test_desc in st.failures {
            let testname = test.name; // Satisfy alias analysis
            st.out.write_line(#fmt("    %s", testname));
        }
    }

    st.out.write_str(#fmt("\nresult: "));
    if success {
        // There's no parallelism at this point so it's safe to use color
        write_ok(st.out, true);
    } else { write_failed(st.out, true); }
    st.out.write_str(#fmt(". %u passed; %u failed; %u ignored\n\n",
                       st.passed, st.failed, st.ignored));

    ret success;

    fn write_ok(out: &io::writer, use_color: bool) {
        write_pretty(out, "ok", term::color_green, use_color);
    }

    fn write_failed(out: &io::writer, use_color: bool) {
        write_pretty(out, "FAILED", term::color_red, use_color);
    }

    fn write_ignored(out: &io::writer, use_color: bool) {
        write_pretty(out, "ignored", term::color_yellow, use_color);
    }

    fn write_pretty(out: &io::writer, word: &str, color: u8,
                    use_color: bool) {
        if use_color && term::color_supported() {
            term::fg(out.get_buf_writer(), color);
        }
        out.write_str(word);
        if use_color && term::color_supported() {
            term::reset(out.get_buf_writer());
        }
    }
}

fn use_color() -> bool {
    ret get_concurrency() == 1u;
}

tag testevent {
    te_filtered([test_desc]);
    te_wait(test_desc);
    te_result(test_desc, test_result);
}

fn run_tests(opts: &test_opts, tests: &[test_desc],
             to_task: &test_to_task, callback: fn(testevent)) {

    let filtered_tests = filter_tests(opts, tests);

    callback(te_filtered(filtered_tests));

    // It's tempting to just spawn all the tests at once but that doesn't
    // provide a great user experience because you might sit waiting for the
    // result of a particular test for an unusually long amount of time.
    let concurrency = get_concurrency();
    log #fmt("using %u test tasks", concurrency);
    let total = vec::len(filtered_tests);
    let run_idx = 0u;
    let wait_idx = 0u;
    let futures = ~[];

    while wait_idx < total {
        while vec::len(futures) < concurrency && run_idx < total {
            futures += ~[run_test(filtered_tests.(run_idx), to_task)];
            run_idx += 1u;
        }

        let future = futures.(0);
        callback(te_wait(future.test));
        let result = future.wait();
        callback(te_result(future.test, result));
        futures = vec::slice(futures, 1u, vec::len(futures));
        wait_idx += 1u;
    }
}

fn get_concurrency() -> uint { rustrt::sched_threads() }

fn filter_tests(opts: &test_opts, tests: &[test_desc]) -> [test_desc] {
    let filtered = tests;

    // Remove tests that don't match the test filter
    filtered =
        if option::is_none(opts.filter) {
            filtered
        } else {
            let filter_str =
                alt opts.filter {
                  option::some(f) { f }
                  option::none. { "" }
                };

            let filter =
                bind fn (test: &test_desc, filter_str: str) ->
                        option::t<test_desc> {
                         if str::find(test.name, filter_str) >= 0 {
                             ret option::some(test);
                         } else { ret option::none; }
                     }(_, filter_str);

            vec::filter_map(filter, filtered)
        };

    // Maybe pull out the ignored test and unignore them
    filtered =
        if !opts.run_ignored {
            filtered
        } else {
            let filter =
                fn (test: &test_desc) -> option::t<test_desc> {
                    if test.ignore {
                        ret option::some({name: test.name,
                                          fn: test.fn,
                                          ignore: false});
                    } else { ret option::none; }
                };

            vec::filter_map(filter, filtered)
        };

    // Sort the tests alphabetically
    filtered =
        {
            fn lteq(t1: &test_desc, t2: &test_desc) -> bool {
                str::lteq(t1.name, t2.name)
            }
            sort::merge_sort(lteq, filtered)
        };

    ret filtered;
}

type test_future =
    {test: test_desc, fnref: @fn() , wait: fn() -> test_result };

fn run_test(test: &test_desc, to_task: &test_to_task) -> test_future {
    // FIXME: Because of the unsafe way we're passing the test function
    // to the test task, we need to make sure we keep a reference to that
    // function around for longer than the lifetime of the task. To that end
    // we keep the function boxed in the test future.
    let fnref = @test.fn;
    if !test.ignore {
        let test_task = to_task(*fnref);
        ret {test: test,
             fnref: fnref,
             wait:
             bind fn (test_task: task_id) -> test_result {
                 alt task::join_id(test_task) {
                   task::tr_success. { tr_ok }
                   task::tr_failure. { tr_failed }
                 }
             }(test_task)};
    } else {
        ret {test: test,
             fnref: fnref,
             wait: fn () -> test_result { tr_ignored }};
    }
}

// We need to run our tests in another task in order to trap test failures.
// This function only works with functions that don't contain closures.
fn default_test_to_task(f: &fn()) -> task_id {
    fn run_task(f: fn()) {
        configure_test_task();
        f();
    }
    ret task::spawn(bind run_task(f));
}

// Call from within a test task to make sure it's set up correctly
fn configure_test_task() {
    // If this task fails we don't want that failure to propagate to the
    // test runner or else we couldn't keep running tests
    task::unsupervise();

    // FIXME (236): Hack supreme - unwinding doesn't work yet so if this
    // task fails memory will not be freed correctly. This turns off the
    // sanity checks in the runtime's memory region for the task, so that
    // the test runner can continue.
    rustrt::hack_allow_leaks();
}

// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C .. 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<commit_msg>Remove more hacks from the test runner<commit_after>// Support code for rustc's built in test runner generator. Currently,
// none of this is meant for users. It is intended to support the
// simplest interface possible for representing and running tests
// while providing a base that other test frameworks may build off of.

import generic_os::getenv;
import task::task_id;

export test_name;
export test_fn;
export test_desc;
export test_main;
export test_main_ivec;
export test_result;
export test_opts;
export tr_ok;
export tr_failed;
export tr_ignored;
export run_tests_console;
export run_tests_console_;
export run_test;
export filter_tests;
export parse_opts;
export test_to_task;
export default_test_to_task;
export configure_test_task;

native "rust" mod rustrt {
    fn hack_allow_leaks();
    fn sched_threads() -> uint;
}

// The name of a test. By convention this follows the rules for rust
// paths, i.e it should be a series of identifiers seperated by double
// colons. This way if some test runner wants to arrange the tests
// heirarchically it may.
type test_name = str;

// A function that runs a test. If the function returns successfully,
// the test succeeds; if the function fails then the test fails. We
// may need to come up with a more clever definition of test in order
// to support isolation of tests into tasks.
type test_fn = fn() ;

// The definition of a single test. A test runner will run a list of
// these.
type test_desc = {name: test_name, fn: test_fn, ignore: bool};

// The default console test runner. It accepts the command line
// arguments and a vector of test_descs (generated at compile time).
fn test_main(args: &[str], tests: &[test_desc]) {
    check (vec::is_not_empty(args));
    let opts =
        alt parse_opts(args) {
          either::left(o) { o }
          either::right(m) { fail m }
        };
    if !run_tests_console(opts, tests) { fail "Some tests failed"; }
}

type test_opts = {filter: option::t<str>, run_ignored: bool};

type opt_res = either::t<test_opts, str>;

// Parses command line arguments into test options
fn parse_opts(args: &[str]) : vec::is_not_empty(args) -> opt_res {

    // FIXME (#649): Shouldn't have to check here
    check (vec::is_not_empty(args));
    let args_ = vec::tail(args);
    let opts = ~[getopts::optflag("ignored")];
    let match =
        alt getopts::getopts(args_, opts) {
          getopts::success(m) { m }
          getopts::failure(f) { ret either::right(getopts::fail_str(f)) }
        };

    let filter =
        if vec::len(match.free) > 0u {
            option::some(match.free.(0))
        } else { option::none };

    let run_ignored = getopts::opt_present(match, "ignored");

    let test_opts = {filter: filter, run_ignored: run_ignored};

    ret either::left(test_opts);
}

tag test_result { tr_ok; tr_failed; tr_ignored; }

// To get isolation and concurrency tests have to be run in their own tasks.
// In cases where test functions and closures it is not ok to just dump them
// into a task and run them, so this transformation gives the caller a chance
// to create the test task.
type test_to_task = fn(&fn()) -> task_id ;

// A simple console test runner
fn run_tests_console(opts: &test_opts, tests: &[test_desc]) -> bool {
    run_tests_console_(opts, tests, default_test_to_task)
}

fn run_tests_console_(opts: &test_opts, tests: &[test_desc],
                      to_task: &test_to_task) -> bool {

    type test_state = @{
        out: io::writer,
        use_color: bool,
        mutable total: uint,
        mutable passed: uint,
        mutable failed: uint,
        mutable ignored: uint,
        mutable failures: [test_desc]
    };

    fn callback(event: testevent, st: test_state) {
        alt event {
          te_filtered(filtered_tests) {
            st.total = vec::len(filtered_tests);
            st.out.write_line(#fmt("\nrunning %u tests", st.total));
          }
          te_wait(test) {
            st.out.write_str(#fmt("test %s ... ", test.name));
          }
          te_result(test, result) {
            alt result {
              tr_ok. {
                st.passed += 1u;
                write_ok(st.out, st.use_color);
                st.out.write_line("");
              }
              tr_failed. {
                st.failed += 1u;
                write_failed(st.out, st.use_color);
                st.out.write_line("");
                st.failures += ~[test];
              }
              tr_ignored. {
                st.ignored += 1u;
                write_ignored(st.out, st.use_color);
                st.out.write_line("");
              }
            }
          }
        }
    }

    let st = @{
        out: io::stdout(),
        use_color: use_color(),
        mutable total: 0u,
        mutable passed: 0u,
        mutable failed: 0u,
        mutable ignored: 0u,
        mutable failures: ~[]
    };

    run_tests(opts, tests, to_task,
              bind callback(_, st));

    assert st.passed + st.failed + st.ignored == st.total;
    let success = st.failed == 0u;

    if !success {
        st.out.write_line("\nfailures:");
        for test: test_desc in st.failures {
            let testname = test.name; // Satisfy alias analysis
            st.out.write_line(#fmt("    %s", testname));
        }
    }

    st.out.write_str(#fmt("\nresult: "));
    if success {
        // There's no parallelism at this point so it's safe to use color
        write_ok(st.out, true);
    } else { write_failed(st.out, true); }
    st.out.write_str(#fmt(". %u passed; %u failed; %u ignored\n\n",
                       st.passed, st.failed, st.ignored));

    ret success;

    fn write_ok(out: &io::writer, use_color: bool) {
        write_pretty(out, "ok", term::color_green, use_color);
    }

    fn write_failed(out: &io::writer, use_color: bool) {
        write_pretty(out, "FAILED", term::color_red, use_color);
    }

    fn write_ignored(out: &io::writer, use_color: bool) {
        write_pretty(out, "ignored", term::color_yellow, use_color);
    }

    fn write_pretty(out: &io::writer, word: &str, color: u8,
                    use_color: bool) {
        if use_color && term::color_supported() {
            term::fg(out.get_buf_writer(), color);
        }
        out.write_str(word);
        if use_color && term::color_supported() {
            term::reset(out.get_buf_writer());
        }
    }
}

fn use_color() -> bool {
    ret get_concurrency() == 1u;
}

tag testevent {
    te_filtered([test_desc]);
    te_wait(test_desc);
    te_result(test_desc, test_result);
}

fn run_tests(opts: &test_opts, tests: &[test_desc],
             to_task: &test_to_task, callback: fn(testevent)) {

    let filtered_tests = filter_tests(opts, tests);

    callback(te_filtered(filtered_tests));

    // It's tempting to just spawn all the tests at once but that doesn't
    // provide a great user experience because you might sit waiting for the
    // result of a particular test for an unusually long amount of time.
    let concurrency = get_concurrency();
    log #fmt("using %u test tasks", concurrency);
    let total = vec::len(filtered_tests);
    let run_idx = 0u;
    let wait_idx = 0u;
    let futures = ~[];

    while wait_idx < total {
        while vec::len(futures) < concurrency && run_idx < total {
            futures += ~[run_test(filtered_tests.(run_idx), to_task)];
            run_idx += 1u;
        }

        let future = futures.(0);
        callback(te_wait(future.test));
        let result = future.wait();
        callback(te_result(future.test, result));
        futures = vec::slice(futures, 1u, vec::len(futures));
        wait_idx += 1u;
    }
}

fn get_concurrency() -> uint { rustrt::sched_threads() }

fn filter_tests(opts: &test_opts, tests: &[test_desc]) -> [test_desc] {
    let filtered = tests;

    // Remove tests that don't match the test filter
    filtered =
        if option::is_none(opts.filter) {
            filtered
        } else {
            let filter_str =
                alt opts.filter {
                  option::some(f) { f }
                  option::none. { "" }
                };

            let filter =
                bind fn (test: &test_desc, filter_str: str) ->
                        option::t<test_desc> {
                         if str::find(test.name, filter_str) >= 0 {
                             ret option::some(test);
                         } else { ret option::none; }
                     }(_, filter_str);

            vec::filter_map(filter, filtered)
        };

    // Maybe pull out the ignored test and unignore them
    filtered =
        if !opts.run_ignored {
            filtered
        } else {
            let filter =
                fn (test: &test_desc) -> option::t<test_desc> {
                    if test.ignore {
                        ret option::some({name: test.name,
                                          fn: test.fn,
                                          ignore: false});
                    } else { ret option::none; }
                };

            vec::filter_map(filter, filtered)
        };

    // Sort the tests alphabetically
    filtered =
        {
            fn lteq(t1: &test_desc, t2: &test_desc) -> bool {
                str::lteq(t1.name, t2.name)
            }
            sort::merge_sort(lteq, filtered)
        };

    ret filtered;
}

type test_future =
    {test: test_desc, wait: fn() -> test_result };

fn run_test(test: &test_desc, to_task: &test_to_task) -> test_future {
    if !test.ignore {
        let test_task = to_task(test.fn);
        ret {test: test,
             wait:
             bind fn (test_task: task_id) -> test_result {
                 alt task::join_id(test_task) {
                   task::tr_success. { tr_ok }
                   task::tr_failure. { tr_failed }
                 }
             }(test_task)};
    } else {
        ret {test: test,
             wait: fn () -> test_result { tr_ignored }};
    }
}

// We need to run our tests in another task in order to trap test failures.
// This function only works with functions that don't contain closures.
fn default_test_to_task(f: &fn()) -> task_id {
    fn run_task(f: fn()) {
        configure_test_task();
        f();
    }
    ret task::spawn(bind run_task(f));
}

// Call from within a test task to make sure it's set up correctly
fn configure_test_task() {
    // If this task fails we don't want that failure to propagate to the
    // test runner or else we couldn't keep running tests
    task::unsupervise();

    // FIXME (236): Hack supreme - unwinding doesn't work yet so if this
    // task fails memory will not be freed correctly. This turns off the
    // sanity checks in the runtime's memory region for the task, so that
    // the test runner can continue.
    rustrt::hack_allow_leaks();
}

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


<commit_before><commit_msg>Add something to build simple meshes for polyominos<commit_after>extern crate lyon;

use lyon::path::builder::*;
use lyon::path::default::Path;
use lyon::tessellation::{FillOptions, FillVertex, LineCap, StrokeOptions, StrokeTessellator,
                         StrokeVertex};
use lyon::tessellation::geometry_builder::{GeometryBuilder};
use lyon::tessellation::basic_shapes::fill_rectangle;

use graphics_defs::*;
use gameplay_constants::*;
use polyomino::*;

use mesh_collector::*;

// TODO: In the future we will probably want art more complicated than
// rectangles. For this we should load SVGs and use the `pathfinder`
// crate to render them nicely at any zoom level.

#[derive(Debug, Clone, Copy)]
pub enum GridVertexType {
    Interior = 0,
    Perimeter,
}

#[derive(Debug, Clone, Copy)]
pub enum FillVertexType {
    FillVertex = 0,
}

#[derive(Debug, Clone, Copy)]
struct GridExtraData {
    vertex_type: GridVertexType,
}

impl VertexConstructor<StrokeVertex, GpuShapeVertex> for GridExtraData {
    fn new_vertex(&mut self, vertex: StrokeVertex) -> GpuShapeVertex {
        debug_assert!(!vertex.position.x.is_nan());
        debug_assert!(!vertex.position.y.is_nan());
        debug_assert!(!vertex.normal.x.is_nan());
        debug_assert!(!vertex.normal.y.is_nan());
        debug_assert!(!vertex.advancement.is_nan());

        let thickness = match self.vertex_type {
            Interior => poly_interior_grid_thickness,
            Perimeter => poly_perimeter_grid_thickness,
        };

        let adjusted_pos = vertex.position + (vertex.normal * thickness);

        GpuShapeVertex {
            position: adjusted_pos.to_array(),
            //            normal: vertex.normal.to_array(),
            vertex_type: self.vertex_type as u32,
        }
    }
}

#[derive(Debug, Clone, Copy)]
struct FillExtraData {
    vertex_type: FillVertexType,
}

impl VertexConstructor<FillVertex, GpuShapeVertex> for FillExtraData {
    fn new_vertex(&mut self, vertex: FillVertex) -> GpuShapeVertex {
        debug_assert!(!vertex.position.x.is_nan());
        debug_assert!(!vertex.position.y.is_nan());
        debug_assert!(!vertex.normal.x.is_nan());
        debug_assert!(!vertex.normal.y.is_nan());
        GpuShapeVertex {
            position: vertex.position.to_array(),
            //            normal: vertex.normal.to_array(),
            vertex_type: self.vertex_type as u32,
        }
    }
}

#[derive(PartialEq, Eq, Hash)]
pub enum PolyMeshType {
    GridMesh,
    FillMesh,
}

#[derive(PartialEq, Eq, Hash)]
pub struct PolyMeshId {
    poly: Polyomino,
    which: PolyMeshType,
}

pub struct MeshStore {
    poly_meshes: MeshCollection<PolyMeshId, GpuShapeVertex>,
}

// Reminder:
// USE MATHS COORDINATES
// X RIGHT
// Y UP
// ALWAYS COUNTER-CLOCKWISE

impl MeshStore {
    const tolerance: f32 = 0.02; // TODO: what should this be?

    pub fn new() -> MeshStore {
        MeshStore { poly_meshes: MeshCollection::new() }
    }

    fn gen_border_path(p: &Polyomino, sort: GridSegmentType) -> Path {
        let mut path_builder = Path::builder();
        for GridSegment(start, end, t) in p.segments() {
            if t != sort {
                continue;
            }
            path_builder.move_to(start.to_untyped().to_f32());
            path_builder.line_to(end.to_untyped().to_f32());
        }
        path_builder.build()
    }

    pub fn gen_polyomino_mesh(&mut self, poly: &Polyomino) {
        let interior_grid_path = MeshStore::gen_border_path(poly, GridSegmentType::Internal);
        let mut grid_adder : MeshAdder<PolyMeshId,GpuShapeVertex,StrokeVertex,GridExtraData> = MeshAdder::new(
            &mut self.poly_meshes,
            PolyMeshId {
                poly: poly.clone(),
                which: PolyMeshType::GridMesh,
            },
            GridExtraData {
                vertex_type: GridVertexType::Interior,
            },
        );

        let interior_counts = StrokeTessellator::new().tessellate_path(
            interior_grid_path.path_iter(),
            &StrokeOptions::tolerance(MeshStore::tolerance).with_line_cap(LineCap::Round),
            &mut grid_adder,
        );

        let perimeter_grid_path = MeshStore::gen_border_path(poly, GridSegmentType::Perimeter);
        grid_adder.update_ctor(GridExtraData {
            vertex_type: GridVertexType::Interior,
        });

        let exterior_counts = StrokeTessellator::new().tessellate_path(
            perimeter_grid_path.path_iter(),
            &StrokeOptions::tolerance(MeshStore::tolerance).with_line_cap(LineCap::Round),
            &mut grid_adder,
        );
        grid_adder.finalise_add();

        let fill_options = FillOptions::default();
        let mut fill_adder = MeshAdder::new(
            &mut self.poly_meshes,
            PolyMeshId {
                poly: poly.clone(),
                which: PolyMeshType::FillMesh,
            },
            FillExtraData {
                vertex_type: FillVertexType::FillVertex,
            },
        );
        fill_adder.begin_geometry();
        for p in poly.square_rects() {
            fill_rectangle(&p.to_untyped().to_f32(), &fill_options, &mut fill_adder);
        }
        fill_adder.end_geometry();
        fill_adder.finalise_add();
    }
}
<|endoftext|>


<commit_before><commit_msg>Add problem #131<commit_after>//! Problem 131 (https://projecteuler.net/problem=131)
//! # 解析
//!
//! ```math
//! n^3 + n^2p = m^3
//! ```
//!
//! とおく。
//!
//! ## 定理 1
//! `n` と `p` は互いに素である。
//!
//! ## 証明
//!
//! `p` は素数なので、`n` と `p` が互いに素でない場合、
//! ある自然数 `k` を使って `n = kp` と書ける。
//! このとき、
//!
//! ```math
//! n^3 + n^2p = p^3k^2(k + 1) = m^3
//! k^3 + k^2 = (m / p)^3
//! ```
//!
//! となる。`k^3` の次に大きい立方数は `(k+1)^3` なので、
//! `k^3 + k^2` は立方数ではなく、矛盾する。
//! よって、`n` と `p` は互いに素である■
//!
//! ## 定理 2
//!
//! `n` は立方数である。また、`p` は立方数の差として表される。
//!
//! ## 証明
//!
//! `n` は、互いに素である因数 `s0`, `s1`, `s2` を用いて、以下のように書ける。
//!
//! ```math
//! n = s0^(3e0) * s1^(3e1+1) * s2^(3e2+2)
//! ```
//!
//! このとき、`n` と `p` は互いに素であるため、
//! `n+p` は以下のように因数分解できなければならない。
//!
//! ```math
//! n + p = s0^(3e0) * s1^(3e1+1) * s2^(3e2+2) + p
//!       = s1^(3e'1+1) * s2^(3e'2+2) * k^3
//! ```
//!
//! 上式を整理して、以下を得る。
//!
//! ```math
//! p = s1^(3e''1+1) * s2^(3e''2+2) * (k^3 - p^3)
//! ```
//!
//! 右辺は合成数ではないため、`s1^(3e''1+1) * s2(3e''2+2) = 1` である。
//! すなわち、`n = s0^(3e0)` と書け、立方数である■
//! ## 定理3
//!
//! `p` は任意の数 `q` を用いて以下のように表される。
//!
//! `p = 3q^2 + 3q + 1`
//!
//! ## 証明
//!
//! 定理2 より、`p` は立方根の差として表される素数である。
//! `p = r^3 - q^3` と置くと、以下を得る。
//!
//! ```math
//! p = (r-q)(r^2+rq+q^2)
//! ```
//!
//! `r^2 + rq + q^2 > 1` より、 `r - q = 1` である。
//! すなわち、
//!
//! ```math
//! p = (q+1)^2 + q(q+1) + q^2
//!   = 3q^2 + 3q + 1
//! ```
//!
//! である ■
//!
//! # 解法
//!
//! `3q^2 + 3q + 1` を `q` について計算し、素数のものを列挙する。
//! `q` が

#[crate_id = "prob0131"];
#[crate_type = "rlib"];

extern mod math;

use std::iter;
use math::prime::Prime;

pub static EXPECTED_ANSWER: &'static str = "173";

pub fn solve() -> ~str {
    let limit = 1000000;
    let ps = Prime::new();

    iter::count(1u, 1)
        .map(|q| 3*q*q + 3*q + 1)
        .take_while(|&p| p <= limit)
        .filter(|&p| ps.contains(p) )
        .len()
        .to_str()
}
<|endoftext|>


<commit_before><commit_msg>(feat) Modernise response construction from files.<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for #53678.<commit_after>// check-pass

#![feature(const_fn, generators, generator_trait, existential_type)]

use std::ops::Generator;

existential type GenOnce<Y, R>: Generator<Yield = Y, Return = R>;

const fn const_generator<Y, R>(yielding: Y, returning: R) -> GenOnce<Y, R> {
    move || {
        yield yielding;

        return returning;
    }
}

const FOO: GenOnce<usize, usize> = const_generator(10, 100);

fn main() {}
<|endoftext|>


<commit_before>//! An Implementation of RFC 1951
//!
//! The DEFLATE compression algorithm
//!
//! # Related Links
//! *http://tools.ietf.org/html/rfc1951 - DEFLATE Compressed Data Format Specification

use std::io;
use std::cmp;
use std::io::IoResult;

static LITERALLENGTHCODES: u16 = 286;
static DISTANCECODES: u16 = 30;
static CODEORDER: [u8, ..19] = [
    16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
];
static LENGTHS: [u16, ..29] = [
    3,  4,  5,   6,   7,   8,   9,  10,  11, 13,
    15, 17, 19,  23,  27,  31,  35,  43,  51, 59,
    67, 83, 99, 115, 131, 163, 195, 227, 258
];
static EXTRA_LENGTHS: [u8, ..29] = [
    0, 0, 0, 0, 0, 0, 0, 0, 1, 1,
    1, 1, 2, 2, 2, 2, 3, 3, 3, 3,
    4, 4, 4, 4, 5, 5, 5, 5, 0
];
static DISTANCES: [u16, ..30] = [
    1,    2,      3,    4,    5,    7,    9,    13,    17,    25,
    33,   49,     65,   97,  129,  193,  257,   385,   513,   769,
    1025,  1537,  2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577
];
static EXTRA_DISTANCES: [u8, ..30] = [
    0, 0,  0,  0,  1,  1,  2,  2,  3,  3,
    4, 4,  5,  5,  6,  6,  7,  7,  8,  8,
    9, 9, 10, 10, 11, 11, 12, 12, 13, 13
];

static TABLESIZE: u8 = 9;

#[deriving(PartialEq, Clone)]
enum TableElement {
    Symbol(u16, u8),
    Table(u16, Vec<TableElement>),
    Nothing
}

impl TableElement {
    pub fn put(&mut self, index: u16, elem: TableElement) {
        match *self {
            Table(_, ref mut a) => a.as_mut_slice()[index as uint] = elem,
            _		    => fail!("requires Table()"),
        }
    }
}

enum BlockType {
    Stored,
    Compressed
}

///A DEFLATE compressed stream decoder.
pub struct Inflater<R> {
    h:
    HuffReader<R>,

    buf: Vec<u8>,
    pos: u64,

    final: bool,
    btype: BlockType,
    block_length: u32,

    ctable: Vec<TableElement>,
    lltable: Vec<TableElement>,
    dtable: Vec<TableElement>,
}

impl<R: Reader> Inflater<R> {
    /// Create a new decoder that decodes from a Reader
    pub fn new(r: R) -> Inflater<R> {
        Inflater {
            h: HuffReader::new(r),

            buf: Vec::new(),
            pos: 0,

            final: false,
            block_length: 0,
            btype: Stored,

            ctable: Vec::new(),
            lltable: Vec::new(),
            dtable: Vec::new(),
        }
    }

    /// Indicate whether the end of the stream has been reached.
    pub fn eof(&self) -> bool {
        self.final && (self.pos as uint == self.buf.len())
    }

    /// Return a mutable reference to the wrapped Reader
    pub fn inner(&mut self) -> &mut R {
        &mut self.h.r
    }

    fn read_block_type(&mut self) -> IoResult<()> {
        let final = try!(self.h.receive(1));
        self.final = final == 1;

        let bits = try!(self.h.receive(2));
        match bits {
            0b00 => {
                let _ = try!(self.read_stored_block_length());
                self.btype = Stored;
            }
            0b01 => {
                self.create_fixed_tables();
                self.btype = Compressed;
            }
            0b10 => {
                let _ = try!(self.read_dynamic_tables());
                self.btype = Compressed;
            }
            _ => fail!("reserved block type")
        }

        Ok(())
    }

    fn read_dynamic_tables(&mut self) -> IoResult<()> {
        let totalcodes = LITERALLENGTHCODES + DISTANCECODES;

        let hlit  = try!(self.h.receive(5)) + 257;
        let hdist = try!(self.h.receive(5)) + 1;
        let hclen = try!(self.h.receive(4)) + 4;

        let mut code_lengths = Vec::from_elem(CODEORDER.len(), 0u8);

        for i in range(0, hclen as uint) {
            let length = try!(self.h.receive(3));
            code_lengths.as_mut_slice()[CODEORDER[i] as uint] = length as u8;
        }

        self.ctable = table_from_lengths(code_lengths.as_slice());
        let mut all_lengths = Vec::from_elem(totalcodes as uint, 0u8);

        let mut i = 0;
        while i < hlit + hdist {
            let s = try!(self.h.decode_symbol(self.ctable.as_slice()));

            match s {
                0 ... 15 => {
                    all_lengths.as_mut_slice()[i as uint] = s as u8;
                    i += 1;
                }

                16 => {
                    let repeat = 3 + try!(self.h.receive(2));

                    for _ in range(0, repeat) {
                        all_lengths.as_mut_slice()[i as uint] = all_lengths[i as uint - 1];
                        i += 1;
                    }
                }

                17 => i += 3 + try!(self.h.receive(3)),

                18 => i += 11 + try!(self.h.receive(7)),

                _ => fail!("out of range code length code symbol")
            }
        }

        let ll_lengths = all_lengths.slice_to(hlit as uint);
        let d_lengths  = all_lengths.slice_from(hlit as uint);

        self.lltable = table_from_lengths(ll_lengths);
        self.dtable = table_from_lengths(d_lengths);

        Ok(())
    }

    fn create_fixed_tables(&mut self) {
        let lengths = Vec::from_fn(288, |i|
            if i < 144 { 8u8 }
            else if i < 256 { 9u8 }
            else if i < 280 { 7u8 }
            else { 8u8 }
        );
        self.lltable = table_from_lengths(lengths.as_slice());

        let lengths = Vec::from_elem(DISTANCECODES as uint, 5u8);
        self.dtable = table_from_lengths(lengths.as_slice());
    }

    fn read_stored_block_length(&mut self) -> IoResult<()> {
        self.h.byte_align();

        let len   = try!(self.h.receive(16));
        let _nlen = try!(self.h.receive(16));

        self.block_length = len as u32;

        Ok(())
    }

    fn read_stored_block(&mut self) -> IoResult<()> {
        while self.block_length > 0 {
            let a = try!(self.h.receive(8));

            self.buf.push(a as u8);
            self.h.consume(8);
            self.block_length -= 1;
        }

        Ok(())
    }

    fn read_compressed_block(&mut self) -> IoResult<()> {
        loop {
            let s = try!(self.h.decode_symbol(self.lltable.as_slice()));

            match s {
                literal @ 0 ... 255 => self.buf.push(literal as u8),

                256 => break,

                length @ 257 ... 285 => {
                    let length = length - 257;

                    let bits = EXTRA_LENGTHS[length as uint];
                    let extra = try!(self.h.receive(bits));

                    let length = LENGTHS[length as uint] + extra;

                    let distance = try!(self.h.decode_symbol(self.dtable.as_slice()));

                    let bits = EXTRA_DISTANCES[distance as uint];
                    let extra = try!(self.h.receive(bits));

                    let distance = DISTANCES[distance as uint] + extra;

                    let len = self.buf.len();
                    for i in range(0, length) {
                        let s = self.buf[len - distance as uint + i as uint];
                        self.buf.push(s);
                    }
                }

                _ => fail!("out of range symbol")
            }
        }

        Ok(())
    }
}

impl<R: Reader> Reader for Inflater<R> {
    fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
        if self.pos as uint == self.buf.len() {
            if self.final {
                return Err(io::standard_error(io::EndOfFile))
            }

            let _ = try!(self.read_block_type());
            let _ = match self.btype {
                Stored => try!(self.read_stored_block()),
                Compressed => try!(self.read_compressed_block())
            };
        }

        let n = cmp::min(buf.len(), self.buf.len() - self.pos as uint);
        for i in range(0u, n) {
            buf.as_mut_slice()[i] = self.buf[self.pos as uint + i];
        }

        self.pos += n as u64;
        Ok(n)
    }
}

fn reverse(a: u16) -> u16 {
    let b = (((!0x5555) & a) >> 1) | ((0x5555 & a) << 1);
    let c = (((!0x3333) & b) >> 2) | ((0x3333 & b) << 2);
    let d = (((!0x0F0F) & c) >> 4) | ((0x0F0F & c) << 4);

    (((!0x00FF) & d) >> 8) | ((0x00FF & d) << 8)
}

fn table_from_lengths(lengths: &[u8]) -> Vec<TableElement> {
    let mut max_len = 0;
    let mut code = 0u16;
    let mut next_code = Vec::from_elem(16, 0u16);
    let mut bl_count = Vec::from_elem(16, 0u8);

    for &len in lengths.iter() {
        bl_count.as_mut_slice()[len as uint] += 1;

        if len > max_len {
            max_len = len;
        }
    }

    let max_overflow = max_len - TABLESIZE;
    bl_count.as_mut_slice()[0] = 0;

    for bits in range(1u, 16) {
        code = (code + bl_count[bits - 1] as u16) << 1;
        next_code.as_mut_slice()[bits] = code;
    }

    let mut lut = Vec::from_elem(1 << TABLESIZE as uint, Nothing);

    for (i, &len) in lengths.iter().enumerate() {
        if len == 0 {
            continue
        }

        let code = next_code[len as uint];
        let code = reverse(code) >> (16 - len) as uint;

        if len <= TABLESIZE {
            let r = TABLESIZE - len;

            for j in range(0u16, 1 << r as uint) {
                let index = (j << len as uint) + code;
                lut.as_mut_slice()[index as uint] = Symbol(i as u16, len);
            }
        } else {
            let index = code & ((1 << TABLESIZE as uint) - 1);

            if lut[index as uint] == Nothing {
                let mask  = (1 << max_overflow as uint) - 1;
                let array = Vec::from_elem(1 << max_overflow as uint, Nothing);

                lut.as_mut_slice()[index as uint] = Table(mask, array);
            }

            let code = code >> TABLESIZE as uint;
            let r = max_len - len;

            for j in range(0u16, 1 << r as uint) {
                let k = (j << (len - TABLESIZE) as uint) + code;
                let s = Symbol(i as u16, len - TABLESIZE);

                lut.as_mut_slice()[index as uint].put(k, s);
            }
        }

        next_code.as_mut_slice()[len as uint] += 1;
    }

    lut
}

struct HuffReader<R> {
    pub r: R,

    bits: u32,
    num_bits: u8,
}

impl<R: Reader> HuffReader<R> {
    pub fn new(r: R) -> HuffReader<R> {
        HuffReader {r: r, bits: 0, num_bits: 0}
    }

    pub fn guarantee(&mut self, n: u8) -> IoResult<()> {
        while self.num_bits < n {
            let byte = try!(self.r.read_u8());

            self.bits |= byte as u32 << self.num_bits as uint;
            self.num_bits += 8;
        }

        Ok(())
    }

    pub fn byte_align(&mut self) {
        let n = self.bits & 0b111;

        self.bits >>= n as uint;
        self.num_bits -= n as u8;
    }

    pub fn consume(&mut self, n: u8) {
        self.bits >>= n as uint;
        self.num_bits -= n;
    }

    pub fn receive(&mut self, n: u8) -> IoResult<u16> {
        let _ = try!(self.guarantee(n));

        let val = self.bits & ((1 << n as uint) - 1);
        self.consume(n);

        Ok(val as u16)
    }

    pub fn decode_symbol(&mut self, table: &[TableElement]) -> IoResult<u16> {
        let _ = try!(self.guarantee(1));

        loop {
            let index = self.bits & ((1 << TABLESIZE as uint) - 1);

            let (val, size) = match table[index as uint] {
                Symbol(val, size) => (val, size),

                Table(mask, ref a) => {
                    let index = (self.bits >> TABLESIZE as uint) & mask as u32;

                    match a[index as uint] {
                        Symbol(val, size) => (val, size + TABLESIZE),
                        _ 		  => fail!("bad huffman code")
                    }
                }

                Nothing => fail!("bad huffman code")
            };

            if size <= self.num_bits {
                self.consume(size);
                return	Ok(val)
            }

            let _ = try!(self.guarantee(size));
        }
    }
}<commit_msg>Final is reserved now, rename stuff<commit_after>//! An Implementation of RFC 1951
//!
//! The DEFLATE compression algorithm
//!
//! # Related Links
//! *http://tools.ietf.org/html/rfc1951 - DEFLATE Compressed Data Format Specification

use std::io;
use std::cmp;
use std::io::IoResult;

static LITERALLENGTHCODES: u16 = 286;
static DISTANCECODES: u16 = 30;
static CODEORDER: [u8, ..19] = [
    16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
];
static LENGTHS: [u16, ..29] = [
    3,  4,  5,   6,   7,   8,   9,  10,  11, 13,
    15, 17, 19,  23,  27,  31,  35,  43,  51, 59,
    67, 83, 99, 115, 131, 163, 195, 227, 258
];
static EXTRA_LENGTHS: [u8, ..29] = [
    0, 0, 0, 0, 0, 0, 0, 0, 1, 1,
    1, 1, 2, 2, 2, 2, 3, 3, 3, 3,
    4, 4, 4, 4, 5, 5, 5, 5, 0
];
static DISTANCES: [u16, ..30] = [
    1,    2,      3,    4,    5,    7,    9,    13,    17,    25,
    33,   49,     65,   97,  129,  193,  257,   385,   513,   769,
    1025,  1537,  2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577
];
static EXTRA_DISTANCES: [u8, ..30] = [
    0, 0,  0,  0,  1,  1,  2,  2,  3,  3,
    4, 4,  5,  5,  6,  6,  7,  7,  8,  8,
    9, 9, 10, 10, 11, 11, 12, 12, 13, 13
];

static TABLESIZE: u8 = 9;

#[deriving(PartialEq, Clone)]
enum TableElement {
    Symbol(u16, u8),
    Table(u16, Vec<TableElement>),
    Nothing
}

impl TableElement {
    pub fn put(&mut self, index: u16, elem: TableElement) {
        match *self {
            Table(_, ref mut a) => a.as_mut_slice()[index as uint] = elem,
            _		    => fail!("requires Table()"),
        }
    }
}

enum BlockType {
    Stored,
    Compressed
}

///A DEFLATE compressed stream decoder.
pub struct Inflater<R> {
    h:
    HuffReader<R>,

    buf: Vec<u8>,
    pos: u64,

    finished: bool,
    btype: BlockType,
    block_length: u32,

    ctable: Vec<TableElement>,
    lltable: Vec<TableElement>,
    dtable: Vec<TableElement>,
}

impl<R: Reader> Inflater<R> {
    /// Create a new decoder that decodes from a Reader
    pub fn new(r: R) -> Inflater<R> {
        Inflater {
            h: HuffReader::new(r),

            buf: Vec::new(),
            pos: 0,

            finished: false,
            block_length: 0,
            btype: Stored,

            ctable: Vec::new(),
            lltable: Vec::new(),
            dtable: Vec::new(),
        }
    }

    /// Indicate whether the end of the stream has been reached.
    pub fn eof(&self) -> bool {
        self.finished && (self.pos as uint == self.buf.len())
    }

    /// Return a mutable reference to the wrapped Reader
    pub fn inner(&mut self) -> &mut R {
        &mut self.h.r
    }

    fn read_block_type(&mut self) -> IoResult<()> {
        let is_final = try!(self.h.receive(1));
        self.finished = is_final == 1;

        let bits = try!(self.h.receive(2));
        match bits {
            0b00 => {
                let _ = try!(self.read_stored_block_length());
                self.btype = Stored;
            }
            0b01 => {
                self.create_fixed_tables();
                self.btype = Compressed;
            }
            0b10 => {
                let _ = try!(self.read_dynamic_tables());
                self.btype = Compressed;
            }
            _ => fail!("reserved block type")
        }

        Ok(())
    }

    fn read_dynamic_tables(&mut self) -> IoResult<()> {
        let totalcodes = LITERALLENGTHCODES + DISTANCECODES;

        let hlit  = try!(self.h.receive(5)) + 257;
        let hdist = try!(self.h.receive(5)) + 1;
        let hclen = try!(self.h.receive(4)) + 4;

        let mut code_lengths = Vec::from_elem(CODEORDER.len(), 0u8);

        for i in range(0, hclen as uint) {
            let length = try!(self.h.receive(3));
            code_lengths.as_mut_slice()[CODEORDER[i] as uint] = length as u8;
        }

        self.ctable = table_from_lengths(code_lengths.as_slice());
        let mut all_lengths = Vec::from_elem(totalcodes as uint, 0u8);

        let mut i = 0;
        while i < hlit + hdist {
            let s = try!(self.h.decode_symbol(self.ctable.as_slice()));

            match s {
                0 ... 15 => {
                    all_lengths.as_mut_slice()[i as uint] = s as u8;
                    i += 1;
                }

                16 => {
                    let repeat = 3 + try!(self.h.receive(2));

                    for _ in range(0, repeat) {
                        all_lengths.as_mut_slice()[i as uint] = all_lengths[i as uint - 1];
                        i += 1;
                    }
                }

                17 => i += 3 + try!(self.h.receive(3)),

                18 => i += 11 + try!(self.h.receive(7)),

                _ => fail!("out of range code length code symbol")
            }
        }

        let ll_lengths = all_lengths.slice_to(hlit as uint);
        let d_lengths  = all_lengths.slice_from(hlit as uint);

        self.lltable = table_from_lengths(ll_lengths);
        self.dtable = table_from_lengths(d_lengths);

        Ok(())
    }

    fn create_fixed_tables(&mut self) {
        let lengths = Vec::from_fn(288, |i|
            if i < 144 { 8u8 }
            else if i < 256 { 9u8 }
            else if i < 280 { 7u8 }
            else { 8u8 }
        );
        self.lltable = table_from_lengths(lengths.as_slice());

        let lengths = Vec::from_elem(DISTANCECODES as uint, 5u8);
        self.dtable = table_from_lengths(lengths.as_slice());
    }

    fn read_stored_block_length(&mut self) -> IoResult<()> {
        self.h.byte_align();

        let len   = try!(self.h.receive(16));
        let _nlen = try!(self.h.receive(16));

        self.block_length = len as u32;

        Ok(())
    }

    fn read_stored_block(&mut self) -> IoResult<()> {
        while self.block_length > 0 {
            let a = try!(self.h.receive(8));

            self.buf.push(a as u8);
            self.h.consume(8);
            self.block_length -= 1;
        }

        Ok(())
    }

    fn read_compressed_block(&mut self) -> IoResult<()> {
        loop {
            let s = try!(self.h.decode_symbol(self.lltable.as_slice()));

            match s {
                literal @ 0 ... 255 => self.buf.push(literal as u8),

                256 => break,

                length @ 257 ... 285 => {
                    let length = length - 257;

                    let bits = EXTRA_LENGTHS[length as uint];
                    let extra = try!(self.h.receive(bits));

                    let length = LENGTHS[length as uint] + extra;

                    let distance = try!(self.h.decode_symbol(self.dtable.as_slice()));

                    let bits = EXTRA_DISTANCES[distance as uint];
                    let extra = try!(self.h.receive(bits));

                    let distance = DISTANCES[distance as uint] + extra;

                    let len = self.buf.len();
                    for i in range(0, length) {
                        let s = self.buf[len - distance as uint + i as uint];
                        self.buf.push(s);
                    }
                }

                _ => fail!("out of range symbol")
            }
        }

        Ok(())
    }
}

impl<R: Reader> Reader for Inflater<R> {
    fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
        if self.pos as uint == self.buf.len() {
            if self.finished {
                return Err(io::standard_error(io::EndOfFile))
            }

            let _ = try!(self.read_block_type());
            let _ = match self.btype {
                Stored => try!(self.read_stored_block()),
                Compressed => try!(self.read_compressed_block())
            };
        }

        let n = cmp::min(buf.len(), self.buf.len() - self.pos as uint);
        for i in range(0u, n) {
            buf.as_mut_slice()[i] = self.buf[self.pos as uint + i];
        }

        self.pos += n as u64;
        Ok(n)
    }
}

fn reverse(a: u16) -> u16 {
    let b = (((!0x5555) & a) >> 1) | ((0x5555 & a) << 1);
    let c = (((!0x3333) & b) >> 2) | ((0x3333 & b) << 2);
    let d = (((!0x0F0F) & c) >> 4) | ((0x0F0F & c) << 4);

    (((!0x00FF) & d) >> 8) | ((0x00FF & d) << 8)
}

fn table_from_lengths(lengths: &[u8]) -> Vec<TableElement> {
    let mut max_len = 0;
    let mut code = 0u16;
    let mut next_code = Vec::from_elem(16, 0u16);
    let mut bl_count = Vec::from_elem(16, 0u8);

    for &len in lengths.iter() {
        bl_count.as_mut_slice()[len as uint] += 1;

        if len > max_len {
            max_len = len;
        }
    }

    let max_overflow = max_len - TABLESIZE;
    bl_count.as_mut_slice()[0] = 0;

    for bits in range(1u, 16) {
        code = (code + bl_count[bits - 1] as u16) << 1;
        next_code.as_mut_slice()[bits] = code;
    }

    let mut lut = Vec::from_elem(1 << TABLESIZE as uint, Nothing);

    for (i, &len) in lengths.iter().enumerate() {
        if len == 0 {
            continue
        }

        let code = next_code[len as uint];
        let code = reverse(code) >> (16 - len) as uint;

        if len <= TABLESIZE {
            let r = TABLESIZE - len;

            for j in range(0u16, 1 << r as uint) {
                let index = (j << len as uint) + code;
                lut.as_mut_slice()[index as uint] = Symbol(i as u16, len);
            }
        } else {
            let index = code & ((1 << TABLESIZE as uint) - 1);

            if lut[index as uint] == Nothing {
                let mask  = (1 << max_overflow as uint) - 1;
                let array = Vec::from_elem(1 << max_overflow as uint, Nothing);

                lut.as_mut_slice()[index as uint] = Table(mask, array);
            }

            let code = code >> TABLESIZE as uint;
            let r = max_len - len;

            for j in range(0u16, 1 << r as uint) {
                let k = (j << (len - TABLESIZE) as uint) + code;
                let s = Symbol(i as u16, len - TABLESIZE);

                lut.as_mut_slice()[index as uint].put(k, s);
            }
        }

        next_code.as_mut_slice()[len as uint] += 1;
    }

    lut
}

struct HuffReader<R> {
    pub r: R,

    bits: u32,
    num_bits: u8,
}

impl<R: Reader> HuffReader<R> {
    pub fn new(r: R) -> HuffReader<R> {
        HuffReader {r: r, bits: 0, num_bits: 0}
    }

    pub fn guarantee(&mut self, n: u8) -> IoResult<()> {
        while self.num_bits < n {
            let byte = try!(self.r.read_u8());

            self.bits |= byte as u32 << self.num_bits as uint;
            self.num_bits += 8;
        }

        Ok(())
    }

    pub fn byte_align(&mut self) {
        let n = self.bits & 0b111;

        self.bits >>= n as uint;
        self.num_bits -= n as u8;
    }

    pub fn consume(&mut self, n: u8) {
        self.bits >>= n as uint;
        self.num_bits -= n;
    }

    pub fn receive(&mut self, n: u8) -> IoResult<u16> {
        let _ = try!(self.guarantee(n));

        let val = self.bits & ((1 << n as uint) - 1);
        self.consume(n);

        Ok(val as u16)
    }

    pub fn decode_symbol(&mut self, table: &[TableElement]) -> IoResult<u16> {
        let _ = try!(self.guarantee(1));

        loop {
            let index = self.bits & ((1 << TABLESIZE as uint) - 1);

            let (val, size) = match table[index as uint] {
                Symbol(val, size) => (val, size),

                Table(mask, ref a) => {
                    let index = (self.bits >> TABLESIZE as uint) & mask as u32;

                    match a[index as uint] {
                        Symbol(val, size) => (val, size + TABLESIZE),
                        _ 		  => fail!("bad huffman code")
                    }
                }

                Nothing => fail!("bad huffman code")
            };

            if size <= self.num_bits {
                self.consume(size);
                return	Ok(val)
            }

            let _ = try!(self.guarantee(size));
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>chore: content as_ref<commit_after><|endoftext|>


<commit_before>//! HTTP/HTTPS URL type for Iron.

use url::{self, Host};
use std::str::FromStr;
use std::fmt;

/// HTTP/HTTPS URL type for Iron.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Url {
    /// The generic rust-url that corresponds to this Url
    generic_url: url::Url,
}

impl Url {
    /// Create a URL from a string.
    ///
    /// The input must be a valid URL with a special scheme for this to succeed.
    ///
    /// HTTP and HTTPS are special schemes.
    ///
    /// See: http://url.spec.whatwg.org/#special-scheme
    pub fn parse(input: &str) -> Result<Url, String> {
        // Parse the string using rust-url, then convert.
        match url::Url::parse(input) {
            Ok(raw_url) => Url::from_generic_url(raw_url),
            Err(e) => Err(format!("{}", e))
        }
    }

    /// Create a `Url` from a `rust-url` `Url`.
    pub fn from_generic_url(raw_url: url::Url) -> Result<Url, String> {
        // Create an Iron URL by verifying the `rust-url` `Url` is a special
        // scheme that Iron supports.
        if raw_url.cannot_be_a_base() {
            Err(format!("Not a special scheme: `{}`", raw_url.scheme()))
        } else if raw_url.port_or_known_default().is_none() {
            Err(format!("Invalid special scheme: `{}`", raw_url.scheme()))
        } else {
            Ok(Url {
                generic_url: raw_url,
            })
        }
    }

    /// Create a `rust-url` `Url` from a `Url`.
    #[deprecated(since="0.4.1", note="use `into` from the `Into` trait instead")]
    pub fn into_generic_url(self) -> url::Url {
        self.generic_url
    }

    /// The lower-cased scheme of the URL, typically "http" or "https".
    pub fn scheme(&self) -> &str {
        self.generic_url.scheme()
    }

    /// The host field of the URL, probably a domain.
    pub fn host(&self) -> Host<&str> {
        // `unwrap` is safe here because urls that cannot be a base don't have a host
        self.generic_url.host().unwrap()
    }

    /// The connection port.
    pub fn port(&self) -> u16 {
        // `unwrap` is safe here because we checked `port_or_known_default`
        // in `from_generic_url`.
        self.generic_url.port_or_known_default().unwrap()
    }

    /// The URL path, the resource to be accessed.
    ///
    /// A *non-empty* vector encoding the parts of the URL path.
    /// Empty entries of `""` correspond to trailing slashes.
    pub fn path(&self) -> Vec<&str> {
        // `unwrap` is safe here because urls that can be a base will have `Some`.
        self.generic_url.path_segments().unwrap().collect()
    }

    /// The URL username field, from the userinfo section of the URL.
    ///
    /// `None` if the `@` character was not part of the input OR
    /// if a blank username was provided.
    /// Otherwise, a non-empty string.
    pub fn username(&self) -> Option<&str> {
        // Map empty usernames to None.
        match self.generic_url.username() {
            "" => None,
            username => Some(username)
        }
    }

    /// The URL password field, from the userinfo section of the URL.
    ///
    /// `None` if the `@` character was not part of the input OR
    /// if a blank password was provided.
    /// Otherwise, a non-empty string.
    pub fn password(&self) -> Option<&str> {
        // Map empty passwords to None.
        match self.generic_url.password() {
            None => None,
            Some(x) if x.is_empty() => None,
            Some(password) => Some(password)
        }
    }

    /// The URL query string.
    ///
    /// `None` if the `?` character was not part of the input.
    /// Otherwise, a possibly empty, percent encoded string.
    pub fn query(&self) -> Option<&str> {
        self.generic_url.query()
    }

    /// The URL fragment.
    ///
    /// `None` if the `#` character was not part of the input.
    /// Otherwise, a possibly empty, percent encoded string.
    pub fn fragment(&self) -> Option<&str> {
        self.generic_url.fragment()
    }
}

impl fmt::Display for Url {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        try!(self.generic_url.fmt(formatter));
        Ok(())
    }
}

impl Into<url::Url> for Url {
    fn into(self) -> url::Url { self.generic_url }
}

impl AsRef<url::Url> for Url {
    fn as_ref(&self) -> &url::Url { &self.generic_url }
}

impl AsMut<url::Url> for Url {
    fn as_mut(&mut self) -> &mut url::Url { &mut self.generic_url }
}

impl FromStr for Url {
    type Err = String;
    #[inline]
    fn from_str(input: &str) -> Result<Url, Self::Err> {
        Ok(Url::parse(input).unwrap())
    }
}

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

    #[test]
    fn test_default_port() {
        assert_eq!(Url::parse("http://example.com/wow").unwrap().port(), 80u16);
        assert_eq!(Url::parse("https://example.com/wow").unwrap().port(), 443u16);
    }

    #[test]
    fn test_explicit_port() {
        assert_eq!(Url::parse("http://localhost:3097").unwrap().port(), 3097u16);
    }

    #[test]
    fn test_empty_username() {
        assert!(Url::parse("http://@example.com").unwrap().username().is_none());
        assert!(Url::parse("http://:password@example.com").unwrap().username().is_none());
    }

    #[test]
    fn test_not_empty_username() {
        let url = Url::parse("http://john:pass@example.com").unwrap();
        assert_eq!(url.username().unwrap(), "john");

        let url = Url::parse("http://john:@example.com").unwrap();
        assert_eq!(url.username().unwrap(), "john");
    }

    #[test]
    fn test_empty_password() {
        assert!(Url::parse("http://michael@example.com").unwrap().password().is_none());
        assert!(Url::parse("http://:@example.com").unwrap().password().is_none());
    }

    #[test]
    fn test_not_empty_password() {
        let url = Url::parse("http://michael:pass@example.com").unwrap();
        assert_eq!(url.password().unwrap(), "pass");

        let url = Url::parse("http://:pass@example.com").unwrap();
        assert_eq!(url.password().unwrap(), "pass");
    }

    #[test]
    fn test_formatting() {
        assert_eq!(Url::parse("http://michael@example.com/path/?q=wow").unwrap().to_string(),
                    "http://michael@example.com/path/?q=wow".to_string());
    }

    #[test]
    fn test_conversion() {
        let url_str = "https://user:password@iron.com:8080/path?q=wow#fragment";
        let url = Url::parse(url_str).unwrap();

        // Convert to a generic URL and check fidelity.
        let raw_url: ::url::Url = url.clone().into();
        assert_eq!(::url::Url::parse(url_str).unwrap(), raw_url);

        // Convert back to an Iron URL and check fidelity.
        let new_url = Url::from_generic_url(raw_url).unwrap();
        assert_eq!(url, new_url);
    }

    #[test]
    fn test_https_non_default_port() {
        let parsed = Url::parse("https://example.com:8080").unwrap().to_string();
        assert_eq!(parsed, "https://example.com:8080/");
    }

    #[test]
    fn test_https_default_port() {
        let parsed = Url::parse("https://example.com:443").unwrap().to_string();
        assert_eq!(parsed, "https://example.com/");
    }
}
<commit_msg>Removed unwrap<commit_after>//! HTTP/HTTPS URL type for Iron.

use url::{self, Host};
use std::str::FromStr;
use std::fmt;

/// HTTP/HTTPS URL type for Iron.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Url {
    /// The generic rust-url that corresponds to this Url
    generic_url: url::Url,
}

impl Url {
    /// Create a URL from a string.
    ///
    /// The input must be a valid URL with a special scheme for this to succeed.
    ///
    /// HTTP and HTTPS are special schemes.
    ///
    /// See: http://url.spec.whatwg.org/#special-scheme
    pub fn parse(input: &str) -> Result<Url, String> {
        // Parse the string using rust-url, then convert.
        match url::Url::parse(input) {
            Ok(raw_url) => Url::from_generic_url(raw_url),
            Err(e) => Err(format!("{}", e))
        }
    }

    /// Create a `Url` from a `rust-url` `Url`.
    pub fn from_generic_url(raw_url: url::Url) -> Result<Url, String> {
        // Create an Iron URL by verifying the `rust-url` `Url` is a special
        // scheme that Iron supports.
        if raw_url.cannot_be_a_base() {
            Err(format!("Not a special scheme: `{}`", raw_url.scheme()))
        } else if raw_url.port_or_known_default().is_none() {
            Err(format!("Invalid special scheme: `{}`", raw_url.scheme()))
        } else {
            Ok(Url {
                generic_url: raw_url,
            })
        }
    }

    /// Create a `rust-url` `Url` from a `Url`.
    #[deprecated(since="0.4.1", note="use `into` from the `Into` trait instead")]
    pub fn into_generic_url(self) -> url::Url {
        self.generic_url
    }

    /// The lower-cased scheme of the URL, typically "http" or "https".
    pub fn scheme(&self) -> &str {
        self.generic_url.scheme()
    }

    /// The host field of the URL, probably a domain.
    pub fn host(&self) -> Host<&str> {
        // `unwrap` is safe here because urls that cannot be a base don't have a host
        self.generic_url.host().unwrap()
    }

    /// The connection port.
    pub fn port(&self) -> u16 {
        // `unwrap` is safe here because we checked `port_or_known_default`
        // in `from_generic_url`.
        self.generic_url.port_or_known_default().unwrap()
    }

    /// The URL path, the resource to be accessed.
    ///
    /// A *non-empty* vector encoding the parts of the URL path.
    /// Empty entries of `""` correspond to trailing slashes.
    pub fn path(&self) -> Vec<&str> {
        // `unwrap` is safe here because urls that can be a base will have `Some`.
        self.generic_url.path_segments().unwrap().collect()
    }

    /// The URL username field, from the userinfo section of the URL.
    ///
    /// `None` if the `@` character was not part of the input OR
    /// if a blank username was provided.
    /// Otherwise, a non-empty string.
    pub fn username(&self) -> Option<&str> {
        // Map empty usernames to None.
        match self.generic_url.username() {
            "" => None,
            username => Some(username)
        }
    }

    /// The URL password field, from the userinfo section of the URL.
    ///
    /// `None` if the `@` character was not part of the input OR
    /// if a blank password was provided.
    /// Otherwise, a non-empty string.
    pub fn password(&self) -> Option<&str> {
        // Map empty passwords to None.
        match self.generic_url.password() {
            None => None,
            Some(x) if x.is_empty() => None,
            Some(password) => Some(password)
        }
    }

    /// The URL query string.
    ///
    /// `None` if the `?` character was not part of the input.
    /// Otherwise, a possibly empty, percent encoded string.
    pub fn query(&self) -> Option<&str> {
        self.generic_url.query()
    }

    /// The URL fragment.
    ///
    /// `None` if the `#` character was not part of the input.
    /// Otherwise, a possibly empty, percent encoded string.
    pub fn fragment(&self) -> Option<&str> {
        self.generic_url.fragment()
    }
}

impl fmt::Display for Url {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        try!(self.generic_url.fmt(formatter));
        Ok(())
    }
}

impl Into<url::Url> for Url {
    fn into(self) -> url::Url { self.generic_url }
}

impl AsRef<url::Url> for Url {
    fn as_ref(&self) -> &url::Url { &self.generic_url }
}

impl AsMut<url::Url> for Url {
    fn as_mut(&mut self) -> &mut url::Url { &mut self.generic_url }
}

impl FromStr for Url {
    type Err = String;
    #[inline]
    fn from_str(input: &str) -> Result<Url, Self::Err> {
        Url::parse(input)
    }
}

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

    #[test]
    fn test_default_port() {
        assert_eq!(Url::parse("http://example.com/wow").unwrap().port(), 80u16);
        assert_eq!(Url::parse("https://example.com/wow").unwrap().port(), 443u16);
    }

    #[test]
    fn test_explicit_port() {
        assert_eq!(Url::parse("http://localhost:3097").unwrap().port(), 3097u16);
    }

    #[test]
    fn test_empty_username() {
        assert!(Url::parse("http://@example.com").unwrap().username().is_none());
        assert!(Url::parse("http://:password@example.com").unwrap().username().is_none());
    }

    #[test]
    fn test_not_empty_username() {
        let url = Url::parse("http://john:pass@example.com").unwrap();
        assert_eq!(url.username().unwrap(), "john");

        let url = Url::parse("http://john:@example.com").unwrap();
        assert_eq!(url.username().unwrap(), "john");
    }

    #[test]
    fn test_empty_password() {
        assert!(Url::parse("http://michael@example.com").unwrap().password().is_none());
        assert!(Url::parse("http://:@example.com").unwrap().password().is_none());
    }

    #[test]
    fn test_not_empty_password() {
        let url = Url::parse("http://michael:pass@example.com").unwrap();
        assert_eq!(url.password().unwrap(), "pass");

        let url = Url::parse("http://:pass@example.com").unwrap();
        assert_eq!(url.password().unwrap(), "pass");
    }

    #[test]
    fn test_formatting() {
        assert_eq!(Url::parse("http://michael@example.com/path/?q=wow").unwrap().to_string(),
                    "http://michael@example.com/path/?q=wow".to_string());
    }

    #[test]
    fn test_conversion() {
        let url_str = "https://user:password@iron.com:8080/path?q=wow#fragment";
        let url = Url::parse(url_str).unwrap();

        // Convert to a generic URL and check fidelity.
        let raw_url: ::url::Url = url.clone().into();
        assert_eq!(::url::Url::parse(url_str).unwrap(), raw_url);

        // Convert back to an Iron URL and check fidelity.
        let new_url = Url::from_generic_url(raw_url).unwrap();
        assert_eq!(url, new_url);
    }

    #[test]
    fn test_https_non_default_port() {
        let parsed = Url::parse("https://example.com:8080").unwrap().to_string();
        assert_eq!(parsed, "https://example.com:8080/");
    }

    #[test]
    fn test_https_default_port() {
        let parsed = Url::parse("https://example.com:443").unwrap().to_string();
        assert_eq!(parsed, "https://example.com/");
    }
}
<|endoftext|>


<commit_before><commit_msg>Add a test for the returned balances from Kraken<commit_after>#[cfg(test)]
mod kraken_tests {
    extern crate coinnect;

    use self::coinnect::kraken::KrakenApi;

    /// IMPORTANT: Real keys are needed in order to retrieve the balance
    #[test]
    fn balance_should_return_a_result() {
        use std::path::PathBuf;
        let path = PathBuf::from("./keys_real.json");
        let mut api = KrakenApi::new_from_file("account_kraken", path);
        let result = api.get_account_balance();

        assert!(result.unwrap().contains_key("result"));
    }
}<|endoftext|>