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

// This test case tests the incremental compilation hash (ICH) implementation
// for `type` definitions.

// The general pattern followed here is: Change one thing between rev1 and rev2
// and make sure that the hash has changed, then change nothing between rev2 and
// rev3 and make sure that the hash has not changed.

// We also test the ICH for `type` definitions exported in metadata. Same as
// above, we want to make sure that the change between rev1 and rev2 also
// results in a change of the ICH for the enum's metadata, and that it stays
// the same between rev2 and rev3.

// must-compile-successfully
// revisions: cfail1 cfail2 cfail3
// compile-flags: -Z query-dep-graph

#![allow(warnings)]
#![feature(rustc_attrs)]
#![crate_type="rlib"]

// Change type (primitive) -----------------------------------------------------
#[cfg(cfail1)]
type ChangePrimitiveType = i32;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type ChangePrimitiveType = i64;

// Change mutability -----------------------------------------------------------
#[cfg(cfail1)]
type ChangeMutability = &'static i32;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type ChangeMutability = &'static mut i32;

// Change mutability -----------------------------------------------------------
#[cfg(cfail1)]
type ChangeLifetime<'a> = (&'static i32, &'a i32);

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type ChangeLifetime<'a> = (&'a i32, &'a i32);

// Change type (struct) -----------------------------------------------------------
struct Struct1;
struct Struct2;

#[cfg(cfail1)]
type ChangeTypeStruct = Struct1;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type ChangeTypeStruct = Struct2;

// Change type (tuple) ---------------------------------------------------------
#[cfg(cfail1)]
type ChangeTypeTuple = (u32, u64);

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type ChangeTypeTuple = (u32, i64);

// Change type (enum) ----------------------------------------------------------
enum Enum1 {
    Var1,
    Var2,
}
enum Enum2 {
    Var1,
    Var2,
}

#[cfg(cfail1)]
type ChangeTypeEnum = Enum1;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type ChangeTypeEnum = Enum2;

// Add tuple field -------------------------------------------------------------
#[cfg(cfail1)]
type AddTupleField = (i32, i64);

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type AddTupleField = (i32, i64, i16);

// Change nested tuple field ---------------------------------------------------
#[cfg(cfail1)]
type ChangeNestedTupleField = (i32, (i64, i16));

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type ChangeNestedTupleField = (i32, (i64, i8));

// Add type param --------------------------------------------------------------
#[cfg(cfail1)]
type AddTypeParam<T1> = (T1, T1);

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type AddTypeParam<T1, T2> = (T1, T2);

// Add type param bound --------------------------------------------------------
#[cfg(cfail1)]
type AddTypeParamBound<T1> = (T1, u32);

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type AddTypeParamBound<T1: Clone> = (T1, u32);

// Add type param bound in where clause ----------------------------------------
#[cfg(cfail1)]
type AddTypeParamBoundWhereClause<T1> where T1: Clone = (T1, u32);

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type AddTypeParamBoundWhereClause<T1> where T1: Clone+Copy = (T1, u32);

// Add lifetime param ----------------------------------------------------------
#[cfg(cfail1)]
type AddLifetimeParam<'a> = (&'a u32, &'a u32);

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type AddLifetimeParam<'a, 'b> = (&'a u32, &'b u32);

// Add lifetime param bound ----------------------------------------------------
#[cfg(cfail1)]
type AddLifetimeParamBound<'a, 'b> = (&'a u32, &'b u32);

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type AddLifetimeParamBound<'a, 'b: 'a> = (&'a u32, &'b u32);

// Add lifetime param bound in where clause ------------------------------------
#[cfg(cfail1)]
type AddLifetimeParamBoundWhereClause<'a, 'b, 'c>
where 'b: 'a
    = (&'a u32, &'b u32, &'c u32);

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail3")]
type AddLifetimeParamBoundWhereClause<'a, 'b, 'c>
where 'b: 'a,
      'c: 'a
    = (&'a u32, &'b u32, &'c u32);

// Change Trait Bound Indirectly -----------------------------------------------
trait ReferencedTrait1 {}
trait ReferencedTrait2 {}

mod change_trait_bound_indirectly {
    #[cfg(cfail1)]
    use super::ReferencedTrait1 as Trait;
    #[cfg(not(cfail1))]
    use super::ReferencedTrait2 as Trait;

    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    type ChangeTraitBoundIndirectly<T: Trait> = (T, u32);
}

// Change Trait Bound Indirectly In Where Clause -------------------------------
mod change_trait_bound_indirectly_in_where_clause {
    #[cfg(cfail1)]
    use super::ReferencedTrait1 as Trait;
    #[cfg(not(cfail1))]
    use super::ReferencedTrait2 as Trait;

    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    type ChangeTraitBoundIndirectly<T> where T : Trait = (T, u32);
}
<|endoftext|>


<commit_before><commit_msg>add executable<commit_after>
fn main() {
    println!("hello, world!")
}
<|endoftext|>


<commit_before><commit_msg>Don't print debugger cursor if mode changed<commit_after><|endoftext|>


<commit_before><commit_msg>Add problem #119<commit_after>#[crate_type = "rlib"];

extern mod extra;
extern mod math;

use std::iter::{AdditiveIterator, Filter, SkipWhile};
use extra::priority_queue::PriorityQueue;
use math::{arith, numconv};

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

struct Power(uint, uint, uint);

impl Ord for Power {
    #[inline]
    fn lt(&self, other: &Power) -> bool {
        let Power(sn, sb, _) = *self;
        let Power(on, ob, _) = *other;
        sn > on || (sn == on && sb > ob)
    }
}

struct Powers {
    queue: PriorityQueue<Power>
}

impl Powers {
    #[inline]
    fn new() -> Powers {
        let mut queue = PriorityQueue::new();
        queue.push(Power(4, 2, 2));
        Powers { queue: queue }
    }
}

impl Iterator<(uint, uint, uint)> for Powers {
    #[inline]
    fn next(&mut self) -> Option<(uint, uint, uint)> {
        let Power(n, b, e) = self.queue.pop();
        if b == 2 { self.queue.push(Power(n * b, b, e + 1)); }
        self.queue.push(Power(arith::pow(b + 1, e), b + 1, e));
        Some((n, b, e))
    }
}

#[inline]
fn a<'a>() -> Filter<'a, (uint, uint, uint), SkipWhile<'a, (uint, uint, uint), Powers>> {
    Powers::new()
        .skip_while(|&(n, _b, _e)| n < 10)
        .filter(|&(n, b, _e)| numconv::to_digits(n, 10).sum() == b)
}

pub fn solve() -> ~str {
    let (n, _b, _e) = a().nth(29).unwrap();
    n.to_str()
}

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

    #[test]
    fn powers() {
        let mut it = Powers::new();
        assert_eq!(Some((4, 2, 2)), it.next());
        assert_eq!(Some((8, 2, 3)), it.next());
        assert_eq!(Some((9, 3, 2)), it.next());
        assert_eq!(Some((16, 2, 4)), it.next());
        assert_eq!(Some((16, 4, 2)), it.next());
        assert_eq!(Some((25, 5, 2)), it.next());
        assert_eq!(Some((27, 3, 3)), it.next());
        assert_eq!(Some((32, 2, 5)), it.next());
        assert_eq!(Some((36, 6, 2)), it.next());
        assert_eq!(Some((49, 7, 2)), it.next());
        assert_eq!(Some((64, 2, 6)), it.next());
        assert_eq!(Some((64, 4, 3)), it.next());
        assert_eq!(Some((64, 8, 2)), it.next());
        assert_eq!(Some((81, 3, 4)), it.next());
        assert_eq!(Some((81, 9, 2)), it.next());
        assert_eq!(Some((100, 10, 2)), it.next());
    }

    #[test]
    fn a() {
        let mut it = super::a();
        assert_eq!(Some((512, 8, 3)), it.nth(1));
        assert_eq!(Some((614656, 28, 4)), it.nth(8 - 1));
    }
}
<|endoftext|>


<commit_before>#![deny(warnings)]
extern crate hyper;
extern crate futures;
extern crate tokio_core;
extern crate pretty_env_logger;

use std::io::{self, Read, Write};
use std::net::TcpListener;
use std::thread;
use std::time::Duration;

use hyper::client::{Client, Request, HttpConnector};
use hyper::{Method, StatusCode};

use futures::{Future, Stream};
use futures::sync::oneshot;

use tokio_core::reactor::{Core, Handle, Timeout};

fn client(handle: &Handle) -> Client<HttpConnector> {
    Client::new(handle)
}

fn s(buf: &[u8]) -> &str {
    ::std::str::from_utf8(buf).unwrap()
}

macro_rules! test {
    (
        name: $name:ident,
        server:
            expected: $server_expected:expr,
            reply: $server_reply:expr,
        client:
            request:
                method: $client_method:ident,
                url: $client_url:expr,
                headers: [ $($request_headers:expr,)* ],
                body: $request_body:expr,

            response:
                status: $client_status:ident,
                headers: [ $($response_headers:expr,)* ],
                body: $response_body:expr,
    ) => (
        #[test]
        fn $name() {
            #![allow(unused)]
            use hyper::header::*;
            let server = TcpListener::bind("127.0.0.1:0").unwrap();
            let addr = server.local_addr().unwrap();
            let mut core = Core::new().unwrap();
            let client = client(&core.handle());
            let mut req = Request::new(Method::$client_method, format!($client_url, addr=addr).parse().unwrap());
            $(
                req.headers_mut().set($request_headers);
            )*

            if let Some(body) = $request_body {
                let body: &'static str = body;
                req.set_body(body);
            }
            let res = client.request(req);

            let (tx, rx) = oneshot::channel();

            thread::spawn(move || {
                let mut inc = server.accept().unwrap().0;
                inc.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
                inc.set_write_timeout(Some(Duration::from_secs(5))).unwrap();
                let expected = format!($server_expected, addr=addr);
                let mut buf = [0; 4096];
                let mut n = 0;
                while n < buf.len() && n < expected.len() {
                    n += inc.read(&mut buf[n..]).unwrap();
                }
                assert_eq!(s(&buf[..n]), expected);

                inc.write_all($server_reply.as_ref()).unwrap();
                tx.complete(());
            });

            let rx = rx.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked")));

            let work = res.join(rx).map(|r| r.0);

            let res = core.run(work).unwrap();
            assert_eq!(res.status(), &StatusCode::$client_status);
            $(
                assert_eq!(res.headers().get(), Some(&$response_headers));
            )*
        }
    );
}

static REPLY_OK: &'static str = "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n";

test! {
    name: client_get,

    server:
        expected: "GET / HTTP/1.1\r\nHost: {addr}\r\n\r\n",
        reply: REPLY_OK,

    client:
        request:
            method: Get,
            url: "http://{addr}/",
            headers: [],
            body: None,
        response:
            status: Ok,
            headers: [
                ContentLength(0),
            ],
            body: None,
}

test! {
    name: client_get_query,

    server:
        expected: "GET /foo?key=val HTTP/1.1\r\nHost: {addr}\r\n\r\n",
        reply: REPLY_OK,

    client:
        request:
            method: Get,
            url: "http://{addr}/foo?key=val#dont_send_me",
            headers: [],
            body: None,
        response:
            status: Ok,
            headers: [
                ContentLength(0),
            ],
            body: None,
}

test! {
    name: client_post_sized,

    server:
        expected: "\
            POST /length HTTP/1.1\r\n\
            Host: {addr}\r\n\
            Content-Length: 7\r\n\
            \r\n\
            foo bar\
            ",
        reply: REPLY_OK,

    client:
        request:
            method: Post,
            url: "http://{addr}/length",
            headers: [
                ContentLength(7),
            ],
            body: Some("foo bar"),
        response:
            status: Ok,
            headers: [],
            body: None,
}

test! {
    name: client_post_chunked,

    server:
        expected: "\
            POST /chunks HTTP/1.1\r\n\
            Host: {addr}\r\n\
            Transfer-Encoding: chunked\r\n\
            \r\n\
            B\r\n\
            foo bar baz\r\n\
            0\r\n\r\n\
            ",
        reply: REPLY_OK,

    client:
        request:
            method: Post,
            url: "http://{addr}/chunks",
            headers: [
                TransferEncoding::chunked(),
            ],
            body: Some("foo bar baz"),
        response:
            status: Ok,
            headers: [],
            body: None,
}

#[test]
fn client_keep_alive() {
    let server = TcpListener::bind("127.0.0.1:0").unwrap();
    let addr = server.local_addr().unwrap();
    let mut core = Core::new().unwrap();
    let client = client(&core.handle());

    let (tx1, rx1) = oneshot::channel();
    let (tx2, rx2) = oneshot::channel();
    thread::spawn(move || {
        let mut sock = server.accept().unwrap().0;
        sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
        sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap();
        let mut buf = [0; 4096];
        sock.read(&mut buf).expect("read 1");
        sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").expect("write 1");
        tx1.complete(());

        sock.read(&mut buf).expect("read 2");
        let second_get = b"GET /b HTTP/1.1\r\n";
        assert_eq!(&buf[..second_get.len()], second_get);
        sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").expect("write 2");
        tx2.complete(());
    });

    let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked")));
    let res = client.get(format!("http://{}/a", addr).parse().unwrap());
    core.run(res.join(rx).map(|r| r.0)).unwrap();

    let rx = rx2.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked")));
    let res = client.get(format!("http://{}/b", addr).parse().unwrap());
    core.run(res.join(rx).map(|r| r.0)).unwrap();
}

#[test]
fn client_pooled_socket_disconnected() {
    let _ = pretty_env_logger::init();
    let server = TcpListener::bind("127.0.0.1:0").unwrap();
    let addr = server.local_addr().unwrap();
    let mut core = Core::new().unwrap();
    let client = client(&core.handle());

    let (tx1, rx1) = oneshot::channel();
    let (tx2, rx2) = oneshot::channel();
    thread::spawn(move || {
        let mut sock = server.accept().unwrap().0;
        sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
        sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap();
        let mut buf = [0; 4096];
        sock.read(&mut buf).expect("read 1");
        let remote_addr = sock.peer_addr().unwrap().to_string();
        let out = format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}", remote_addr.len(), remote_addr);
        sock.write_all(out.as_bytes()).expect("write 1");
        drop(sock);
        tx1.complete(());

        let mut sock = server.accept().unwrap().0;
        sock.read(&mut buf).expect("read 2");
        let second_get = b"GET /b HTTP/1.1\r\n";
        assert_eq!(&buf[..second_get.len()], second_get);
        let remote_addr = sock.peer_addr().unwrap().to_string();
        let out = format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}", remote_addr.len(), remote_addr);
        sock.write_all(out.as_bytes()).expect("write 2");
        tx2.complete(());
    });

    // spin shortly so we receive the hangup on the client socket
    let sleep = Timeout::new(Duration::from_millis(500), &core.handle()).unwrap();
    core.run(sleep).unwrap();

    let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked")));
    let res = client.get(format!("http://{}/a", addr).parse().unwrap())
        .and_then(|res| {
            res.body()
                .map(|chunk| chunk.to_vec())
                .collect()
                .map(|vec| vec.concat())
                .map(|vec| String::from_utf8(vec).unwrap())
        });
    let addr1 = core.run(res.join(rx).map(|r| r.0)).unwrap();

    let rx = rx2.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked")));
    let res = client.get(format!("http://{}/b", addr).parse().unwrap())
        .and_then(|res| {
            res.body()
                .map(|chunk| chunk.to_vec())
                .collect()
                .map(|vec| vec.concat())
                .map(|vec| String::from_utf8(vec).unwrap())
        });
    let addr2 = core.run(res.join(rx).map(|r| r.0)).unwrap();

    assert_ne!(addr1, addr2);
}
<commit_msg>test(client): disable flaky disconnect test<commit_after>#![deny(warnings)]
extern crate hyper;
extern crate futures;
extern crate tokio_core;
extern crate pretty_env_logger;

use std::io::{self, Read, Write};
use std::net::TcpListener;
use std::thread;
use std::time::Duration;

use hyper::client::{Client, Request, HttpConnector};
use hyper::{Method, StatusCode};

use futures::Future;
use futures::sync::oneshot;

use tokio_core::reactor::{Core, Handle};

fn client(handle: &Handle) -> Client<HttpConnector> {
    Client::new(handle)
}

fn s(buf: &[u8]) -> &str {
    ::std::str::from_utf8(buf).unwrap()
}

macro_rules! test {
    (
        name: $name:ident,
        server:
            expected: $server_expected:expr,
            reply: $server_reply:expr,
        client:
            request:
                method: $client_method:ident,
                url: $client_url:expr,
                headers: [ $($request_headers:expr,)* ],
                body: $request_body:expr,

            response:
                status: $client_status:ident,
                headers: [ $($response_headers:expr,)* ],
                body: $response_body:expr,
    ) => (
        #[test]
        fn $name() {
            #![allow(unused)]
            use hyper::header::*;
            let server = TcpListener::bind("127.0.0.1:0").unwrap();
            let addr = server.local_addr().unwrap();
            let mut core = Core::new().unwrap();
            let client = client(&core.handle());
            let mut req = Request::new(Method::$client_method, format!($client_url, addr=addr).parse().unwrap());
            $(
                req.headers_mut().set($request_headers);
            )*

            if let Some(body) = $request_body {
                let body: &'static str = body;
                req.set_body(body);
            }
            let res = client.request(req);

            let (tx, rx) = oneshot::channel();

            thread::spawn(move || {
                let mut inc = server.accept().unwrap().0;
                inc.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
                inc.set_write_timeout(Some(Duration::from_secs(5))).unwrap();
                let expected = format!($server_expected, addr=addr);
                let mut buf = [0; 4096];
                let mut n = 0;
                while n < buf.len() && n < expected.len() {
                    n += inc.read(&mut buf[n..]).unwrap();
                }
                assert_eq!(s(&buf[..n]), expected);

                inc.write_all($server_reply.as_ref()).unwrap();
                tx.complete(());
            });

            let rx = rx.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked")));

            let work = res.join(rx).map(|r| r.0);

            let res = core.run(work).unwrap();
            assert_eq!(res.status(), &StatusCode::$client_status);
            $(
                assert_eq!(res.headers().get(), Some(&$response_headers));
            )*
        }
    );
}

static REPLY_OK: &'static str = "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n";

test! {
    name: client_get,

    server:
        expected: "GET / HTTP/1.1\r\nHost: {addr}\r\n\r\n",
        reply: REPLY_OK,

    client:
        request:
            method: Get,
            url: "http://{addr}/",
            headers: [],
            body: None,
        response:
            status: Ok,
            headers: [
                ContentLength(0),
            ],
            body: None,
}

test! {
    name: client_get_query,

    server:
        expected: "GET /foo?key=val HTTP/1.1\r\nHost: {addr}\r\n\r\n",
        reply: REPLY_OK,

    client:
        request:
            method: Get,
            url: "http://{addr}/foo?key=val#dont_send_me",
            headers: [],
            body: None,
        response:
            status: Ok,
            headers: [
                ContentLength(0),
            ],
            body: None,
}

test! {
    name: client_post_sized,

    server:
        expected: "\
            POST /length HTTP/1.1\r\n\
            Host: {addr}\r\n\
            Content-Length: 7\r\n\
            \r\n\
            foo bar\
            ",
        reply: REPLY_OK,

    client:
        request:
            method: Post,
            url: "http://{addr}/length",
            headers: [
                ContentLength(7),
            ],
            body: Some("foo bar"),
        response:
            status: Ok,
            headers: [],
            body: None,
}

test! {
    name: client_post_chunked,

    server:
        expected: "\
            POST /chunks HTTP/1.1\r\n\
            Host: {addr}\r\n\
            Transfer-Encoding: chunked\r\n\
            \r\n\
            B\r\n\
            foo bar baz\r\n\
            0\r\n\r\n\
            ",
        reply: REPLY_OK,

    client:
        request:
            method: Post,
            url: "http://{addr}/chunks",
            headers: [
                TransferEncoding::chunked(),
            ],
            body: Some("foo bar baz"),
        response:
            status: Ok,
            headers: [],
            body: None,
}

#[test]
fn client_keep_alive() {
    let server = TcpListener::bind("127.0.0.1:0").unwrap();
    let addr = server.local_addr().unwrap();
    let mut core = Core::new().unwrap();
    let client = client(&core.handle());

    let (tx1, rx1) = oneshot::channel();
    let (tx2, rx2) = oneshot::channel();
    thread::spawn(move || {
        let mut sock = server.accept().unwrap().0;
        sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
        sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap();
        let mut buf = [0; 4096];
        sock.read(&mut buf).expect("read 1");
        sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").expect("write 1");
        tx1.complete(());

        sock.read(&mut buf).expect("read 2");
        let second_get = b"GET /b HTTP/1.1\r\n";
        assert_eq!(&buf[..second_get.len()], second_get);
        sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").expect("write 2");
        tx2.complete(());
    });

    let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked")));
    let res = client.get(format!("http://{}/a", addr).parse().unwrap());
    core.run(res.join(rx).map(|r| r.0)).unwrap();

    let rx = rx2.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked")));
    let res = client.get(format!("http://{}/b", addr).parse().unwrap());
    core.run(res.join(rx).map(|r| r.0)).unwrap();
}

/* TODO: re-enable once rety works, its currently a flaky test
#[test]
fn client_pooled_socket_disconnected() {
    let _ = pretty_env_logger::init();
    let server = TcpListener::bind("127.0.0.1:0").unwrap();
    let addr = server.local_addr().unwrap();
    let mut core = Core::new().unwrap();
    let client = client(&core.handle());

    let (tx1, rx1) = oneshot::channel();
    let (tx2, rx2) = oneshot::channel();
    thread::spawn(move || {
        let mut sock = server.accept().unwrap().0;
        sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
        sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap();
        let mut buf = [0; 4096];
        sock.read(&mut buf).expect("read 1");
        let remote_addr = sock.peer_addr().unwrap().to_string();
        let out = format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}", remote_addr.len(), remote_addr);
        sock.write_all(out.as_bytes()).expect("write 1");
        drop(sock);
        tx1.complete(());

        let mut sock = server.accept().unwrap().0;
        sock.read(&mut buf).expect("read 2");
        let second_get = b"GET /b HTTP/1.1\r\n";
        assert_eq!(&buf[..second_get.len()], second_get);
        let remote_addr = sock.peer_addr().unwrap().to_string();
        let out = format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}", remote_addr.len(), remote_addr);
        sock.write_all(out.as_bytes()).expect("write 2");
        tx2.complete(());
    });

    // spin shortly so we receive the hangup on the client socket
    let sleep = Timeout::new(Duration::from_millis(500), &core.handle()).unwrap();
    core.run(sleep).unwrap();

    let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked")));
    let res = client.get(format!("http://{}/a", addr).parse().unwrap())
        .and_then(|res| {
            res.body()
                .map(|chunk| chunk.to_vec())
                .collect()
                .map(|vec| vec.concat())
                .map(|vec| String::from_utf8(vec).unwrap())
        });
    let addr1 = core.run(res.join(rx).map(|r| r.0)).unwrap();

    let rx = rx2.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked")));
    let res = client.get(format!("http://{}/b", addr).parse().unwrap())
        .and_then(|res| {
            res.body()
                .map(|chunk| chunk.to_vec())
                .collect()
                .map(|vec| vec.concat())
                .map(|vec| String::from_utf8(vec).unwrap())
        });
    let addr2 = core.run(res.join(rx).map(|r| r.0)).unwrap();

    assert_ne!(addr1, addr2);
}
*/
<|endoftext|>


<commit_before><commit_msg>field level mutability in structs used<commit_after><|endoftext|>


<commit_before><commit_msg>Add example parsing ISO 8601 duration<commit_after>extern crate pom;
use pom::parser::*;
use pom::Parser;

use std::str::{self, FromStr};

#[derive(Debug, PartialEq)]
struct Duration {
	years: Option<f32>,
	months: Option<f32>,
	weeks: Option<f32>,
	days: Option<f32>,
	hours: Option<f32>,
	minutes: Option<f32>,
	seconds: Option<f32>,
}

fn number_separator() -> Parser<u8, ()> {
	// either '.' or ',' can be used as a separator between the whole and decimal part of a number
	one_of(b".,").discard()
}

fn number() -> Parser<u8, f32> {
	let integer = one_of(b"0123456789").repeat(0..);
	let frac = number_separator() + one_of(b"0123456789").repeat(1..);
	let number = integer + frac.opt();
	number.collect().convert(str::from_utf8).convert(f32::from_str)
}

fn date_part() -> Parser<u8, (Option<f32>, Option<f32>, Option<f32>, Option<f32>)> {
	(
		(number() - sym(b'Y')).opt() +
		(number() - sym(b'M')).opt() +
		(number() - sym(b'W')).opt() +
		(number() - sym(b'D')).opt()
	)
		.map(|(((years,months), weeks), days)| {
			(years, months, weeks, days)
		})
}

fn time_part() -> Parser<u8, Option<(Option<f32>, Option<f32>, Option<f32>)>> {
	(
		sym(b'T') *
			(
				(number() - sym(b'H')).opt() +
					(number() - sym(b'M')).opt() +
					(number() - sym(b'S')).opt()
			)
				.map(|((hours,minutes), seconds)| {
					(hours, minutes, seconds)
				})
	).opt()
}

fn parser() -> Parser<u8, Duration> {
	(
		sym(b'P') *
		date_part() +
		time_part()
	)
		.map(|(date_elements, time_elements)|{
			let (years, months, weeks, days) = date_elements;
			let (hours, minutes, seconds) = match time_elements {
				None => (None, None, None),
				Some(elements) => elements,
			};

			Duration {
				years,
				months,
				weeks,
				days,
				hours,
				minutes,
				seconds,
			}
		})
}

/// Parses the ISO 8601 Duration standard
/// https://en.wikipedia.org/wiki/ISO_8601#Durations
fn main() {
	let input = "P3Y6M4DT12H30M5S";
	let result = parser().parse(input.as_bytes());

	assert_eq!(
		Duration {
			years: Some(3f32),
			months: Some(6f32),
			weeks: None,
			days: Some(4f32),
			hours: Some(12f32),
			minutes: Some(30f32),
			seconds: Some(5f32)
		},
		result.unwrap()
	);

}
<|endoftext|>


<commit_before>use libc::*;
use std::ffi::CString;
use std::mem::transmute;

#[repr(C)]
pub struct CPDReaderAPI {
    private_data: *mut c_void,
    read_u8: extern "C" fn(data: *mut c_void),

    pub data: *mut c_void,
    pub read_get_event: extern fn(reader: *mut c_void) -> uint32_t,
    pub read_iterator_next_event: extern fn(reader: *mut c_void,
                                            it: *mut uint64_t) -> uint32_t,
    pub read_iterator_begin: extern fn(reader: *mut c_void, it: *mut uint64_t,
                                       keyName: *mut *const c_char, parentIt: uint64_t)
                                    -> uint32_t,
    pub read_iterator_next: extern fn(reader: *mut c_void, keyName: *mut *const c_char,
                                      it: *mut uint64_t) -> uint32_t,
    pub read_next_entry: extern fn(reader: *mut c_void, arrayIt: *mut uint64_t)
                                -> int32_t,
    pub read_find_s8: extern fn(reader: *mut c_void, res: *mut int8_t, id: *const c_char,
                                it: uint64_t) -> uint32_t,
    pub read_find_u8: extern fn(reader: *mut c_void, res: *mut uint8_t, id: *const c_char,
                                it: uint64_t) -> uint32_t,
    pub read_find_s16: extern fn(reader: *mut c_void, res: *mut int16_t, id: *const c_char,
                                 it: uint64_t) -> uint32_t,
    pub read_find_u16: extern fn(reader: *mut c_void, res: *mut uint16_t, id: *const c_char,
                                 it: uint64_t) -> uint32_t,
    pub read_find_s32: extern fn(reader: *mut c_void, res: *mut int32_t, id: *const c_char,
                                 it: uint64_t) -> uint32_t,
    pub read_find_u32: extern fn(reader: *mut c_void, res: *mut uint32_t, id: *const c_char,
                                 it: uint64_t) -> uint32_t,
    pub read_find_s64: extern fn(reader: *mut c_void, res: *mut int64_t, id: *const c_char,
                                 it: uint64_t) -> uint32_t,
    pub read_find_u64: extern fn(reader: *mut c_void, res: *mut uint64_t, id: *const c_char,
                                 it: uint64_t) -> uint32_t,
    pub read_find_float: extern fn(reader: *mut c_void, res: *mut c_float, id: *const c_char,
                                   it: uint64_t) -> uint32_t,
    pub read_find_double: extern fn(reader: *mut c_void, res: *mut c_double, id: *const c_char,
                                    it: uint64_t) -> uint32_t,
    pub read_find_string: extern fn(reader: *mut c_void, res: *mut *const c_char, id: *const c_char,
                                    it: uint64_t) -> uint32_t,
    pub read_find_data: extern fn(reader: *mut c_void, data: *mut *mut c_void, size: *mut uint64_t,
                                  id: *const c_char, it: uint64_t) -> uint32_t,
    pub read_find_array: extern fn(reader: *mut c_void, arrayIt: *mut uint64_t, id: *const c_char,
                                   it: uint64_t) -> uint32_t,
    pub read_dump_data: extern fn(reader: *mut c_void),
}

#[repr(C)]
pub enum WriteStatus {
    Ok,
    Fail,
}

#[repr(C)]
pub struct CPDWriterAPI {
    private_data: *mut c_void,
    pub write_event_begin: extern "C" fn(writer: *mut c_void, event: uint16_t) -> WriteStatus,
    pub write_event_end: extern fn(writer: *mut c_void) -> WriteStatus,
    pub write_header_array_begin: extern fn(writer: *mut c_void, ids: *mut *const c_char)
                                         -> WriteStatus,
    pub write_header_array_end: extern fn(writer: *mut c_void) -> WriteStatus,
    pub write_array_begin: extern fn(writer: *mut c_void, name: *const c_char) -> WriteStatus,
    pub write_array_end: extern fn(writer: *mut c_void) -> WriteStatus,
    pub write_array_entry_begin: extern fn(writer: *mut c_void) -> WriteStatus,
    pub write_array_entry_end: extern fn(writer: *mut c_void) -> WriteStatus,
    pub write_s8: extern fn(writer: *mut c_void, id: *const c_char, v: int8_t) -> WriteStatus,
    pub write_u8: extern fn(writer: *mut c_void, id: *const c_char, v: uint8_t) -> WriteStatus,
    pub write_s16: extern fn(writer: *mut c_void, id: *const c_char, v: int16_t) -> WriteStatus,
    pub write_u16: extern fn(writer: *mut c_void, id: *const c_char, v: uint16_t) -> WriteStatus,
    pub write_s32: extern fn(writer: *mut c_void, id: *const c_char, v: int32_t) -> WriteStatus,
    pub write_u32: extern fn(writer: *mut c_void, id: *const c_char, v: uint32_t) -> WriteStatus,
    pub write_s64: extern fn(writer: *mut c_void, id: *const c_char, v: int64_t) -> WriteStatus,
    pub write_u64: extern fn(writer: *mut c_void, id: *const c_char, v: uint64_t) -> WriteStatus,
    pub write_float: extern fn(writer: *mut c_void, id: *const c_char, v: c_float) -> WriteStatus,
    pub write_double: extern fn(writer: *mut c_void, id: *const c_char, v: c_double) -> WriteStatus,
    pub write_string: extern fn(writer: *mut c_void, id: *const c_char, v: *const c_char)
                             -> WriteStatus,
    pub write_data: extern fn(w: *mut c_void, id: *const c_char, d: *const uint8_t, l: c_uint)
                            -> WriteStatus,
}

pub struct Reader {
    pub api: *mut CPDReaderAPI,
    pub it: u64,
}

pub struct Writer {
    pub api: *mut CPDWriterAPI,
}

#[repr(C)]
pub enum ReadType {
    None,
    S8,
    U8,
    S16,
    U16,
    S32,
    U32,
    S64,
    U64,
    Float,
    Double,
    EndNumericTypes,
    Str,
    Data,
    Event,
    Array,
    ArrayEntry,
    Count,
}

#[repr(C)]
pub enum ReadStatus {
    Ok = 1 << 8,
    Converted = 2 << 8,
    IllegalType = 3 << 8,
    NotFound = 4 << 8,
    Fail = 5 << 8,
    TypeMask = 0xff,
}

pub struct ReaderIter {
    reader: Reader,
    curr_iter: u64,
}

impl Clone for Reader {
    fn clone(&self) -> Self {
        return Reader {
            api: self.api,
            it: self.it,
        };
    }
}

fn status_res<T>(res: T, s: u32) -> Result<T, ReadStatus> {
    match (s >> 8) & 0xff {
        1...2 => Ok(res),
        3 => Err(ReadStatus::IllegalType),
        _ => Err(ReadStatus::NotFound),
    }
}

impl Reader {
    pub fn new(in_api: *mut CPDReaderAPI, iter: u64) -> Self {
        return Reader {
            api: in_api,
            it: iter,
        };
    }

    pub fn find_u8(&self, id: &str) -> Result<u8, ReadStatus> {
        let s = CString::new(id).unwrap();
        let mut res = 0u8;
        let ret;

        unsafe {
            ret = ((*self.api).read_find_u8)(transmute(self.api),
                                             &mut res,
                                             s.as_ptr(),
                                             self.it);
        }

        return status_res(res, ret);
    }

    pub fn find_array(&self, id: &str) -> ReaderIter {
        let s = CString::new(id).unwrap();
        let mut t = 0u64;

        unsafe {
            ((*self.api).read_find_array)(transmute(self.api), &mut t, s.as_ptr(), 0);
        }

        ReaderIter {
            reader: self.clone(),
            curr_iter: t,
        }
    }
}

impl Iterator for ReaderIter {
    type Item = Reader;
    fn next(&mut self) -> Option<Reader> {
        let ret;
        unsafe {
            ret = ((*self.reader.api).read_next_entry)((*self.reader.api).private_data,
                                                       &mut self.curr_iter);
        }

        match ret {
            0 => None,
            _ => Some(Reader::new(self.reader.api, self.curr_iter)),
        }
    }
}

impl Writer {
    pub fn event_begin(&mut self, event: u16) {
        unsafe {
            ((*self.api).write_event_begin)(transmute(self.api), event);
        }
    }

    pub fn event_end(&mut self) {
        unsafe {
            ((*self.api).write_event_end)(transmute(self.api));
        }
    }

    pub fn write_array_begin(&mut self, name: &str) {
        let s = CString::new(name).unwrap();
        unsafe {
            ((*self.api).write_array_begin)(transmute(self.api), s.as_ptr());
        }
    }

    pub fn write_array_end(&mut self) {
        unsafe {
            ((*self.api).write_array_end)(transmute(self.api));
        }
    }

    pub fn write_array_entry_begin(&mut self) {
        unsafe {
            ((*self.api).write_array_entry_begin)(transmute(self.api));
        }
    }

    pub fn write_array_entry_end(&mut self) {
        unsafe {
            ((*self.api).write_array_entry_end)(transmute(self.api));
        }
    }

    pub fn write_s8(&mut self, id: &str, v: i8) {
        let s = CString::new(id).unwrap();
        unsafe {
            ((*self.api).write_s8)(transmute(self.api), s.as_ptr(), v);
        }
    }

    pub fn write_u8(&mut self, id: &str, v: u8) {
        let s = CString::new(id).unwrap();
        unsafe {
            ((*self.api).write_u8)(transmute(self.api), s.as_ptr(), v);
        }
    }

    pub fn write_s16(&mut self, id: &str, v: i16) {
        let s = CString::new(id).unwrap();
        unsafe {
            ((*self.api).write_s16)(transmute(self.api), s.as_ptr(), v);
        }
    }

    pub fn write_u16(&mut self, id: &str, v: u16) {
        let s = CString::new(id).unwrap();
        unsafe {
            ((*self.api).write_u16)(transmute(self.api), s.as_ptr(), v);
        }
    }

    pub fn write_s32(&mut self, id: &str, v: i32) {
        let s = CString::new(id).unwrap();
        unsafe {
            ((*self.api).write_s32)(transmute(self.api), s.as_ptr(), v);
        }
    }

    pub fn write_u32(&mut self, id: &str, v: u32) {
        let s = CString::new(id).unwrap();
        unsafe {
            ((*self.api).write_u32)(transmute(self.api), s.as_ptr(), v);
        }
    }

    pub fn write_s64(&mut self, id: &str, v: i64) {
        let s = CString::new(id).unwrap();
        unsafe {
            ((*self.api).write_s64)(transmute(self.api), s.as_ptr(), v);
        }
    }

    pub fn write_u64(&mut self, id: &str, v: u64) {
        let s = CString::new(id).unwrap();
        unsafe {
            ((*self.api).write_u64)(transmute(self.api), s.as_ptr(), v);
        }
    }

    pub fn write_float(&mut self, id: &str, v: f32) {
        let s = CString::new(id).unwrap();
        unsafe {
            ((*self.api).write_float)(transmute(self.api), s.as_ptr(), v);
        }
    }

    pub fn write_double(&mut self, id: &str, v: f64) {
        let s = CString::new(id).unwrap();
        unsafe {
            ((*self.api).write_double)(transmute(self.api), s.as_ptr(), v);
        }
    }

    pub fn write_string(&mut self, id: &str, v: &str) {
        let id_s = CString::new(id).unwrap();
        let v_s = CString::new(v).unwrap();
        unsafe {
            ((*self.api).write_string)(transmute(self.api), id_s.as_ptr(), v_s.as_ptr());
        }
    }

    pub fn write_data(&mut self, id: &str, data: &[u8]) {
        let s = CString::new(id).unwrap();
        unsafe {
            ((*self.api).write_data)(transmute(self.api),
                                     s.as_ptr(),
                                     data.as_ptr(),
                                     data.len() as u32);
        }
    }
}
<commit_msg>Use macros to reduce code size<commit_after>use libc::*;
use std::ffi::CString;
use std::mem::transmute;

#[repr(C)]
pub struct CPDReaderAPI {
    pub data: *mut c_void,
    pub read_get_event: extern fn(reader: *mut c_void) -> uint32_t,
    pub read_iterator_next_event: extern fn(reader: *mut c_void,
                                            it: *mut uint64_t) -> uint32_t,
    pub read_iterator_begin: extern fn(reader: *mut c_void, it: *mut uint64_t,
                                       keyName: *mut *const c_char, parentIt: uint64_t)
                                    -> uint32_t,
    pub read_iterator_next: extern fn(reader: *mut c_void, keyName: *mut *const c_char,
                                      it: *mut uint64_t) -> uint32_t,
    pub read_next_entry: extern fn(reader: *mut c_void, arrayIt: *mut uint64_t)
                                -> int32_t,
    pub read_find_s8: extern fn(reader: *mut c_void, res: *mut int8_t, id: *const c_char,
                                it: uint64_t) -> uint32_t,
    pub read_find_u8: extern fn(reader: *mut c_void, res: *mut uint8_t, id: *const c_char,
                                it: uint64_t) -> uint32_t,
    pub read_find_s16: extern fn(reader: *mut c_void, res: *mut int16_t, id: *const c_char,
                                 it: uint64_t) -> uint32_t,
    pub read_find_u16: extern fn(reader: *mut c_void, res: *mut uint16_t, id: *const c_char,
                                 it: uint64_t) -> uint32_t,
    pub read_find_s32: extern fn(reader: *mut c_void, res: *mut int32_t, id: *const c_char,
                                 it: uint64_t) -> uint32_t,
    pub read_find_u32: extern fn(reader: *mut c_void, res: *mut uint32_t, id: *const c_char,
                                 it: uint64_t) -> uint32_t,
    pub read_find_s64: extern fn(reader: *mut c_void, res: *mut int64_t, id: *const c_char,
                                 it: uint64_t) -> uint32_t,
    pub read_find_u64: extern fn(reader: *mut c_void, res: *mut uint64_t, id: *const c_char,
                                 it: uint64_t) -> uint32_t,
    pub read_find_float: extern fn(reader: *mut c_void, res: *mut c_float, id: *const c_char,
                                   it: uint64_t) -> uint32_t,
    pub read_find_double: extern fn(reader: *mut c_void, res: *mut c_double, id: *const c_char,
                                    it: uint64_t) -> uint32_t,
    pub read_find_string: extern fn(reader: *mut c_void, res: *mut *const c_char, id: *const c_char,
                                    it: uint64_t) -> uint32_t,
    pub read_find_data: extern fn(reader: *mut c_void, data: *mut *mut c_void, size: *mut uint64_t,
                                  id: *const c_char, it: uint64_t) -> uint32_t,
    pub read_find_array: extern fn(reader: *mut c_void, arrayIt: *mut uint64_t, id: *const c_char,
                                   it: uint64_t) -> uint32_t,
    pub read_dump_data: extern fn(reader: *mut c_void),
}

#[repr(C)]
pub enum WriteStatus {
    Ok,
    Fail,
}

#[repr(C)]
pub struct CPDWriterAPI {
    private_data: *mut c_void,
    pub write_event_begin: extern "C" fn(writer: *mut c_void, event: uint16_t) -> WriteStatus,
    pub write_event_end: extern fn(writer: *mut c_void) -> WriteStatus,
    pub write_header_array_begin: extern fn(writer: *mut c_void, ids: *mut *const c_char)
                                         -> WriteStatus,
    pub write_header_array_end: extern fn(writer: *mut c_void) -> WriteStatus,
    pub write_array_begin: extern fn(writer: *mut c_void, name: *const c_char) -> WriteStatus,
    pub write_array_end: extern fn(writer: *mut c_void) -> WriteStatus,
    pub write_array_entry_begin: extern fn(writer: *mut c_void) -> WriteStatus,
    pub write_array_entry_end: extern fn(writer: *mut c_void) -> WriteStatus,
    pub write_s8: extern fn(writer: *mut c_void, id: *const c_char, v: int8_t) -> WriteStatus,
    pub write_u8: extern fn(writer: *mut c_void, id: *const c_char, v: uint8_t) -> WriteStatus,
    pub write_s16: extern fn(writer: *mut c_void, id: *const c_char, v: int16_t) -> WriteStatus,
    pub write_u16: extern fn(writer: *mut c_void, id: *const c_char, v: uint16_t) -> WriteStatus,
    pub write_s32: extern fn(writer: *mut c_void, id: *const c_char, v: int32_t) -> WriteStatus,
    pub write_u32: extern fn(writer: *mut c_void, id: *const c_char, v: uint32_t) -> WriteStatus,
    pub write_s64: extern fn(writer: *mut c_void, id: *const c_char, v: int64_t) -> WriteStatus,
    pub write_u64: extern fn(writer: *mut c_void, id: *const c_char, v: uint64_t) -> WriteStatus,
    pub write_float: extern fn(writer: *mut c_void, id: *const c_char, v: c_float) -> WriteStatus,
    pub write_double: extern fn(writer: *mut c_void, id: *const c_char, v: c_double) -> WriteStatus,
    pub write_string: extern fn(writer: *mut c_void, id: *const c_char, v: *const c_char)
                             -> WriteStatus,
    pub write_data: extern fn(w: *mut c_void, id: *const c_char, d: *const uint8_t, l: c_uint)
                            -> WriteStatus,
}

pub struct Reader {
    pub api: *mut CPDReaderAPI,
    pub it: u64,
}

pub struct Writer {
    pub api: *mut CPDWriterAPI,
}

#[repr(C)]
pub enum ReadType {
    None,
    S8,
    U8,
    S16,
    U16,
    S32,
    U32,
    S64,
    U64,
    Float,
    Double,
    EndNumericTypes,
    Str,
    Data,
    Event,
    Array,
    ArrayEntry,
    Count,
}

#[repr(C)]
pub enum ReadStatus {
    Ok = 1 << 8,
    Converted = 2 << 8,
    IllegalType = 3 << 8,
    NotFound = 4 << 8,
    Fail = 5 << 8,
    TypeMask = 0xff,
}

pub struct ReaderIter {
    reader: Reader,
    curr_iter: u64,
}

impl Clone for Reader {
    fn clone(&self) -> Self {
        return Reader {
            api: self.api,
            it: self.it,
        };
    }
}

fn status_res<T>(res: T, s: u32) -> Result<T, ReadStatus> {
    match (s >> 8) & 0xff {
        1...2 => Ok(res),
        3 => Err(ReadStatus::IllegalType),
        _ => Err(ReadStatus::NotFound),
    }
}

macro_rules! find_fun {
    ($c_name:ident, $name:ident, $data_type:ident) => {
        pub fn $name(&self, id: &str) -> Result<$data_type, ReadStatus> {
            let s = CString::new(id).unwrap();
            let mut res = 0 as $data_type;
            let ret;

            unsafe {
                ret = ((*self.api).$c_name)(transmute(self.api), &mut res, s.as_ptr(), self.it);
            }

            return status_res(res, ret);
        }
    }
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

impl Reader {
    pub fn new(in_api: *mut CPDReaderAPI, iter: u64) -> Self {
        return Reader {
            api: in_api,
            it: iter,
        };
    }

    find_fun!(read_find_s8, find_s8, i8);
    find_fun!(read_find_u8, find_u8, u8);
    find_fun!(read_find_s16, find_s16, i16);
    find_fun!(read_find_u16, find_u16, u16);
    find_fun!(read_find_s32, find_s32, i32);
    find_fun!(read_find_u32, find_u32, u32);
    find_fun!(read_find_s64, find_s64, i64);
    find_fun!(read_find_u64, find_u64, u64);
    find_fun!(read_find_float, find_float, f32);
    find_fun!(read_find_double, find_double, f64);

    pub fn find_array(&self, id: &str) -> ReaderIter {
        let s = CString::new(id).unwrap();
        let mut t = 0u64;

        unsafe {
            ((*self.api).read_find_array)(transmute(self.api), &mut t, s.as_ptr(), 0);
        }

        ReaderIter {
            reader: self.clone(),
            curr_iter: t,
        }
    }
}

impl Iterator for ReaderIter {
    type Item = Reader;
    fn next(&mut self) -> Option<Reader> {
        let ret;
        unsafe {
            ret = ((*self.reader.api).read_next_entry)(transmute(self.reader.api),
                                                       &mut self.curr_iter);
        }

        match ret {
            0 => None,
            _ => Some(Reader::new(self.reader.api, self.curr_iter)),
        }
    }
}

macro_rules! write_fun {
    ($name:ident, $data_type:ident) => {
        pub fn $name(&mut self, id: &str, v: $data_type) {
            let s = CString::new(id).unwrap();
            unsafe {
                ((*self.api).$name)(transmute(self.api), s.as_ptr(), v);
            }
        }
    }
}

impl Writer {
    pub fn event_begin(&mut self, event: u16) {
        unsafe {
            ((*self.api).write_event_begin)(transmute(self.api), event);
        }
    }

    pub fn event_end(&mut self) {
        unsafe {
            ((*self.api).write_event_end)(transmute(self.api));
        }
    }

    pub fn array_begin(&mut self, name: &str) {
        let s = CString::new(name).unwrap();
        unsafe {
            ((*self.api).write_array_begin)(transmute(self.api), s.as_ptr());
        }
    }

    pub fn array_end(&mut self) {
        unsafe {
            ((*self.api).write_array_end)(transmute(self.api));
        }
    }

    pub fn array_entry_begin(&mut self) {
        unsafe {
            ((*self.api).write_array_entry_begin)(transmute(self.api));
        }
    }

    pub fn array_entry_end(&mut self) {
        unsafe {
            ((*self.api).write_array_entry_end)(transmute(self.api));
        }
    }

    write_fun!(write_s8, i8);
    write_fun!(write_u8, u8);
    write_fun!(write_s16, i16);
    write_fun!(write_u16, u16);
    write_fun!(write_s32, i32);
    write_fun!(write_u32, u32);
    write_fun!(write_s64, i64);
    write_fun!(write_u64, u64);
    write_fun!(write_float, f32);
    write_fun!(write_double, f64);

    pub fn write_string(&mut self, id: &str, v: &str) {
        let id_s = CString::new(id).unwrap();
        let v_s = CString::new(v).unwrap();
        unsafe {
            ((*self.api).write_string)(transmute(self.api), id_s.as_ptr(), v_s.as_ptr());
        }
    }

    pub fn write_data(&mut self, id: &str, data: &[u8]) {
        let s = CString::new(id).unwrap();
        unsafe {
            ((*self.api).write_data)(transmute(self.api),
                                     s.as_ptr(),
                                     data.as_ptr(),
                                     data.len() as u32);
        }
    }
}
<|endoftext|>


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

use std::sys;

#[packed]
struct S4 {
    a: u8,
    b: [u8, .. 3],
}

#[packed]
struct S5 {
    a: u8,
    b: u32
}

#[packed]
struct S13_str {
    a: i64,
    b: f32,
    c: u8,
    d: ~str
}

enum Foo {
    Bar = 1,
    Baz = 2
}

#[packed]
struct S3_Foo {
    a: u8,
    b: u16,
    c: Foo
}

#[packed]
struct S7_Option {
    a: f32,
    b: u8,
    c: u16,
    d: Option<@mut f64>
}

pub fn main() {
    assert_eq!(sys::size_of::<S4>(), 4);
    assert_eq!(sys::size_of::<S5>(), 5);
    assert_eq!(sys::size_of::<S13_str>(), 13 + sys::size_of::<~str>());
    assert_eq!(sys::size_of::<S3_Foo>(), 3 + sys::size_of::<Foo>());
    assert_eq!(sys::size_of::<S7_Option>(), 7 + sys::size_of::<Option<@mut f64>>());
}
<commit_msg>Update test for packed structs to also test being placed in statics.<commit_after>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::sys;

#[packed]
struct S4 {
    a: u8,
    b: [u8, .. 3],
}

#[packed]
struct S5 {
    a: u8,
    b: u32
}

#[packed]
struct S13_str {
    a: i64,
    b: f32,
    c: u8,
    d: ~str
}

enum Foo {
    Bar = 1,
    Baz = 2
}

#[packed]
struct S3_Foo {
    a: u8,
    b: u16,
    c: Foo
}

#[packed]
struct S7_Option {
    a: f32,
    b: u8,
    c: u16,
    d: Option<@mut f64>
}

// Placing packed structs in statics should work
static TEST_S4: S4 = S4 { a: 1, b: [2, 3, 4] };
static TEST_S5: S5 = S5 { a: 3, b: 67 };
static TEST_S3_Foo: S3_Foo = S3_Foo { a: 1, b: 2, c: Baz };

pub fn main() {
    assert_eq!(sys::size_of::<S4>(), 4);
    assert_eq!(sys::size_of::<S5>(), 5);
    assert_eq!(sys::size_of::<S13_str>(), 13 + sys::size_of::<~str>());
    assert_eq!(sys::size_of::<S3_Foo>(), 3 + sys::size_of::<Foo>());
    assert_eq!(sys::size_of::<S7_Option>(), 7 + sys::size_of::<Option<@mut f64>>());
}
<|endoftext|>


<commit_before><commit_msg>Commit the example of the doc in an examples<commit_after>extern crate cabot;

use cabot::{RequestBuilder, Client};

fn main() {
    let request = RequestBuilder::new("https://www.rust-lang.org/")
        .build()
        .unwrap();
    let client = Client::new();
    let response = client.execute(&request).unwrap();
    print!("{}", response.body_as_string().unwrap());
}

<|endoftext|>


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

use std::mem::size_of;

pub fn main() {
    let x: [int, ..4] = [1, 2, 3, 4];
    assert_eq!(x[0], 1);
    assert_eq!(x[1], 2);
    assert_eq!(x[2], 3);
    assert_eq!(x[3], 4);

    assert_eq!(size_of::<[u8, ..4]>(), 4u);

    // FIXME #10183
    if cfg!(target_word_size = "64") {
        assert_eq!(size_of::<[u8, ..(1 << 32)]>(), (1u << 32));
    }
}
<commit_msg>fix a failing test<commit_after>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::mem::size_of;

pub fn main() {
    let x: [int, ..4] = [1, 2, 3, 4];
    assert_eq!(x[0], 1);
    assert_eq!(x[1], 2);
    assert_eq!(x[2], 3);
    assert_eq!(x[3], 4);

    assert_eq!(size_of::<[u8, ..4]>(), 4u);

    // FIXME #10183
    // FIXME #18069
    //if cfg!(target_word_size = "64") {
    //    assert_eq!(size_of::<[u8, ..(1 << 32)]>(), (1u << 32));
    //}
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use browser_host::{ServoCefBrowserHost, ServoCefBrowserHostExtensions};
use eutil::Downcast;
use frame::{ServoCefFrame, ServoCefFrameExtensions};
use interfaces::{CefBrowser, CefBrowserHost, CefClient, CefFrame, CefRequestContext};
use interfaces::{cef_browser_t, cef_browser_host_t, cef_client_t, cef_frame_t};
use interfaces::{cef_request_context_t};
use servo::Browser;
use types::{cef_browser_settings_t, cef_string_t, cef_window_info_t, cef_window_handle_t};
use window;

use compositing::windowing::{WindowNavigateMsg, WindowEvent};
use glutin_app;
use libc::c_int;
use std::cell::{Cell, RefCell, BorrowState};
use std::rc::Rc;
use std::sync::atomic::{AtomicIsize, Ordering};

thread_local!(pub static ID_COUNTER: AtomicIsize = AtomicIsize::new(0));
thread_local!(pub static BROWSERS: RefCell<Vec<CefBrowser>> = RefCell::new(vec!()));

pub enum ServoBrowser {
    Invalid,
    OnScreen(Browser),
    OffScreen(Browser),
}

impl ServoBrowser {
    fn handle_event(&mut self, event: WindowEvent) {
        match *self {
            ServoBrowser::OnScreen(ref mut browser) => { browser.handle_events(vec![event]); }
            ServoBrowser::OffScreen(ref mut browser) => { browser.handle_events(vec![event]); }
            ServoBrowser::Invalid => {}
        }
    }

    pub fn get_title_for_main_frame(&self) {
        match *self {
            ServoBrowser::OnScreen(ref browser) => browser.get_title_for_main_frame(),
            ServoBrowser::OffScreen(ref browser) => browser.get_title_for_main_frame(),
            ServoBrowser::Invalid => {}
        }
    }

    pub fn pinch_zoom_level(&self) -> f32 {
        match *self {
            ServoBrowser::OnScreen(ref browser) => browser.pinch_zoom_level(),
            ServoBrowser::OffScreen(ref browser) => browser.pinch_zoom_level(),
            ServoBrowser::Invalid => 1.0,
        }
    }
}

cef_class_impl! {
    ServoCefBrowser : CefBrowser, cef_browser_t {
        fn get_host(&this,) -> *mut cef_browser_host_t {{
            this.downcast().host.clone()
        }}

        fn can_go_back(&this,) -> c_int {{
            this.downcast().back.get() as c_int
        }}

        fn can_go_forward(&this,) -> c_int {{
            this.downcast().forward.get() as c_int
        }}

        fn is_loading(&this,) -> c_int {{
            this.downcast().loading.get() as c_int
        }}

        fn go_back(&this,) -> () {{
            this.send_window_event(WindowEvent::Navigation(WindowNavigateMsg::Back));
        }}

        fn go_forward(&this,) -> () {{
            this.send_window_event(WindowEvent::Navigation(WindowNavigateMsg::Forward));
        }}

        // Returns the main (top-level) frame for the browser window.
        fn get_main_frame(&this,) -> *mut cef_frame_t {{
            this.downcast().frame.clone()
        }}

        fn get_identifier(&this,) -> c_int {{
            this.downcast().id as c_int
        }}
    }
}

pub struct ServoCefBrowser {
    /// A reference to the browser's primary frame.
    pub frame: CefFrame,
    /// A reference to the browser's host.
    pub host: CefBrowserHost,
    /// A reference to the browser client.
    pub client: CefClient,
    /// the glutin window when using windowed rendering
    pub window: Option<Rc<glutin_app::window::Window>>,
    /// Whether the on-created callback has fired yet.
    pub callback_executed: Cell<bool>,
    /// whether the browser can navigate back
    pub back: Cell<bool>,
    /// whether the browser can navigate forward
    pub forward: Cell<bool>,
    /// whether the browser is loading
    pub loading: Cell<bool>,
    /// the display system window handle: only to be used with host.get_window_handle()
    window_handle: cef_window_handle_t,

    id: isize,
    servo_browser: RefCell<ServoBrowser>,
    message_queue: RefCell<Vec<WindowEvent>>,
}

impl ServoCefBrowser {
    pub fn new(window_info: &cef_window_info_t, client: CefClient) -> ServoCefBrowser {
        let frame = ServoCefFrame::new().as_cef_interface();
        let host = ServoCefBrowserHost::new(client.clone()).as_cef_interface();
        let mut window_handle: cef_window_handle_t = get_null_window_handle();
        let mut glutin_window: Option<Rc<glutin_app::window::Window>> = None;

        let servo_browser = if window_info.windowless_rendering_enabled == 0 {
            glutin_window = Some(glutin_app::create_window(window_info.parent_window as glutin_app::WindowID));
            let servo_browser = Browser::new(glutin_window.clone());
            window_handle = match glutin_window {
                Some(ref win) => win.platform_window() as cef_window_handle_t,
                None => get_null_window_handle()
            };
            ServoBrowser::OnScreen(servo_browser)
        } else {
            ServoBrowser::Invalid
        };

        let id = ID_COUNTER.with(|counter| {
            counter.fetch_add(1, Ordering::SeqCst)
        });

        ServoCefBrowser {
            frame: frame,
            host: host,
            client: client,
            window: glutin_window,
            callback_executed: Cell::new(false),
            servo_browser: RefCell::new(servo_browser),
            message_queue: RefCell::new(vec!()),
            id: id,
            back: Cell::new(false),
            forward: Cell::new(false),
            loading: Cell::new(false),
            window_handle: window_handle,
        }
    }
}

pub trait ServoCefBrowserExtensions {
    fn init(&self, window_info: &cef_window_info_t);
    fn send_window_event(&self, event: WindowEvent);
    fn get_title_for_main_frame(&self);
    fn pinch_zoom_level(&self) -> f32;
}

impl ServoCefBrowserExtensions for CefBrowser {
    fn init(&self, window_info: &cef_window_info_t) {
        if window_info.windowless_rendering_enabled != 0 {
            let window = window::Window::new(window_info.width, window_info.height);
            window.set_browser(self.clone());
            let servo_browser = Browser::new(Some(window.clone()));
            *self.downcast().servo_browser.borrow_mut() = ServoBrowser::OffScreen(servo_browser);
        }

        self.downcast().host.set_browser((*self).clone());
        self.downcast().frame.set_browser((*self).clone());
        if window_info.windowless_rendering_enabled == 0 {
            self.downcast().host.initialize_compositing();
        }
    }

    fn send_window_event(&self, event: WindowEvent) {
        self.downcast().message_queue.borrow_mut().push(event);

        loop {
            match self.downcast().servo_browser.borrow_state() {
                BorrowState::Unused => {
                    let event = match self.downcast().message_queue.borrow_mut().pop() {
                        None => return,
                        Some(event) => event,
                    };
                    self.downcast().servo_browser.borrow_mut().handle_event(event);
                }
                _ => {
                    // We're trying to send an event while processing another one. This will
                    // cause general badness, so queue up that event instead of immediately
                    // processing it.
                    break
                }
            }
        }
    }

    fn get_title_for_main_frame(&self) {
        self.downcast().servo_browser.borrow().get_title_for_main_frame()
    }

    fn pinch_zoom_level(&self) -> f32 {
        self.downcast().servo_browser.borrow().pinch_zoom_level()
    }
}

#[cfg(target_os="macos")]
pub fn get_null_window_handle() -> cef_window_handle_t {
    ptr::null_mut()
}
#[cfg(target_os="linux")]
pub fn get_null_window_handle() -> cef_window_handle_t {
    0
}

pub fn update() {
    BROWSERS.with(|browsers| {
        for browser in browsers.borrow().iter() {
            if browser.downcast().callback_executed.get() == false {
                browser_callback_after_created(browser.clone());
            }
            let mut events = match browser.downcast().window {
                Some(ref win) => win.wait_events(),
                None => vec![WindowEvent::Idle]
            };
            loop {
               match events.pop() {
                   Some(event) => browser.send_window_event(event),
                   None => break
               }
            }
        }
    });
}

pub fn close(browser: CefBrowser) {
    BROWSERS.with(|browsers| {
        let mut browsers = browsers.borrow_mut();
        browsers.iter()
                .position(|&ref n| n.downcast().id == browser.downcast().id)
                .map(|e| browsers.remove(e));
    });
}

pub fn get_window(browser: &CefBrowser) -> cef_window_handle_t {
    browser.downcast().window_handle
}

pub fn browser_callback_after_created(browser: CefBrowser) {
    if browser.downcast().client.is_null_cef_object() {
        return
    }
    let client = browser.downcast().client.clone();
    let life_span_handler = client.get_life_span_handler();
    if life_span_handler.is_not_null_cef_object() {
        life_span_handler.on_after_created(browser.clone());
    }
    browser.downcast().callback_executed.set(true);
}

fn browser_host_create(window_info: &cef_window_info_t,
                       client: CefClient,
                       url: *const cef_string_t,
                       callback_executed: bool)
                       -> CefBrowser {
    let browser = ServoCefBrowser::new(window_info, client).as_cef_interface();
    browser.init(window_info);
    if callback_executed {
        browser_callback_after_created(browser.clone());
    }
    //if url != ptr::null() {
       //unsafe { browser.downcast().frame.load_url(CefWrap::to_rust(url)); }
    //}
    BROWSERS.with(|browsers| {
        browsers.borrow_mut().push(browser.clone());
    });
    browser
}

cef_static_method_impls! {
    fn cef_browser_host_create_browser(window_info: *const cef_window_info_t,
                                       client: *mut cef_client_t,
                                       url: *const cef_string_t,
                                       _browser_settings: *const cef_browser_settings_t,
                                       _request_context: *mut cef_request_context_t)
                                       -> c_int {{
        let client: CefClient = client;
        let _browser_settings: &cef_browser_settings_t = _browser_settings;
        let _request_context: CefRequestContext = _request_context;
        browser_host_create(window_info, client, url, false);
        1i32
    }}
    fn cef_browser_host_create_browser_sync(window_info: *const cef_window_info_t,
                                            client: *mut cef_client_t,
                                            url: *const cef_string_t,
                                            _browser_settings: *const cef_browser_settings_t,
                                            _request_context: *mut cef_request_context_t)
                                            -> *mut cef_browser_t {{
        let client: CefClient = client;
        let _browser_settings: &cef_browser_settings_t = _browser_settings;
        let _request_context: CefRequestContext = _request_context;
        browser_host_create(window_info, client, url, true)
    }}
}
<commit_msg>force resize after sending cef_browser::on_after_created() callback<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use browser_host::{ServoCefBrowserHost, ServoCefBrowserHostExtensions};
use eutil::Downcast;
use frame::{ServoCefFrame, ServoCefFrameExtensions};
use interfaces::{CefBrowser, CefBrowserHost, CefClient, CefFrame, CefRequestContext};
use interfaces::{cef_browser_t, cef_browser_host_t, cef_client_t, cef_frame_t};
use interfaces::{cef_request_context_t};
use servo::Browser;
use types::{cef_browser_settings_t, cef_string_t, cef_window_info_t, cef_window_handle_t};
use window;

use compositing::windowing::{WindowNavigateMsg, WindowEvent};
use glutin_app;
use libc::c_int;
use std::cell::{Cell, RefCell, BorrowState};
use std::rc::Rc;
use std::sync::atomic::{AtomicIsize, Ordering};

thread_local!(pub static ID_COUNTER: AtomicIsize = AtomicIsize::new(0));
thread_local!(pub static BROWSERS: RefCell<Vec<CefBrowser>> = RefCell::new(vec!()));

pub enum ServoBrowser {
    Invalid,
    OnScreen(Browser),
    OffScreen(Browser),
}

impl ServoBrowser {
    fn handle_event(&mut self, event: WindowEvent) {
        match *self {
            ServoBrowser::OnScreen(ref mut browser) => { browser.handle_events(vec![event]); }
            ServoBrowser::OffScreen(ref mut browser) => { browser.handle_events(vec![event]); }
            ServoBrowser::Invalid => {}
        }
    }

    pub fn get_title_for_main_frame(&self) {
        match *self {
            ServoBrowser::OnScreen(ref browser) => browser.get_title_for_main_frame(),
            ServoBrowser::OffScreen(ref browser) => browser.get_title_for_main_frame(),
            ServoBrowser::Invalid => {}
        }
    }

    pub fn pinch_zoom_level(&self) -> f32 {
        match *self {
            ServoBrowser::OnScreen(ref browser) => browser.pinch_zoom_level(),
            ServoBrowser::OffScreen(ref browser) => browser.pinch_zoom_level(),
            ServoBrowser::Invalid => 1.0,
        }
    }
}

cef_class_impl! {
    ServoCefBrowser : CefBrowser, cef_browser_t {
        fn get_host(&this,) -> *mut cef_browser_host_t {{
            this.downcast().host.clone()
        }}

        fn can_go_back(&this,) -> c_int {{
            this.downcast().back.get() as c_int
        }}

        fn can_go_forward(&this,) -> c_int {{
            this.downcast().forward.get() as c_int
        }}

        fn is_loading(&this,) -> c_int {{
            this.downcast().loading.get() as c_int
        }}

        fn go_back(&this,) -> () {{
            this.send_window_event(WindowEvent::Navigation(WindowNavigateMsg::Back));
        }}

        fn go_forward(&this,) -> () {{
            this.send_window_event(WindowEvent::Navigation(WindowNavigateMsg::Forward));
        }}

        // Returns the main (top-level) frame for the browser window.
        fn get_main_frame(&this,) -> *mut cef_frame_t {{
            this.downcast().frame.clone()
        }}

        fn get_identifier(&this,) -> c_int {{
            this.downcast().id as c_int
        }}
    }
}

pub struct ServoCefBrowser {
    /// A reference to the browser's primary frame.
    pub frame: CefFrame,
    /// A reference to the browser's host.
    pub host: CefBrowserHost,
    /// A reference to the browser client.
    pub client: CefClient,
    /// the glutin window when using windowed rendering
    pub window: Option<Rc<glutin_app::window::Window>>,
    /// Whether the on-created callback has fired yet.
    pub callback_executed: Cell<bool>,
    /// whether the browser can navigate back
    pub back: Cell<bool>,
    /// whether the browser can navigate forward
    pub forward: Cell<bool>,
    /// whether the browser is loading
    pub loading: Cell<bool>,
    /// the display system window handle: only to be used with host.get_window_handle()
    window_handle: cef_window_handle_t,

    id: isize,
    servo_browser: RefCell<ServoBrowser>,
    message_queue: RefCell<Vec<WindowEvent>>,
}

impl ServoCefBrowser {
    pub fn new(window_info: &cef_window_info_t, client: CefClient) -> ServoCefBrowser {
        let frame = ServoCefFrame::new().as_cef_interface();
        let host = ServoCefBrowserHost::new(client.clone()).as_cef_interface();
        let mut window_handle: cef_window_handle_t = get_null_window_handle();
        let mut glutin_window: Option<Rc<glutin_app::window::Window>> = None;

        let servo_browser = if window_info.windowless_rendering_enabled == 0 {
            glutin_window = Some(glutin_app::create_window(window_info.parent_window as glutin_app::WindowID));
            let servo_browser = Browser::new(glutin_window.clone());
            window_handle = match glutin_window {
                Some(ref win) => win.platform_window() as cef_window_handle_t,
                None => get_null_window_handle()
            };
            ServoBrowser::OnScreen(servo_browser)
        } else {
            ServoBrowser::Invalid
        };

        let id = ID_COUNTER.with(|counter| {
            counter.fetch_add(1, Ordering::SeqCst)
        });

        ServoCefBrowser {
            frame: frame,
            host: host,
            client: client,
            window: glutin_window,
            callback_executed: Cell::new(false),
            servo_browser: RefCell::new(servo_browser),
            message_queue: RefCell::new(vec!()),
            id: id,
            back: Cell::new(false),
            forward: Cell::new(false),
            loading: Cell::new(false),
            window_handle: window_handle,
        }
    }
}

pub trait ServoCefBrowserExtensions {
    fn init(&self, window_info: &cef_window_info_t);
    fn send_window_event(&self, event: WindowEvent);
    fn get_title_for_main_frame(&self);
    fn pinch_zoom_level(&self) -> f32;
}

impl ServoCefBrowserExtensions for CefBrowser {
    fn init(&self, window_info: &cef_window_info_t) {
        if window_info.windowless_rendering_enabled != 0 {
            let window = window::Window::new(window_info.width, window_info.height);
            window.set_browser(self.clone());
            let servo_browser = Browser::new(Some(window.clone()));
            *self.downcast().servo_browser.borrow_mut() = ServoBrowser::OffScreen(servo_browser);
        }

        self.downcast().host.set_browser((*self).clone());
        self.downcast().frame.set_browser((*self).clone());
        if window_info.windowless_rendering_enabled == 0 {
            self.downcast().host.initialize_compositing();
        }
    }

    fn send_window_event(&self, event: WindowEvent) {
        self.downcast().message_queue.borrow_mut().push(event);

        loop {
            match self.downcast().servo_browser.borrow_state() {
                BorrowState::Unused => {
                    let event = match self.downcast().message_queue.borrow_mut().pop() {
                        None => return,
                        Some(event) => event,
                    };
                    self.downcast().servo_browser.borrow_mut().handle_event(event);
                }
                _ => {
                    // We're trying to send an event while processing another one. This will
                    // cause general badness, so queue up that event instead of immediately
                    // processing it.
                    break
                }
            }
        }
    }

    fn get_title_for_main_frame(&self) {
        self.downcast().servo_browser.borrow().get_title_for_main_frame()
    }

    fn pinch_zoom_level(&self) -> f32 {
        self.downcast().servo_browser.borrow().pinch_zoom_level()
    }
}

#[cfg(target_os="macos")]
pub fn get_null_window_handle() -> cef_window_handle_t {
    ptr::null_mut()
}
#[cfg(target_os="linux")]
pub fn get_null_window_handle() -> cef_window_handle_t {
    0
}

pub fn update() {
    BROWSERS.with(|browsers| {
        for browser in browsers.borrow().iter() {
            if browser.downcast().callback_executed.get() == false {
                browser_callback_after_created(browser.clone());
            }
            let mut events = match browser.downcast().window {
                Some(ref win) => win.wait_events(),
                None => vec![WindowEvent::Idle]
            };
            loop {
               match events.pop() {
                   Some(event) => browser.send_window_event(event),
                   None => break
               }
            }
        }
    });
}

pub fn close(browser: CefBrowser) {
    BROWSERS.with(|browsers| {
        let mut browsers = browsers.borrow_mut();
        browsers.iter()
                .position(|&ref n| n.downcast().id == browser.downcast().id)
                .map(|e| browsers.remove(e));
    });
}

pub fn get_window(browser: &CefBrowser) -> cef_window_handle_t {
    browser.downcast().window_handle
}

pub fn browser_callback_after_created(browser: CefBrowser) {
    if browser.downcast().client.is_null_cef_object() {
        return
    }
    let client = browser.downcast().client.clone();
    let life_span_handler = client.get_life_span_handler();
    if life_span_handler.is_not_null_cef_object() {
        life_span_handler.on_after_created(browser.clone());
    }
    browser.downcast().callback_executed.set(true);
    browser.downcast().host.was_resized();
}

fn browser_host_create(window_info: &cef_window_info_t,
                       client: CefClient,
                       url: *const cef_string_t,
                       callback_executed: bool)
                       -> CefBrowser {
    let browser = ServoCefBrowser::new(window_info, client).as_cef_interface();
    browser.init(window_info);
    if callback_executed {
        browser_callback_after_created(browser.clone());
    }
    //if url != ptr::null() {
       //unsafe { browser.downcast().frame.load_url(CefWrap::to_rust(url)); }
    //}
    BROWSERS.with(|browsers| {
        browsers.borrow_mut().push(browser.clone());
    });
    browser
}

cef_static_method_impls! {
    fn cef_browser_host_create_browser(window_info: *const cef_window_info_t,
                                       client: *mut cef_client_t,
                                       url: *const cef_string_t,
                                       _browser_settings: *const cef_browser_settings_t,
                                       _request_context: *mut cef_request_context_t)
                                       -> c_int {{
        let client: CefClient = client;
        let _browser_settings: &cef_browser_settings_t = _browser_settings;
        let _request_context: CefRequestContext = _request_context;
        browser_host_create(window_info, client, url, false);
        1i32
    }}
    fn cef_browser_host_create_browser_sync(window_info: *const cef_window_info_t,
                                            client: *mut cef_client_t,
                                            url: *const cef_string_t,
                                            _browser_settings: *const cef_browser_settings_t,
                                            _request_context: *mut cef_request_context_t)
                                            -> *mut cef_browser_t {{
        let client: CefClient = client;
        let _browser_settings: &cef_browser_settings_t = _browser_settings;
        let _request_context: CefRequestContext = _request_context;
        browser_host_create(window_info, client, url, true)
    }}
}
<|endoftext|>


<commit_before><commit_msg>Only show calling points for now.<commit_after><|endoftext|>


<commit_before><commit_msg>Log latencies at debug.<commit_after><|endoftext|>


<commit_before><commit_msg>for demo<commit_after><|endoftext|>


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

#[feature(managed_boxes)];

use std::cell::RefCell;

// Regresion test for issue 7364
static managed: @RefCell<int> = @RefCell::new(0);
//~^ ERROR static items are not allowed to have managed pointers

fn main() { }
<|endoftext|>


<commit_before><commit_msg> removed filter for testing<commit_after><|endoftext|>


<commit_before><commit_msg>an empy message<commit_after><|endoftext|>


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

#[start]
fn start(argc: int, argv: **u8, crate_map: *u8) -> int {
    //~^ ERROR start function expects type: `fn(int, **u8) -> int`
    0
}
<|endoftext|>


<commit_before><commit_msg>Add a regression test for #80772<commit_after>// check-pass

trait SomeTrait {}

pub struct Exhibit {
    constant: usize,
    factory: fn(&usize) -> Box<dyn SomeTrait>,
}

pub const A_CONSTANT: &[Exhibit] = &[
    Exhibit {
        constant: 1,
        factory: |_| unimplemented!(),
    },
    Exhibit {
        constant: "Hello world".len(),
        factory: |_| unimplemented!(),
    },
];

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Update (7 kyu) Complementary DNA.rs<commit_after><|endoftext|>


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

extern crate sync;

use std::task;
use sync::MutexArc;

fn test_mutex_arc_nested() {
    let arc = ~MutexArc::new(1);
    let arc2 = ~MutexArc::new(*arc);

    task::spawn(proc() {
        (*arc2).access(|mutex| { //~ ERROR instantiating a type parameter with an incompatible type
        })
    });
}

fn main() {}
<commit_msg>Remove the compile-fail test that's now obsolete<commit_after><|endoftext|>


<commit_before>// ignore-fast

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

#[feature(managed_boxes)];

extern crate collections;

use collections::list::{List, Cons, Nil};

fn pure_length_go<T>(ls: &List<T>, acc: uint) -> uint {
    match *ls { Nil => { acc } Cons(_, ref tl) => { pure_length_go(&**tl, acc + 1u) } }
}

fn pure_length<T>(ls: &List<T>) -> uint { pure_length_go(ls, 0u) }

fn nonempty_list<T>(ls: &List<T>) -> bool { pure_length(ls) > 0u }

fn safe_head<T:Clone>(ls: &List<T>) -> T {
    assert!(!ls.is_empty());
    return ls.head().unwrap().clone();
}

pub fn main() {
    let mylist = Cons(1u, ~Nil);
    assert!((nonempty_list(&mylist)));
    assert_eq!(safe_head(&mylist), 1u);
}
<commit_msg>test: remove pure test, which is now redundant with inline tests<commit_after><|endoftext|>