<commit_before>#![deny(missing_docs)]

//! A stable version of `std::thread::scoped`
//!
//! ## Warning
//!
//! This is inherently unsafe if the `JoinGuard` is allowed to leak without being dropped.
//! See #24292 for more details.

use std::marker::PhantomData;
use std::thread::{spawn, JoinHandle, Thread};
use std::mem::{transmute, forget};

/// A RAII guard for that joins a scoped thread upon drop
///
/// # Panics
///
/// `JoinGuard` will panic on join or drop if its owned thread panics
#[must_use = "thread will be immediately joined if `JoinGuard` is not used"]
pub struct JoinGuard<'a, T: Send + 'a> {
    inner: Option<JoinHandle<BoxedThing>>,
    _marker: PhantomData<&'a T>,
}

unsafe impl<'a, T: Send + 'a> Sync for JoinGuard<'a, T> {}

impl<'a, T: Send + 'a> JoinGuard<'a, T> {
    /// Provides the backing `Thread` object
    pub fn thread(&self) -> &Thread {
        &self.inner.as_ref().unwrap().thread()
    }

    /// Joins the guarded thread and returns its result
    ///
    /// # Panics
    ///
    /// `join()` will panic if the owned thread panics
    pub fn join(mut self) -> T {
        match self.inner.take().unwrap().join() {
            Ok(res) => unsafe { *res.into_inner() },
            Err(_) => panic!("child thread {:?} panicked", self.thread()),
        }
    }
}

/// Detaches a child thread from its guard
pub trait ScopedDetach {
    /// Detaches a child thread from its guard
    ///
    /// Note: Only valid for the 'static lifetime
    fn detach(self);
}

impl<T: Send + 'static> ScopedDetach for JoinGuard<'static, T> {
    fn detach(mut self) {
        let _ = self.inner.take();
    }
}

impl<'a, T: Send + 'a> Drop for JoinGuard<'a, T> {
    fn drop(&mut self) {
        self.inner.take().map(|v| if v.join().is_err() {
            panic!("child thread {:?} panicked", self.thread());
        });
    }
}

/// Spawns a new scoped thread
pub unsafe fn scoped<'a, T, F>(f: F) -> JoinGuard<'a, T> where
    T: Send + 'a, F: FnOnce() -> T, F: Send + 'a
{
    let f = BoxedThing::new(f);

    JoinGuard {
        inner: Some(spawn(move ||
            BoxedThing::new(f.into_inner::<F>()())
        )),
        _marker: PhantomData,
    }
}

struct BoxedThing(usize);
impl BoxedThing {
    fn new<T>(v: T) -> Self {
        let mut b = Box::new(v);
        let b_ptr = &mut *b as *mut _ as usize;
        forget(b);
        BoxedThing(b_ptr)
    }

    unsafe fn into_inner<T>(self) -> Box<T> {
        transmute(self.0 as *mut T)
    }
}

#[cfg(test)]
mod tests {
    use std::thread::sleep_ms;
    use super::scoped;

    #[test]
    fn test_scoped_stack() {
        unsafe {
            let mut a = 5;
            scoped(|| {
                sleep_ms(50);
                a = 2;
            }).join();
            assert_eq!(a, 2);
        }
    }

    #[test]
    fn test_join_success() {
        unsafe {
            assert!(scoped(move|| -> String {
                "Success!".to_string()
            }).join() == "Success!");
        }
    }

    #[test]
    fn test_scoped_success() {
        unsafe {
            let res = scoped(move|| -> String {
                "Success!".to_string()
            }).join();
            assert!(res == "Success!");
        }
    }

    #[test]
    #[should_panic]
    fn test_scoped_panic() {
        unsafe {
            scoped(|| panic!()).join();
        }
    }

    #[test]
    #[should_panic]
    fn test_scoped_implicit_panic() {
        unsafe {
            let _ = scoped(|| panic!());
        }
    }
}
<commit_msg>replace use of deprecated sleep_ms<commit_after>#![deny(missing_docs)]

//! A stable version of `std::thread::scoped`
//!
//! ## Warning
//!
//! This is inherently unsafe if the `JoinGuard` is allowed to leak without being dropped.
//! See #24292 for more details.

use std::marker::PhantomData;
use std::thread::{spawn, JoinHandle, Thread};
use std::mem::{transmute, forget};

/// A RAII guard for that joins a scoped thread upon drop
///
/// # Panics
///
/// `JoinGuard` will panic on join or drop if its owned thread panics
#[must_use = "thread will be immediately joined if `JoinGuard` is not used"]
pub struct JoinGuard<'a, T: Send + 'a> {
    inner: Option<JoinHandle<BoxedThing>>,
    _marker: PhantomData<&'a T>,
}

unsafe impl<'a, T: Send + 'a> Sync for JoinGuard<'a, T> {}

impl<'a, T: Send + 'a> JoinGuard<'a, T> {
    /// Provides the backing `Thread` object
    pub fn thread(&self) -> &Thread {
        &self.inner.as_ref().unwrap().thread()
    }

    /// Joins the guarded thread and returns its result
    ///
    /// # Panics
    ///
    /// `join()` will panic if the owned thread panics
    pub fn join(mut self) -> T {
        match self.inner.take().unwrap().join() {
            Ok(res) => unsafe { *res.into_inner() },
            Err(_) => panic!("child thread {:?} panicked", self.thread()),
        }
    }
}

/// Detaches a child thread from its guard
pub trait ScopedDetach {
    /// Detaches a child thread from its guard
    ///
    /// Note: Only valid for the 'static lifetime
    fn detach(self);
}

impl<T: Send + 'static> ScopedDetach for JoinGuard<'static, T> {
    fn detach(mut self) {
        let _ = self.inner.take();
    }
}

impl<'a, T: Send + 'a> Drop for JoinGuard<'a, T> {
    fn drop(&mut self) {
        self.inner.take().map(|v| if v.join().is_err() {
            panic!("child thread {:?} panicked", self.thread());
        });
    }
}

/// Spawns a new scoped thread
pub unsafe fn scoped<'a, T, F>(f: F) -> JoinGuard<'a, T> where
    T: Send + 'a, F: FnOnce() -> T, F: Send + 'a
{
    let f = BoxedThing::new(f);

    JoinGuard {
        inner: Some(spawn(move ||
            BoxedThing::new(f.into_inner::<F>()())
        )),
        _marker: PhantomData,
    }
}

struct BoxedThing(usize);
impl BoxedThing {
    fn new<T>(v: T) -> Self {
        let mut b = Box::new(v);
        let b_ptr = &mut *b as *mut _ as usize;
        forget(b);
        BoxedThing(b_ptr)
    }

    unsafe fn into_inner<T>(self) -> Box<T> {
        transmute(self.0 as *mut T)
    }
}

#[cfg(test)]
mod tests {
    use std::thread::sleep;
    use std::time::Duration;
    use super::scoped;

    #[test]
    fn test_scoped_stack() {
        unsafe {
            let mut a = 5;
            scoped(|| {
                sleep(Duration::from_millis(100));
                a = 2;
            }).join();
            assert_eq!(a, 2);
        }
    }

    #[test]
    fn test_join_success() {
        unsafe {
            assert!(scoped(move|| -> String {
                "Success!".to_string()
            }).join() == "Success!");
        }
    }

    #[test]
    fn test_scoped_success() {
        unsafe {
            let res = scoped(move|| -> String {
                "Success!".to_string()
            }).join();
            assert!(res == "Success!");
        }
    }

    #[test]
    #[should_panic]
    fn test_scoped_panic() {
        unsafe {
            scoped(|| panic!()).join();
        }
    }

    #[test]
    #[should_panic]
    fn test_scoped_implicit_panic() {
        unsafe {
            let _ = scoped(|| panic!());
        }
    }
}
<|endoftext|>


<commit_before>// Copyright 2013-2014 Valentin Vasilyev.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![crate_name="heliotrope"]

extern crate serialize;
extern crate url;
extern crate http;
extern crate debug;

use url::{Url, UrlParser};
use serialize::{json, Encodable, Encoder, Decodable, Decoder};

mod http_utils;

pub type SolrResult<'a> = Result<SolrResponse, SolrError<'a>>;

pub struct Document<'a>{
  fields: Vec<(&'a str, &'a str)>
}

impl<'a> Document<'a> {
  pub fn new() -> Document<'a> {
    let fields: Vec<(&'a str, &'a str)> = Vec::with_capacity(10);
    Document{fields: fields}
  }

  pub fn add_field(&mut self, name: &'a str, value: &'a str) {
    self.fields.push((name, value));
  }
}

impl<'a, E, S: Encoder<E>> Encodable<S, E> for Document<'a> {
  fn encode(&self, s: &mut S) -> Result<(), E> {
    s.emit_seq(self.fields.len(), |e| {
      e.emit_map(self.fields.len(), |e| {
        let mut i = 0;
        for &(ref k, ref v) in self.fields.iter() {
          try!(e.emit_map_elt_key(i, |e| k.encode(e)));
          try!(e.emit_map_elt_val(i, |e| v.encode(e)));
          i += 1;
        }
        Ok(())
      });
    Ok(())
    })
  }
}

pub struct Solr {
  pub base_url: Url,
  update_url: Url,
  commit_url: Url
}

impl Solr {

  fn build_update_url(url: &Url) -> Url{
    let mut url_parser = UrlParser::new();
    url_parser.base_url(url).parse("./update").unwrap()
  }

  fn build_commit_url(url: &Url) -> Url {
    let mut url_parser = UrlParser::new();
    url_parser.base_url(url).parse("./update?commit=true").unwrap()
  }
  pub fn new(url: &Url) -> Solr {
    Solr {base_url: url.clone(),
      update_url: Solr::build_update_url(url),
      commit_url: Solr::build_commit_url(url)}
  }

  pub fn add(&self, document: &Document) -> SolrResult {
    let raw_json = json::encode(&document);
    match http_utils::post_json(&self.update_url, raw_json.as_slice()) {
      Ok(http_response) => {
        match http_response.code {
          200 => {
            let response: SolrResponse = json::decode(http_response.body_str().unwrap()).unwrap();
            Ok(response)
          },
          _ => {
            let error: SolrError = json::decode(http_response.body_str().unwrap()).unwrap();
            Err(error)
          }
        }
      },
      Err(err) => {
        Err(SolrError{status: 0, time: 0, message: err.desc.to_string()})
      }
    }
  }

  pub fn commit(&self) -> SolrResult {
    match http_utils::post(&self.commit_url) {
      Ok(http_response) => {
        match http_response.code {
          200 => {
            let response: SolrResponse = json::decode(http_response.body_str().unwrap()).unwrap();
            Ok(response)
          },
          _ => {
            let error: SolrError = json::decode(http_response.body_str().unwrap()).unwrap();
            Err(error)
          }
        }
      },
      Err(err) => {
        Err(SolrError{status: 0, time: 0, message: err.desc.to_string()})
      }
    }
  }
}

struct SolrError<'a> {
  status: int,
  time: int,
  message: String
}

impl<'a, D: Decoder<E>, E> Decodable<D, E> for SolrError<'a> {
  fn decode(d: &mut D) -> Result<SolrError<'a>, E> {
    d.read_struct("root", 0, |d| {
      d.read_struct_field("error", 0, |d| {
        Ok(SolrError{
          message: try!(d.read_struct_field("msg", 0, |d| Decodable::decode(d))),
          status: try!(d.read_struct_field("code", 1, |d| Decodable::decode(d))),
          // TODO: implement time parsing from request header
          time: 0})
      })
    })
  }
}

struct SolrResponse {
  status: int,
  time: int
}

impl<D: Decoder<E>, E> Decodable<D, E> for SolrResponse {
  fn decode(d: &mut D) -> Result<SolrResponse, E> {
    d.read_struct("root", 0, |d| {
      d.read_struct_field("responseHeader", 0, |d| {
        Ok(SolrResponse{
          status: try!(d.read_struct_field("status", 0, |d| Decodable::decode(d))),
          time: try!(d.read_struct_field("QTime", 1, |d| Decodable::decode(d)))
        })
      })
    })
  }
}
<commit_msg>Visibility fixes<commit_after>// Copyright 2013-2014 Valentin Vasilyev.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![crate_name="heliotrope"]

extern crate serialize;
extern crate url;
extern crate http;
extern crate debug;

use url::{Url, UrlParser};
use serialize::{json, Encodable, Encoder, Decodable, Decoder};

mod http_utils;

pub type SolrResult = Result<SolrResponse, SolrError>;

pub struct Document<'a>{
  fields: Vec<(&'a str, &'a str)>
}

impl<'a> Document<'a> {
  pub fn new() -> Document<'a> {
    let fields: Vec<(&'a str, &'a str)> = Vec::with_capacity(10);
    Document{fields: fields}
  }

  pub fn add_field(&mut self, name: &'a str, value: &'a str) {
    self.fields.push((name, value));
  }
}

impl<'a, E, S: Encoder<E>> Encodable<S, E> for Document<'a> {
  fn encode(&self, s: &mut S) -> Result<(), E> {
    s.emit_seq(self.fields.len(), |e| {
      e.emit_map(self.fields.len(), |e| {
        let mut i = 0;
        for &(ref k, ref v) in self.fields.iter() {
          try!(e.emit_map_elt_key(i, |e| k.encode(e)));
          try!(e.emit_map_elt_val(i, |e| v.encode(e)));
          i += 1;
        }
        Ok(())
      });
    Ok(())
    })
  }
}

pub struct Solr {
  pub base_url: Url,
  update_url: Url,
  commit_url: Url
}

impl Solr {

  fn build_update_url(url: &Url) -> Url{
    let mut url_parser = UrlParser::new();
    url_parser.base_url(url).parse("./update").unwrap()
  }

  fn build_commit_url(url: &Url) -> Url {
    let mut url_parser = UrlParser::new();
    url_parser.base_url(url).parse("./update?commit=true").unwrap()
  }
  pub fn new(url: &Url) -> Solr {
    Solr {base_url: url.clone(),
      update_url: Solr::build_update_url(url),
      commit_url: Solr::build_commit_url(url)}
  }

  pub fn add(&self, document: &Document) -> SolrResult {
    let raw_json = json::encode(&document);
    match http_utils::post_json(&self.update_url, raw_json.as_slice()) {
      Ok(http_response) => {
        match http_response.code {
          200 => {
            let response: SolrResponse = json::decode(http_response.body_str().unwrap()).unwrap();
            Ok(response)
          },
          _ => {
            let error: SolrError = json::decode(http_response.body_str().unwrap()).unwrap();
            Err(error)
          }
        }
      },
      Err(err) => {
        Err(SolrError{status: 0, time: 0, message: err.desc.to_string()})
      }
    }
  }

  pub fn commit(&self) -> SolrResult {
    match http_utils::post(&self.commit_url) {
      Ok(http_response) => {
        match http_response.code {
          200 => {
            let response: SolrResponse = json::decode(http_response.body_str().unwrap()).unwrap();
            Ok(response)
          },
          _ => {
            let error: SolrError = json::decode(http_response.body_str().unwrap()).unwrap();
            Err(error)
          }
        }
      },
      Err(err) => {
        Err(SolrError{status: 0, time: 0, message: err.desc.to_string()})
      }
    }
  }
}

pub struct SolrError {
  pub status: int,
  pub time: int,
  pub message: String
}

impl<D: Decoder<E>, E> Decodable<D, E> for SolrError {
  fn decode(d: &mut D) -> Result<SolrError, E> {
    d.read_struct("root", 0, |d| {
      d.read_struct_field("error", 0, |d| {
        Ok(SolrError{
          message: try!(d.read_struct_field("msg", 0, |d| Decodable::decode(d))),
          status: try!(d.read_struct_field("code", 1, |d| Decodable::decode(d))),
          // TODO: implement time parsing from request header
          time: 0})
      })
    })
  }
}

pub struct SolrResponse {
  pub status: int,
  pub time: int
}

impl<D: Decoder<E>, E> Decodable<D, E> for SolrResponse {
  fn decode(d: &mut D) -> Result<SolrResponse, E> {
    d.read_struct("root", 0, |d| {
      d.read_struct_field("responseHeader", 0, |d| {
        Ok(SolrResponse{
          status: try!(d.read_struct_field("status", 0, |d| Decodable::decode(d))),
          time: try!(d.read_struct_field("QTime", 1, |d| Decodable::decode(d)))
        })
      })
    })
  }
}
<|endoftext|>


<commit_before>/*!

#rust-amqp
[![Build Status](https://travis-ci.org/Antti/rust-amqp.svg)](https://travis-ci.org/Antti/rust-amqp)

AMQ protocol implementation in pure rust.

> Note:
> The project is still in very early stages of development,
> it implements all the protocol parsing, but not all the protocol methods are wrapped/easy to use.
> Expect the API to be changed in the future.

## What it currently can do:
* Connect to server
* Open/close channels
* Declare queues/exchanges
* All the methods from the Basic class are implemented, including get, publish, ack, nack, reject, consume. So you can send/receive messages.

Have a look at the examples in examples folder.

### Connecting to the server & openning channel:
>Note: Currently it can't connect using TLS connections.

```ignore
    use amqp::session::Session;
    use amqp::table;

    let mut session = Session::open_url("amqp://localhost/").unwrap();
    let mut channel = session.open_channel(1).unwrap();
```

### Declaring queue:
```ignore
    use amqp::table;
    //The arguments come in following order:
    //queue: &str, passive: bool, durable: bool, exclusive: bool, auto_delete: bool, nowait: bool, arguments: Table
    let queue_declare = channel.queue_declare("my_queue_name", false, true, false, false, false, table::new());
```

### Publishing message:
```ignore
    channel.basic_publish("", "my_queue_name", true, false,
    amqp::protocol::basic::BasicProperties{ content_type: Some("text".to_string()), ..Default::default()}, (b"Hello from rust!").to_vec());
```

This will send message: "Hello from rust!" to the queue named "my_queue_name".

The messages have type of Vec<u8>, so if you want to send string, first you must convert it to Vec<u8>.

## Development notes:

The methods encoding/decoding code is generated using codegen.rb & amqp-rabbitmq-0.9.1.json spec.

To generate a new spec, run:

```sh
make
```

To build project, use cargo:

```sh
cargo build
```

To build examples:
```sh
cargo test
```
*/

#![feature(collections)]
#![feature(convert)]

// extern crate bst;
extern crate url;
extern crate byteorder;
#[macro_use]
extern crate log;

#[macro_use] extern crate enum_primitive;

pub mod connection;
pub mod channel;
pub mod framing;
pub mod table;
pub mod protocol;
pub mod session;
pub mod basic;
pub mod amqp_error;
<commit_msg>Fix build.<commit_after>/*!

#rust-amqp
[![Build Status](https://travis-ci.org/Antti/rust-amqp.svg)](https://travis-ci.org/Antti/rust-amqp)

AMQ protocol implementation in pure rust.

> Note:
> The project is still in very early stages of development,
> it implements all the protocol parsing, but not all the protocol methods are wrapped/easy to use.
> Expect the API to be changed in the future.

## What it currently can do:
* Connect to server
* Open/close channels
* Declare queues/exchanges
* All the methods from the Basic class are implemented, including get, publish, ack, nack, reject, consume. So you can send/receive messages.

Have a look at the examples in examples folder.

### Connecting to the server & openning channel:
>Note: Currently it can't connect using TLS connections.

```ignore
    use amqp::session::Session;
    use amqp::table;

    let mut session = Session::open_url("amqp://localhost/").unwrap();
    let mut channel = session.open_channel(1).unwrap();
```

### Declaring queue:
```ignore
    use amqp::table;
    //The arguments come in following order:
    //queue: &str, passive: bool, durable: bool, exclusive: bool, auto_delete: bool, nowait: bool, arguments: Table
    let queue_declare = channel.queue_declare("my_queue_name", false, true, false, false, false, table::new());
```

### Publishing message:
```ignore
    channel.basic_publish("", "my_queue_name", true, false,
    amqp::protocol::basic::BasicProperties{ content_type: Some("text".to_string()), ..Default::default()}, (b"Hello from rust!").to_vec());
```

This will send message: "Hello from rust!" to the queue named "my_queue_name".

The messages have type of Vec<u8>, so if you want to send string, first you must convert it to Vec<u8>.

## Development notes:

The methods encoding/decoding code is generated using codegen.rb & amqp-rabbitmq-0.9.1.json spec.

To generate a new spec, run:

```sh
make
```

To build project, use cargo:

```sh
cargo build
```

To build examples:
```sh
cargo test
```
*/

#![feature(convert)]
#![feature(bitvec)]

// extern crate bst;
extern crate url;
extern crate byteorder;
#[macro_use]
extern crate log;

#[macro_use] extern crate enum_primitive;

pub mod connection;
pub mod channel;
pub mod framing;
pub mod table;
pub mod protocol;
pub mod session;
pub mod basic;
pub mod amqp_error;
<|endoftext|>


<commit_before>#![warn(rust_2018_idioms)]
extern crate conduit;

use std::io::prelude::*;
use std::io::Cursor;
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};

use conduit::{
    header::{HeaderValue, IntoHeaderName},
    Extensions, HeaderMap, Host, Method, Scheme, TypeMap, Version,
};

pub struct MockRequest {
    path: String,
    method: Method,
    query_string: Option<String>,
    body: Option<Vec<u8>>,
    headers: HeaderMap,
    extensions: TypeMap,
    reader: Option<Cursor<Vec<u8>>>,
}

impl MockRequest {
    pub fn new(method: Method, path: &str) -> MockRequest {
        let headers = HeaderMap::new();

        MockRequest {
            path: path.to_string(),
            extensions: TypeMap::new(),
            query_string: None,
            body: None,
            headers,
            method,
            reader: None,
        }
    }

    pub fn with_method(&mut self, method: Method) -> &mut MockRequest {
        self.method = method;
        self
    }

    pub fn with_path(&mut self, path: &str) -> &mut MockRequest {
        self.path = path.to_string();
        self
    }

    pub fn with_query(&mut self, string: &str) -> &mut MockRequest {
        self.query_string = Some(string.to_string());
        self
    }

    pub fn with_body(&mut self, bytes: &[u8]) -> &mut MockRequest {
        self.body = Some(bytes.to_vec());
        self.reader = None;
        self
    }

    pub fn header<K>(&mut self, name: K, value: &str) -> &mut MockRequest
    where
        K: IntoHeaderName,
    {
        self.headers
            .insert(name, HeaderValue::from_str(value).unwrap());
        self
    }
}

impl conduit::RequestExt for MockRequest {
    fn http_version(&self) -> Version {
        Version::HTTP_11
    }

    fn method(&self) -> &Method {
        &self.method
    }
    fn scheme(&self) -> Scheme {
        Scheme::Http
    }
    fn host(&self) -> Host<'_> {
        Host::Name("example.com")
    }
    fn virtual_root(&self) -> Option<&str> {
        None
    }

    fn path(&self) -> &str {
        &self.path
    }

    fn query_string(&self) -> Option<&str> {
        self.query_string.as_ref().map(|s| &s[..])
    }

    fn remote_addr(&self) -> SocketAddr {
        SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 80))
    }

    fn content_length(&self) -> Option<u64> {
        self.body.as_ref().map(|b| b.len() as u64)
    }

    fn headers(&self) -> &HeaderMap {
        &self.headers
    }

    fn body(&mut self) -> &mut dyn Read {
        if self.reader.is_none() {
            let body = self.body.clone().unwrap_or_default();
            self.reader = Some(Cursor::new(body));
        }
        self.reader.as_mut().unwrap()
    }

    fn extensions(&self) -> &Extensions {
        &self.extensions
    }
    fn mut_extensions(&mut self) -> &mut Extensions {
        &mut self.extensions
    }
}

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

    use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};

    use conduit::{header, Host, Method, RequestExt, Scheme, Version};

    #[test]
    fn simple_request_test() {
        let mut req = MockRequest::new(Method::GET, "/");

        assert_eq!(req.http_version(), Version::HTTP_11);
        assert_eq!(req.method(), Method::GET);
        assert_eq!(req.scheme(), Scheme::Http);
        assert_eq!(req.host(), Host::Name("example.com"));
        assert_eq!(req.virtual_root(), None);
        assert_eq!(req.path(), "/");
        assert_eq!(req.query_string(), None);
        assert_eq!(
            req.remote_addr(),
            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 80))
        );
        assert_eq!(req.content_length(), None);
        assert_eq!(req.headers().len(), 0);
        let mut s = String::new();
        req.body().read_to_string(&mut s).ok().expect("No body");
        assert_eq!(s, "".to_string());
    }

    #[test]
    fn request_body_test() {
        let mut req = MockRequest::new(Method::POST, "/articles");
        req.with_body(b"Hello world");

        assert_eq!(req.method(), Method::POST);
        assert_eq!(req.path(), "/articles");
        let mut s = String::new();
        req.body().read_to_string(&mut s).ok().expect("No body");
        assert_eq!(s, "Hello world".to_string());
        assert_eq!(req.content_length(), Some(11));
    }

    #[test]
    fn request_query_test() {
        let mut req = MockRequest::new(Method::POST, "/articles");
        req.with_query("foo=bar");

        assert_eq!(req.query_string().expect("No query string"), "foo=bar");
    }

    #[test]
    fn request_headers() {
        let mut req = MockRequest::new(Method::POST, "/articles");
        req.header(header::USER_AGENT, "lulz");
        req.header(header::DNT, "1");

        assert_eq!(req.headers().len(), 2);
        assert_eq!(req.headers().get(header::USER_AGENT).unwrap(), "lulz");
        assert_eq!(req.headers().get(header::DNT).unwrap(), "1");
    }
}
<commit_msg>Drop `.ok().expect()` pattern<commit_after>#![warn(rust_2018_idioms)]
extern crate conduit;

use std::io::prelude::*;
use std::io::Cursor;
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};

use conduit::{
    header::{HeaderValue, IntoHeaderName},
    Extensions, HeaderMap, Host, Method, Scheme, TypeMap, Version,
};

pub struct MockRequest {
    path: String,
    method: Method,
    query_string: Option<String>,
    body: Option<Vec<u8>>,
    headers: HeaderMap,
    extensions: TypeMap,
    reader: Option<Cursor<Vec<u8>>>,
}

impl MockRequest {
    pub fn new(method: Method, path: &str) -> MockRequest {
        let headers = HeaderMap::new();

        MockRequest {
            path: path.to_string(),
            extensions: TypeMap::new(),
            query_string: None,
            body: None,
            headers,
            method,
            reader: None,
        }
    }

    pub fn with_method(&mut self, method: Method) -> &mut MockRequest {
        self.method = method;
        self
    }

    pub fn with_path(&mut self, path: &str) -> &mut MockRequest {
        self.path = path.to_string();
        self
    }

    pub fn with_query(&mut self, string: &str) -> &mut MockRequest {
        self.query_string = Some(string.to_string());
        self
    }

    pub fn with_body(&mut self, bytes: &[u8]) -> &mut MockRequest {
        self.body = Some(bytes.to_vec());
        self.reader = None;
        self
    }

    pub fn header<K>(&mut self, name: K, value: &str) -> &mut MockRequest
    where
        K: IntoHeaderName,
    {
        self.headers
            .insert(name, HeaderValue::from_str(value).unwrap());
        self
    }
}

impl conduit::RequestExt for MockRequest {
    fn http_version(&self) -> Version {
        Version::HTTP_11
    }

    fn method(&self) -> &Method {
        &self.method
    }
    fn scheme(&self) -> Scheme {
        Scheme::Http
    }
    fn host(&self) -> Host<'_> {
        Host::Name("example.com")
    }
    fn virtual_root(&self) -> Option<&str> {
        None
    }

    fn path(&self) -> &str {
        &self.path
    }

    fn query_string(&self) -> Option<&str> {
        self.query_string.as_ref().map(|s| &s[..])
    }

    fn remote_addr(&self) -> SocketAddr {
        SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 80))
    }

    fn content_length(&self) -> Option<u64> {
        self.body.as_ref().map(|b| b.len() as u64)
    }

    fn headers(&self) -> &HeaderMap {
        &self.headers
    }

    fn body(&mut self) -> &mut dyn Read {
        if self.reader.is_none() {
            let body = self.body.clone().unwrap_or_default();
            self.reader = Some(Cursor::new(body));
        }
        self.reader.as_mut().unwrap()
    }

    fn extensions(&self) -> &Extensions {
        &self.extensions
    }
    fn mut_extensions(&mut self) -> &mut Extensions {
        &mut self.extensions
    }
}

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

    use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};

    use conduit::{header, Host, Method, RequestExt, Scheme, Version};

    #[test]
    fn simple_request_test() {
        let mut req = MockRequest::new(Method::GET, "/");

        assert_eq!(req.http_version(), Version::HTTP_11);
        assert_eq!(req.method(), Method::GET);
        assert_eq!(req.scheme(), Scheme::Http);
        assert_eq!(req.host(), Host::Name("example.com"));
        assert_eq!(req.virtual_root(), None);
        assert_eq!(req.path(), "/");
        assert_eq!(req.query_string(), None);
        assert_eq!(
            req.remote_addr(),
            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 80))
        );
        assert_eq!(req.content_length(), None);
        assert_eq!(req.headers().len(), 0);
        let mut s = String::new();
        req.body().read_to_string(&mut s).expect("No body");
        assert_eq!(s, "".to_string());
    }

    #[test]
    fn request_body_test() {
        let mut req = MockRequest::new(Method::POST, "/articles");
        req.with_body(b"Hello world");

        assert_eq!(req.method(), Method::POST);
        assert_eq!(req.path(), "/articles");
        let mut s = String::new();
        req.body().read_to_string(&mut s).expect("No body");
        assert_eq!(s, "Hello world".to_string());
        assert_eq!(req.content_length(), Some(11));
    }

    #[test]
    fn request_query_test() {
        let mut req = MockRequest::new(Method::POST, "/articles");
        req.with_query("foo=bar");

        assert_eq!(req.query_string().expect("No query string"), "foo=bar");
    }

    #[test]
    fn request_headers() {
        let mut req = MockRequest::new(Method::POST, "/articles");
        req.header(header::USER_AGENT, "lulz");
        req.header(header::DNT, "1");

        assert_eq!(req.headers().len(), 2);
        assert_eq!(req.headers().get(header::USER_AGENT).unwrap(), "lulz");
        assert_eq!(req.headers().get(header::DNT).unwrap(), "1");
    }
}
<|endoftext|>


<commit_before>#![feature(test)]

extern crate byteorder;
use byteorder::{LittleEndian, ReadBytesExt};

use std::collections::HashMap;
use std::io::{self, Read, Seek, SeekFrom, BufRead, BufReader};
use std::fs::File;
use std::cell::RefCell;

pub mod errors;
use errors::ReadError;

pub struct BigArchive<T: Read + Seek> {
    pub format: Format,
    pub size: u32,

    _buf_reader: RefCell<BufReader<T>>,
    _entries: HashMap<String, BigEntry>,
}

impl BigArchive<File> {
    pub fn new_from_path(path: &str) -> Result<Self, ReadError> {
        let f = try!(File::open(&path));
        let br = BufReader::new(f);
        Ok(try!(BigArchive::new(br)))
    }
}

impl<T: Read + Seek> BigArchive<T> {
    pub fn new(mut data: BufReader<T>) -> Result<Self, ReadError> {
        let format = read_format(&mut data).expect("Failed to read format");

        if let Format::Unknown(bytes) = format {
            return Err(ReadError::UnknownArchiveFormat(bytes));
        }

        let size = try!(data.read_u32::<LittleEndian>());
        let size = invert_endianness(size);

        let num_entries = try!(data.read_u32::<LittleEndian>());
        let num_entries = invert_endianness(num_entries);

        // Offset to the first entry, I think.
        let _ = data.read_u32::<LittleEndian>();

        let mut entries = HashMap::new();

        for i in 0..num_entries {
            let offset = try!(data.read_u32::<LittleEndian>());
            let offset = invert_endianness(offset);

            let size = try!(data.read_u32::<LittleEndian>());
            let size = invert_endianness(size);

            let mut buf = Vec::new();
            data.read_until(b'\0', &mut buf)
                .expect(&format!("Failed to read name for entry {}", i + 1));

            // Remove the trailing \0
            let name = String::from_utf8_lossy(&buf[..buf.len() - 1]);

            let entry = BigEntry {
                offset: offset,
                size: size,
                name: name.to_string(),
            };

            entries.insert(entry.name.clone(), entry);
        }

        Ok(BigArchive {
            format: format,
            size: size,
            _buf_reader: RefCell::new(data),
            _entries: entries,
        })
    }

    /// TODO: Don't return owned data, instead give the caller back a slice
    pub fn read_entry(&self, entry_name: &str) -> Option<Vec<u8>> {
        if let Some(entry) = self._entries.get(entry_name) {
            let br = &mut self._buf_reader.borrow_mut();

            if br.seek(SeekFrom::Start((*entry).offset as u64)).is_err() {
                return None;
            }

            let mut buf = vec![0; entry.size as usize];
            if br.read_exact(&mut buf).is_err() {
                return None;
            }

            Some(buf)
        } else {
            None
        }
    }

    pub fn contains(&self, entry_name: &str) -> bool {
        self._entries.contains_key(entry_name)
    }

    pub fn get_entry(&self, entry_name: &str) -> Option<&BigEntry> {
        self._entries.get(entry_name)
    }

    pub fn get_entry_mut(&mut self, entry_name: &str) -> Option<&mut BigEntry> {
        self._entries.get_mut(entry_name)
    }

    pub fn get_all_entry_names(&self) -> std::collections::hash_map::Keys<String, BigEntry> {
        self._entries.keys()
    }
}

#[derive(Debug)]
pub struct BigEntry {
    pub offset: u32,
    pub size: u32,
    pub name: String,
}

#[derive(Debug, PartialEq)]
pub enum Format {
    Unknown(Vec<u8>),
    Big4,
    BigF,
}

impl<'a> From<&'a mut BufRead> for Format {
    fn from(data: &'a mut BufRead) -> Self {
        let mut buf = [0; 4];
        let _ = data.read_exact(&mut buf);
        match &buf {
            b"BIG4" => Format::Big4,
            b"BIGF" => Format::BigF,
            _ => Format::Unknown(Vec::from(&buf[..])),
        }
    }
}

fn read_format(data: &mut BufRead) -> Result<Format, io::Error> {
    Ok(Format::from(data))
}

fn invert_endianness(v: u32) -> u32 {
    (v << 24) | (v << 8 & 0xff0000) | (v >> 8 & 0xff00) | (v >> 24)
}

#[cfg(test)]
mod tests_bytes {
    const TEST_BYTES: &'static [u8] = include_bytes!("../test.big");
    use std::io::{BufReader, Cursor};
    use super::{Format, BigArchive};

    #[test]
    fn is_big4() {
        let c = Cursor::new(TEST_BYTES);
        let br = BufReader::new(c);
        let archive = BigArchive::new(br).unwrap();
        assert_eq!(archive.format, Format::Big4);
    }

    #[test]
    fn has_two_entries() {
        let c = Cursor::new(TEST_BYTES);
        let br = BufReader::new(c);
        let archive = BigArchive::new(br).unwrap();
        assert_eq!(archive.get_all_entry_names().len(), 2);
    }

    #[test]
    fn contains_art_slash_image_dot_txt() {
        let c = Cursor::new(TEST_BYTES);
        let br = BufReader::new(c);
        let archive = BigArchive::new(br).unwrap();
        assert!(archive.contains("art/image.txt"));
    }

    #[test]
    fn contains_data_slash_test_dot_ini() {
        let c = Cursor::new(TEST_BYTES);
        let br = BufReader::new(c);
        let archive = BigArchive::new(br).unwrap();
        assert!(archive.contains("data/test.ini"));
    }

    #[test]
    fn read_entry_art_slash_image_dot_txt() {
        let c = Cursor::new(TEST_BYTES);
        let br = BufReader::new(c);
        let archive = BigArchive::new(br).unwrap();
        let data = archive.read_entry("art/image.txt").unwrap();
        assert_eq!(data, vec![98, 108, 97, 98, 108, 98, 97]);
    }

    #[test]
    fn read_entry_data_slash_test_dot_ini() {
        let c = Cursor::new(TEST_BYTES);
        let br = BufReader::new(c);
        let archive = BigArchive::new(br).unwrap();
        let data = archive.read_entry("data/test.ini").unwrap();
        assert_eq!(data,
                   vec![84, 104, 105, 115, 32, 105, 115, 32, 97, 32, 115, 105, 109, 112, 108,
                        101, 32, 116, 101, 115, 116, 32, 102, 105, 108, 101]);
    }

    mod benches {
        extern crate test;
        use self::test::Bencher;

        #[bench]
        fn is_big4(b: &mut Bencher) {
            b.iter(|| super::is_big4());
        }

        #[bench]
        fn has_two_entries(b: &mut Bencher) {
            b.iter(|| super::has_two_entries());
        }

        #[bench]
        fn contains_art_slash_image_dot_txt(b: &mut Bencher) {
            b.iter(|| super::contains_art_slash_image_dot_txt());
        }

        #[bench]
        fn contains_data_slash_test_dot_ini(b: &mut Bencher) {
            b.iter(|| super::contains_data_slash_test_dot_ini());
        }

        #[bench]
        fn read_entry_art_slash_image_dot_txt(b: &mut Bencher) {
            b.iter(|| super::read_entry_art_slash_image_dot_txt());
        }

        #[bench]
        fn read_entry_data_slash_test_dot_ini(b: &mut Bencher) {
            b.iter(|| super::read_entry_data_slash_test_dot_ini());
        }
    }
}

#[cfg(test)]
mod tests_file {
    use super::{Format, BigArchive};
    const ARCHIVE_PATH: &'static str = concat!(env!("CARGO_MANIFEST_DIR"), "/test.big");

    #[test]
    fn is_big4() {
        let archive = BigArchive::new_from_path(&ARCHIVE_PATH).unwrap();
        assert_eq!(archive.format, Format::Big4);
    }

    #[test]
    fn has_two_entries() {
        let archive = BigArchive::new_from_path(&ARCHIVE_PATH).unwrap();
        assert_eq!(archive.get_all_entry_names().len(), 2);
    }

    #[test]
    fn contains_art_slash_image_dot_txt() {
        let archive = BigArchive::new_from_path(&ARCHIVE_PATH).unwrap();
        assert!(archive.contains("art/image.txt"));
    }

    #[test]
    fn contains_data_slash_test_dot_ini() {
        let archive = BigArchive::new_from_path(&ARCHIVE_PATH).unwrap();
        assert!(archive.contains("data/test.ini"));
    }

    #[test]
    fn read_entry_art_slash_image_dot_txt() {
        let archive = BigArchive::new_from_path(&ARCHIVE_PATH).unwrap();
        let data = archive.read_entry("art/image.txt").unwrap();
        assert_eq!(data, vec![98, 108, 97, 98, 108, 98, 97]);
    }

    #[test]
    fn read_entry_data_slash_test_dot_ini() {
        let archive = BigArchive::new_from_path(&ARCHIVE_PATH).unwrap();
        let data = archive.read_entry("data/test.ini").unwrap();
        assert_eq!(data,
                   vec![84, 104, 105, 115, 32, 105, 115, 32, 97, 32, 115, 105, 109, 112, 108,
                        101, 32, 116, 101, 115, 116, 32, 102, 105, 108, 101]);
    }

    mod benches {
        extern crate test;
        use self::test::Bencher;

        #[bench]
        fn is_big4(b: &mut Bencher) {
            b.iter(|| super::is_big4());
        }

        #[bench]
        fn has_two_entries(b: &mut Bencher) {
            b.iter(|| super::has_two_entries());
        }

        #[bench]
        fn contains_art_slash_image_dot_txt(b: &mut Bencher) {
            b.iter(|| super::contains_art_slash_image_dot_txt());
        }

        #[bench]
        fn contains_data_slash_test_dot_ini(b: &mut Bencher) {
            b.iter(|| super::contains_data_slash_test_dot_ini());
        }

        #[bench]
        fn read_entry_art_slash_image_dot_txt(b: &mut Bencher) {
            b.iter(|| super::read_entry_art_slash_image_dot_txt());
        }

        #[bench]
        fn read_entry_data_slash_test_dot_ini(b: &mut Bencher) {
            b.iter(|| super::read_entry_data_slash_test_dot_ini());
        }
    }
}
<commit_msg>Only apply feature(test) in cfg(test) builds<commit_after>#![cfg_attr(test, feature(test))]

extern crate byteorder;
use byteorder::{LittleEndian, ReadBytesExt};

use std::collections::HashMap;
use std::io::{self, Read, Seek, SeekFrom, BufRead, BufReader};
use std::fs::File;
use std::cell::RefCell;

pub mod errors;
use errors::ReadError;

pub struct BigArchive<T: Read + Seek> {
    pub format: Format,
    pub size: u32,

    _buf_reader: RefCell<BufReader<T>>,
    _entries: HashMap<String, BigEntry>,
}

impl BigArchive<File> {
    pub fn new_from_path(path: &str) -> Result<Self, ReadError> {
        let f = try!(File::open(&path));
        let br = BufReader::new(f);
        Ok(try!(BigArchive::new(br)))
    }
}

impl<T: Read + Seek> BigArchive<T> {
    pub fn new(mut data: BufReader<T>) -> Result<Self, ReadError> {
        let format = read_format(&mut data).expect("Failed to read format");

        if let Format::Unknown(bytes) = format {
            return Err(ReadError::UnknownArchiveFormat(bytes));
        }

        let size = try!(data.read_u32::<LittleEndian>());
        let size = invert_endianness(size);

        let num_entries = try!(data.read_u32::<LittleEndian>());
        let num_entries = invert_endianness(num_entries);

        // Offset to the first entry, I think.
        let _ = data.read_u32::<LittleEndian>();

        let mut entries = HashMap::new();

        for i in 0..num_entries {
            let offset = try!(data.read_u32::<LittleEndian>());
            let offset = invert_endianness(offset);

            let size = try!(data.read_u32::<LittleEndian>());
            let size = invert_endianness(size);

            let mut buf = Vec::new();
            data.read_until(b'\0', &mut buf)
                .expect(&format!("Failed to read name for entry {}", i + 1));

            // Remove the trailing \0
            let name = String::from_utf8_lossy(&buf[..buf.len() - 1]);

            let entry = BigEntry {
                offset: offset,
                size: size,
                name: name.to_string(),
            };

            entries.insert(entry.name.clone(), entry);
        }

        Ok(BigArchive {
            format: format,
            size: size,
            _buf_reader: RefCell::new(data),
            _entries: entries,
        })
    }

    /// TODO: Don't return owned data, instead give the caller back a slice
    pub fn read_entry(&self, entry_name: &str) -> Option<Vec<u8>> {
        if let Some(entry) = self._entries.get(entry_name) {
            let br = &mut self._buf_reader.borrow_mut();

            if br.seek(SeekFrom::Start((*entry).offset as u64)).is_err() {
                return None;
            }

            let mut buf = vec![0; entry.size as usize];
            if br.read_exact(&mut buf).is_err() {
                return None;
            }

            Some(buf)
        } else {
            None
        }
    }

    pub fn contains(&self, entry_name: &str) -> bool {
        self._entries.contains_key(entry_name)
    }

    pub fn get_entry(&self, entry_name: &str) -> Option<&BigEntry> {
        self._entries.get(entry_name)
    }

    pub fn get_entry_mut(&mut self, entry_name: &str) -> Option<&mut BigEntry> {
        self._entries.get_mut(entry_name)
    }

    pub fn get_all_entry_names(&self) -> std::collections::hash_map::Keys<String, BigEntry> {
        self._entries.keys()
    }
}

#[derive(Debug)]
pub struct BigEntry {
    pub offset: u32,
    pub size: u32,
    pub name: String,
}

#[derive(Debug, PartialEq)]
pub enum Format {
    Unknown(Vec<u8>),
    Big4,
    BigF,
}

impl<'a> From<&'a mut BufRead> for Format {
    fn from(data: &'a mut BufRead) -> Self {
        let mut buf = [0; 4];
        let _ = data.read_exact(&mut buf);
        match &buf {
            b"BIG4" => Format::Big4,
            b"BIGF" => Format::BigF,
            _ => Format::Unknown(Vec::from(&buf[..])),
        }
    }
}

fn read_format(data: &mut BufRead) -> Result<Format, io::Error> {
    Ok(Format::from(data))
}

fn invert_endianness(v: u32) -> u32 {
    (v << 24) | (v << 8 & 0xff0000) | (v >> 8 & 0xff00) | (v >> 24)
}

#[cfg(test)]
mod tests_bytes {
    const TEST_BYTES: &'static [u8] = include_bytes!("../test.big");
    use std::io::{BufReader, Cursor};
    use super::{Format, BigArchive};

    #[test]
    fn is_big4() {
        let c = Cursor::new(TEST_BYTES);
        let br = BufReader::new(c);
        let archive = BigArchive::new(br).unwrap();
        assert_eq!(archive.format, Format::Big4);
    }

    #[test]
    fn has_two_entries() {
        let c = Cursor::new(TEST_BYTES);
        let br = BufReader::new(c);
        let archive = BigArchive::new(br).unwrap();
        assert_eq!(archive.get_all_entry_names().len(), 2);
    }

    #[test]
    fn contains_art_slash_image_dot_txt() {
        let c = Cursor::new(TEST_BYTES);
        let br = BufReader::new(c);
        let archive = BigArchive::new(br).unwrap();
        assert!(archive.contains("art/image.txt"));
    }

    #[test]
    fn contains_data_slash_test_dot_ini() {
        let c = Cursor::new(TEST_BYTES);
        let br = BufReader::new(c);
        let archive = BigArchive::new(br).unwrap();
        assert!(archive.contains("data/test.ini"));
    }

    #[test]
    fn read_entry_art_slash_image_dot_txt() {
        let c = Cursor::new(TEST_BYTES);
        let br = BufReader::new(c);
        let archive = BigArchive::new(br).unwrap();
        let data = archive.read_entry("art/image.txt").unwrap();
        assert_eq!(data, vec![98, 108, 97, 98, 108, 98, 97]);
    }

    #[test]
    fn read_entry_data_slash_test_dot_ini() {
        let c = Cursor::new(TEST_BYTES);
        let br = BufReader::new(c);
        let archive = BigArchive::new(br).unwrap();
        let data = archive.read_entry("data/test.ini").unwrap();
        assert_eq!(data,
                   vec![84, 104, 105, 115, 32, 105, 115, 32, 97, 32, 115, 105, 109, 112, 108,
                        101, 32, 116, 101, 115, 116, 32, 102, 105, 108, 101]);
    }

    mod benches {
        extern crate test;
        use self::test::Bencher;

        #[bench]
        fn is_big4(b: &mut Bencher) {
            b.iter(|| super::is_big4());
        }

        #[bench]
        fn has_two_entries(b: &mut Bencher) {
            b.iter(|| super::has_two_entries());
        }

        #[bench]
        fn contains_art_slash_image_dot_txt(b: &mut Bencher) {
            b.iter(|| super::contains_art_slash_image_dot_txt());
        }

        #[bench]
        fn contains_data_slash_test_dot_ini(b: &mut Bencher) {
            b.iter(|| super::contains_data_slash_test_dot_ini());
        }

        #[bench]
        fn read_entry_art_slash_image_dot_txt(b: &mut Bencher) {
            b.iter(|| super::read_entry_art_slash_image_dot_txt());
        }

        #[bench]
        fn read_entry_data_slash_test_dot_ini(b: &mut Bencher) {
            b.iter(|| super::read_entry_data_slash_test_dot_ini());
        }
    }
}

#[cfg(test)]
mod tests_file {
    use super::{Format, BigArchive};
    const ARCHIVE_PATH: &'static str = concat!(env!("CARGO_MANIFEST_DIR"), "/test.big");

    #[test]
    fn is_big4() {
        let archive = BigArchive::new_from_path(&ARCHIVE_PATH).unwrap();
        assert_eq!(archive.format, Format::Big4);
    }

    #[test]
    fn has_two_entries() {
        let archive = BigArchive::new_from_path(&ARCHIVE_PATH).unwrap();
        assert_eq!(archive.get_all_entry_names().len(), 2);
    }

    #[test]
    fn contains_art_slash_image_dot_txt() {
        let archive = BigArchive::new_from_path(&ARCHIVE_PATH).unwrap();
        assert!(archive.contains("art/image.txt"));
    }

    #[test]
    fn contains_data_slash_test_dot_ini() {
        let archive = BigArchive::new_from_path(&ARCHIVE_PATH).unwrap();
        assert!(archive.contains("data/test.ini"));
    }

    #[test]
    fn read_entry_art_slash_image_dot_txt() {
        let archive = BigArchive::new_from_path(&ARCHIVE_PATH).unwrap();
        let data = archive.read_entry("art/image.txt").unwrap();
        assert_eq!(data, vec![98, 108, 97, 98, 108, 98, 97]);
    }

    #[test]
    fn read_entry_data_slash_test_dot_ini() {
        let archive = BigArchive::new_from_path(&ARCHIVE_PATH).unwrap();
        let data = archive.read_entry("data/test.ini").unwrap();
        assert_eq!(data,
                   vec![84, 104, 105, 115, 32, 105, 115, 32, 97, 32, 115, 105, 109, 112, 108,
                        101, 32, 116, 101, 115, 116, 32, 102, 105, 108, 101]);
    }

    mod benches {
        extern crate test;
        use self::test::Bencher;

        #[bench]
        fn is_big4(b: &mut Bencher) {
            b.iter(|| super::is_big4());
        }

        #[bench]
        fn has_two_entries(b: &mut Bencher) {
            b.iter(|| super::has_two_entries());
        }

        #[bench]
        fn contains_art_slash_image_dot_txt(b: &mut Bencher) {
            b.iter(|| super::contains_art_slash_image_dot_txt());
        }

        #[bench]
        fn contains_data_slash_test_dot_ini(b: &mut Bencher) {
            b.iter(|| super::contains_data_slash_test_dot_ini());
        }

        #[bench]
        fn read_entry_art_slash_image_dot_txt(b: &mut Bencher) {
            b.iter(|| super::read_entry_art_slash_image_dot_txt());
        }

        #[bench]
        fn read_entry_data_slash_test_dot_ini(b: &mut Bencher) {
            b.iter(|| super::read_entry_data_slash_test_dot_ini());
        }
    }
}
<|endoftext|>


<commit_before>extern crate time;

use std::thread;

use std::ops::{Div, Range};

extern crate num;
use num::{One};

#[inline]
pub fn ns_to_s(ns: u64) -> f64 {
    (ns as f64) / 1_000_000_000.
}

/// seconds to nanoseconds
#[inline]
pub fn s_to_ns(s: f64) -> f64 {
    s * 1_000_000_000.
}

#[inline]
pub fn ns_to_ms(ns: u64) -> f64 {
    (ns as f64) / 1_000_000.
}

#[inline]
pub fn ms_to_ns(ns: f64) -> f64 {
    ns * 1_000_000.
}

#[inline]
pub fn fps_to_ns_per_frame(fps: usize) -> u64 {
    (s_to_ns(1.0) / (fps as f64)).round() as u64
}

#[inline]
pub fn current_time_ns() -> u64 {
    time::precise_time_ns()
}

pub fn sleep_for_constant_rate(fps: usize, ns_before: u64) {
    let ns_per_frame = fps_to_ns_per_frame(fps);
    let ns_after: u64 = time::precise_time_ns();
    let ns_elapsed = ns_after - ns_before;
    if ns_elapsed < ns_per_frame {
        let ns_left_to_sleep = ns_per_frame - ns_elapsed;
        thread::sleep_ms(ns_to_ms(ns_left_to_sleep) as u32);
    }
}

/// frequency range that can be modeled when taking the short
/// time fourier transform of a signal with `sample_rate` with
/// a sliding window of `window_sizew`.
/// equivalent to `rayleigh(sample_rate, window_size)..nyquist(sample_rate)`
/// increase the window size to increase the lower frequency
/// increase the sample rate to increase the upper frequency
fn hertz_range<T>(sample_rate: T, window_size: T) -> Range<T>
    where T: Div<T, Output=T> + From<u16> + Clone
{
    rayleigh(sample_rate.clone(), window_size)..nyquist(sample_rate)
}

#[test]
fn test_hertz_range() {
    assert_eq!(
        hertz_range(44100., 1024. * 8.),
        (5.38330078125)..22050.);
    assert_eq!(
        hertz_range(44100., 1024. * 4.),
        (10.7666015625)..22050.);
    assert_eq!(
        hertz_range(44100., 1024.),
        (43.06640625)..22050.);
    assert_eq!(
        hertz_range(44100., 512.),
        (86.1328125)..22050.);
}

/// maximum frequency in hertz that can be modeled with a given rate
fn nyquist<T>(sample_rate: T) -> T
    where T: Div<T, Output=T> + From<u16>
{
    sample_rate / T::from(2 as u16)
}

#[test]
fn test_nyquist() {
    assert_eq!(nyquist(44100.), 22050.);
}

/// minimum frequency in hertz
fn rayleigh<T>(sample_rate: T, window_size: T) -> T
    where T: Div<T, Output=T> + From<u16>
{
    T::from(1 as u16) / seconds_per_window(sample_rate, window_size)
}

#[test]
fn test_rayleigh() {
    assert_eq!(rayleigh(44100., 1024.), 43.06640625);
}

/// window duration in seconds
/// sample_rate in hertz
fn seconds_per_window<T>(samples_per_second: T, samples_per_window: T) -> T
    where T: Div<T, Output=T>
{
    samples_per_window / samples_per_second
}

#[test]
fn test_seconds_per_window() {
    // 11ms time resolution
    assert_eq!(seconds_per_window(44100., 512.), 0.011609977324263039);
    assert_eq!(seconds_per_window(44100., 1024.), 0.023219954648526078);
}
<commit_msg>make functions public<commit_after>extern crate time;

use std::thread;

use std::ops::{Div, Range};

extern crate num;
use num::{One};

#[inline]
pub fn ns_to_s(ns: u64) -> f64 {
    (ns as f64) / 1_000_000_000.
}

/// seconds to nanoseconds
#[inline]
pub fn s_to_ns(s: f64) -> f64 {
    s * 1_000_000_000.
}

#[inline]
pub fn ns_to_ms(ns: u64) -> f64 {
    (ns as f64) / 1_000_000.
}

#[inline]
pub fn ms_to_ns(ns: f64) -> f64 {
    ns * 1_000_000.
}

#[inline]
pub fn fps_to_ns_per_frame(fps: usize) -> u64 {
    (s_to_ns(1.0) / (fps as f64)).round() as u64
}

#[inline]
pub fn current_time_ns() -> u64 {
    time::precise_time_ns()
}

pub fn sleep_for_constant_rate(fps: usize, ns_before: u64) {
    let ns_per_frame = fps_to_ns_per_frame(fps);
    let ns_after: u64 = time::precise_time_ns();
    let ns_elapsed = ns_after - ns_before;
    if ns_elapsed < ns_per_frame {
        let ns_left_to_sleep = ns_per_frame - ns_elapsed;
        thread::sleep_ms(ns_to_ms(ns_left_to_sleep) as u32);
    }
}

/// frequency range that can be modeled when taking the short
/// time fourier transform of a signal with `sample_rate` with
/// a sliding window of `window_sizew`.
/// equivalent to `rayleigh(sample_rate, window_size)..nyquist(sample_rate)`
/// increase the window size to increase the lower frequency
/// increase the sample rate to increase the upper frequency
pub fn hertz_range<T>(sample_rate: T, window_size: T) -> Range<T>
    where T: Div<T, Output=T> + From<u16> + Clone
{
    rayleigh(sample_rate.clone(), window_size)..nyquist(sample_rate)
}

#[test]
fn test_hertz_range() {
    assert_eq!(
        hertz_range(44100., 1024. * 8.),
        (5.38330078125)..22050.);
    assert_eq!(
        hertz_range(44100., 1024. * 4.),
        (10.7666015625)..22050.);
    assert_eq!(
        hertz_range(44100., 1024.),
        (43.06640625)..22050.);
    assert_eq!(
        hertz_range(44100., 512.),
        (86.1328125)..22050.);
}

/// maximum frequency in hertz that can be modeled with a given rate
pub fn nyquist<T>(sample_rate: T) -> T
    where T: Div<T, Output=T> + From<u16>
{
    sample_rate / T::from(2 as u16)
}

#[test]
fn test_nyquist() {
    assert_eq!(nyquist(44100.), 22050.);
}

/// minimum frequency in hertz
pub fn rayleigh<T>(sample_rate: T, window_size: T) -> T
    where T: Div<T, Output=T> + From<u16>
{
    T::from(1 as u16) / seconds_per_window(sample_rate, window_size)
}

#[test]
fn test_rayleigh() {
    assert_eq!(rayleigh(44100., 1024.), 43.06640625);
}

/// window duration in seconds
/// sample_rate in hertz
fn seconds_per_window<T>(samples_per_second: T, samples_per_window: T) -> T
    where T: Div<T, Output=T>
{
    samples_per_window / samples_per_second
}

#[test]
fn test_seconds_per_window() {
    // 11ms time resolution
    assert_eq!(seconds_per_window(44100., 512.), 0.011609977324263039);
    assert_eq!(seconds_per_window(44100., 1024.), 0.023219954648526078);
}
<|endoftext|>


<commit_before>// Copyright 2015 Jakob Lautrup Nysom

//! A simple string tokenizer, and a tokenizer of sentences based on it.
//! The tokenizer ignores all the given separator chars, and returns the
//! characters between as string slice
//!
//! # Examples
//!
//! This is what to expect when parsing a string (or input from a reader)
//!
//! ```
//! let separators = vec![' ', '\n', '\t', '\r'];
//! let source: &str = "    Hello world \n  How do you do\t-Finely I hope";
//!
//! let mut tokenizer = token::Tokenizer::new(source.as_bytes(), separators);
//! assert_eq!(Some("Hello"),  tokenizer.next().unwrap());
//! assert_eq!(Some("world"),  tokenizer.next().unwrap());
//! assert_eq!(Some("How"),     tokenizer.next().unwrap());
//! assert_eq!(Some("do"),      tokenizer.next().unwrap());
//! assert_eq!(Some("you"),     tokenizer.next().unwrap());
//! assert_eq!(Some("do"),      tokenizer.next().unwrap());
//! assert_eq!(Some("-Finely"), tokenizer.next().unwrap());
//! assert_eq!(Some("I"),       tokenizer.next().unwrap());
//! assert_eq!(Some("hope"),    tokenizer.next().unwrap());
//! assert_eq!(None,            tokenizer.next().unwrap());
//! ```

#![feature(io)]

use std::vec::Vec;
use std::iter::Iterator;
use std::io;
use std::io::Read;

/// A tokenizer returning string slices from a reader
pub struct Tokenizer<R: Read> {
    separators: Vec<char>,
    chars: io::Chars<R>,
    current: String,
}

impl <R> Tokenizer<R> where R: Read {
    /// Creates a new tokenizer from a reader and a set of separating characters
    ///
    /// ```
    /// let seps = vec![' ', '\n', '\t'];
    /// let source: &str = "   Hello world\nHow do you do\t-Finely I hope";
    ///
    /// let mut tokenizer = token::Tokenizer::new(source.as_bytes(), seps);
    /// ```
    ///
    pub fn new(reader: R, separators: Vec<char>) -> Tokenizer<R> {
        Tokenizer {
            chars: reader.chars(),
            separators: separators,
            current: String::new(),
        }
    }

    /// Returns a string slice of the next non-empty sequence that terminates
    /// in one of the specified separator strings
    pub fn next(&mut self) -> Result<Option<&str>, io::CharsError> {
        self.current.clear();
        for res in &mut self.chars {
            let c = try!(res);
            // Is `c` a separator?
            if self.separators.iter().any(|t| *t == c) {
                if !&self.current.is_empty() {
                    return Ok(Some(&self.current));
                }
            } else {
                // Just add the char
                self.current.push(c);
            }
        }
        // Handle leftover chars
        if !self.current.is_empty() {
            Ok(Some(&self.current))
        } else {
            Ok(None) // No more chars left
        }
    }
}

/// A structure for iteratively splitting stringy things into sentences
pub struct SentenceSplitter<'a, R: Read> {
    tokenizer: Tokenizer<R>,
    terminators: Vec<&'a str>,
    current: String,
    quotes: Vec<&'a str>,
}

impl <'a, R: Read> SentenceSplitter<'a, R> {

    /// Creates a new sentence-splitting iterator
    ///
    /// ```
    /// let separators  = vec![' ', '\n', '\t', '\r'];
    /// let terminators = vec![".", "!", "?"];
    /// let quotes = vec![]; // For when whole lines are quoted
    ///
    /// let text = "I walked down the road.\n\"What did he say\", she asked me.\n\"Nothing\", I replied, and continued walking...\nit wasn't any of my business.\nOr was it?";
    ///
    /// let mut tokenizer = token::Tokenizer::new(text.as_bytes(), separators);
    /// let mut splitter = token::SentenceSplitter::new(
    ///     tokenizer, terminators, quotes
    /// );
    ///
    /// assert_eq!(Some("I walked down the road."), splitter.next().unwrap());
    /// assert_eq!(Some("\"What did he say\", she asked me."),
    ///            splitter.next().unwrap());
    /// assert_eq!(Some("\"Nothing\", I replied, and continued walking... \
    ///                  it wasn't any of my business."),
    ///            splitter.next().unwrap());
    /// assert_eq!(Some("Or was it?"), splitter.next().unwrap());
    /// assert_eq!(None, splitter.next().unwrap());
    /// ```
    pub fn new(source: Tokenizer<R>, terminators: Vec<&'a str>,
               quotes: Vec<&'a str>) -> SentenceSplitter<'a, R>
    {
        SentenceSplitter{
            tokenizer: source,
            current: String::new(),
            terminators: terminators,
            quotes: quotes,
        }
    }

    /// Returns the next sentence
    pub fn next(&mut self) -> Result<Option<&str>, io::CharsError> {
        self.current.clear();
        let mut quote = "";
        loop {
            let s = match try!(self.tokenizer.next()) {
                Some(s) => s,
                None => {
                    if self.current.len() != 0 {
                        return Ok(Some(&self.current));
                    } else {
                        return Ok(None);
                    }
                }
            };
            self.current.push_str(s);

            // Inside a quote
            if !quote.is_empty() {
                if s.ends_with(quote) {
                    return Ok(Some(&self.current))
                } else {
                    self.current.push_str(" ");
                    continue;
                }
            }

            // Not inside a quote
            // Check to see if a quote is starting
            match self.quotes.iter().find(|q| s.starts_with(*q)) {
                Some(q) => {
                    if s.ends_with(q) { // It can end again
                        return Ok(Some(&self.current));
                    }
                    quote = q;
                    self.current.push_str(" ");
                    continue;
                }
                None => {}
            }

            // Check whether the token is ending normally
            // It ends in a terminating character
            if s.ends_with("..") {
                // Continue thought trails
                self.current.push_str(" ");
                continue;
            }
            if self.terminators.iter().any(|t| s.ends_with(*t)) {
                return Ok(Some(&self.current));
            }
            // SPAAAAAAAAACE
            self.current.push_str(" ");
        }
    }
}
<commit_msg>Changed len comparison to is_empty<commit_after>// Copyright 2015 Jakob Lautrup Nysom

//! A simple string tokenizer, and a tokenizer of sentences based on it.
//! The tokenizer ignores all the given separator chars, and returns the
//! characters between as string slice
//!
//! # Examples
//!
//! This is what to expect when parsing a string (or input from a reader)
//!
//! ```
//! let separators = vec![' ', '\n', '\t', '\r'];
//! let source: &str = "    Hello world \n  How do you do\t-Finely I hope";
//!
//! let mut tokenizer = token::Tokenizer::new(source.as_bytes(), separators);
//! assert_eq!(Some("Hello"),  tokenizer.next().unwrap());
//! assert_eq!(Some("world"),  tokenizer.next().unwrap());
//! assert_eq!(Some("How"),     tokenizer.next().unwrap());
//! assert_eq!(Some("do"),      tokenizer.next().unwrap());
//! assert_eq!(Some("you"),     tokenizer.next().unwrap());
//! assert_eq!(Some("do"),      tokenizer.next().unwrap());
//! assert_eq!(Some("-Finely"), tokenizer.next().unwrap());
//! assert_eq!(Some("I"),       tokenizer.next().unwrap());
//! assert_eq!(Some("hope"),    tokenizer.next().unwrap());
//! assert_eq!(None,            tokenizer.next().unwrap());
//! ```

#![feature(io)]

use std::vec::Vec;
use std::iter::Iterator;
use std::io;
use std::io::Read;

/// A tokenizer returning string slices from a reader
pub struct Tokenizer<R: Read> {
    separators: Vec<char>,
    chars: io::Chars<R>,
    current: String,
}

impl <R> Tokenizer<R> where R: Read {
    /// Creates a new tokenizer from a reader and a set of separating characters
    ///
    /// ```
    /// let seps = vec![' ', '\n', '\t'];
    /// let source: &str = "   Hello world\nHow do you do\t-Finely I hope";
    ///
    /// let mut tokenizer = token::Tokenizer::new(source.as_bytes(), seps);
    /// ```
    ///
    pub fn new(reader: R, separators: Vec<char>) -> Tokenizer<R> {
        Tokenizer {
            chars: reader.chars(),
            separators: separators,
            current: String::new(),
        }
    }

    /// Returns a string slice of the next non-empty sequence that terminates
    /// in one of the specified separator strings
    pub fn next(&mut self) -> Result<Option<&str>, io::CharsError> {
        self.current.clear();
        for res in &mut self.chars {
            let c = try!(res);
            // Is `c` a separator?
            if self.separators.iter().any(|t| *t == c) {
                if !&self.current.is_empty() {
                    return Ok(Some(&self.current));
                }
            } else {
                // Just add the char
                self.current.push(c);
            }
        }
        // Handle leftover chars
        if !self.current.is_empty() {
            Ok(Some(&self.current))
        } else {
            Ok(None) // No more chars left
        }
    }
}

/// A structure for iteratively splitting stringy things into sentences
pub struct SentenceSplitter<'a, R: Read> {
    tokenizer: Tokenizer<R>,
    terminators: Vec<&'a str>,
    current: String,
    quotes: Vec<&'a str>,
}

impl <'a, R: Read> SentenceSplitter<'a, R> {

    /// Creates a new sentence-splitting iterator
    ///
    /// ```
    /// let separators  = vec![' ', '\n', '\t', '\r'];
    /// let terminators = vec![".", "!", "?"];
    /// let quotes = vec![]; // For when whole lines are quoted
    ///
    /// let text = "I walked down the road.\n\"What did he say\", she asked me.\n\"Nothing\", I replied, and continued walking...\nit wasn't any of my business.\nOr was it?";
    ///
    /// let mut tokenizer = token::Tokenizer::new(text.as_bytes(), separators);
    /// let mut splitter = token::SentenceSplitter::new(
    ///     tokenizer, terminators, quotes
    /// );
    ///
    /// assert_eq!(Some("I walked down the road."), splitter.next().unwrap());
    /// assert_eq!(Some("\"What did he say\", she asked me."),
    ///            splitter.next().unwrap());
    /// assert_eq!(Some("\"Nothing\", I replied, and continued walking... \
    ///                  it wasn't any of my business."),
    ///            splitter.next().unwrap());
    /// assert_eq!(Some("Or was it?"), splitter.next().unwrap());
    /// assert_eq!(None, splitter.next().unwrap());
    /// ```
    pub fn new(source: Tokenizer<R>, terminators: Vec<&'a str>,
               quotes: Vec<&'a str>) -> SentenceSplitter<'a, R>
    {
        SentenceSplitter{
            tokenizer: source,
            current: String::new(),
            terminators: terminators,
            quotes: quotes,
        }
    }

    /// Returns the next sentence
    pub fn next(&mut self) -> Result<Option<&str>, io::CharsError> {
        self.current.clear();
        let mut quote = "";
        loop {
            let s = match try!(self.tokenizer.next()) {
                Some(s) => s,
                None => {
                    if !self.current.is_empty() {
                        return Ok(Some(&self.current));
                    } else {
                        return Ok(None);
                    }
                }
            };
            self.current.push_str(s);

            // Inside a quote
            if !quote.is_empty() {
                if s.ends_with(quote) {
                    return Ok(Some(&self.current))
                } else {
                    self.current.push_str(" ");
                    continue;
                }
            }

            // Not inside a quote
            // Check to see if a quote is starting
            match self.quotes.iter().find(|q| s.starts_with(*q)) {
                Some(q) => {
                    if s.ends_with(q) { // It can end again
                        return Ok(Some(&self.current));
                    }
                    quote = q;
                    self.current.push_str(" ");
                    continue;
                }
                None => {}
            }

            // Check whether the token is ending normally
            // It ends in a terminating character
            if s.ends_with("..") {
                // Continue thought trails
                self.current.push_str(" ");
                continue;
            }
            if self.terminators.iter().any(|t| s.ends_with(*t)) {
                return Ok(Some(&self.current));
            }
            // SPAAAAAAAAACE
            self.current.push_str(" ");
        }
    }
}
<|endoftext|>


<commit_before>// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![feature(core)]
#![feature(simd)]
#![feature(step_by)]
#![feature(convert)]
#![cfg_attr(test, feature(test))]

extern crate rand;
extern crate rustc_serialize as serialize;
extern crate time;
#[cfg(test)] extern crate test;
extern crate libc;

pub mod aead;
pub mod aes;
pub mod aes_gcm;
pub mod aessafe;
pub mod bcrypt;
pub mod bcrypt_pbkdf;
pub mod blake2b;
pub mod blockmodes;
pub mod blowfish;
pub mod buffer;
pub mod chacha20;
pub mod chacha20poly1305;
mod cryptoutil;
pub mod curve25519;
pub mod digest;
pub mod ed25519;
pub mod fortuna;
pub mod ghash;
pub mod hc128;
pub mod hmac;
pub mod hkdf;
pub mod mac;
pub mod md5;
pub mod pbkdf2;
pub mod poly1305;
pub mod rc4;
pub mod ripemd160;
pub mod salsa20;
pub mod scrypt;
pub mod sha1;
pub mod sha2;
mod simd;
pub mod sosemanuk;
pub mod symmetriccipher;
pub mod util;
pub mod whirlpool;

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub mod aesni;
<commit_msg>Remove #![feature(core)] since its no longer needed<commit_after>// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![feature(simd)]
#![feature(step_by)]
#![feature(convert)]
#![cfg_attr(test, feature(test))]

extern crate rand;
extern crate rustc_serialize as serialize;
extern crate time;
#[cfg(test)] extern crate test;
extern crate libc;

pub mod aead;
pub mod aes;
pub mod aes_gcm;
pub mod aessafe;
pub mod bcrypt;
pub mod bcrypt_pbkdf;
pub mod blake2b;
pub mod blockmodes;
pub mod blowfish;
pub mod buffer;
pub mod chacha20;
pub mod chacha20poly1305;
mod cryptoutil;
pub mod curve25519;
pub mod digest;
pub mod ed25519;
pub mod fortuna;
pub mod ghash;
pub mod hc128;
pub mod hmac;
pub mod hkdf;
pub mod mac;
pub mod md5;
pub mod pbkdf2;
pub mod poly1305;
pub mod rc4;
pub mod ripemd160;
pub mod salsa20;
pub mod scrypt;
pub mod sha1;
pub mod sha2;
mod simd;
pub mod sosemanuk;
pub mod symmetriccipher;
pub mod util;
pub mod whirlpool;

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub mod aesni;
<|endoftext|>


<commit_before>extern crate graphics;

use graphics::{ Context, Graphics };

pub struct Timeline {
    pub frames: u32,
    pub current_frame: u32,
    pub bounds: [u32; 4],
}

impl Timeline {
    pub fn new_frames_bounds(frames: u32, bounds: [u32; 4]) -> Timeline {
        Timeline {
            frames: frames,
            current_frame: 0,
            bounds: bounds,
        }
    }

    pub fn draw_timeline<G: Graphics>(&self, c: &Context, g: &mut G) {
        let left_to_frame: f64 = 5.0;
        let top_to_frame: f64 = 10.0;
        let frame_width: f64 = 10.0;
        let frame_height: f64 = 10.0;
        let frame_offset_x: f64 = 5.0;

        // Draw bounds to see where the control is.
        {
            use graphics::Rectangle;

            let bounds = [
                    self.bounds[0] as f64,
                    self.bounds[1] as f64,
                    self.bounds[2] as f64,
                    self.bounds[3] as f64
                ];
            Rectangle::new_border([0.0, 0.0, 1.0, 1.0], 0.5)
                .draw(bounds, &c.draw_state, c.transform, g);
        }

        // Draw a sequence of squares for each frame.
        {
            use graphics::Rectangle;

            let rect = Rectangle::new_border([0.0, 0.0, 1.0, 1.0], 0.5);
            for i in 0..self.frames {
                let bounds = [
                    self.bounds[0] as f64 + left_to_frame +
                        i as f64 * (frame_width + frame_offset_x),
                    self.bounds[1] as f64 + top_to_frame,
                    frame_width,
                    frame_height
                ];
                rect.draw(bounds, &c.draw_state, c.transform, g);
            }
        }
    }

    pub fn draw_drag<G: Graphics>(&self, c: &Context, g: &mut G) {

    }
}
<commit_msg>Added slide_offset<commit_after>extern crate graphics;

use graphics::{ Context, Graphics };

pub struct Timeline {
    pub frames: u32,
    pub current_frame: u32,
    pub bounds: [u32; 4],
}

impl Timeline {
    pub fn new_frames_bounds(frames: u32, bounds: [u32; 4]) -> Timeline {
        Timeline {
            frames: frames,
            current_frame: 0,
            bounds: bounds,
        }
    }

    pub fn draw_timeline<G: Graphics>(&self, c: &Context, g: &mut G) {
        let left_to_frame: f64 = 5.0;
        let top_to_frame: f64 = 15.0;
        let frame_width: f64 = 10.0;
        let frame_height: f64 = 10.0;
        let frame_offset_x: f64 = 5.0;
        let slide_offset: f64 = 0.0;

        // Draw bounds to see where the control is.
        {
            use graphics::Rectangle;

            let bounds = [
                    self.bounds[0] as f64,
                    self.bounds[1] as f64,
                    self.bounds[2] as f64,
                    self.bounds[3] as f64
                ];
            Rectangle::new_border([0.0, 0.0, 1.0, 1.0], 0.5)
                .draw(bounds, &c.draw_state, c.transform, g);
        }

        // Draw a sequence of squares for each frame.
        {
            use graphics::Rectangle;

            let rect = Rectangle::new_border([0.0, 0.0, 1.0, 1.0], 0.5);
            for i in 0..self.frames {
                let bounds = [
                    self.bounds[0] as f64 + left_to_frame
                        + i as f64 * (frame_width + frame_offset_x)
                        - slide_offset,
                    self.bounds[1] as f64 + top_to_frame,
                    frame_width,
                    frame_height
                ];
                rect.draw(bounds, &c.draw_state, c.transform, g);
            }
        }
    }

    pub fn draw_drag<G: Graphics>(&self, c: &Context, g: &mut G) {

    }
}
<|endoftext|>


<commit_before>#![crate_type= "lib"]

#![feature(collections, core, libc, env)]

//! A simply library for parsing command line arguments when writing
//! command line and console applications.
//!
//!
//! You can use `clap` to lay out a list of possible valid command line arguments and let `clap` parse the string given by the user at runtime.
//! When using `clap` you define a set of parameters and rules for your arguments and at runtime `clap` will determine their validity.
//! Also, `clap` provides the traditional version and help switches 'for free' by parsing the list of possible valid arguments lazily at runtime.
//! i.e. only when it's been determined that the user wants or needs to see the help and version information.
//!
//! After defining a list of possible valid arguments you get a list of matches that the user supplied at runtime. You can then use this list to
//! determine the functioning of your program.
//!
//! Example:
//!
//! ```rust.example
//! extern crate clap;
//! use clap::{Arg, App};
//!
//! // ...
//!
//! let matches = App::new("MyApp")
//!						.version("1.0")
//!						.author("Kevin K. <kbknapp@gmail.com>")
//!						.about("Does awesome things")
//!						.arg(Arg::new("config")
//!									.short("c")
//!									.long("config")
//!									.help("Sets a custom config file")
//!									.takes_value(true))
//!						.arg(Arg::new("output")
//!									.help("Sets an optional output file")
//!									.index(1)
//!						.arg(Arg::new("debug")
//!									.short("d")
//! 								.multiple(true)
//!									.help("Turn debugging information on"))
//!						.get_matches();
//!
//!	if let Some(o) = matches.value_of("output") {
//!		println!("Value for output: {}", o);
//!	}
//!
//!	if let Some(c) = matches.value_of("config") {
//!		println!("Value for config: {}", c);
//!	}
//!
//! match matches.occurrences_of("debug") {
//! 	0 => println!("Debug mode is off"),
//!		1 => println!("Debug mode is kind of on"),
//!		2 => println!("Debug mode is on"),
//!		3 | _ => println!("Don't be crazy"),
//! }
//!
//! // more porgram logic goes here...
//! ```

pub use argmatches::ArgMatches;
pub use arg::Arg;
pub use app::App;

mod app;
mod argmatches;
mod arg;
mod args;
<commit_msg>Added documentation<commit_after>#![crate_type= "lib"]

#![feature(collections, core, libc, env)]

//! A simply library for parsing command line arguments when writing
//! command line and console applications.
//!
//!
//! You can use `clap` to lay out a list of possible valid command line arguments and let `clap` parse the string given by the user at runtime.
//! When using `clap` you define a set of parameters and rules for your arguments and at runtime `clap` will determine their validity.
//! Also, `clap` provides the traditional version and help switches 'for free' by parsing the list of possible valid arguments lazily at runtime.
//! i.e. only when it's been determined that the user wants or needs to see the help and version information.
//!
//! After defining a list of possible valid arguments you get a list of matches that the user supplied at runtime. You can then use this list to
//! determine the functioning of your program.
//!
//! Example:
//!
//! ```rust.example
//! extern crate clap;
//! use clap::{Arg, App};
//!
//! // ...
//!
//! let matches = App::new("MyApp")
//!						.version("1.0")
//!						.author("Kevin K. <kbknapp@gmail.com>")
//!						.about("Does awesome things")
//!						.arg(Arg::new("config")
//!									.short("c")
//!									.long("config")
//!									.help("Sets a custom config file")
//!									.takes_value(true))
//!						.arg(Arg::new("output")
//!									.help("Sets an optional output file")
//!									.index(1))
//!						.arg(Arg::new("debug")
//!									.short("d")
//! 								.multiple(true)
//!									.help("Turn debugging information on"))
//!						.get_matches();
//!
//!	if let Some(o) = matches.value_of("output") {
//!		println!("Value for output: {}", o);
//!	}
//!
//!	if let Some(c) = matches.value_of("config") {
//!		println!("Value for config: {}", c);
//!	}
//!
//! match matches.occurrences_of("debug") {
//! 	0 => println!("Debug mode is off"),
//!		1 => println!("Debug mode is kind of on"),
//!		2 => println!("Debug mode is on"),
//!		3 | _ => println!("Don't be crazy"),
//! }
//!
//! // more porgram logic goes here...
//! ```
//!
//! If you were to compile the above program and run it with the flag `--help` or `-h` the following output woud be presented
//!
//! ```sh
//! $ myprog --help
//! MyApp 1.0
//! Kevin K. <kbknapp@gmail.com>
//! Does awesome things
//!
//! USAGE: MyApp [FLAGS] [OPTIONS] [POSITIONAL]
//! Where...
//!
//! FLAGS:
//! -d   		Turn debugging information on
//!
//! OPTIONS:
//! -c,--config <config>		Sets a custom config file
//!
//! POSITIONAL ARGUMENTS:
//! output			Sets an optional output file
//! ```

pub use argmatches::ArgMatches;
pub use arg::Arg;
pub use app::App;

mod app;
mod argmatches;
mod arg;
mod args;
<|endoftext|>


<commit_before>#![feature(unsafe_destructor)]
#![feature(globs)]
#![unstable]

extern crate libc;

pub use events::*;

#[cfg(windows)]
use winimpl = win32;
#[cfg(unix)]
use winimpl = x11;

#[cfg(windows)]
mod win32;
#[cfg(unix)]
mod x11;

#[allow(dead_code)]
//mod egl;

mod events;

/// Identifier for a monitor.
pub struct MonitorID(winimpl::MonitorID);

/// Object that allows you to build windows.
pub struct WindowBuilder {
    dimensions: (uint, uint),
    title: String,
    monitor: Option<winimpl::MonitorID>,
    gl_version: Option<(uint, uint)>,
}

impl WindowBuilder {
    /// Initializes a new `WindowBuilder` with default values.
    pub fn new() -> WindowBuilder {
        WindowBuilder {
            dimensions: (1024, 768),
            title: String::new(),
            monitor: None,
            gl_version: None,
        }
    }

    /// Requests the window to be of specific dimensions.
    ///
    /// Width and height are in pixels.
    pub fn with_dimensions(mut self, width: uint, height: uint) -> WindowBuilder {
        self.dimensions = (width, height);
        self
    }

    /// Requests a specific title for the window.
    pub fn with_title(mut self, title: String) -> WindowBuilder {
        self.title = title;
        self
    }

    /// Requests fullscreen mode.
    pub fn with_fullscreen(mut self, monitor: MonitorID) -> WindowBuilder {
        let MonitorID(monitor) = monitor;
        self.monitor = Some(monitor);
        self
    }

    /// Requests to use a specific OpenGL version.
    ///
    /// Version is a (major, minor) pair. For example to request OpenGL 3.3
    ///  you would pass `(3, 3)`.
    pub fn with_gl_version(mut self, version: (uint, uint)) -> WindowBuilder {
        self.gl_version = Some(version);
        self
    }

    /// Builds the window.
    ///
    /// Error should be very rare and only occur in case of permission denied, incompatible system,
    ///  out of memory, etc.
    pub fn build(self) -> Result<Window, String> {
        winimpl::Window::new(self).map(|w| Window { window: w })
    }
}

/// Represents an OpenGL context and the Window or environment around it.
///
/// # Example
///
/// ```
/// let window = Window::new().unwrap();
///
/// unsafe { window.make_current() };
///
/// loop {
///     for event in window.poll_events().move_iter() {     // note: this may change in the future
///         match event {
///             // process events here
///             _ => ()
///         }
///     }
///
///     // draw everything here
///
///     window.swap_buffers();
///     std::io::timer::sleep(17);
/// }
/// ```
pub struct Window {
    window: winimpl::Window,
}

impl Window {
    /// Creates a new OpenGL context, and a Window for platforms where this is appropriate.
    ///
    /// This function is equivalent to `WindowBuilder::new().build()`.
    ///
    /// Error should be very rare and only occur in case of permission denied, incompatible system,
    ///  out of memory, etc.
    #[inline]
    pub fn new() -> Result<Window, String> {
        let builder = WindowBuilder::new();
        builder.build()
    }

    /// Returns true if the window has previously been closed by the user.
    #[inline]
    pub fn is_closed(&self) -> bool {
        self.window.is_closed()
    }

    /// Returns true if the window has previously been closed by the user.
    #[inline]
    #[deprecated = "Use is_closed instead"]
    pub fn should_close(&self) -> bool {
        self.is_closed()
    }

    /// Modifies the title of the window.
    ///
    /// This is a no-op if the window has already been closed.
    #[inline]
    pub fn set_title(&self, title: &str) {
        self.window.set_title(title)
    }

    /// Returns the position of the top-left hand corner of the window relative to the
    ///  top-left hand corner of the desktop.
    ///
    /// Note that the top-left hand corner of the desktop is not necessarly the same as
    ///  the screen. If the user uses a desktop with multiple monitors, the top-left hand corner
    ///  of the desktop is the top-left hand corner of the monitor at the top-left of the desktop.
    ///
    /// The coordinates can be negative if the top-left hand corner of the window is outside
    ///  of the visible screen region.
    ///
    /// Returns `None` if the window no longer exists.
    #[inline]
    pub fn get_position(&self) -> Option<(int, int)> {
        self.window.get_position()
    }

    /// Modifies the position of the window.
    ///
    /// See `get_position` for more informations about the coordinates.
    ///
    /// This is a no-op if the window has already been closed.
    #[inline]
    pub fn set_position(&self, x: uint, y: uint) {
        self.window.set_position(x, y)
    }

    /// Returns the size in pixels of the client area of the window.
    ///
    /// The client area is the content of the window, excluding the title bar and borders.
    /// These are the dimensions of the frame buffer, and the dimensions that you should use
    ///  when you call `glViewport`.
    ///
    /// Returns `None` if the window no longer exists.
    #[inline]
    pub fn get_inner_size(&self) -> Option<(uint, uint)> {
        self.window.get_inner_size()
    }

    /// Returns the size in pixels of the window.
    ///
    /// These dimensions include title bar and borders. If you don't want these, you should use
    ///  use `get_inner_size` instead.
    ///
    /// Returns `None` if the window no longer exists.
    #[inline]
    pub fn get_outer_size(&self) -> Option<(uint, uint)> {
        self.window.get_outer_size()
    }

    /// Modifies the inner size of the window.
    ///
    /// See `get_inner_size` for more informations about the values.
    ///
    /// This is a no-op if the window has already been closed.
    #[inline]
    pub fn set_inner_size(&self, x: uint, y: uint) {
        self.window.set_inner_size(x, y)
    }

    /// Returns an iterator to all the events that are currently in the window's events queue.
    ///
    /// Contrary to `wait_events`, this function never blocks.
    #[inline]
    pub fn poll_events(&self) -> PollEventsIterator {
        PollEventsIterator { data: self.window.poll_events() }
    }

    /// Waits for an event, then returns an iterator to all the events that are currently
    ///  in the window's events queue.
    ///
    /// If there are no events in queue when you call the function,
    ///  this function will block until there is one.
    #[inline]
    pub fn wait_events(&self) -> WaitEventsIterator {
        WaitEventsIterator { data: self.window.wait_events() }
    }

    /// Sets the context as the current context.
    #[inline]
    #[experimental]
    pub unsafe fn make_current(&self) {
        self.window.make_current()
    }

    /// Returns the address of an OpenGL function.
    ///
    /// Contrary to `wglGetProcAddress`, all available OpenGL functions return an address.
    #[inline]
    pub fn get_proc_address(&self, addr: &str) -> *const () {
        self.window.get_proc_address(addr)
    }

    /// Swaps the buffers in case of double or triple buffering.
    ///
    /// You should call this function every time you have finished rendering, or the image
    ///  may not be displayed on the screen.
    #[inline]
    pub fn swap_buffers(&self) {
        self.window.swap_buffers()
    }
}

/// An iterator for the `poll_events` function.
// Implementation note: we retreive the list once, then serve each element by one by one.
// This may change in the future.
pub struct PollEventsIterator<'a> {
    data: Vec<Event>,
}

impl<'a> Iterator<Event> for PollEventsIterator<'a> {
    fn next(&mut self) -> Option<Event> {
        self.data.remove(0)
    }
}

/// An iterator for the `wait_events` function.
// Implementation note: we retreive the list once, then serve each element by one by one.
// This may change in the future.
pub struct WaitEventsIterator<'a> {
    data: Vec<Event>,
}

impl<'a> Iterator<Event> for WaitEventsIterator<'a> {
    fn next(&mut self) -> Option<Event> {
        self.data.remove(0)
    }
}

/// An iterator for the list of available monitors.
// Implementation note: we retreive the list once, then serve each element by one by one.
// This may change in the future.
pub struct AvailableMonitorsIter {
    data: Vec<winimpl::MonitorID>,
}

impl Iterator<MonitorID> for AvailableMonitorsIter {
    fn next(&mut self) -> Option<MonitorID> {
        self.data.remove(0).map(|id| MonitorID(id))
    }
}

/// Returns the list of all available monitors.
pub fn get_available_monitors() -> AvailableMonitorsIter {
    let data = winimpl::get_available_monitors();
    AvailableMonitorsIter{ data: data }
}

/// Returns the primary monitor of the system.
pub fn get_primary_monitor() -> MonitorID {
    MonitorID(winimpl::get_primary_monitor())
}

impl MonitorID {
    /// Returns a human-readable name of the monitor.
    pub fn get_name(&self) -> Option<String> {
        let &MonitorID(ref id) = self;
        id.get_name()
    }
}
<commit_msg>Fix docs for Window<commit_after>#![feature(unsafe_destructor)]
#![feature(globs)]
#![unstable]

extern crate libc;

pub use events::*;

#[cfg(windows)]
use winimpl = win32;
#[cfg(unix)]
use winimpl = x11;

#[cfg(windows)]
mod win32;
#[cfg(unix)]
mod x11;

#[allow(dead_code)]
//mod egl;

mod events;

/// Identifier for a monitor.
pub struct MonitorID(winimpl::MonitorID);

/// Object that allows you to build windows.
pub struct WindowBuilder {
    dimensions: (uint, uint),
    title: String,
    monitor: Option<winimpl::MonitorID>,
    gl_version: Option<(uint, uint)>,
}

impl WindowBuilder {
    /// Initializes a new `WindowBuilder` with default values.
    pub fn new() -> WindowBuilder {
        WindowBuilder {
            dimensions: (1024, 768),
            title: String::new(),
            monitor: None,
            gl_version: None,
        }
    }

    /// Requests the window to be of specific dimensions.
    ///
    /// Width and height are in pixels.
    pub fn with_dimensions(mut self, width: uint, height: uint) -> WindowBuilder {
        self.dimensions = (width, height);
        self
    }

    /// Requests a specific title for the window.
    pub fn with_title(mut self, title: String) -> WindowBuilder {
        self.title = title;
        self
    }

    /// Requests fullscreen mode.
    pub fn with_fullscreen(mut self, monitor: MonitorID) -> WindowBuilder {
        let MonitorID(monitor) = monitor;
        self.monitor = Some(monitor);
        self
    }

    /// Requests to use a specific OpenGL version.
    ///
    /// Version is a (major, minor) pair. For example to request OpenGL 3.3
    ///  you would pass `(3, 3)`.
    pub fn with_gl_version(mut self, version: (uint, uint)) -> WindowBuilder {
        self.gl_version = Some(version);
        self
    }

    /// Builds the window.
    ///
    /// Error should be very rare and only occur in case of permission denied, incompatible system,
    ///  out of memory, etc.
    pub fn build(self) -> Result<Window, String> {
        winimpl::Window::new(self).map(|w| Window { window: w })
    }
}

/// Represents an OpenGL context and the Window or environment around it.
///
/// # Example
///
/// ```
/// let window = Window::new().unwrap();
///
/// unsafe { window.make_current() };
///
/// loop {
///     for event in window.poll_events() {
///             // process events here
///             _ => ()
///         }
///     }
///
///     // draw everything here
///
///     window.swap_buffers();
///     std::io::timer::sleep(17);
/// }
/// ```
pub struct Window {
    window: winimpl::Window,
}

impl Window {
    /// Creates a new OpenGL context, and a Window for platforms where this is appropriate.
    ///
    /// This function is equivalent to `WindowBuilder::new().build()`.
    ///
    /// Error should be very rare and only occur in case of permission denied, incompatible system,
    ///  out of memory, etc.
    #[inline]
    pub fn new() -> Result<Window, String> {
        let builder = WindowBuilder::new();
        builder.build()
    }

    /// Returns true if the window has previously been closed by the user.
    #[inline]
    pub fn is_closed(&self) -> bool {
        self.window.is_closed()
    }

    /// Returns true if the window has previously been closed by the user.
    #[inline]
    #[deprecated = "Use is_closed instead"]
    pub fn should_close(&self) -> bool {
        self.is_closed()
    }

    /// Modifies the title of the window.
    ///
    /// This is a no-op if the window has already been closed.
    #[inline]
    pub fn set_title(&self, title: &str) {
        self.window.set_title(title)
    }

    /// Returns the position of the top-left hand corner of the window relative to the
    ///  top-left hand corner of the desktop.
    ///
    /// Note that the top-left hand corner of the desktop is not necessarly the same as
    ///  the screen. If the user uses a desktop with multiple monitors, the top-left hand corner
    ///  of the desktop is the top-left hand corner of the monitor at the top-left of the desktop.
    ///
    /// The coordinates can be negative if the top-left hand corner of the window is outside
    ///  of the visible screen region.
    ///
    /// Returns `None` if the window no longer exists.
    #[inline]
    pub fn get_position(&self) -> Option<(int, int)> {
        self.window.get_position()
    }

    /// Modifies the position of the window.
    ///
    /// See `get_position` for more informations about the coordinates.
    ///
    /// This is a no-op if the window has already been closed.
    #[inline]
    pub fn set_position(&self, x: uint, y: uint) {
        self.window.set_position(x, y)
    }

    /// Returns the size in pixels of the client area of the window.
    ///
    /// The client area is the content of the window, excluding the title bar and borders.
    /// These are the dimensions of the frame buffer, and the dimensions that you should use
    ///  when you call `glViewport`.
    ///
    /// Returns `None` if the window no longer exists.
    #[inline]
    pub fn get_inner_size(&self) -> Option<(uint, uint)> {
        self.window.get_inner_size()
    }

    /// Returns the size in pixels of the window.
    ///
    /// These dimensions include title bar and borders. If you don't want these, you should use
    ///  use `get_inner_size` instead.
    ///
    /// Returns `None` if the window no longer exists.
    #[inline]
    pub fn get_outer_size(&self) -> Option<(uint, uint)> {
        self.window.get_outer_size()
    }

    /// Modifies the inner size of the window.
    ///
    /// See `get_inner_size` for more informations about the values.
    ///
    /// This is a no-op if the window has already been closed.
    #[inline]
    pub fn set_inner_size(&self, x: uint, y: uint) {
        self.window.set_inner_size(x, y)
    }

    /// Returns an iterator to all the events that are currently in the window's events queue.
    ///
    /// Contrary to `wait_events`, this function never blocks.
    #[inline]
    pub fn poll_events(&self) -> PollEventsIterator {
        PollEventsIterator { data: self.window.poll_events() }
    }

    /// Waits for an event, then returns an iterator to all the events that are currently
    ///  in the window's events queue.
    ///
    /// If there are no events in queue when you call the function,
    ///  this function will block until there is one.
    #[inline]
    pub fn wait_events(&self) -> WaitEventsIterator {
        WaitEventsIterator { data: self.window.wait_events() }
    }

    /// Sets the context as the current context.
    #[inline]
    #[experimental]
    pub unsafe fn make_current(&self) {
        self.window.make_current()
    }

    /// Returns the address of an OpenGL function.
    ///
    /// Contrary to `wglGetProcAddress`, all available OpenGL functions return an address.
    #[inline]
    pub fn get_proc_address(&self, addr: &str) -> *const () {
        self.window.get_proc_address(addr)
    }

    /// Swaps the buffers in case of double or triple buffering.
    ///
    /// You should call this function every time you have finished rendering, or the image
    ///  may not be displayed on the screen.
    #[inline]
    pub fn swap_buffers(&self) {
        self.window.swap_buffers()
    }
}

/// An iterator for the `poll_events` function.
// Implementation note: we retreive the list once, then serve each element by one by one.
// This may change in the future.
pub struct PollEventsIterator<'a> {
    data: Vec<Event>,
}

impl<'a> Iterator<Event> for PollEventsIterator<'a> {
    fn next(&mut self) -> Option<Event> {
        self.data.remove(0)
    }
}

/// An iterator for the `wait_events` function.
// Implementation note: we retreive the list once, then serve each element by one by one.
// This may change in the future.
pub struct WaitEventsIterator<'a> {
    data: Vec<Event>,
}

impl<'a> Iterator<Event> for WaitEventsIterator<'a> {
    fn next(&mut self) -> Option<Event> {
        self.data.remove(0)
    }
}

/// An iterator for the list of available monitors.
// Implementation note: we retreive the list once, then serve each element by one by one.
// This may change in the future.
pub struct AvailableMonitorsIter {
    data: Vec<winimpl::MonitorID>,
}

impl Iterator<MonitorID> for AvailableMonitorsIter {
    fn next(&mut self) -> Option<MonitorID> {
        self.data.remove(0).map(|id| MonitorID(id))
    }
}

/// Returns the list of all available monitors.
pub fn get_available_monitors() -> AvailableMonitorsIter {
    let data = winimpl::get_available_monitors();
    AvailableMonitorsIter{ data: data }
}

/// Returns the primary monitor of the system.
pub fn get_primary_monitor() -> MonitorID {
    MonitorID(winimpl::get_primary_monitor())
}

impl MonitorID {
    /// Returns a human-readable name of the monitor.
    pub fn get_name(&self) -> Option<String> {
        let &MonitorID(ref id) = self;
        id.get_name()
    }
}
<|endoftext|>