<commit_before>//! Adapts the `solicit`-provided HTTP/2 implementation into the `HttpMessage` API.

use std::io::{self, Write, Read, Cursor};
use std::net::Shutdown;
use std::ascii::AsciiExt;
use std::mem;
use std::time::Duration;

use http::{
    Protocol,
    HttpMessage,
    RequestHead,
    ResponseHead,
    RawStatus,
};
use net::{NetworkStream, NetworkConnector};
use net::{HttpConnector, HttpStream};
use url::Position as UrlPosition;
use header::Headers;

use header;
use version;

use solicit::http::Header as Http2Header;
use solicit::http::HttpScheme;
use solicit::http::HttpError as Http2Error;
use solicit::http::transport::TransportStream;
use solicit::http::client::{ClientStream, HttpConnect, HttpConnectError, write_preface};
use solicit::client::SimpleClient;

use httparse;

/// A trait alias representing all types that are both `NetworkStream` and `Clone`.
pub trait CloneableStream: NetworkStream + Clone {}
impl<S: NetworkStream + Clone> CloneableStream for S {}

/// A newtype wrapping any `CloneableStream` in order to provide an implementation of a
/// `TransportSream` trait for all types that are a `CloneableStream`.
#[derive(Clone)]
struct Http2Stream<S: CloneableStream>(S);

impl<S> Write for Http2Stream<S> where S: CloneableStream {
    #[inline]
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.0.write(buf)
    }
    #[inline]
    fn flush(&mut self) -> io::Result<()> {
        self.0.flush()
    }
}

impl<S> Read for Http2Stream<S> where S: CloneableStream {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.0.read(buf)
    }
}

impl<S> TransportStream for Http2Stream<S> where S: CloneableStream {
    fn try_split(&self) -> Result<Http2Stream<S>, io::Error> {
        Ok(self.clone())
    }

    fn close(&mut self) -> Result<(), io::Error> {
        self.0.close(Shutdown::Both)
    }
}

/// A helper struct that implements the `HttpConnect` trait from the `solicit` crate.
///
/// This is used by the `Http2Protocol` when it needs to create a new `SimpleClient`.
struct Http2Connector<S> where S: CloneableStream {
    stream: S,
    scheme: HttpScheme,
    host: String,
}

#[derive(Debug)]
struct Http2ConnectError(io::Error);

impl ::std::fmt::Display for Http2ConnectError {
    fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        write!(fmt, "HTTP/2 connect error: {}", (self as &::std::error::Error).description())
    }
}

impl ::std::error::Error for Http2ConnectError {
    fn description(&self) -> &str {
        self.0.description()
    }

    fn cause(&self) -> Option<&::std::error::Error> {
        self.0.cause()
    }
}

impl HttpConnectError for Http2ConnectError {}

impl From<io::Error> for Http2ConnectError {
    fn from(e: io::Error) -> Http2ConnectError { Http2ConnectError(e) }
}

impl<S> HttpConnect for Http2Connector<S> where S: CloneableStream {
    /// The type of the underlying transport stream that the `HttpConnection`s
    /// produced by this `HttpConnect` implementation will be based on.
    type Stream = Http2Stream<S>;
    /// The type of the error that can be produced by trying to establish the
    /// connection (i.e. calling the `connect` method).
    type Err = Http2ConnectError;

    /// Establishes a network connection that can be used by HTTP/2 connections.
    fn connect(mut self) -> Result<ClientStream<Self::Stream>, Self::Err> {
        try!(write_preface(&mut self.stream));
        Ok(ClientStream(Http2Stream(self.stream), self.scheme, self.host))
    }
}

/// The `Protocol` implementation that provides HTTP/2 messages (i.e. `Http2Message`).
pub struct Http2Protocol<C, S> where C: NetworkConnector<Stream=S> + Send + 'static,
                                 S: NetworkStream + Send + Clone {
    connector: C,
}

impl<C, S> Http2Protocol<C, S> where C: NetworkConnector<Stream=S> + Send + 'static,
                                     S: NetworkStream + Send + Clone {
    /// Create a new `Http2Protocol` that will use the given `NetworkConnector` to establish TCP
    /// connections to the server.
    pub fn with_connector(connector: C) -> Http2Protocol<C, S> {
        Http2Protocol {
            connector: connector,
        }
    }

    /// A private helper method that creates a new `SimpleClient` that will use the given
    /// `NetworkStream` to communicate to the remote host.
    fn new_client(&self, stream: S, host: String, scheme: HttpScheme)
            -> ::Result<SimpleClient<Http2Stream<S>>> {
        Ok(try!(SimpleClient::with_connector(Http2Connector {
            stream: stream,
            scheme: scheme,
            host: host,
        })))
    }
}

impl<C, S> Protocol for Http2Protocol<C, S> where C: NetworkConnector<Stream=S> + Send + 'static,
                                                  S: NetworkStream + Send + Clone {
    fn new_message(&self, host: &str, port: u16, scheme: &str) -> ::Result<Box<HttpMessage>> {
        let stream = try!(self.connector.connect(host, port, scheme)).into();

        let scheme = match scheme {
            "http" => HttpScheme::Http,
            "https" => HttpScheme::Https,
            _ => return Err(From::from(Http2Error::from(
                        io::Error::new(io::ErrorKind::Other, "Invalid scheme")))),
        };
        let client = try!(self.new_client(stream, host.into(), scheme));

        Ok(Box::new(Http2Message::with_client(client)))
    }
}

/// Represents an HTTP/2 request, described by a `RequestHead` and the body of the request.
/// A convenience struct only in use by the `Http2Message`.
#[derive(Clone, Debug)]
struct Http2Request {
    head: RequestHead,
    body: Vec<u8>,
}

/// Represents an HTTP/2 response.
/// A convenience struct only in use by the `Http2Message`.
#[derive(Clone, Debug)]
struct Http2Response {
    body: Cursor<Vec<u8>>,
}

/// The enum tracks the state of the `Http2Message`.
enum MessageState {
    /// State corresponding to no message being set to outgoing yet.
    Idle,
    /// State corresponding to an outgoing message being written out.
    Writing(Http2Request),
    /// State corresponding to an incoming message being read.
    Reading(Http2Response),
}

impl MessageState {
    fn take_request(&mut self) -> Option<Http2Request> {
        match *self {
            MessageState::Idle | MessageState::Reading(_) => return None,
            MessageState::Writing(_) => {},
        }
        let old = mem::replace(self, MessageState::Idle);

        match old {
            // These states are effectively unreachable since we already know the state
            MessageState::Idle | MessageState::Reading(_) => None,
            MessageState::Writing(req) => Some(req),
        }
    }
}

/// An implementation of the `HttpMessage` trait for HTTP/2.
///
/// Relies on the `solicit::http::SimpleClient` for HTTP/2 communication. Adapts both outgoing and
/// incoming messages to the API that `hyper` expects in order to be able to use the message in
/// the `hyper::client` module.
pub struct Http2Message<S> where S: CloneableStream {
    client: SimpleClient<Http2Stream<S>>,
    state: MessageState,
}

impl<S> ::std::fmt::Debug for Http2Message<S> where S: CloneableStream {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> {
        write!(f, "<Http2Message>")
    }
}

impl<S> Http2Message<S> where S: CloneableStream {
    /// Helper method that creates a new completely fresh `Http2Message`, which will use the given
    /// `SimpleClient` for its HTTP/2 communication.
    fn with_client(client: SimpleClient<Http2Stream<S>>) -> Http2Message<S> {
        Http2Message {
            client: client,
            state: MessageState::Idle,
        }
    }
}

impl<S> Write for Http2Message<S> where S: CloneableStream {
    #[inline]
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        if let MessageState::Writing(ref mut req) = self.state {
            req.body.write(buf)
        } else {
            Err(io::Error::new(io::ErrorKind::Other,
                               "Not in a writable state"))
        }
    }
    #[inline]
    fn flush(&mut self) -> io::Result<()> {
        if let MessageState::Writing(ref mut req) = self.state {
            req.body.flush()
        } else {
            Err(io::Error::new(io::ErrorKind::Other,
                               "Not in a writable state"))
        }
    }
}

impl<S> Read for Http2Message<S> where S: CloneableStream {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if let MessageState::Reading(ref mut res) = self.state {
            res.body.read(buf)
        } else {
            Err(io::Error::new(io::ErrorKind::Other,
                               "Not in a readable state"))
        }
    }
}

/// A helper function that prepares the headers that should be sent in an HTTP/2 message.
///
/// Adapts the `Headers` into a list of octet string pairs.
fn prepare_headers(mut headers: Headers) -> Vec<Http2Header> {
    if headers.remove::<header::Connection>() {
        warn!("The `Connection` header is not valid for an HTTP/2 connection.");
    }
    let mut http2_headers: Vec<_> = headers.iter().filter_map(|h| {
        if h.is::<header::SetCookie>() {
            None
        } else {
            // HTTP/2 header names MUST be lowercase.
            Some((h.name().to_ascii_lowercase().into_bytes(), h.value_string().into_bytes()))
        }
    }).collect();

    // Now separately add the cookies, as `hyper` considers `Set-Cookie` to be only a single
    // header, even in the face of multiple cookies being set.
    if let Some(set_cookie) = headers.get::<header::SetCookie>() {
        for cookie in set_cookie.iter() {
            http2_headers.push((b"set-cookie".to_vec(), cookie.to_string().into_bytes()));
        }
    }

    http2_headers
}

/// A helper function that prepares the body for sending in an HTTP/2 request.
#[inline]
fn prepare_body(body: Vec<u8>) -> Option<Vec<u8>> {
    if body.is_empty() {
        None
    } else {
        Some(body)
    }
}

/// Parses a set of HTTP/2 headers into a `hyper::header::Headers` struct.
fn parse_headers(http2_headers: Vec<Http2Header>) -> ::Result<Headers> {
    // Adapt the header name from `Vec<u8>` to `String`, without making any copies.
    let mut headers = Vec::new();
    for (name, value) in http2_headers.into_iter() {
        let name = match String::from_utf8(name) {
            Ok(name) => name,
            Err(_) => return Err(From::from(Http2Error::MalformedResponse)),
        };
        headers.push((name, value));
    }

    let mut raw_headers = Vec::new();
    for &(ref name, ref value) in &headers {
        raw_headers.push(httparse::Header { name: &name, value: &value });
    }

    Headers::from_raw(&raw_headers)
}

/// Parses the response, as returned by `solicit`, into a `ResponseHead` and the full response
/// body.
///
/// Returns them as a two-tuple.
fn parse_response(response: ::solicit::http::Response) -> ::Result<(ResponseHead, Vec<u8>)> {
    let status = try!(response.status_code());
    let headers = try!(parse_headers(response.headers));
    Ok((ResponseHead {
        headers: headers,
        raw_status: RawStatus(status, "".into()),
        version: version::HttpVersion::Http20,
    }, response.body))
}

impl<S> HttpMessage for Http2Message<S> where S: CloneableStream {
    fn set_outgoing(&mut self, head: RequestHead) -> ::Result<RequestHead> {
        match self.state {
            MessageState::Writing(_) | MessageState::Reading(_) => {
                return Err(From::from(Http2Error::from(
                            io::Error::new(io::ErrorKind::Other,
                                           "An outoging has already been set"))));
            },
            MessageState::Idle => {},
        };
        self.state = MessageState::Writing(Http2Request {
            head: head.clone(),
            body: Vec::new(),
        });

        Ok(head)
    }

    fn get_incoming(&mut self) -> ::Result<ResponseHead> {
        // Prepare the request so that it can be passed off to the HTTP/2 client.
        let request = match self.state.take_request() {
            None => {
                return Err(From::from(Http2Error::from(
                            io::Error::new(io::ErrorKind::Other,
                                           "No request in progress"))));
            },
            Some(req) => req,
        };
        let (RequestHead { headers, method, url }, body) = (request.head, request.body);

        let method = method.as_ref().as_bytes();
        let path = url[UrlPosition::BeforePath..UrlPosition::AfterQuery].as_bytes();
        let extra_headers = prepare_headers(headers);
        let body = prepare_body(body);

        // Finally, everything is ready and we issue the request.
        let stream_id = try!(self.client.request(method, &path, &extra_headers, body));

        // Wait for the response
        let resp = try!(self.client.get_response(stream_id));

        // Now that the response is back, adapt it to the structs that hyper expects/provides.
        let (head, body) = try!(parse_response(resp));

        // For now, since `solicit` has already read the full response, we just wrap the body into
        // a `Cursor` to allow for the public interface to support `io::Read`.
        let body = Cursor::new(body);

        // The body is saved so that it can be read out from the message.
        self.state = MessageState::Reading(Http2Response {
            body: body,
        });

        Ok(head)
    }

    fn has_body(&self) -> bool {
        true
    }

    #[inline]
    fn set_read_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
        Ok(())
    }

    #[inline]
    fn set_write_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
        Ok(())
    }

    #[inline]
    fn close_connection(&mut self) -> ::Result<()> {
        Ok(())
    }
}

/// A convenience method that creates a default `Http2Protocol` that uses a `net::HttpConnector`
/// (which produces an `HttpStream` for the underlying transport layer).
#[inline]
pub fn new_protocol() -> Http2Protocol<HttpConnector, HttpStream> {
    Http2Protocol::with_connector(HttpConnector)
}

#[cfg(test)]
mod tests {
    use super::{Http2Protocol, prepare_headers, parse_headers, parse_response};

    use std::io::{Read};

    use mock::{MockHttp2Connector, MockStream};
    use http::{RequestHead, ResponseHead, Protocol};

    use header::Headers;
    use header;
    use Url;
    use method;
    use cookie;
    use version;

    use solicit::http::connection::{HttpFrame, ReceiveFrame};

    /// Tests that the `Http2Message` correctly reads a response with no body.
    #[test]
    fn test_http2_response_no_body() {
        let mut mock_connector = MockHttp2Connector::new();
        mock_connector.new_response_stream(b"200", &Headers::new(), None);
        let protocol = Http2Protocol::with_connector(mock_connector);

        let mut message = protocol.new_message("127.0.0.1", 1337, "http").unwrap();
        message.set_outgoing(RequestHead {
            headers: Headers::new(),
            method: method::Method::Get,
            url: Url::parse("http://127.0.0.1/hello").unwrap(),
        }).unwrap();
        let resp = message.get_incoming().unwrap();

        assert_eq!(resp.raw_status.0, 200);
        let mut body = Vec::new();
        message.read_to_end(&mut body).unwrap();
        assert_eq!(body.len(), 0);
    }

    /// Tests that the `Http2Message` correctly reads a response with a body.
    #[test]
    fn test_http2_response_with_body() {
        let mut mock_connector = MockHttp2Connector::new();
        mock_connector.new_response_stream(b"200", &Headers::new(), Some(vec![1, 2, 3]));
        let protocol = Http2Protocol::with_connector(mock_connector);

        let mut message = protocol.new_message("127.0.0.1", 1337, "http").unwrap();
        message.set_outgoing(RequestHead {
            headers: Headers::new(),
            method: method::Method::Get,
            url: Url::parse("http://127.0.0.1/hello").unwrap(),
        }).unwrap();
        let resp = message.get_incoming().unwrap();

        assert_eq!(resp.raw_status.0, 200);
        let mut body = Vec::new();
        message.read_to_end(&mut body).unwrap();
        assert_eq!(vec![1, 2, 3], body);
    }

    /// Tests that the `Http2Message` correctly reads a response with an empty body.
    #[test]
    fn test_http2_response_empty_body() {
        let mut mock_connector = MockHttp2Connector::new();
        mock_connector.new_response_stream(b"200", &Headers::new(), Some(vec![]));
        let protocol = Http2Protocol::with_connector(mock_connector);

        let mut message = protocol.new_message("127.0.0.1", 1337, "http").unwrap();
        message.set_outgoing(RequestHead {
            headers: Headers::new(),
            method: method::Method::Get,
            url: Url::parse("http://127.0.0.1/hello").unwrap(),
        }).unwrap();
        let resp = message.get_incoming().unwrap();

        assert_eq!(resp.raw_status.0, 200);
        let mut body = Vec::new();
        message.read_to_end(&mut body).unwrap();
        assert_eq!(Vec::<u8>::new(), body);
    }

    /// Tests that the `Http2Message` correctly parses out the headers into the `ResponseHead`.
    #[test]
    fn test_http2_response_headers() {
        let mut mock_connector = MockHttp2Connector::new();
        let mut headers = Headers::new();
        headers.set(header::ContentLength(3));
        headers.set(header::ETag(header::EntityTag::new(true, "tag".into())));
        mock_connector.new_response_stream(b"200", &headers, Some(vec![1, 2, 3]));
        let protocol = Http2Protocol::with_connector(mock_connector);

        let mut message = protocol.new_message("127.0.0.1", 1337, "http").unwrap();
        message.set_outgoing(RequestHead {
            headers: Headers::new(),
            method: method::Method::Get,
            url: Url::parse("http://127.0.0.1/hello").unwrap(),
        }).unwrap();
        let resp = message.get_incoming().unwrap();

        assert_eq!(resp.raw_status.0, 200);
        assert!(resp.headers.has::<header::ContentLength>());
        let &header::ContentLength(len) = resp.headers.get::<header::ContentLength>().unwrap();
        assert_eq!(3, len);
        assert!(resp.headers.has::<header::ETag>());
        let &header::ETag(ref tag) = resp.headers.get::<header::ETag>().unwrap();
        assert_eq!(tag.tag(), "tag");
    }

    /// Tests that an error is returned when the `Http2Message` is not in a readable state.
    #[test]
    fn test_http2_message_not_readable() {
        let mut mock_connector = MockHttp2Connector::new();
        mock_connector.new_response_stream(b"200", &Headers::new(), None);
        let protocol = Http2Protocol::with_connector(mock_connector);

        let mut message = protocol.new_message("127.0.0.1", 1337, "http").unwrap();

        // No outgoing set yet, so nothing can be read at this point.
        assert!(message.read(&mut [0; 5]).is_err());
    }

    /// Tests that an error is returned when the `Http2Message` is not in a writable state.
    #[test]
    fn test_http2_message_not_writable() {
        let mut mock_connector = MockHttp2Connector::new();
        mock_connector.new_response_stream(b"200", &Headers::new(), None);
        let protocol = Http2Protocol::with_connector(mock_connector);

        let mut message = protocol.new_message("127.0.0.1", 1337, "http").unwrap();
        message.set_outgoing(RequestHead {
            headers: Headers::new(),
            method: method::Method::Get,
            url: Url::parse("http://127.0.0.1/hello").unwrap(),
        }).unwrap();
        let _ = message.get_incoming().unwrap();
        // Writes are invalid now
        assert!(message.write(&[1]).is_err());
    }

    /// Asserts that the given stream contains the full expected client preface: the preface bytes,
    /// settings frame, and settings ack frame.
    fn assert_client_preface(server_stream: &mut MockStream) {
        // Skip client preface
        server_stream.read(&mut [0; 24]).unwrap();
        // The first frame are the settings
        assert!(match server_stream.recv_frame().unwrap() {
            HttpFrame::SettingsFrame(_) => true,
            _ => false,
        });
        // Now the ACK to the server's settings.
        assert!(match server_stream.recv_frame().unwrap() {
            HttpFrame::SettingsFrame(_) => true,
            _ => false,
        });
    }

    /// Tests that sending a request with no body works correctly.
    #[test]
    fn test_http2_request_no_body() {
        let mut mock_connector = MockHttp2Connector::new();
        let stream = mock_connector.new_response_stream(b"200", &Headers::new(), Some(vec![]));
        let protocol = Http2Protocol::with_connector(mock_connector);

        let mut message = protocol.new_message("127.0.0.1", 1337, "http").unwrap();
        message.set_outgoing(RequestHead {
            headers: Headers::new(),
            method: method::Method::Get,
            url: Url::parse("http://127.0.0.1/hello").unwrap(),
        }).unwrap();
        let _ = message.get_incoming().unwrap();

        let stream = stream.inner.lock().unwrap();
        assert!(stream.write.len() > 0);
        // The output stream of the client side gets flipped so that we can read the stream from
        // the server's end.
        let mut server_stream = MockStream::with_input(&stream.write);
        assert_client_preface(&mut server_stream);
        let frame = server_stream.recv_frame().unwrap();
        assert!(match frame {
            HttpFrame::HeadersFrame(ref frame) => frame.is_end_of_stream(),
            _ => false,
        });
    }

    /// Tests that sending a request with a body works correctly.
    #[test]
    fn test_http2_request_with_body() {
        let mut mock_connector = MockHttp2Connector::new();
        let stream = mock_connector.new_response_stream(b"200", &Headers::new(), None);
        let protocol = Http2Protocol::with_connector(mock_connector);

        let mut message = protocol.new_message("127.0.0.1", 1337, "http").unwrap();
        message.set_outgoing(RequestHead {
            headers: Headers::new(),
            method: method::Method::Get,
            url: Url::parse("http://127.0.0.1/hello").unwrap(),
        }).unwrap();
        // Write a few things to the request in multiple writes.
        message.write(&[1]).unwrap();
        message.write(&[2, 3]).unwrap();
        let _ = message.get_incoming().unwrap();

        let stream = stream.inner.lock().unwrap();
        assert!(stream.write.len() > 0);
        // The output stream of the client side gets flipped so that we can read the stream from
        // the server's end.
        let mut server_stream = MockStream::with_input(&stream.write);
        assert_client_preface(&mut server_stream);
        let frame = server_stream.recv_frame().unwrap();
        assert!(match frame {
            HttpFrame::HeadersFrame(ref frame) => !frame.is_end_of_stream(),
            _ => false,
        });
        assert!(match server_stream.recv_frame().unwrap() {
            HttpFrame::DataFrame(ref frame) => frame.data == vec![1, 2, 3],
            _ => false,
        });
    }

    /// Tests that headers are correctly prepared when they include a `Set-Cookie` header.
    #[test]
    fn test_http2_prepare_headers_with_set_cookie() {
        let cookies = header::SetCookie(vec![
            cookie::Cookie::new("foo".to_owned(), "bar".to_owned()),
            cookie::Cookie::new("baz".to_owned(), "quux".to_owned())
        ]);
        let mut headers = Headers::new();
        headers.set(cookies);

        let h2headers = prepare_headers(headers);

        assert_eq!(vec![
            (b"set-cookie".to_vec(), b"foo=bar".to_vec()),
            (b"set-cookie".to_vec(), b"baz=quux".to_vec()),
        ], h2headers);
    }

    /// Tests that headers are correctly prepared when they include a `Cookie` header.
    #[test]
    fn test_http2_prepapre_headers_with_cookie() {
        let cookies = header::Cookie(vec![
            cookie::Cookie::new("foo".to_owned(), "bar".to_owned()),
            cookie::Cookie::new("baz".to_owned(), "quux".to_owned())
        ]);
        let mut headers = Headers::new();
        headers.set(cookies);

        let h2headers = prepare_headers(headers);

        assert_eq!(vec![
            (b"cookie".to_vec(), b"foo=bar; baz=quux".to_vec()),
        ], h2headers);
    }

    /// Tests that HTTP/2 headers are correctly prepared.
    #[test]
    fn test_http2_prepare_headers() {
        let mut headers = Headers::new();
        headers.set(header::ContentLength(3));
        let expected = vec![
            (b"content-length".to_vec(), b"3".to_vec()),
        ];

        assert_eq!(expected, prepare_headers(headers));
    }

    /// Tests that the headers of a response are correctly parsed when they include a `Set-Cookie`
    /// header.
    #[test]
    fn test_http2_parse_headers_with_set_cookie() {
        let h2headers = vec![
            (b"set-cookie".to_vec(), b"foo=bar".to_vec()),
            (b"set-cookie".to_vec(), b"baz=quux".to_vec()),
        ];
        let expected = header::SetCookie(vec![
            cookie::Cookie::new("foo".to_owned(), "bar".to_owned()),
            cookie::Cookie::new("baz".to_owned(), "quux".to_owned())
        ]);

        let headers = parse_headers(h2headers).unwrap();

        assert!(headers.has::<header::SetCookie>());
        let set_cookie = headers.get::<header::SetCookie>().unwrap();
        assert_eq!(expected, *set_cookie);
    }

    /// Tests that parsing HTTP/2 headers with `Cookie` headers works correctly.
    #[test]
    fn test_http2_parse_headers_with_cookie() {
        let expected = header::Cookie(vec![
            cookie::Cookie::new("foo".to_owned(), "bar".to_owned()),
            cookie::Cookie::new("baz".to_owned(), "quux".to_owned())
        ]);
        // HTTP/2 allows the `Cookie` header to be split into multiple ones to facilitate better
        // compression.
        let h2headers = vec![
            (b"cookie".to_vec(), b"foo=bar".to_vec()),
            (b"cookie".to_vec(), b"baz=quux".to_vec()),
        ];

        let headers = parse_headers(h2headers).unwrap();

        assert!(headers.has::<header::Cookie>());
        assert_eq!(*headers.get::<header::Cookie>().unwrap(), expected);
    }

    /// Tests that the headers of a response are correctly parsed.
    #[test]
    fn test_http2_parse_headers() {
        let h2headers = vec![
            (b":status".to_vec(), b"200".to_vec()),
            (b"content-length".to_vec(), b"3".to_vec()),
        ];

        let headers = parse_headers(h2headers).unwrap();

        assert!(headers.has::<header::ContentLength>());
        let &header::ContentLength(len) = headers.get::<header::ContentLength>().unwrap();
        assert_eq!(3, len);
    }

    /// Tests that if a header name is not a valid utf8 byte sequence, an error is returned.
    #[test]
    fn test_http2_parse_headers_invalid_name() {
        let h2headers = vec![
            (vec![0xfe], vec![]),
        ];

        assert!(parse_headers(h2headers).is_err());
    }

    /// Tests that a response with no pseudo-header for status is considered invalid.
    #[test]
    fn test_http2_parse_response_no_status_code() {
        let response = ::solicit::http::Response {
            body: Vec::new(),
            headers: vec![
                (b"content-length".to_vec(), b"3".to_vec()),
            ],
            stream_id: 1,
        };

        assert!(parse_response(response).is_err());
    }

    /// Tests that an HTTP/2 response gets correctly parsed into a body and response head, when
    /// the body is empty.
    #[test]
    fn test_http2_parse_response_no_body() {
        let response = ::solicit::http::Response {
            body: Vec::new(),
            headers: vec![
                (b":status".to_vec(), b"200".to_vec()),
                (b"content-length".to_vec(), b"0".to_vec()),
            ],
            stream_id: 1,
        };

        let (head, body) = parse_response(response).unwrap();

        assert_eq!(body, vec![]);
        let ResponseHead { headers, raw_status, version } = head;
        assert_eq!(raw_status.0, 200);
        assert_eq!(raw_status.1, "");
        assert!(headers.has::<header::ContentLength>());
        assert_eq!(version, version::HttpVersion::Http20);
    }

    /// Tests that an HTTP/2 response gets correctly parsed into a body and response head, when
    /// the body is not empty.
    #[test]
    fn test_http2_parse_response_with_body() {
        let expected_body = vec![1, 2, 3];
        let response = ::solicit::http::Response {
            body: expected_body.clone(),
            headers: vec![
                (b":status".to_vec(), b"200".to_vec()),
                (b"content-length".to_vec(), b"3".to_vec()),
            ],
            stream_id: 1,
        };

        let (head, body) = parse_response(response).unwrap();

        assert_eq!(body, expected_body);
        let ResponseHead { headers, raw_status, version } = head;
        assert_eq!(raw_status.0, 200);
        assert_eq!(raw_status.1, "");
        assert!(headers.has::<header::ContentLength>());
        assert_eq!(version, version::HttpVersion::Http20);
    }
}
<commit_msg>chore(h2): clear out unused h2 module<commit_after>
<|endoftext|>


<commit_before>use std::default::Default;
use rustc_serialize::json;
use rustc_serialize::base64::{
    FromBase64,
    ToBase64,
};
use error::Error;
use BASE_CONFIG;

#[derive(Debug, PartialEq, RustcDecodable, RustcEncodable)]
pub struct Header {
    pub typ: String,
    pub alg: Option<String>,
}

impl Header {
    pub fn parse(raw: &str) -> Result<Header, Error> {
        let data = try!(raw.from_base64());
        let s = try!(String::from_utf8(data));
        let header = try!(json::decode(&*s));

        Ok(header)
    }

    pub fn encode(&self) -> Result<String, Error> {
        let s = try!(json::encode(&self));
        let enc = (&*s).as_bytes().to_base64(BASE_CONFIG);
        Ok(enc)
    }
}

impl Default for Header {
    fn default() -> Header {
        Header {
            typ: "JWT".into(),
            alg: Some("HS256".into()),
        }
    }
}

#[cfg(test)]
mod tests {
    use header::Header;

    #[test]
    fn parse() {
        let enc = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";
        let header = Header::parse(enc).unwrap();

        assert_eq!(header.typ, "JWT");
        assert_eq!(header.alg.unwrap(), "HS256");
    }

    #[test]
    fn roundtrip() {
        let header: Header = Default::default();
        let enc = header.encode().unwrap();
        assert_eq!(header, Header::parse(&*enc).unwrap());
    }
}
<commit_msg>Make header type into enum<commit_after>use std::default::Default;
use rustc_serialize::json;
use rustc_serialize::base64::{
    FromBase64,
    ToBase64,
};
use error::Error;
use BASE_CONFIG;

#[derive(Debug, PartialEq, RustcDecodable, RustcEncodable)]
pub struct Header {
    pub typ: HeaderType,
    pub alg: Option<String>,
}

impl Header {
    pub fn parse(raw: &str) -> Result<Header, Error> {
        let data = try!(raw.from_base64());
        let s = try!(String::from_utf8(data));
        let header = try!(json::decode(&*s));

        Ok(header)
    }

    pub fn encode(&self) -> Result<String, Error> {
        let s = try!(json::encode(&self));
        let enc = (&*s).as_bytes().to_base64(BASE_CONFIG);
        Ok(enc)
    }
}

#[derive(Debug, PartialEq, RustcDecodable, RustcEncodable)]
pub enum HeaderType {
    JWT,
}

impl Default for Header {
    fn default() -> Header {
        Header {
            typ: HeaderType::JWT,
            alg: Some("HS256".into()),
        }
    }
}

#[cfg(test)]
mod tests {
    use header::{
        Header,
        HeaderType,
    };

    #[test]
    fn parse() {
        let enc = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";
        let header = Header::parse(enc).unwrap();

        assert_eq!(header.typ, HeaderType::JWT);
        assert_eq!(header.alg.unwrap(), "HS256");
    }

    #[test]
    fn roundtrip() {
        let header: Header = Default::default();
        let enc = header.encode().unwrap();
        assert_eq!(header, Header::parse(&*enc).unwrap());
    }
}
<|endoftext|>


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

// Format list-like macro invocations. These are invocations whose token trees
// can be interpreted as expressions and separated by commas.
// Note that these token trees do not actually have to be interpreted as
// expressions by the compiler. An example of an invocation we would reformat is
// foo!( x, y, z ). The token x may represent an identifier in the code, but we
// interpreted as an expression.
// Macro uses which are not-list like, such as bar!(key => val), will not be
// reformated.
// List-like invocations with parentheses will be formatted as function calls,
// and those with brackets will be formatted as array literals.

use syntax::ast;
use syntax::parse::token::{Eof, Comma, Token};
use syntax::parse::tts_to_parser;
use syntax::codemap::{mk_sp, BytePos};

use Indent;
use rewrite::RewriteContext;
use expr::{rewrite_call, rewrite_array};
use comment::FindUncommented;
use utils::{wrap_str, span_after};

static FORCED_BRACKET_MACROS: &'static [&'static str] = &["vec!"];

// FIXME: use the enum from libsyntax?
#[derive(Clone, Copy)]
enum MacroStyle {
    Parens,
    Brackets,
    Braces,
}

impl MacroStyle {
    fn opener(&self) -> &'static str {
        match *self {
            MacroStyle::Parens => "(",
            MacroStyle::Brackets => "[",
            MacroStyle::Braces => "{",
        }
    }
}

pub fn rewrite_macro(mac: &ast::Mac,
                     context: &RewriteContext,
                     width: usize,
                     offset: Indent)
                     -> Option<String> {
    let original_style = macro_style(mac, context);
    let macro_name = format!("{}!", mac.node.path);
    let style = if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {
        MacroStyle::Brackets
    } else {
        original_style
    };

    if let MacroStyle::Braces = style {
        return None;
    } else if mac.node.tts.is_empty() {
        return if let MacroStyle::Parens = style {
            Some(format!("{}()", macro_name))
        } else {
            Some(format!("{}[]", macro_name))
        };
    }

    let mut parser = tts_to_parser(context.parse_session, mac.node.tts.clone(), Vec::new());
    let mut expr_vec = Vec::new();

    loop {
        expr_vec.push(match parser.parse_expr() {
            Ok(expr) => expr,
            Err(..) => return None,
        });

        match parser.token {
            Token::Eof => break,
            Token::Comma => (),
            _ => return None,
        }

        let _ = parser.bump();

        if parser.token == Token::Eof {
            return None;
        }
    }

    match style {
        MacroStyle::Parens => {
            // Format macro invocation as function call.
            rewrite_call(context, &macro_name, &expr_vec, mac.span, width, offset)
        }
        MacroStyle::Brackets => {
            // Format macro invocation as array literal.
            let extra_offset = macro_name.len();
            let rewrite = try_opt!(rewrite_array(expr_vec.iter().map(|x| &**x),
                                                 mk_sp(span_after(mac.span,
                                                                  original_style.opener(),
                                                                  context.codemap),
                                                       mac.span.hi - BytePos(1)),
                                                 context,
                                                 try_opt!(width.checked_sub(extra_offset)),
                                                 offset + extra_offset));

            Some(format!("{}{}", macro_name, rewrite))
        }
        MacroStyle::Braces => {
            // Skip macro invocations with braces, for now.
            wrap_str(context.snippet(mac.span),
                     context.config.max_width,
                     width,
                     offset)
        }
    }
}

fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> MacroStyle {
    let snippet = context.snippet(mac.span);
    let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
    let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
    let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());

    if paren_pos < bracket_pos && paren_pos < brace_pos {
        MacroStyle::Parens
    } else if bracket_pos < brace_pos {
        MacroStyle::Brackets
    } else {
        MacroStyle::Braces
    }
}
<commit_msg>Remove unused imports<commit_after>// Copyright 2015 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.

// Format list-like macro invocations. These are invocations whose token trees
// can be interpreted as expressions and separated by commas.
// Note that these token trees do not actually have to be interpreted as
// expressions by the compiler. An example of an invocation we would reformat is
// foo!( x, y, z ). The token x may represent an identifier in the code, but we
// interpreted as an expression.
// Macro uses which are not-list like, such as bar!(key => val), will not be
// reformated.
// List-like invocations with parentheses will be formatted as function calls,
// and those with brackets will be formatted as array literals.

use syntax::ast;
use syntax::parse::token::Token;
use syntax::parse::tts_to_parser;
use syntax::codemap::{mk_sp, BytePos};

use Indent;
use rewrite::RewriteContext;
use expr::{rewrite_call, rewrite_array};
use comment::FindUncommented;
use utils::{wrap_str, span_after};

static FORCED_BRACKET_MACROS: &'static [&'static str] = &["vec!"];

// FIXME: use the enum from libsyntax?
#[derive(Clone, Copy)]
enum MacroStyle {
    Parens,
    Brackets,
    Braces,
}

impl MacroStyle {
    fn opener(&self) -> &'static str {
        match *self {
            MacroStyle::Parens => "(",
            MacroStyle::Brackets => "[",
            MacroStyle::Braces => "{",
        }
    }
}

pub fn rewrite_macro(mac: &ast::Mac,
                     context: &RewriteContext,
                     width: usize,
                     offset: Indent)
                     -> Option<String> {
    let original_style = macro_style(mac, context);
    let macro_name = format!("{}!", mac.node.path);
    let style = if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {
        MacroStyle::Brackets
    } else {
        original_style
    };

    if let MacroStyle::Braces = style {
        return None;
    } else if mac.node.tts.is_empty() {
        return if let MacroStyle::Parens = style {
            Some(format!("{}()", macro_name))
        } else {
            Some(format!("{}[]", macro_name))
        };
    }

    let mut parser = tts_to_parser(context.parse_session, mac.node.tts.clone(), Vec::new());
    let mut expr_vec = Vec::new();

    loop {
        expr_vec.push(match parser.parse_expr() {
            Ok(expr) => expr,
            Err(..) => return None,
        });

        match parser.token {
            Token::Eof => break,
            Token::Comma => (),
            _ => return None,
        }

        let _ = parser.bump();

        if parser.token == Token::Eof {
            return None;
        }
    }

    match style {
        MacroStyle::Parens => {
            // Format macro invocation as function call.
            rewrite_call(context, &macro_name, &expr_vec, mac.span, width, offset)
        }
        MacroStyle::Brackets => {
            // Format macro invocation as array literal.
            let extra_offset = macro_name.len();
            let rewrite = try_opt!(rewrite_array(expr_vec.iter().map(|x| &**x),
                                                 mk_sp(span_after(mac.span,
                                                                  original_style.opener(),
                                                                  context.codemap),
                                                       mac.span.hi - BytePos(1)),
                                                 context,
                                                 try_opt!(width.checked_sub(extra_offset)),
                                                 offset + extra_offset));

            Some(format!("{}{}", macro_name, rewrite))
        }
        MacroStyle::Braces => {
            // Skip macro invocations with braces, for now.
            wrap_str(context.snippet(mac.span),
                     context.config.max_width,
                     width,
                     offset)
        }
    }
}

fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> MacroStyle {
    let snippet = context.snippet(mac.span);
    let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
    let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
    let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());

    if paren_pos < bracket_pos && paren_pos < brace_pos {
        MacroStyle::Parens
    } else if bracket_pos < brace_pos {
        MacroStyle::Brackets
    } else {
        MacroStyle::Braces
    }
}
<|endoftext|>


<commit_before><commit_msg>Add a compare_dyldinfos integration test<commit_after>extern crate goblin;
use std::process;

fn compare(args: Vec<&str>) {
    let apple = process::Command::new("/Library/Developer/CommandLineTools/usr/bin/dyldinfo")
        .args(&args)
        .output()
        .expect("run Apple dyldinfo");

    let goblin = process::Command::new("cargo")
        .arg("run")
        .arg("--quiet")
        .arg("--example")
        .arg("dyldinfo")
        .arg("--")
        .args(&args)
        .output()
        .expect("run cargo dyldinfo");

    if apple.stdout.as_slice() != goblin.stdout.as_slice() {
        eprintln!("dyldinfo calls disagree!");
        eprintln!("Apple dyldinfo {:?} output:\n{}", &args, String::from_utf8_lossy(&apple.stdout));
        eprintln!("---");
        eprintln!("cargo dyldinfo {:?} output:\n{}", &args, String::from_utf8_lossy(&goblin.stdout));
        panic!("Apple dyldinfo and cargo dyldinfo differed (args: {:?})", args);
    }
}

#[cfg(target_os="macos")]
#[test]
fn compare_binds() {
    compare(vec!["-bind", "/Library/Developer/CommandLineTools/usr/bin/dyldinfo"]);
    compare(vec!["-bind", "/Library/Developer/CommandLineTools/usr/bin/clang"]);
    compare(vec!["-bind", "/usr/bin/tmutil"]);
}

#[cfg(not(target_os="macos"))]
#[test]
fn skipped_on_this_platform() {
    // this test does nothing on other platforms
}
<|endoftext|>


<commit_before>// Copyright (c) 2015 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

extern crate num;

use libc::{c_long, c_double};
use std;
use python::{Python, PythonObject, ToPythonPointer};
use err::{self, PyResult, PyErr};
use super::object::PyObject;
use super::exc;
use ffi::{self, Py_ssize_t};
use conversion::{ToPyObject, FromPyObject};

#[cfg(feature="python27-sys")]
pyobject_newtype!(PyInt, PyInt_Check, PyInt_Type);

pyobject_newtype!(PyLong, PyLong_Check, PyLong_Type);
pyobject_newtype!(PyFloat, PyFloat_Check, PyFloat_Type);

#[cfg(feature="python27-sys")]
impl <'p> PyInt<'p> {
    /// Creates a new python `int` object.
    pub fn new(py: Python<'p>, val: c_long) -> PyInt<'p> {
        unsafe {
            err::cast_from_owned_ptr_or_panic(py, ffi::PyInt_FromLong(val))
        }
    }

    /// Gets the value of this integer.
    pub fn value(&self) -> c_long {
        unsafe { ffi::PyInt_AS_LONG(self.as_ptr()) }
    }
}

impl <'p> PyFloat<'p> {
    /// Creates a new python `float` object.
    pub fn new(py: Python<'p>, val: c_double) -> PyFloat<'p> {
        unsafe {
            err::cast_from_owned_ptr_or_panic(py, ffi::PyFloat_FromDouble(val))
        }
    }

    /// Gets the value of this float.
    pub fn value(&self) -> c_double {
        unsafe { ffi::PyFloat_AsDouble(self.as_ptr()) }
    }
}

macro_rules! int_fits_c_long(
    ($rust_type:ty) => (
        #[cfg(feature="python27-sys")]
        impl <'p> ToPyObject<'p> for $rust_type {
            type ObjectType = PyInt<'p>;

            fn to_py_object(&self, py: Python<'p>) -> PyInt<'p> {
                unsafe {
                    err::cast_from_owned_ptr_or_panic(py,
                        ffi::PyInt_FromLong(*self as c_long))
                }
            }
        }

        #[cfg(feature="python3-sys")]
        impl <'p> ToPyObject<'p> for $rust_type {
            type ObjectType = PyLong<'p>;

            fn to_py_object(&self, py: Python<'p>) -> PyLong<'p> {
                unsafe {
                    err::cast_from_owned_ptr_or_panic(py,
                        ffi::PyLong_FromLong(*self as c_long))
                }
            }
        }

        #[cfg(feature="python27-sys")]
        impl <'p> FromPyObject<'p> for $rust_type {
            fn from_py_object(s: &PyObject<'p>) -> PyResult<'p, $rust_type> {
                let py = s.python();
                let val = unsafe { ffi::PyInt_AsLong(s.as_ptr()) };
                if val == -1 && PyErr::occurred(py) {
                    return Err(PyErr::fetch(py));
                }
                match num::traits::cast::<c_long, $rust_type>(val) {
                    Some(v) => Ok(v),
                    None => Err(overflow_error(py))
                }
            }
        }

        #[cfg(feature="python3-sys")]
        impl <'p> FromPyObject<'p> for $rust_type {
            fn from_py_object(s: &PyObject<'p>) -> PyResult<'p, $rust_type> {
                let py = s.python();
                let val = unsafe { ffi::PyLong_AsLong(s.as_ptr()) };
                if val == -1 && PyErr::occurred(py) {
                    return Err(PyErr::fetch(py));
                }
                match num::traits::cast::<c_long, $rust_type>(val) {
                    Some(v) => Ok(v),
                    None => Err(overflow_error(py))
                }
            }
        }
    )
);

macro_rules! int_fits_larger_int(
    ($rust_type:ty, $larger_type:ty) => (
        impl <'p> ToPyObject<'p> for $rust_type {
            type ObjectType = <$larger_type as ToPyObject<'p>>::ObjectType;

            #[inline]
            fn to_py_object(&self, py: Python<'p>) -> <$larger_type as ToPyObject<'p>>::ObjectType {
                (*self as $larger_type).to_py_object(py)
            }
        }

        impl <'p> FromPyObject<'p> for $rust_type {
            fn from_py_object(s: &PyObject<'p>) -> PyResult<'p, $rust_type> {
                let py = s.python();
                let val = try!(s.extract::<$larger_type>());
                match num::traits::cast::<$larger_type, $rust_type>(val) {
                    Some(v) => Ok(v),
                    None => Err(overflow_error(py))
                }
            }
        }
    )
);

int_fits_c_long!(i8);
int_fits_c_long!(u8);
int_fits_c_long!(i16);
int_fits_c_long!(u16);
int_fits_c_long!(i32);

// If c_long is 64-bits, we can use more types with int_fits_c_long!:
#[cfg(all(target_pointer_width="64", not(target_os="windows")))]
int_fits_c_long!(u32);
#[cfg(any(target_pointer_width="32", target_os="windows"))]
int_fits_larger_int!(u32, u64);

#[cfg(all(target_pointer_width="64", not(target_os="windows")))]
int_fits_c_long!(i64);
// TODO: manual implementation for i64 on systems with 32-bit long

// u64 has a manual implementation as it never fits into signed long

#[cfg(all(target_pointer_width="64", not(target_os="windows")))]
int_fits_c_long!(isize);
#[cfg(any(target_pointer_width="32", target_os="windows"))]
int_fits_larger_int!(isize, i64);

int_fits_larger_int!(usize, u64);

impl <'p> ToPyObject<'p> for u64 {
    #[cfg(feature="python27-sys")]
    type ObjectType = PyObject<'p>;

    #[cfg(feature="python3-sys")]
    type ObjectType = PyLong<'p>;

    #[cfg(feature="python27-sys")]
    fn to_py_object(&self, py: Python<'p>) -> PyObject<'p> {
        unsafe {
            let ptr = match num::traits::cast::<u64, c_long>(*self) {
                Some(v) => ffi::PyInt_FromLong(v),
                None => ffi::PyLong_FromUnsignedLongLong(*self)
            };
            err::from_owned_ptr_or_panic(py, ptr)
        }
    }

    #[cfg(feature="python3-sys")]
    fn to_py_object(&self, py: Python<'p>) -> PyLong<'p> {
        unsafe {
            err::cast_from_owned_ptr_or_panic(py, ffi::PyLong_FromUnsignedLongLong(*self))
        }
    }
}

fn pylong_as_u64<'p>(obj: &PyObject<'p>) -> PyResult<'p, u64> {
    let py = obj.python();
    let v = unsafe { ffi::PyLong_AsUnsignedLongLong(obj.as_ptr()) };
    if v == !0 && PyErr::occurred(py) {
        Err(PyErr::fetch(py))
    } else {
        Ok(v)
    }
}

impl <'p> FromPyObject<'p> for u64 {
    #[cfg(feature="python27-sys")]
    fn from_py_object(s: &PyObject<'p>) -> PyResult<'p, u64> {
        let py = s.python();
        let ptr = s.as_ptr();
        unsafe {
            if ffi::PyLong_Check(ptr) != 0 {
                pylong_as_u64(s)
            } else if ffi::PyInt_Check(ptr) != 0 {
                match num::traits::cast::<c_long, u64>(ffi::PyInt_AS_LONG(ptr)) {
                    Some(v) => Ok(v),
                    None => Err(overflow_error(py))
                }
            } else {
                let num = try!(err::result_from_owned_ptr(py, ffi::PyNumber_Long(ptr)));
                pylong_as_u64(&num)
            }
        }
    }

    #[cfg(feature="python3-sys")]
    fn from_py_object(s: &PyObject<'p>) -> PyResult<'p, u64> {
        let py = s.python();
        let ptr = s.as_ptr();
        unsafe {
            if ffi::PyLong_Check(ptr) != 0 {
                pylong_as_u64(s)
            } else {
                let num = try!(err::result_from_owned_ptr(py, ffi::PyNumber_Long(ptr)));
                pylong_as_u64(&num)
            }
        }
    }
}

impl <'p> ToPyObject<'p> for f64 {
    type ObjectType = PyFloat<'p>;

    fn to_py_object(&self, py: Python<'p>) -> PyFloat<'p> {
       PyFloat::new(py, *self)
    }
}

impl <'p> FromPyObject<'p> for f64 {
    fn from_py_object(s: &PyObject<'p>) -> PyResult<'p, f64> {
        let py = s.python();
        let v = unsafe { ffi::PyFloat_AsDouble(s.as_ptr()) };
        if v == -1.0 && PyErr::occurred(py) {
            Err(PyErr::fetch(py))
        } else {
            Ok(v)
        }
    }
}

fn overflow_error(py: Python) -> PyErr {
    PyErr::new_lazy_init(py.get_type::<exc::OverflowError>(), None)
}

impl <'p> ToPyObject<'p> for f32 {
    type ObjectType = PyFloat<'p>;

    fn to_py_object(&self, py: Python<'p>) -> PyFloat<'p> {
       PyFloat::new(py, *self as f64)
    }
}

impl <'p, 's> FromPyObject<'p> for f32 {
    fn from_py_object(s: &PyObject<'p>) -> PyResult<'p, f32> {
        Ok(try!(s.extract::<f64>()) as f32)
    }
}

#[cfg(test)]
mod test {
    use std;
    use python::{Python, PythonObject};
    use conversion::ToPyObject;

    macro_rules! num_to_py_object_and_back (
        ($func_name:ident, $t1:ty, $t2:ty) => (
            #[test]
            fn $func_name() {
                let gil = Python::acquire_gil();
                let py = gil.python();
                let val = 123 as $t1;
                let obj = val.to_py_object(py).into_object();
                assert_eq!(obj.extract::<$t2>().unwrap(), val as $t2);
            }
        )
    );

    num_to_py_object_and_back!(to_from_f64, f64, f64);
    num_to_py_object_and_back!(to_from_f32, f32, f32);
    num_to_py_object_and_back!(to_from_i8,   i8,  i8);
    num_to_py_object_and_back!(to_from_u8,   u8,  u8);
    num_to_py_object_and_back!(to_from_i16, i16, i16);
    num_to_py_object_and_back!(to_from_u16, u16, u16);
    num_to_py_object_and_back!(to_from_i32, i32, i32);
    num_to_py_object_and_back!(to_from_u32, u32, u32);
    num_to_py_object_and_back!(to_from_i64, i64, i64);
    num_to_py_object_and_back!(to_from_u64, u64, u64);
    num_to_py_object_and_back!(to_from_isize, isize, isize);
    num_to_py_object_and_back!(to_from_usize, usize, usize);
    num_to_py_object_and_back!(float_to_i32, f64, i32);
    num_to_py_object_and_back!(float_to_u32, f64, u32);
    num_to_py_object_and_back!(float_to_i64, f64, i64);
    num_to_py_object_and_back!(float_to_u64, f64, u64);
    num_to_py_object_and_back!(int_to_float, i32, f64);

    #[test]
    fn test_u32_max() {
        let gil = Python::acquire_gil();
        let py = gil.python();
        let v = std::u32::MAX;
        let obj = v.to_py_object(py).into_object();
        assert_eq!(v, obj.extract::<u32>().unwrap());
        assert_eq!(v as u64, obj.extract::<u64>().unwrap());
        assert!(obj.extract::<i32>().is_err());
    }

    #[test]
    fn test_u64_max() {
        let gil = Python::acquire_gil();
        let py = gil.python();
        let v = std::u64::MAX;
        let obj = v.to_py_object(py).into_object();
        println!("{:?}", obj);
        assert_eq!(v, obj.extract::<u64>().unwrap());
        assert!(obj.extract::<i64>().is_err());
    }
}

<commit_msg>Generalize pylong_as_u64.<commit_after>// Copyright (c) 2015 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

extern crate num;

use libc::{c_long, c_double};
use std;
use python::{Python, PythonObject, ToPythonPointer};
use err::{self, PyResult, PyErr};
use super::object::PyObject;
use super::exc;
use ffi::{self, Py_ssize_t};
use conversion::{ToPyObject, FromPyObject};

#[cfg(feature="python27-sys")]
pyobject_newtype!(PyInt, PyInt_Check, PyInt_Type);

pyobject_newtype!(PyLong, PyLong_Check, PyLong_Type);
pyobject_newtype!(PyFloat, PyFloat_Check, PyFloat_Type);

#[cfg(feature="python27-sys")]
impl <'p> PyInt<'p> {
    /// Creates a new python `int` object.
    pub fn new(py: Python<'p>, val: c_long) -> PyInt<'p> {
        unsafe {
            err::cast_from_owned_ptr_or_panic(py, ffi::PyInt_FromLong(val))
        }
    }

    /// Gets the value of this integer.
    pub fn value(&self) -> c_long {
        unsafe { ffi::PyInt_AS_LONG(self.as_ptr()) }
    }
}

impl <'p> PyFloat<'p> {
    /// Creates a new python `float` object.
    pub fn new(py: Python<'p>, val: c_double) -> PyFloat<'p> {
        unsafe {
            err::cast_from_owned_ptr_or_panic(py, ffi::PyFloat_FromDouble(val))
        }
    }

    /// Gets the value of this float.
    pub fn value(&self) -> c_double {
        unsafe { ffi::PyFloat_AsDouble(self.as_ptr()) }
    }
}

macro_rules! int_fits_c_long(
    ($rust_type:ty) => (
        #[cfg(feature="python27-sys")]
        impl <'p> ToPyObject<'p> for $rust_type {
            type ObjectType = PyInt<'p>;

            fn to_py_object(&self, py: Python<'p>) -> PyInt<'p> {
                unsafe {
                    err::cast_from_owned_ptr_or_panic(py,
                        ffi::PyInt_FromLong(*self as c_long))
                }
            }
        }

        #[cfg(feature="python3-sys")]
        impl <'p> ToPyObject<'p> for $rust_type {
            type ObjectType = PyLong<'p>;

            fn to_py_object(&self, py: Python<'p>) -> PyLong<'p> {
                unsafe {
                    err::cast_from_owned_ptr_or_panic(py,
                        ffi::PyLong_FromLong(*self as c_long))
                }
            }
        }

        #[cfg(feature="python27-sys")]
        impl <'p> FromPyObject<'p> for $rust_type {
            fn from_py_object(s: &PyObject<'p>) -> PyResult<'p, $rust_type> {
                let py = s.python();
                let val = unsafe { ffi::PyInt_AsLong(s.as_ptr()) };
                if val == -1 && PyErr::occurred(py) {
                    return Err(PyErr::fetch(py));
                }
                match num::traits::cast::<c_long, $rust_type>(val) {
                    Some(v) => Ok(v),
                    None => Err(overflow_error(py))
                }
            }
        }

        #[cfg(feature="python3-sys")]
        impl <'p> FromPyObject<'p> for $rust_type {
            fn from_py_object(s: &PyObject<'p>) -> PyResult<'p, $rust_type> {
                let py = s.python();
                let val = unsafe { ffi::PyLong_AsLong(s.as_ptr()) };
                if val == -1 && PyErr::occurred(py) {
                    return Err(PyErr::fetch(py));
                }
                match num::traits::cast::<c_long, $rust_type>(val) {
                    Some(v) => Ok(v),
                    None => Err(overflow_error(py))
                }
            }
        }
    )
);

macro_rules! int_fits_larger_int(
    ($rust_type:ty, $larger_type:ty) => (
        impl <'p> ToPyObject<'p> for $rust_type {
            type ObjectType = <$larger_type as ToPyObject<'p>>::ObjectType;

            #[inline]
            fn to_py_object(&self, py: Python<'p>) -> <$larger_type as ToPyObject<'p>>::ObjectType {
                (*self as $larger_type).to_py_object(py)
            }
        }

        impl <'p> FromPyObject<'p> for $rust_type {
            fn from_py_object(s: &PyObject<'p>) -> PyResult<'p, $rust_type> {
                let py = s.python();
                let val = try!(s.extract::<$larger_type>());
                match num::traits::cast::<$larger_type, $rust_type>(val) {
                    Some(v) => Ok(v),
                    None => Err(overflow_error(py))
                }
            }
        }
    )
);

int_fits_c_long!(i8);
int_fits_c_long!(u8);
int_fits_c_long!(i16);
int_fits_c_long!(u16);
int_fits_c_long!(i32);

// If c_long is 64-bits, we can use more types with int_fits_c_long!:
#[cfg(all(target_pointer_width="64", not(target_os="windows")))]
int_fits_c_long!(u32);
#[cfg(any(target_pointer_width="32", target_os="windows"))]
int_fits_larger_int!(u32, u64);

#[cfg(all(target_pointer_width="64", not(target_os="windows")))]
int_fits_c_long!(i64);
// TODO: manual implementation for i64 on systems with 32-bit long

// u64 has a manual implementation as it never fits into signed long

#[cfg(all(target_pointer_width="64", not(target_os="windows")))]
int_fits_c_long!(isize);
#[cfg(any(target_pointer_width="32", target_os="windows"))]
int_fits_larger_int!(isize, i64);

int_fits_larger_int!(usize, u64);

fn err_if_invalid_value<'p, T: PartialEq, F: Fn() -> T>
   (obj: &PyObject<'p>, invalid_value: T, func: F) -> PyResult<'p, T> {
    let py = obj.python();
    let v = func();
    if v == invalid_value && PyErr::occurred(py) {
        Err(PyErr::fetch(py))
    } else {
        Ok(v)
    }
}

impl <'p> ToPyObject<'p> for u64 {
    #[cfg(feature="python27-sys")]
    type ObjectType = PyObject<'p>;

    #[cfg(feature="python3-sys")]
    type ObjectType = PyLong<'p>;

    #[cfg(feature="python27-sys")]
    fn to_py_object(&self, py: Python<'p>) -> PyObject<'p> {
        unsafe {
            let ptr = match num::traits::cast::<u64, c_long>(*self) {
                Some(v) => ffi::PyInt_FromLong(v),
                None => ffi::PyLong_FromUnsignedLongLong(*self)
            };
            err::from_owned_ptr_or_panic(py, ptr)
        }
    }

    #[cfg(feature="python3-sys")]
    fn to_py_object(&self, py: Python<'p>) -> PyLong<'p> {
        unsafe {
            err::cast_from_owned_ptr_or_panic(py, ffi::PyLong_FromUnsignedLongLong(*self))
        }
    }
}

impl <'p> FromPyObject<'p> for u64 {
    #[cfg(feature="python27-sys")]
    fn from_py_object(s: &PyObject<'p>) -> PyResult<'p, u64> {
        let py = s.python();
        let ptr = s.as_ptr();

        unsafe {
            if ffi::PyLong_Check(ptr) != 0 {
                err_if_invalid_value(s, !0, || ffi::PyLong_AsUnsignedLongLong(s.as_ptr()) )
            } else if ffi::PyInt_Check(ptr) != 0 {
                match num::traits::cast::<c_long, u64>(ffi::PyInt_AS_LONG(ptr)) {
                    Some(v) => Ok(v),
                    None => Err(overflow_error(py))
                }
            } else {
                let num = try!(err::result_from_owned_ptr(py, ffi::PyNumber_Long(ptr)));
                err_if_invalid_value(&num, !0, || ffi::PyLong_AsUnsignedLongLong(num.as_ptr()) )
            }
        }
    }

    #[cfg(feature="python3-sys")]
    fn from_py_object(s: &PyObject<'p>) -> PyResult<'p, u64> {
        let py = s.python();
        let ptr = s.as_ptr();
        unsafe {
            if ffi::PyLong_Check(ptr) != 0 {
                err_if_invalid_value(s, !0, || ffi::PyLong_AsUnsignedLongLong(s.as_ptr()) )
            } else {
                let num = try!(err::result_from_owned_ptr(py, ffi::PyNumber_Long(ptr)));
                err_if_invalid_value(&num, !0, || ffi::PyLong_AsUnsignedLongLong(num.as_ptr()) )
            }
        }
    }
}

impl <'p> ToPyObject<'p> for f64 {
    type ObjectType = PyFloat<'p>;

    fn to_py_object(&self, py: Python<'p>) -> PyFloat<'p> {
       PyFloat::new(py, *self)
    }
}

impl <'p> FromPyObject<'p> for f64 {
    fn from_py_object(s: &PyObject<'p>) -> PyResult<'p, f64> {
        let py = s.python();
        let v = unsafe { ffi::PyFloat_AsDouble(s.as_ptr()) };
        if v == -1.0 && PyErr::occurred(py) {
            Err(PyErr::fetch(py))
        } else {
            Ok(v)
        }
    }
}

fn overflow_error(py: Python) -> PyErr {
    PyErr::new_lazy_init(py.get_type::<exc::OverflowError>(), None)
}

impl <'p> ToPyObject<'p> for f32 {
    type ObjectType = PyFloat<'p>;

    fn to_py_object(&self, py: Python<'p>) -> PyFloat<'p> {
       PyFloat::new(py, *self as f64)
    }
}

impl <'p, 's> FromPyObject<'p> for f32 {
    fn from_py_object(s: &PyObject<'p>) -> PyResult<'p, f32> {
        Ok(try!(s.extract::<f64>()) as f32)
    }
}

#[cfg(test)]
mod test {
    use std;
    use python::{Python, PythonObject};
    use conversion::ToPyObject;

    macro_rules! num_to_py_object_and_back (
        ($func_name:ident, $t1:ty, $t2:ty) => (
            #[test]
            fn $func_name() {
                let gil = Python::acquire_gil();
                let py = gil.python();
                let val = 123 as $t1;
                let obj = val.to_py_object(py).into_object();
                assert_eq!(obj.extract::<$t2>().unwrap(), val as $t2);
            }
        )
    );

    num_to_py_object_and_back!(to_from_f64, f64, f64);
    num_to_py_object_and_back!(to_from_f32, f32, f32);
    num_to_py_object_and_back!(to_from_i8,   i8,  i8);
    num_to_py_object_and_back!(to_from_u8,   u8,  u8);
    num_to_py_object_and_back!(to_from_i16, i16, i16);
    num_to_py_object_and_back!(to_from_u16, u16, u16);
    num_to_py_object_and_back!(to_from_i32, i32, i32);
    num_to_py_object_and_back!(to_from_u32, u32, u32);
    num_to_py_object_and_back!(to_from_i64, i64, i64);
    num_to_py_object_and_back!(to_from_u64, u64, u64);
    num_to_py_object_and_back!(to_from_isize, isize, isize);
    num_to_py_object_and_back!(to_from_usize, usize, usize);
    num_to_py_object_and_back!(float_to_i32, f64, i32);
    num_to_py_object_and_back!(float_to_u32, f64, u32);
    num_to_py_object_and_back!(float_to_i64, f64, i64);
    num_to_py_object_and_back!(float_to_u64, f64, u64);
    num_to_py_object_and_back!(int_to_float, i32, f64);

    #[test]
    fn test_u32_max() {
        let gil = Python::acquire_gil();
        let py = gil.python();
        let v = std::u32::MAX;
        let obj = v.to_py_object(py).into_object();
        assert_eq!(v, obj.extract::<u32>().unwrap());
        assert_eq!(v as u64, obj.extract::<u64>().unwrap());
        assert!(obj.extract::<i32>().is_err());
    }

    #[test]
    fn test_u64_max() {
        let gil = Python::acquire_gil();
        let py = gil.python();
        let v = std::u64::MAX;
        let obj = v.to_py_object(py).into_object();
        println!("{:?}", obj);
        assert_eq!(v, obj.extract::<u64>().unwrap());
        assert!(obj.extract::<i64>().is_err());
    }
}
<|endoftext|>


<commit_before><commit_msg>renaming TrackerRequest to QueryString, moving to submodule, adding methods<commit_after>use std::collections::HashMap;
use url::percent_encoding::{utf8_percent_encode, DEFAULT_ENCODE_SET};

//generic query string builder, automatically escapes each parameter val if necessary
//KEYS ARE TAKEN AS IS

pub struct QueryString<'a> {
    params: HashMap<&'a str, String>
}

impl <'a> QueryString<'a> {

    pub fn from (params: Vec<(&'a str, String)>) -> QueryString <'a> {
        let mut hm = QueryString {params: HashMap::new()};
        hm.add_params(params);
        hm
    }

    pub fn add_params (&mut self, params: Vec<(&'a str, String)>) {
        for (key, val) in params {
            self.params.insert(key, utf8_percent_encode(&val, DEFAULT_ENCODE_SET));
        }
    }

    pub fn to_param_string (&self) -> String {
        self.params.iter().map(|(k, v)| k.to_string() + "=" + v)
                          .collect::<Vec<String>>()
                          .join("&")
    }

}
<|endoftext|>


<commit_before><commit_msg>simple thread<commit_after>use std::thread;

static NTHREADS: i32 = 10;

fn main() {

    let mut children = vec![];

    for i in 0..NTHREADS {
        children.push(
            thread::spawn(move || {
                println!("Thread no: {}", i);
            })
        );
    }

    for c in children {
        let _ = c.join();
    }

}<|endoftext|>


<commit_before><commit_msg>Change auth test to pass in config<commit_after><|endoftext|>


<commit_before><commit_msg>added empty test<commit_after>fn main() {
}
<|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/. */

// Timing functions.
use extra::time::precise_time_ns;
use std::cell::Cell;
use std::comm::{Port, SharedChan};
use extra::sort::tim_sort;
use std::iterator::AdditiveIterator;

// front-end representation of the profiler used to communicate with the profiler
#[deriving(Clone)]
pub struct ProfilerChan {
    chan: SharedChan<ProfilerMsg>,
}

impl ProfilerChan {
    pub fn new(chan: Chan<ProfilerMsg>) -> ProfilerChan {
        ProfilerChan {
            chan: SharedChan::new(chan),
        }
    }
    pub fn send(&self, msg: ProfilerMsg) {
        self.chan.send(msg);
    }
}

#[deriving(Eq, Clone)]
pub enum ProfilerCategory {
    CompositingCategory,
    LayoutQueryCategory,
    LayoutPerformCategory,
    LayoutAuxInitCategory,
    LayoutSelectorMatchCategory,
    LayoutTreeBuilderCategory,
    LayoutMainCategory,
    LayoutShapingCategory,
    LayoutDispListBuildCategory,
    GfxRegenAvailableFontsCategory,
    RenderingDrawingCategory,
    RenderingPrepBuffCategory,
    RenderingCategory,
    // hackish but helps prevent errors when adding new categories
    NUM_BUCKETS,
}
// FIXME(#5873) this should be initialized by a NUM_BUCKETS cast,
static BUCKETS: uint = 13;
type ProfilerBuckets = [(ProfilerCategory, ~[float]), ..BUCKETS];

pub enum ProfilerMsg {
    // Normal message used for reporting time
    TimeMsg(ProfilerCategory, float),
    // Message used to force print the profiling metrics
    PrintMsg,
}

// back end of the profiler that handles data aggregation and performance metrics
pub struct Profiler {
    port: Port<ProfilerMsg>,
    buckets: ProfilerBuckets,
    last_msg: Option<ProfilerMsg>,
}

impl ProfilerCategory {
    // convenience function to not have to cast every time
    pub fn num_buckets() -> uint {
        NUM_BUCKETS as uint
    }

    // enumeration of all ProfilerCategory types
    // TODO(tkuehn): is there a better way to ensure proper order of categories?
    fn empty_buckets() -> ProfilerBuckets {
        let buckets = [
            (CompositingCategory, ~[]),
            (LayoutQueryCategory, ~[]),
            (LayoutPerformCategory, ~[]),
            (LayoutAuxInitCategory, ~[]),
            (LayoutSelectorMatchCategory, ~[]),
            (LayoutTreeBuilderCategory, ~[]),
            (LayoutMainCategory, ~[]),
            (LayoutShapingCategory, ~[]),
            (LayoutDispListBuildCategory, ~[]),
            (GfxRegenAvailableFontsCategory, ~[]),
            (RenderingDrawingCategory, ~[]),
            (RenderingPrepBuffCategory, ~[]),
            (RenderingCategory, ~[]),
        ];

        ProfilerCategory::check_order(&buckets);
        buckets
    }

    // ensure that the order of the buckets matches the order of the enum categories
    fn check_order(vec: &ProfilerBuckets) {
        for &(category, _) in vec.iter() {
            if category != vec[category as uint].first() {
                fail!("Enum category does not match bucket index. This is a bug.");
            }
        }
    }

    // some categories are subcategories of LayoutPerformCategory
    // and should be printed to indicate this
    pub fn format(self) -> ~str {
        let padding = match self {
            LayoutAuxInitCategory | LayoutSelectorMatchCategory | LayoutTreeBuilderCategory |
            LayoutMainCategory | LayoutDispListBuildCategory | LayoutShapingCategory=> " - ",
            _ => ""
        };
        fmt!("%s%?", padding, self)
    }
}

impl Profiler {
    pub fn create(port: Port<ProfilerMsg>) {
        let port = Cell::new(port);
        do spawn {
            let mut profiler = Profiler::new(port.take());
            profiler.start();
        }
    }

    pub fn new(port: Port<ProfilerMsg>) -> Profiler {
        Profiler {
            port: port,
            buckets: ProfilerCategory::empty_buckets(),
            last_msg: None,
        }
    }

    pub fn start(&mut self) {
        loop {
            let msg = self.port.recv();
            self.handle_msg(msg);
        }
    }

    fn handle_msg(&mut self, msg: ProfilerMsg) {
        match msg {
            TimeMsg(category, t) => match self.buckets[category as uint] {
                //TODO(tkuehn): would be nice to have tuple.second_mut()
                (_, ref mut data) => data.push(t),
            },
            PrintMsg => match self.last_msg {
                // only print if more data has arrived since the last printout
                Some(TimeMsg(*)) => self.print_buckets(),
                _ => {}
            },
        };
        self.last_msg = Some(msg);
    }

    fn print_buckets(&mut self) {
        println(fmt!("%31s %15s %15s %15s %15s %15s",
                         "_category_", "_mean (ms)_", "_median (ms)_",
                         "_min (ms)_", "_max (ms)_", "_bucket size_"));
        for bucket in self.buckets.mut_iter() {
            let (category, data) = match *bucket {
                (category, ref mut data) => (category, data),
            };
            tim_sort(*data);
            let data_len = data.len();
            if data_len > 0 {
                let (mean, median, &min, &max) =
                    (data.iter().map(|&x|x).sum() / (data_len as float),
                     data[data_len / 2],
                     data.iter().min().unwrap(),
                     data.iter().max().unwrap());
                println(fmt!("%-30s: %15.4f %15.4f %15.4f %15.4f %15u",
                             category.format(), mean, median, min, max, data_len));
            }
        }
        println("");
    }
}

pub fn profile<T>(category: ProfilerCategory,
                  profiler_chan: ProfilerChan,
                  callback: &fn() -> T)
                  -> T {
    let start_time = precise_time_ns();
    let val = callback();
    let end_time = precise_time_ns();
    let ms = ((end_time - start_time) as float / 1000000f);
    profiler_chan.send(TimeMsg(category, ms));
    return val;
}

pub fn time<T>(msg: &str, callback: &fn() -> T) -> T{
    let start_time = precise_time_ns();
    let val = callback();
    let end_time = precise_time_ns();
    let ms = ((end_time - start_time) as float / 1000000f);
    if ms >= 5f {
        debug!("%s took %? ms", msg, ms);
    }
    return val;
}

<commit_msg>auto merge of #772 : larsbergstrom/servo/profile-chan-fix, r=jdm<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/. */

// Timing functions.
use extra::time::precise_time_ns;
use std::cell::Cell;
use std::comm::{Port, SharedChan};
use extra::sort::tim_sort;
use std::iterator::AdditiveIterator;

// front-end representation of the profiler used to communicate with the profiler
#[deriving(Clone)]
pub struct ProfilerChan {
    chan: SharedChan<ProfilerMsg>,
}

impl ProfilerChan {
    pub fn new(chan: Chan<ProfilerMsg>) -> ProfilerChan {
        ProfilerChan {
            chan: SharedChan::new(chan),
        }
    }
    pub fn send(&self, msg: ProfilerMsg) {
        self.chan.send(msg);
    }
}

#[deriving(Eq, Clone)]
pub enum ProfilerCategory {
    CompositingCategory,
    LayoutQueryCategory,
    LayoutPerformCategory,
    LayoutAuxInitCategory,
    LayoutSelectorMatchCategory,
    LayoutTreeBuilderCategory,
    LayoutMainCategory,
    LayoutShapingCategory,
    LayoutDispListBuildCategory,
    GfxRegenAvailableFontsCategory,
    RenderingDrawingCategory,
    RenderingPrepBuffCategory,
    RenderingCategory,
    // hackish but helps prevent errors when adding new categories
    NUM_BUCKETS,
}
// FIXME(#5873) this should be initialized by a NUM_BUCKETS cast,
static BUCKETS: uint = 13;
type ProfilerBuckets = [(ProfilerCategory, ~[float]), ..BUCKETS];

pub enum ProfilerMsg {
    // Normal message used for reporting time
    TimeMsg(ProfilerCategory, float),
    // Message used to force print the profiling metrics
    PrintMsg,
}

// back end of the profiler that handles data aggregation and performance metrics
pub struct Profiler {
    port: Port<ProfilerMsg>,
    buckets: ProfilerBuckets,
    last_msg: Option<ProfilerMsg>,
}

impl ProfilerCategory {
    // convenience function to not have to cast every time
    pub fn num_buckets() -> uint {
        NUM_BUCKETS as uint
    }

    // enumeration of all ProfilerCategory types
    // TODO(tkuehn): is there a better way to ensure proper order of categories?
    fn empty_buckets() -> ProfilerBuckets {
        let buckets = [
            (CompositingCategory, ~[]),
            (LayoutQueryCategory, ~[]),
            (LayoutPerformCategory, ~[]),
            (LayoutAuxInitCategory, ~[]),
            (LayoutSelectorMatchCategory, ~[]),
            (LayoutTreeBuilderCategory, ~[]),
            (LayoutMainCategory, ~[]),
            (LayoutShapingCategory, ~[]),
            (LayoutDispListBuildCategory, ~[]),
            (GfxRegenAvailableFontsCategory, ~[]),
            (RenderingDrawingCategory, ~[]),
            (RenderingPrepBuffCategory, ~[]),
            (RenderingCategory, ~[]),
        ];

        ProfilerCategory::check_order(&buckets);
        buckets
    }

    // ensure that the order of the buckets matches the order of the enum categories
    fn check_order(vec: &ProfilerBuckets) {
        for &(category, _) in vec.iter() {
            if category != vec[category as uint].first() {
                fail!("Enum category does not match bucket index. This is a bug.");
            }
        }
    }

    // some categories are subcategories of LayoutPerformCategory
    // and should be printed to indicate this
    pub fn format(self) -> ~str {
        let padding = match self {
            LayoutAuxInitCategory | LayoutSelectorMatchCategory | LayoutTreeBuilderCategory |
            LayoutMainCategory | LayoutDispListBuildCategory | LayoutShapingCategory=> " - ",
            _ => ""
        };
        fmt!("%s%?", padding, self)
    }
}

impl Profiler {
    pub fn create(port: Port<ProfilerMsg>) {
        let port = Cell::new(port);
        do spawn {
            let mut profiler = Profiler::new(port.take());
            profiler.start();
        }
    }

    pub fn new(port: Port<ProfilerMsg>) -> Profiler {
        Profiler {
            port: port,
            buckets: ProfilerCategory::empty_buckets(),
            last_msg: None,
        }
    }

    pub fn start(&mut self) {
        loop {
            let msg = self.port.try_recv();
            match msg {
               Some (msg) => self.handle_msg(msg),
               None => break
            }
        }
    }

    fn handle_msg(&mut self, msg: ProfilerMsg) {
        match msg {
            TimeMsg(category, t) => match self.buckets[category as uint] {
                //TODO(tkuehn): would be nice to have tuple.second_mut()
                (_, ref mut data) => data.push(t),
            },
            PrintMsg => match self.last_msg {
                // only print if more data has arrived since the last printout
                Some(TimeMsg(*)) => self.print_buckets(),
                _ => {}
            },
        };
        self.last_msg = Some(msg);
    }

    fn print_buckets(&mut self) {
        println(fmt!("%31s %15s %15s %15s %15s %15s",
                         "_category_", "_mean (ms)_", "_median (ms)_",
                         "_min (ms)_", "_max (ms)_", "_bucket size_"));
        for bucket in self.buckets.mut_iter() {
            let (category, data) = match *bucket {
                (category, ref mut data) => (category, data),
            };
            tim_sort(*data);
            let data_len = data.len();
            if data_len > 0 {
                let (mean, median, &min, &max) =
                    (data.iter().map(|&x|x).sum() / (data_len as float),
                     data[data_len / 2],
                     data.iter().min().unwrap(),
                     data.iter().max().unwrap());
                println(fmt!("%-30s: %15.4f %15.4f %15.4f %15.4f %15u",
                             category.format(), mean, median, min, max, data_len));
            }
        }
        println("");
    }
}

pub fn profile<T>(category: ProfilerCategory,
                  profiler_chan: ProfilerChan,
                  callback: &fn() -> T)
                  -> T {
    let start_time = precise_time_ns();
    let val = callback();
    let end_time = precise_time_ns();
    let ms = ((end_time - start_time) as float / 1000000f);
    profiler_chan.send(TimeMsg(category, ms));
    return val;
}

pub fn time<T>(msg: &str, callback: &fn() -> T) -> T{
    let start_time = precise_time_ns();
    let val = callback();
    let end_time = precise_time_ns();
    let ms = ((end_time - start_time) as float / 1000000f);
    if ms >= 5f {
        debug!("%s took %? ms", msg, ms);
    }
    return val;
}

<|endoftext|>