<commit_before>/*!

# juniper_rocket

This repository contains the [Rocket][Rocket] web server integration for
[Juniper][Juniper], a [GraphQL][GraphQL] implementation for Rust.

## Documentation

For documentation, including guides and examples, check out [Juniper][Juniper].

A basic usage example can also be found in the [Api documentation][documentation].

## Examples

Check [examples/rocket_server.rs][example] for example code of a working Rocket
server with GraphQL handlers.

## Links

* [Juniper][Juniper]
* [Api Reference][documentation]
* [Rocket][Rocket]

## License

This project is under the BSD-2 license.

Check the LICENSE file for details.

[Rocket]: https://rocket.rs
[Juniper]: https://github.com/graphql-rust/juniper
[GraphQL]: http://graphql.org
[documentation]: https://docs.rs/juniper_rocket
[example]: https://github.com/graphql-rust/juniper_rocket/blob/master/examples/rocket_server.rs

*/

#![feature(plugin)]
#![plugin(rocket_codegen)]

extern crate juniper;
extern crate rocket;
extern crate serde_json;

use std::io::{Cursor, Read};
use std::error::Error;

use rocket::Request;
use rocket::request::{FormItems, FromForm};
use rocket::data::{FromData, Outcome as FromDataOutcome};
use rocket::response::{content, Responder, Response};
use rocket::http::{ContentType, Status};
use rocket::Data;
use rocket::Outcome::{Failure, Forward, Success};

use juniper::InputValue;
use juniper::http;

use juniper::GraphQLType;
use juniper::RootNode;

/// Simple wrapper around an incoming GraphQL request
///
/// See the `http` module for more information. This type can be constructed
/// automatically from both GET and POST routes by implementing the `FromForm`
/// and `FromData` traits.
#[derive(Debug, PartialEq)]
pub struct GraphQLRequest(http::GraphQLRequest);

/// Simple wrapper around the result of executing a GraphQL query
pub struct GraphQLResponse(Status, String);

/// Generate an HTML page containing GraphiQL
pub fn graphiql_source(graphql_endpoint_url: &str) -> content::Html<String> {
    content::Html(juniper::graphiql::graphiql_source(graphql_endpoint_url))
}

impl GraphQLRequest {
    /// Execute an incoming GraphQL query
    pub fn execute<CtxT, QueryT, MutationT>(
        &self,
        root_node: &RootNode<QueryT, MutationT>,
        context: &CtxT,
    ) -> GraphQLResponse
    where
        QueryT: GraphQLType<Context = CtxT>,
        MutationT: GraphQLType<Context = CtxT>,
    {
        let response = self.0.execute(root_node, context);
        let status = if response.is_ok() {
            Status::Ok
        } else {
            Status::BadRequest
        };
        let json = serde_json::to_string_pretty(&response).unwrap();

        GraphQLResponse(status, json)
    }
}

impl<'f> FromForm<'f> for GraphQLRequest {
    type Error = String;

    fn from_form(form_items: &mut FormItems<'f>, strict: bool) -> Result<Self, String> {
        let mut query = None;
        let mut operation_name = None;
        let mut variables = None;

        for (key, value) in form_items {
            // Note: we explicitly decode in the match arms to save work rather
            // than decoding every form item blindly.
            match key.as_str() {
                "query" => {
                    if query.is_some() {
                        return Err("Query parameter must not occur more than once".to_owned());
                    } else {
                        match value.url_decode() {
                            Ok(v) => query = Some(v),
                            Err(e) => return Err(e.description().to_string()),
                        }
                    }
                }
                "operation_name" => {
                    if operation_name.is_some() {
                        return Err("Operation name parameter must not occur more than once"
                            .to_owned());
                    } else {
                        match value.url_decode() {
                            Ok(v) => operation_name = Some(v),
                            Err(e) => return Err(e.description().to_string()),
                        }
                    }
                }
                "variables" => {
                    if variables.is_some() {
                        return Err("Variables parameter must not occur more than once".to_owned());
                    } else {
                        let decoded;
                        match value.url_decode() {
                            Ok(v) => decoded = v,
                            Err(e) => return Err(e.description().to_string()),
                        }
                        variables = Some(serde_json::from_str::<InputValue>(&decoded)
                            .map_err(|err| err.description().to_owned())?);
                    }
                }
                _ => {
                    if strict {
                        return Err(format!("Prohibited extra field '{}'", key).to_owned());
                    }
                }
            }
        }

        if let Some(query) = query {
            Ok(GraphQLRequest(http::GraphQLRequest::new(
                query,
                operation_name,
                variables,
            )))
        } else {
            Err("Query parameter missing".to_owned())
        }
    }
}

impl FromData for GraphQLRequest {
    type Error = String;

    fn from_data(request: &Request, data: Data) -> FromDataOutcome<Self, Self::Error> {
        if !request.content_type().map_or(false, |ct| ct.is_json()) {
            return Forward(data);
        }

        let mut body = String::new();
        if let Err(e) = data.open().read_to_string(&mut body) {
            return Failure((Status::InternalServerError, format!("{:?}", e)));
        }

        match serde_json::from_str(&body) {
            Ok(value) => Success(GraphQLRequest(value)),
            Err(failure) => return Failure((Status::BadRequest, format!("{}", failure))),
        }
    }
}

impl<'r> Responder<'r> for GraphQLResponse {
    fn respond_to(self, _: &Request) -> Result<Response<'r>, Status> {
        let GraphQLResponse(status, body) = self;

        Ok(Response::build()
            .header(ContentType::new("application", "json"))
            .status(status)
            .sized_body(Cursor::new(body))
            .finalize())
    }
}

#[cfg(test)]
mod fromform_tests {
    use super::*;
    use std::str;
    use juniper::InputValue;
    use rocket::request::{FormItems, FromForm};

    fn check_error(input: &str, error: &str, strict: bool) {
        let mut items = FormItems::from(input);
        let result = GraphQLRequest::from_form(&mut items, strict);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), error);
    }

    #[test]
    fn test_empty_form() {
        check_error("", "Query parameter missing", false);
    }

    #[test]
    fn test_no_query() {
        check_error(
            "operation_name=foo&variables={}",
            "Query parameter missing",
            false,
        );
    }

    #[test]
    fn test_strict() {
        check_error("query=test&foo=bar", "Prohibited extra field \'foo\'", true);
    }

    #[test]
    fn test_duplicate_query() {
        check_error(
            "query=foo&query=bar",
            "Query parameter must not occur more than once",
            false,
        );
    }

    #[test]
    fn test_duplicate_operation_name() {
        check_error(
            "query=test&operation_name=op1&operation_name=op2",
            "Operation name parameter must not occur more than once",
            false,
        );
    }

    #[test]
    fn test_duplicate_variables() {
        check_error(
            "query=test&variables={}&variables={}",
            "Variables parameter must not occur more than once",
            false,
        );
    }

    #[test]
    fn test_variables_invalid_json() {
        check_error("query=test&variables=NOT_JSON", "JSON error", false);
    }

    #[test]
    fn test_variables_valid_json() {
        let form_string = r#"query=test&variables={"foo":"bar"}"#;
        let mut items = FormItems::from(form_string);
        let result = GraphQLRequest::from_form(&mut items, false);
        assert!(result.is_ok());
        let variables = ::serde_json::from_str::<InputValue>(r#"{"foo":"bar"}"#).unwrap();
        let expected = GraphQLRequest(http::GraphQLRequest::new(
            "test".to_string(),
            None,
            Some(variables),
        ));
        assert_eq!(result.unwrap(), expected);
    }

    #[test]
    fn test_variables_encoded_json() {
        let form_string = r#"query=test&variables={"foo": "x%20y%26%3F+z"}"#;
        let mut items = FormItems::from(form_string);
        let result = GraphQLRequest::from_form(&mut items, false);
        assert!(result.is_ok());
        let variables = ::serde_json::from_str::<InputValue>(r#"{"foo":"x y&? z"}"#).unwrap();
        let expected = GraphQLRequest(http::GraphQLRequest::new(
            "test".to_string(),
            None,
            Some(variables),
        ));
        assert_eq!(result.unwrap(), expected);
    }

    #[test]
    fn test_url_decode() {
        let form_string = "query=%25foo%20bar+baz%26%3F&operation_name=test";
        let mut items = FormItems::from(form_string);
        let result = GraphQLRequest::from_form(&mut items, false);
        assert!(result.is_ok());
        let expected = GraphQLRequest(http::GraphQLRequest::new(
            "%foo bar baz&?".to_string(),
            Some("test".to_string()),
            None,
        ));
        assert_eq!(result.unwrap(), expected);
    }
}

#[cfg(test)]
mod tests {

    use rocket;
    use rocket::Rocket;
    use rocket::http::ContentType;
    use rocket::State;
    use rocket::local::{Client, LocalRequest};

    use juniper::RootNode;
    use juniper::tests::model::Database;
    use juniper::http::tests as http_tests;
    use juniper::EmptyMutation;

    type Schema = RootNode<'static, Database, EmptyMutation<Database>>;

    #[get("/?<request>")]
    fn get_graphql_handler(
        context: State<Database>,
        request: super::GraphQLRequest,
        schema: State<Schema>,
    ) -> super::GraphQLResponse {
        request.execute(&schema, &context)
    }

    #[post("/", data = "<request>")]
    fn post_graphql_handler(
        context: State<Database>,
        request: super::GraphQLRequest,
        schema: State<Schema>,
    ) -> super::GraphQLResponse {
        request.execute(&schema, &context)
    }

    struct TestRocketIntegration {
        client: Client,
    }

    impl http_tests::HTTPIntegration for TestRocketIntegration {
        fn get(&self, url: &str) -> http_tests::TestResponse {
            let req = &self.client.get(url);
            make_test_response(req)
        }

        fn post(&self, url: &str, body: &str) -> http_tests::TestResponse {
            let req = &self.client.post(url).header(ContentType::JSON).body(body);
            make_test_response(req)
        }
    }

    #[test]
    fn test_rocket_integration() {
        let rocket = make_rocket();
        let client = Client::new(rocket).expect("valid rocket");
        let integration = TestRocketIntegration { client };

        http_tests::run_http_test_suite(&integration);
    }

    fn make_rocket() -> Rocket {
        rocket::ignite()
            .manage(Database::new())
            .manage(Schema::new(
                Database::new(),
                EmptyMutation::<Database>::new(),
            ))
            .mount("/", routes![post_graphql_handler, get_graphql_handler])
    }

    fn make_test_response<'r>(request: &LocalRequest<'r>) -> http_tests::TestResponse {
        let mut response = request.cloned_dispatch();
        let status_code = response.status().code as i32;
        let content_type = response
            .content_type()
            .expect("No content type header from handler")
            .to_string();
        let body = response
            .body()
            .expect("No body returned from GraphQL handler")
            .into_string();

        http_tests::TestResponse {
            status_code: status_code,
            body: body,
            content_type: content_type,
        }
    }
}
<commit_msg>Change pretty json string to compact json string<commit_after>/*!

# juniper_rocket

This repository contains the [Rocket][Rocket] web server integration for
[Juniper][Juniper], a [GraphQL][GraphQL] implementation for Rust.

## Documentation

For documentation, including guides and examples, check out [Juniper][Juniper].

A basic usage example can also be found in the [Api documentation][documentation].

## Examples

Check [examples/rocket_server.rs][example] for example code of a working Rocket
server with GraphQL handlers.

## Links

* [Juniper][Juniper]
* [Api Reference][documentation]
* [Rocket][Rocket]

## License

This project is under the BSD-2 license.

Check the LICENSE file for details.

[Rocket]: https://rocket.rs
[Juniper]: https://github.com/graphql-rust/juniper
[GraphQL]: http://graphql.org
[documentation]: https://docs.rs/juniper_rocket
[example]: https://github.com/graphql-rust/juniper_rocket/blob/master/examples/rocket_server.rs

*/

#![feature(plugin)]
#![plugin(rocket_codegen)]

extern crate juniper;
extern crate rocket;
extern crate serde_json;

use std::io::{Cursor, Read};
use std::error::Error;

use rocket::Request;
use rocket::request::{FormItems, FromForm};
use rocket::data::{FromData, Outcome as FromDataOutcome};
use rocket::response::{content, Responder, Response};
use rocket::http::{ContentType, Status};
use rocket::Data;
use rocket::Outcome::{Failure, Forward, Success};

use juniper::InputValue;
use juniper::http;

use juniper::GraphQLType;
use juniper::RootNode;

/// Simple wrapper around an incoming GraphQL request
///
/// See the `http` module for more information. This type can be constructed
/// automatically from both GET and POST routes by implementing the `FromForm`
/// and `FromData` traits.
#[derive(Debug, PartialEq)]
pub struct GraphQLRequest(http::GraphQLRequest);

/// Simple wrapper around the result of executing a GraphQL query
pub struct GraphQLResponse(Status, String);

/// Generate an HTML page containing GraphiQL
pub fn graphiql_source(graphql_endpoint_url: &str) -> content::Html<String> {
    content::Html(juniper::graphiql::graphiql_source(graphql_endpoint_url))
}

impl GraphQLRequest {
    /// Execute an incoming GraphQL query
    pub fn execute<CtxT, QueryT, MutationT>(
        &self,
        root_node: &RootNode<QueryT, MutationT>,
        context: &CtxT,
    ) -> GraphQLResponse
    where
        QueryT: GraphQLType<Context = CtxT>,
        MutationT: GraphQLType<Context = CtxT>,
    {
        let response = self.0.execute(root_node, context);
        let status = if response.is_ok() {
            Status::Ok
        } else {
            Status::BadRequest
        };
        let json = serde_json::to_string(&response).unwrap();

        GraphQLResponse(status, json)
    }
}

impl<'f> FromForm<'f> for GraphQLRequest {
    type Error = String;

    fn from_form(form_items: &mut FormItems<'f>, strict: bool) -> Result<Self, String> {
        let mut query = None;
        let mut operation_name = None;
        let mut variables = None;

        for (key, value) in form_items {
            // Note: we explicitly decode in the match arms to save work rather
            // than decoding every form item blindly.
            match key.as_str() {
                "query" => {
                    if query.is_some() {
                        return Err("Query parameter must not occur more than once".to_owned());
                    } else {
                        match value.url_decode() {
                            Ok(v) => query = Some(v),
                            Err(e) => return Err(e.description().to_string()),
                        }
                    }
                }
                "operation_name" => {
                    if operation_name.is_some() {
                        return Err("Operation name parameter must not occur more than once"
                            .to_owned());
                    } else {
                        match value.url_decode() {
                            Ok(v) => operation_name = Some(v),
                            Err(e) => return Err(e.description().to_string()),
                        }
                    }
                }
                "variables" => {
                    if variables.is_some() {
                        return Err("Variables parameter must not occur more than once".to_owned());
                    } else {
                        let decoded;
                        match value.url_decode() {
                            Ok(v) => decoded = v,
                            Err(e) => return Err(e.description().to_string()),
                        }
                        variables = Some(serde_json::from_str::<InputValue>(&decoded)
                            .map_err(|err| err.description().to_owned())?);
                    }
                }
                _ => {
                    if strict {
                        return Err(format!("Prohibited extra field '{}'", key).to_owned());
                    }
                }
            }
        }

        if let Some(query) = query {
            Ok(GraphQLRequest(http::GraphQLRequest::new(
                query,
                operation_name,
                variables,
            )))
        } else {
            Err("Query parameter missing".to_owned())
        }
    }
}

impl FromData for GraphQLRequest {
    type Error = String;

    fn from_data(request: &Request, data: Data) -> FromDataOutcome<Self, Self::Error> {
        if !request.content_type().map_or(false, |ct| ct.is_json()) {
            return Forward(data);
        }

        let mut body = String::new();
        if let Err(e) = data.open().read_to_string(&mut body) {
            return Failure((Status::InternalServerError, format!("{:?}", e)));
        }

        match serde_json::from_str(&body) {
            Ok(value) => Success(GraphQLRequest(value)),
            Err(failure) => return Failure((Status::BadRequest, format!("{}", failure))),
        }
    }
}

impl<'r> Responder<'r> for GraphQLResponse {
    fn respond_to(self, _: &Request) -> Result<Response<'r>, Status> {
        let GraphQLResponse(status, body) = self;

        Ok(Response::build()
            .header(ContentType::new("application", "json"))
            .status(status)
            .sized_body(Cursor::new(body))
            .finalize())
    }
}

#[cfg(test)]
mod fromform_tests {
    use super::*;
    use std::str;
    use juniper::InputValue;
    use rocket::request::{FormItems, FromForm};

    fn check_error(input: &str, error: &str, strict: bool) {
        let mut items = FormItems::from(input);
        let result = GraphQLRequest::from_form(&mut items, strict);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), error);
    }

    #[test]
    fn test_empty_form() {
        check_error("", "Query parameter missing", false);
    }

    #[test]
    fn test_no_query() {
        check_error(
            "operation_name=foo&variables={}",
            "Query parameter missing",
            false,
        );
    }

    #[test]
    fn test_strict() {
        check_error("query=test&foo=bar", "Prohibited extra field \'foo\'", true);
    }

    #[test]
    fn test_duplicate_query() {
        check_error(
            "query=foo&query=bar",
            "Query parameter must not occur more than once",
            false,
        );
    }

    #[test]
    fn test_duplicate_operation_name() {
        check_error(
            "query=test&operation_name=op1&operation_name=op2",
            "Operation name parameter must not occur more than once",
            false,
        );
    }

    #[test]
    fn test_duplicate_variables() {
        check_error(
            "query=test&variables={}&variables={}",
            "Variables parameter must not occur more than once",
            false,
        );
    }

    #[test]
    fn test_variables_invalid_json() {
        check_error("query=test&variables=NOT_JSON", "JSON error", false);
    }

    #[test]
    fn test_variables_valid_json() {
        let form_string = r#"query=test&variables={"foo":"bar"}"#;
        let mut items = FormItems::from(form_string);
        let result = GraphQLRequest::from_form(&mut items, false);
        assert!(result.is_ok());
        let variables = ::serde_json::from_str::<InputValue>(r#"{"foo":"bar"}"#).unwrap();
        let expected = GraphQLRequest(http::GraphQLRequest::new(
            "test".to_string(),
            None,
            Some(variables),
        ));
        assert_eq!(result.unwrap(), expected);
    }

    #[test]
    fn test_variables_encoded_json() {
        let form_string = r#"query=test&variables={"foo": "x%20y%26%3F+z"}"#;
        let mut items = FormItems::from(form_string);
        let result = GraphQLRequest::from_form(&mut items, false);
        assert!(result.is_ok());
        let variables = ::serde_json::from_str::<InputValue>(r#"{"foo":"x y&? z"}"#).unwrap();
        let expected = GraphQLRequest(http::GraphQLRequest::new(
            "test".to_string(),
            None,
            Some(variables),
        ));
        assert_eq!(result.unwrap(), expected);
    }

    #[test]
    fn test_url_decode() {
        let form_string = "query=%25foo%20bar+baz%26%3F&operation_name=test";
        let mut items = FormItems::from(form_string);
        let result = GraphQLRequest::from_form(&mut items, false);
        assert!(result.is_ok());
        let expected = GraphQLRequest(http::GraphQLRequest::new(
            "%foo bar baz&?".to_string(),
            Some("test".to_string()),
            None,
        ));
        assert_eq!(result.unwrap(), expected);
    }
}

#[cfg(test)]
mod tests {

    use rocket;
    use rocket::Rocket;
    use rocket::http::ContentType;
    use rocket::State;
    use rocket::local::{Client, LocalRequest};

    use juniper::RootNode;
    use juniper::tests::model::Database;
    use juniper::http::tests as http_tests;
    use juniper::EmptyMutation;

    type Schema = RootNode<'static, Database, EmptyMutation<Database>>;

    #[get("/?<request>")]
    fn get_graphql_handler(
        context: State<Database>,
        request: super::GraphQLRequest,
        schema: State<Schema>,
    ) -> super::GraphQLResponse {
        request.execute(&schema, &context)
    }

    #[post("/", data = "<request>")]
    fn post_graphql_handler(
        context: State<Database>,
        request: super::GraphQLRequest,
        schema: State<Schema>,
    ) -> super::GraphQLResponse {
        request.execute(&schema, &context)
    }

    struct TestRocketIntegration {
        client: Client,
    }

    impl http_tests::HTTPIntegration for TestRocketIntegration {
        fn get(&self, url: &str) -> http_tests::TestResponse {
            let req = &self.client.get(url);
            make_test_response(req)
        }

        fn post(&self, url: &str, body: &str) -> http_tests::TestResponse {
            let req = &self.client.post(url).header(ContentType::JSON).body(body);
            make_test_response(req)
        }
    }

    #[test]
    fn test_rocket_integration() {
        let rocket = make_rocket();
        let client = Client::new(rocket).expect("valid rocket");
        let integration = TestRocketIntegration { client };

        http_tests::run_http_test_suite(&integration);
    }

    fn make_rocket() -> Rocket {
        rocket::ignite()
            .manage(Database::new())
            .manage(Schema::new(
                Database::new(),
                EmptyMutation::<Database>::new(),
            ))
            .mount("/", routes![post_graphql_handler, get_graphql_handler])
    }

    fn make_test_response<'r>(request: &LocalRequest<'r>) -> http_tests::TestResponse {
        let mut response = request.cloned_dispatch();
        let status_code = response.status().code as i32;
        let content_type = response
            .content_type()
            .expect("No content type header from handler")
            .to_string();
        let body = response
            .body()
            .expect("No body returned from GraphQL handler")
            .into_string();

        http_tests::TestResponse {
            status_code: status_code,
            body: body,
            content_type: content_type,
        }
    }
}
<|endoftext|>


<commit_before>#![feature(plugin)]
#![plugin(stainless)]

extern crate proton_cli;
extern crate tempdir;
extern crate git2;
extern crate rustc_serialize;

pub use std::{env, fs};
pub use std::fs::File;
pub use std::path::{Path, PathBuf};
pub use std::io::Read;

pub use git2::{Repository, Signature, Time};
pub use tempdir::TempDir;
pub use rustc_serialize::json;

pub use proton_cli::{Error, Project, initialize_project};

describe! initialize_project {
    before_each {
        let signature = Signature::now(
            "Proton Lights", "proton@teslaworks.net").unwrap();
        let root_dir = TempDir::new("proton_cli_tests").unwrap();
    }

    it "works with an empty directory" {
        let root = root_dir.path();
        initialize_project(root, &signature).expect("Initialization failed");
    }

    after_each {
        // Assert that exactly Protonfile.json and .git exist.
        let protonfile_path = root.join(Path::new("Protonfile.json"));
        let git_path = root.join(Path::new(".git"));
        assert!(protonfile_path.is_file());
        assert!(git_path.is_dir());
        assert_eq!(2, fs::read_dir(root).unwrap().count());

        // Check that protonfile has right content
        assert_eq!(Project::empty(), File::open(&protonfile_path)
            .and_then(|mut protonfile| {
                let mut content = "".to_owned();
                protonfile.read_to_string(&mut content).map(|_| content)
            })
            .map_err(Error::Io)
            .and_then(|content|
                json::decode(&content).map_err(Error::JsonDecode))
            .expect("Failed to load protonfile into Project"));

        // Open a git repo
        // Check that there is exactly 1 commit
        // Check that it includes the protonfile
        // Check that it has the right signature
    }
}
<commit_msg>Stuff<commit_after>#![feature(plugin)]
#![plugin(stainless)]

extern crate proton_cli;
extern crate tempdir;
extern crate git2;
extern crate rustc_serialize;

pub use std::{env, fs};
pub use std::fs::File;
pub use std::path::{Path, PathBuf};
pub use std::io::Read;

pub use git2::{Repository, Signature, Time};
pub use tempdir::TempDir;
pub use rustc_serialize::json;

pub use proton_cli::{Error, Project, initialize_project};

describe! initialize_project {
    before_each {
        let signature = Signature::now(
            "Proton Lights", "proton@teslaworks.net").unwrap();
        let root_dir = TempDir::new("proton_cli_tests").unwrap();
    }

    it "works with an empty directory" {
        let root = root_dir.path();
        initialize_project(root, &signature).expect("Initialization failed");
    }

    after_each {
        // Assert that exactly Protonfile.json and .git exist.
        let protonfile_path = root.join(Path::new("Protonfile.json"));
        let git_path = root.join(Path::new(".git"));
        assert!(protonfile_path.is_file());
        assert!(git_path.is_dir());
        assert_eq!(2, fs::read_dir(root).unwrap().count());

        // Check that protonfile has right content
        let protonfile_project = File::open(&protonfile_path)
            .and_then(|mut protonfile| {
                let mut content = "".to_owned();
                protonfile.read_to_string(&mut content).map(|_| content)
            })
            .map_err(Error::Io)
            .and_then(|content| json::decode(&content).map_err(Error::JsonDecode))
            .expect("Failed to load protonfile into Project");
        assert_eq!(Project::empty(), protonfile_project);

        // Open a git repo
        let repo = Repository::open(root).unwrap();
        match repo.refname_to_id("HEAD")
            .and_then(|oid| repo.find_commit(oid))
            .and_then(|commit| Ok(commit.message().unwrap().to_owned())) {
            Ok(c) => println!("{:?}", c),
            Err(e) => println!("{:?}", e),
        }
        panic!("Hellooerogerv");
        // Check that master has exactly 1 commit
        // Check that it includes the protonfile
        // Check that it has the right signature
    }
}
<|endoftext|>


<commit_before>extern crate assert;
extern crate fft;

mod fixtures;

#[test]
fn forward() {
    let mut data = fixtures::TIME_DATA.to_vec();
    fft::forward(&mut data);
    assert::close(&data, &fixtures::FREQUENCY_DATA[..], 1e-13);
}

#[test]
fn inverse() {
    let mut data = fixtures::FREQUENCY_DATA.to_vec();
    fft::inverse(&mut data, true);
    assert::close(&data, &fixtures::TIME_DATA[..], 1e-13);
}
<commit_msg>Increase the comparison precision in the tests<commit_after>extern crate assert;
extern crate fft;

mod fixtures;

#[test]
fn forward() {
    let mut data = fixtures::TIME_DATA.to_vec();
    fft::forward(&mut data);
    assert::close(&data, &fixtures::FREQUENCY_DATA[..], 1e-14);
}

#[test]
fn inverse() {
    let mut data = fixtures::FREQUENCY_DATA.to_vec();
    fft::inverse(&mut data, true);
    assert::close(&data, &fixtures::TIME_DATA[..], 1e-14);
}
<|endoftext|>


<commit_before>use std::net::IpAddr;
use std::io::{Write, ErrorKind};
use std::io::Read;

use mio::*;
use mio::tcp::TcpStream;
use mio::unix::UnixReady;
use nom::IResult::*;
use network::protocol::proxy_protocol::header;
use network::{Protocol, ClientResult};
use network::Readiness;
use network::protocol::ProtocolResult;
use network::socket::{SocketHandler, SocketResult};
use network::buffer_queue::BufferQueue;
use network::SessionMetrics;
use network::protocol::pipe::Pipe;
use parser::proxy_protocol::parse_v2_header;
use pool::Checkout;

pub struct RelayProxyProtocol<Front:SocketHandler> {
  pub header:         Option<Vec<u8>>,
  pub frontend:       Front,
  pub backend:        Option<TcpStream>,
  pub frontend_token: Option<Token>,
  pub backend_token:  Option<Token>,
  pub front_buf:      Checkout<BufferQueue>,
  pub readiness:      Readiness,
  cursor_header:      usize,
}

impl <Front:SocketHandler + Read>RelayProxyProtocol<Front> {
  pub fn new(frontend: Front, backend: Option<TcpStream>, front_buf: Checkout<BufferQueue>) -> Self {
    RelayProxyProtocol {
      header: None,
      frontend,
      backend,
      frontend_token: None,
      backend_token:  None,
      front_buf,
      readiness: Readiness {
        front_interest:  UnixReady::from(Ready::readable()) | UnixReady::hup() | UnixReady::error(),
        back_interest:   UnixReady::hup() | UnixReady::error(),
        front_readiness: UnixReady::from(Ready::empty()),
        back_readiness:  UnixReady::from(Ready::empty()),
      },
      cursor_header: 0,
    }
  }

  pub fn readable(&mut self, metrics: &mut SessionMetrics) -> ClientResult {
    let (sz, res) = self.frontend.socket_read(self.front_buf.buffer.space());
    debug!("FRONT proxy protocol [{:?}]: read {} bytes and res={:?}", self.frontend_token, sz, res);

    if sz > 0 {
      self.front_buf.buffer.fill(sz);
      self.front_buf.sliced_input(sz);
      self.front_buf.consume_parsed_data(sz);
      self.front_buf.slice_output(sz);

      let buf = self.front_buf.next_output_data();

      count!("bytes_in", sz as i64);
      metrics.bin += sz;

      match res {
        SocketResult::Continue
        | SocketResult::WouldBlock => {
          match parse_v2_header(buf) {
            Done(rest, header) => {
              debug!("We received the proxy protocol header: {:?}", header);
              self.header = Some(header.into_bytes());
              self.readiness.back_interest.insert(Ready::writable());
              self.readiness.front_readiness.remove(Ready::readable());
              return ClientResult::Continue
            },
            Incomplete(_) => {
              return ClientResult::Continue
            },
            Error(e) => {
              return ClientResult::CloseClient
            }
          }
        },
        SocketResult::Error => {
          error!("[{:?}] front socket error, closing the connection", self.frontend_token);
          metrics.service_stop();
          incr_ereq!();
          self.readiness.reset();
          return ClientResult::CloseClient
        }
      }
    }

    return ClientResult::Continue;
  }

  // The header is send immediately at once upon the connection is establish
  // and prepended before any data.
  pub fn back_writable(&mut self, metrics: &mut SessionMetrics) -> (ProtocolResult, ClientResult) {
    debug!("Writing proxy protocol header");

    if let Some(ref mut socket) = self.backend {
      if let Some(ref mut header) = self.header {
        loop {
          match socket.write(&mut header[self.cursor_header..]) {
            Ok(sz) => {
              self.cursor_header += sz;

              metrics.backend_bout += sz;

              if self.cursor_header == header.len() {
                debug!("Proxy protocol sent, upgrading");
                return (ProtocolResult::Upgrade, ClientResult::Continue)
              }
            },
            Err(e) => {
              metrics.service_stop();
              incr_ereq!();
              self.readiness.reset();
              debug!("PROXY PROTOCOL {}", e);
              break;
            },
          }
        }
      }
    }
    (ProtocolResult::Continue, ClientResult::Continue)
  }

  pub fn front_socket(&self) -> &TcpStream {
    self.frontend.socket_ref()
  }

  pub fn back_socket(&self) -> Option<&TcpStream> {
    self.backend.as_ref()
  }

  pub fn set_back_socket(&mut self, socket: TcpStream) {
    self.backend = Some(socket);
  }

  pub fn front_token(&self) -> Option<Token> {
    self.frontend_token
  }

  pub fn set_front_token(&mut self, token: Token) {
    self.frontend_token = Some(token);
  }

  pub fn back_token(&self) -> Option<Token> {
    self.backend_token
  }

  pub fn set_back_token(&mut self, token: Token) {
    self.backend_token = Some(token);
  }

  pub fn readiness(&mut self) -> &mut Readiness {
    &mut self.readiness
  }

  pub fn into_pipe(mut self, back_buf: Checkout<BufferQueue>) -> Pipe<Front> {
    let backend_socket = self.backend.take().unwrap();
    let addr = backend_socket.peer_addr().map(|s| s.ip()).ok();

    let mut pipe = Pipe::new(
      self.frontend.take(0).into_inner(),
      Some(backend_socket),
      self.front_buf,
      back_buf,
      addr,
    );

    pipe.readiness.front_readiness = self.readiness.front_readiness;
    pipe.readiness.back_readiness  = self.readiness.back_readiness;

    if let Some(front_token) = self.frontend_token {
      pipe.set_front_token(front_token);
    }

    if let Some(back_token) = self.backend_token {
      pipe.set_back_token(back_token);
    }

    pipe
  }
}
<commit_msg>fix relay logic<commit_after>use std::net::IpAddr;
use std::io::{Write, ErrorKind};
use std::io::Read;

use mio::*;
use mio::tcp::TcpStream;
use mio::unix::UnixReady;
use nom::IResult::*;
use nom::Offset;
use network::protocol::proxy_protocol::header;
use network::{Protocol, ClientResult};
use network::Readiness;
use network::protocol::ProtocolResult;
use network::socket::{SocketHandler, SocketResult};
use network::buffer_queue::BufferQueue;
use network::SessionMetrics;
use network::protocol::pipe::Pipe;
use parser::proxy_protocol::parse_v2_header;
use pool::Checkout;

pub struct RelayProxyProtocol<Front:SocketHandler> {
  pub header_size:    Option<usize>,
  pub frontend:       Front,
  pub backend:        Option<TcpStream>,
  pub frontend_token: Option<Token>,
  pub backend_token:  Option<Token>,
  pub front_buf:      Checkout<BufferQueue>,
  pub readiness:      Readiness,
  cursor_header:      usize,
}

impl <Front:SocketHandler + Read>RelayProxyProtocol<Front> {
  pub fn new(frontend: Front, backend: Option<TcpStream>, front_buf: Checkout<BufferQueue>) -> Self {
    RelayProxyProtocol {
      header_size: None,
      frontend,
      backend,
      frontend_token: None,
      backend_token:  None,
      front_buf,
      readiness: Readiness {
        front_interest:  UnixReady::from(Ready::readable()) | UnixReady::hup() | UnixReady::error(),
        back_interest:   UnixReady::hup() | UnixReady::error(),
        front_readiness: UnixReady::from(Ready::empty()),
        back_readiness:  UnixReady::from(Ready::empty()),
      },
      cursor_header: 0,
    }
  }

  pub fn readable(&mut self, metrics: &mut SessionMetrics) -> ClientResult {
    let (sz, res) = self.frontend.socket_read(self.front_buf.buffer.space());
    debug!("FRONT proxy protocol [{:?}]: read {} bytes and res={:?}", self.frontend_token, sz, res);

    if sz > 0 {
      self.front_buf.buffer.fill(sz);
      self.front_buf.sliced_input(sz);

      count!("bytes_in", sz as i64);
      metrics.bin += sz;

      if res == SocketResult::Error {
        error!("[{:?}] front socket error, closing the connection", self.frontend_token);
        metrics.service_stop();
        incr_ereq!();
        self.readiness.reset();
        return ClientResult::CloseClient;
      }

      if res == SocketResult::WouldBlock {
        self.readiness.front_readiness.remove(Ready::readable());
      }

      let read_sz = match parse_v2_header(self.front_buf.unparsed_data()) {
        Done(rest, header) => {
          self.readiness.front_interest.remove(Ready::readable());
          self.readiness.back_interest.insert(Ready::writable());
          self.front_buf.next_output_data().offset(rest)
        },
        Incomplete(_) => {
          return ClientResult::Continue
        },
        Error(e) => {
          return ClientResult::CloseClient
        }
      };

      self.header_size = Some(read_sz);
      self.front_buf.consume_parsed_data(sz);
      self.front_buf.slice_output(sz);
      return ClientResult::Continue
    }

    return ClientResult::Continue;
  }

  // The header is send immediately at once upon the connection is establish
  // and prepended before any data.
  pub fn back_writable(&mut self, metrics: &mut SessionMetrics) -> (ProtocolResult, ClientResult) {
    debug!("Writing proxy protocol header");

    if let Some(ref mut socket) = self.backend {
      if let Some(ref header_size) = self.header_size {
        loop {
          match socket.write(self.front_buf.next_output_data()) {
            Ok(sz) => {
              self.cursor_header += sz;

              metrics.backend_bout += sz;
              self.front_buf.consume_output_data(sz);

              if self.cursor_header >= *header_size {
                info!("Proxy protocol sent, upgrading");
                return (ProtocolResult::Upgrade, ClientResult::Continue)
              }
            },
            Err(e) => {
              metrics.service_stop();
              incr_ereq!();
              self.readiness.reset();
              debug!("PROXY PROTOCOL {}", e);
              break;
            },
          }
        }
      }
    }
    (ProtocolResult::Continue, ClientResult::Continue)
  }

  pub fn front_socket(&self) -> &TcpStream {
    self.frontend.socket_ref()
  }

  pub fn back_socket(&self) -> Option<&TcpStream> {
    self.backend.as_ref()
  }

  pub fn set_back_socket(&mut self, socket: TcpStream) {
    self.backend = Some(socket);
  }

  pub fn front_token(&self) -> Option<Token> {
    self.frontend_token
  }

  pub fn set_front_token(&mut self, token: Token) {
    self.frontend_token = Some(token);
  }

  pub fn back_token(&self) -> Option<Token> {
    self.backend_token
  }

  pub fn set_back_token(&mut self, token: Token) {
    self.backend_token = Some(token);
  }

  pub fn readiness(&mut self) -> &mut Readiness {
    &mut self.readiness
  }

  pub fn into_pipe(mut self, back_buf: Checkout<BufferQueue>) -> Pipe<Front> {
    let backend_socket = self.backend.take().unwrap();
    let addr = backend_socket.peer_addr().map(|s| s.ip()).ok();

    let mut pipe = Pipe::new(
      self.frontend.take(0).into_inner(),
      Some(backend_socket),
      self.front_buf,
      back_buf,
      addr,
    );

    pipe.readiness.front_readiness = self.readiness.front_readiness;
    pipe.readiness.back_readiness  = self.readiness.back_readiness;

    if let Some(front_token) = self.frontend_token {
      pipe.set_front_token(front_token);
    }

    if let Some(back_token) = self.backend_token {
      pipe.set_back_token(back_token);
    }

    pipe
  }
}
<|endoftext|>


<commit_before>extern crate getopts;

use std::env;
use getopts::Options;

fn start(files: &Vec<String>, flag_n:bool){
    for filename in files{
        println!("{}", filename);
    }
}

fn print_usage(program: &str, options:Options){
    let brief = format!("{} [-n] file [file..]", program);
    print!("{}", options.usage(&brief));
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let mut parser = Options::new();
    let program = args[0].clone();

    parser.optflag("n", "", "Number the output lines, starting at 1.");

    let options = match parser.parse(&args[1..]){
        Ok(m) => {m}
        Err(f) => { panic!(f.to_string())}
    };

    let flag_n = options.opt_present("n");

    if options.free.is_empty(){
        print_usage(&program, parser);
        return;
    }

    start(&options.free, flag_n);
}
<commit_msg>added the cat command's basic feature<commit_after>extern crate getopts;

use std::env;
use std::io;
use std::io::prelude::*;
use std::fs::File;
use getopts::Options;

fn run(filename:String, flag_n:bool) -> Result<(String),io::Error>{
    println!("{}, {}", filename, flag_n);
    let mut file = try!(File::open(filename));
    let mut content = String::new();
    try!(file.read_to_string(&mut content));
    Ok(content)
}

fn start(files: Vec<String>, flag_n:bool){
    for filename in files{
        match run(filename, flag_n){
            Err(reason) => panic!(reason),
            Ok(content) => print!("{}", content)
        }
    }
}

fn print_usage(program: &str, options:Options){
    let brief = format!("{} [-n] file [file..]", program);
    print!("{}", options.usage(&brief));
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let mut parser = Options::new();
    let program = args[0].clone();

    parser.optflag("n", "", "Number the output lines, starting at 1.");

    let options = match parser.parse(&args[1..]){
        Ok(m) => {m}
        Err(f) => { panic!(f.to_string())}
    };

    let flag_n = options.opt_present("n");

    if options.free.is_empty(){
        print_usage(&program, parser);
        return;
    }

    start(options.free, flag_n);
}
<|endoftext|>


<commit_before>extern crate libc;
extern crate fst;

use std::error::Error;
use std::fs::File;
use std::io;
use std::ptr;
use fst::{IntoStreamer, Streamer, Levenshtein, Set, SetBuilder};
use fst::set;

use util::{Context, cstr_to_str, to_raw_ptr};

pub type FileSetBuilder = SetBuilder<&'static mut io::BufWriter<File>>;
pub type MemSetBuilder = SetBuilder<Vec<u8>>;
pub type SetLevStream = set::Stream<'static, &'static Levenshtein>;

#[no_mangle]
pub extern "C" fn fst_filesetbuilder_new(ctx: *mut Context,
                                         wtr_ptr: *mut io::BufWriter<File>)
                                         -> *mut FileSetBuilder {
    let wtr = mutref_from_ptr!(wtr_ptr);
    to_raw_ptr(with_context!(ctx, ptr::null_mut(), SetBuilder::new(wtr)))
}

#[no_mangle]
pub extern "C" fn fst_filesetbuilder_insert(ctx: *mut Context,
                                            ptr: *mut FileSetBuilder,
                                            s: *mut libc::c_char)
                                            -> bool {
    let build = mutref_from_ptr!(ptr);
    with_context!(ctx, false, build.insert(cstr_to_str(s)));
    true
}

#[no_mangle]
pub extern "C" fn fst_filesetbuilder_finish(ctx: *mut Context, ptr: *mut FileSetBuilder) -> bool {
    let build = val_from_ptr!(ptr);
    with_context!(ctx, false, build.finish());
    true
}

#[no_mangle]
pub extern "C" fn fst_memsetbuilder_new() -> *mut MemSetBuilder {
    to_raw_ptr(SetBuilder::memory())
}

#[no_mangle]
pub extern "C" fn fst_memsetbuilder_insert(ctx: *mut Context,
                                           ptr: *mut MemSetBuilder,
                                           s: *mut libc::c_char)
                                           -> bool {
    let build = mutref_from_ptr!(ptr);
    with_context!(ctx, false, build.insert(cstr_to_str(s)));
    true
}

#[no_mangle]
pub extern "C" fn fst_memsetbuilder_finish(ctx: *mut Context, ptr: *mut MemSetBuilder) -> *mut Set {
    let build = val_from_ptr!(ptr);
    let data = with_context!(ctx, ptr::null_mut(), build.into_inner());
    let set = with_context!(ctx, ptr::null_mut(), Set::from_bytes(data));
    to_raw_ptr(set)
}

#[no_mangle]
pub extern "C" fn fst_set_open(ctx: *mut Context, cpath: *mut libc::c_char) -> *mut Set {
    let path = cstr_to_str(cpath);
    let set = with_context!(ctx, ptr::null_mut(), Set::from_path(path));
    to_raw_ptr(set)
}
make_free_fn!(fst_set_free, *mut Set);

#[no_mangle]
pub extern "C" fn fst_set_contains(ptr: *mut Set, s: *mut libc::c_char) -> bool {
    let set = mutref_from_ptr!(ptr);
    set.contains(cstr_to_str(s))
}

#[no_mangle]
pub extern "C" fn fst_set_stream(ptr: *mut Set) -> *mut set::Stream<'static> {
    let set = mutref_from_ptr!(ptr);
    to_raw_ptr(set.stream())
}
make_free_fn!(fst_set_stream_free, *mut set::Stream);
set_make_next_fn!(fst_set_stream_next, *mut set::Stream);

#[no_mangle]
pub extern "C" fn fst_set_len(ptr: *mut Set) -> libc::size_t {
    let set = mutref_from_ptr!(ptr);
    set.len()
}

#[no_mangle]
pub extern "C" fn fst_set_isdisjoint(self_ptr: *mut Set, oth_ptr: *mut Set) -> bool {
    let slf = ref_from_ptr!(self_ptr);
    let oth = ref_from_ptr!(oth_ptr);
    slf.is_disjoint(oth)
}

#[no_mangle]
pub extern "C" fn fst_set_issubset(self_ptr: *mut Set, oth_ptr: *mut Set) -> bool {
    let slf = ref_from_ptr!(self_ptr);
    let oth = ref_from_ptr!(oth_ptr);
    slf.is_subset(oth)
}

#[no_mangle]
pub extern "C" fn fst_set_issuperset(self_ptr: *mut Set, oth_ptr: *mut Set) -> bool {
    let slf = ref_from_ptr!(self_ptr);
    let oth = ref_from_ptr!(oth_ptr);
    slf.is_superset(oth)
}

#[no_mangle]
pub extern "C" fn fst_set_levsearch(set_ptr: *mut Set,
                                    lev_ptr: *mut Levenshtein)
                                    -> *mut SetLevStream {
    let set = mutref_from_ptr!(set_ptr);
    let lev = ref_from_ptr!(lev_ptr);
    to_raw_ptr(set.search(lev).into_stream())
}
make_free_fn!(fst_set_levstream_free, *mut SetLevStream);
set_make_next_fn!(fst_set_levstream_next, *mut SetLevStream);

#[no_mangle]
pub extern "C" fn fst_set_make_opbuilder(ptr: *mut Set) -> *mut set::OpBuilder<'static> {
    let set = ref_from_ptr!(ptr);
    let ob = set.op();
    to_raw_ptr(ob)
}
make_free_fn!(fst_set_opbuilder_free, *mut set::OpBuilder<'static>);

#[no_mangle]
pub extern "C" fn fst_set_opbuilder_push(ptr: *mut set::OpBuilder, set_ptr: *mut Set) {
    let set = ref_from_ptr!(set_ptr);
    let ob = mutref_from_ptr!(ptr);
    ob.push(set);
}

#[no_mangle]
pub extern "C" fn fst_set_opbuilder_union(ptr: *mut set::OpBuilder<'static>)
                                          -> *mut set::Union<'static> {
    let ob = val_from_ptr!(ptr);
    to_raw_ptr(ob.union())
}
make_free_fn!(fst_set_union_free, *mut set::Union<'static>);
set_make_next_fn!(fst_set_union_next, *mut set::Union<'static>);

#[no_mangle]
pub extern "C" fn fst_set_opbuilder_intersection(ptr: *mut set::OpBuilder<'static>)
                                                 -> *mut set::Intersection<'static> {
    let ob = val_from_ptr!(ptr);
    to_raw_ptr(ob.intersection())
}
make_free_fn!(fst_set_intersection_free, *mut set::Intersection);
set_make_next_fn!(fst_set_intersection_next, *mut set::Intersection);

#[no_mangle]
pub extern "C" fn fst_set_opbuilder_difference(ptr: *mut set::OpBuilder<'static>)
                                               -> *mut set::Difference<'static> {
    let ob = val_from_ptr!(ptr);
    to_raw_ptr(ob.difference())
}
make_free_fn!(fst_set_difference_free, *mut set::Difference);
set_make_next_fn!(fst_set_difference_next, *mut set::Difference);

#[no_mangle]
pub extern "C" fn fst_set_opbuilder_symmetricdifference
    (ptr: *mut set::OpBuilder<'static>)
     -> *mut set::SymmetricDifference<'static> {
    let ob = val_from_ptr!(ptr);
    to_raw_ptr(ob.symmetric_difference())
}
make_free_fn!(fst_set_symmetricdifference_free, *mut set::SymmetricDifference);
set_make_next_fn!(fst_set_symmetricdifference_next, *mut set::SymmetricDifference);
<commit_msg>fstwrapper: remove some unneccesary 'static parameters<commit_after>extern crate libc;
extern crate fst;

use std::error::Error;
use std::fs::File;
use std::io;
use std::ptr;
use fst::{IntoStreamer, Streamer, Levenshtein, Set, SetBuilder};
use fst::set;

use util::{Context, cstr_to_str, to_raw_ptr};

pub type FileSetBuilder = SetBuilder<&'static mut io::BufWriter<File>>;
pub type MemSetBuilder = SetBuilder<Vec<u8>>;
pub type SetLevStream = set::Stream<'static, &'static Levenshtein>;

#[no_mangle]
pub extern "C" fn fst_filesetbuilder_new(ctx: *mut Context,
                                         wtr_ptr: *mut io::BufWriter<File>)
                                         -> *mut FileSetBuilder {
    let wtr = mutref_from_ptr!(wtr_ptr);
    to_raw_ptr(with_context!(ctx, ptr::null_mut(), SetBuilder::new(wtr)))
}

#[no_mangle]
pub extern "C" fn fst_filesetbuilder_insert(ctx: *mut Context,
                                            ptr: *mut FileSetBuilder,
                                            s: *mut libc::c_char)
                                            -> bool {
    let build = mutref_from_ptr!(ptr);
    with_context!(ctx, false, build.insert(cstr_to_str(s)));
    true
}

#[no_mangle]
pub extern "C" fn fst_filesetbuilder_finish(ctx: *mut Context, ptr: *mut FileSetBuilder) -> bool {
    let build = val_from_ptr!(ptr);
    with_context!(ctx, false, build.finish());
    true
}

#[no_mangle]
pub extern "C" fn fst_memsetbuilder_new() -> *mut MemSetBuilder {
    to_raw_ptr(SetBuilder::memory())
}

#[no_mangle]
pub extern "C" fn fst_memsetbuilder_insert(ctx: *mut Context,
                                           ptr: *mut MemSetBuilder,
                                           s: *mut libc::c_char)
                                           -> bool {
    let build = mutref_from_ptr!(ptr);
    with_context!(ctx, false, build.insert(cstr_to_str(s)));
    true
}

#[no_mangle]
pub extern "C" fn fst_memsetbuilder_finish(ctx: *mut Context, ptr: *mut MemSetBuilder) -> *mut Set {
    let build = val_from_ptr!(ptr);
    let data = with_context!(ctx, ptr::null_mut(), build.into_inner());
    let set = with_context!(ctx, ptr::null_mut(), Set::from_bytes(data));
    to_raw_ptr(set)
}

#[no_mangle]
pub extern "C" fn fst_set_open(ctx: *mut Context, cpath: *mut libc::c_char) -> *mut Set {
    let path = cstr_to_str(cpath);
    let set = with_context!(ctx, ptr::null_mut(), Set::from_path(path));
    to_raw_ptr(set)
}
make_free_fn!(fst_set_free, *mut Set);

#[no_mangle]
pub extern "C" fn fst_set_contains(ptr: *mut Set, s: *mut libc::c_char) -> bool {
    let set = mutref_from_ptr!(ptr);
    set.contains(cstr_to_str(s))
}

#[no_mangle]
pub extern "C" fn fst_set_stream(ptr: *mut Set) -> *mut set::Stream<'static> {
    let set = mutref_from_ptr!(ptr);
    to_raw_ptr(set.stream())
}
make_free_fn!(fst_set_stream_free, *mut set::Stream);
set_make_next_fn!(fst_set_stream_next, *mut set::Stream);

#[no_mangle]
pub extern "C" fn fst_set_len(ptr: *mut Set) -> libc::size_t {
    let set = mutref_from_ptr!(ptr);
    set.len()
}

#[no_mangle]
pub extern "C" fn fst_set_isdisjoint(self_ptr: *mut Set, oth_ptr: *mut Set) -> bool {
    let slf = ref_from_ptr!(self_ptr);
    let oth = ref_from_ptr!(oth_ptr);
    slf.is_disjoint(oth)
}

#[no_mangle]
pub extern "C" fn fst_set_issubset(self_ptr: *mut Set, oth_ptr: *mut Set) -> bool {
    let slf = ref_from_ptr!(self_ptr);
    let oth = ref_from_ptr!(oth_ptr);
    slf.is_subset(oth)
}

#[no_mangle]
pub extern "C" fn fst_set_issuperset(self_ptr: *mut Set, oth_ptr: *mut Set) -> bool {
    let slf = ref_from_ptr!(self_ptr);
    let oth = ref_from_ptr!(oth_ptr);
    slf.is_superset(oth)
}

#[no_mangle]
pub extern "C" fn fst_set_levsearch(set_ptr: *mut Set,
                                    lev_ptr: *mut Levenshtein)
                                    -> *mut SetLevStream {
    let set = mutref_from_ptr!(set_ptr);
    let lev = ref_from_ptr!(lev_ptr);
    to_raw_ptr(set.search(lev).into_stream())
}
make_free_fn!(fst_set_levstream_free, *mut SetLevStream);
set_make_next_fn!(fst_set_levstream_next, *mut SetLevStream);

#[no_mangle]
pub extern "C" fn fst_set_make_opbuilder(ptr: *mut Set) -> *mut set::OpBuilder<'static> {
    let set = ref_from_ptr!(ptr);
    let ob = set.op();
    to_raw_ptr(ob)
}
make_free_fn!(fst_set_opbuilder_free, *mut set::OpBuilder);

#[no_mangle]
pub extern "C" fn fst_set_opbuilder_push(ptr: *mut set::OpBuilder, set_ptr: *mut Set) {
    let set = ref_from_ptr!(set_ptr);
    let ob = mutref_from_ptr!(ptr);
    ob.push(set);
}

#[no_mangle]
pub extern "C" fn fst_set_opbuilder_union(ptr: *mut set::OpBuilder)
                                          -> *mut set::Union {
    let ob = val_from_ptr!(ptr);
    to_raw_ptr(ob.union())
}
make_free_fn!(fst_set_union_free, *mut set::Union);
set_make_next_fn!(fst_set_union_next, *mut set::Union);

#[no_mangle]
pub extern "C" fn fst_set_opbuilder_intersection(ptr: *mut set::OpBuilder)
                                                 -> *mut set::Intersection {
    let ob = val_from_ptr!(ptr);
    to_raw_ptr(ob.intersection())
}
make_free_fn!(fst_set_intersection_free, *mut set::Intersection);
set_make_next_fn!(fst_set_intersection_next, *mut set::Intersection);

#[no_mangle]
pub extern "C" fn fst_set_opbuilder_difference(ptr: *mut set::OpBuilder)
                                               -> *mut set::Difference {
    let ob = val_from_ptr!(ptr);
    to_raw_ptr(ob.difference())
}
make_free_fn!(fst_set_difference_free, *mut set::Difference);
set_make_next_fn!(fst_set_difference_next, *mut set::Difference);

#[no_mangle]
pub extern "C" fn fst_set_opbuilder_symmetricdifference
    (ptr: *mut set::OpBuilder)
     -> *mut set::SymmetricDifference {
    let ob = val_from_ptr!(ptr);
    to_raw_ptr(ob.symmetric_difference())
}
make_free_fn!(fst_set_symmetricdifference_free, *mut set::SymmetricDifference);
set_make_next_fn!(fst_set_symmetricdifference_next, *mut set::SymmetricDifference);
<|endoftext|>


<commit_before>// Copyright 2017 Serde Developers
//
// 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.

#![doc(html_root_url = "https://docs.rs/serde_derive/0.9.14")]

#![cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
#![cfg_attr(feature = "cargo-clippy", allow(used_underscore_binding))]

// The `quote!` macro requires deep recursion.
#![recursion_limit = "192"]

extern crate syn;
#[macro_use]
extern crate quote;

extern crate serde_derive_internals as internals;

extern crate proc_macro;
use proc_macro::TokenStream;

#[macro_use]
mod bound;
#[macro_use]
mod fragment;

mod ser;
mod de;

#[proc_macro_derive(Serialize, attributes(serde))]
pub fn derive_serialize(input: TokenStream) -> TokenStream {
    let input = syn::parse_derive_input(&input.to_string()).unwrap();
    match ser::expand_derive_serialize(&input) {
        Ok(expanded) => expanded.parse().unwrap(),
        Err(msg) => panic!(msg),
    }
}

#[proc_macro_derive(Deserialize, attributes(serde))]
pub fn derive_deserialize(input: TokenStream) -> TokenStream {
    let input = syn::parse_derive_input(&input.to_string()).unwrap();
    match de::expand_derive_deserialize(&input) {
        Ok(expanded) => expanded.parse().unwrap(),
        Err(msg) => panic!(msg),
    }
}
<commit_msg>Minimal serde_derive documentation<commit_after>// Copyright 2017 Serde Developers
//
// 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 crate provides Serde's two derive macros.
//!
//! ```rust,ignore
//! #[derive(Serialize, Deserialize)]
//! ```
//!
//! Please refer to [https://serde.rs/derive.html] for how to set this up.
//!
//! [https://serde.rs/derive.html]: https://serde.rs/derive.html

#![doc(html_root_url = "https://docs.rs/serde_derive/0.9.14")]

#![cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
#![cfg_attr(feature = "cargo-clippy", allow(used_underscore_binding))]

// The `quote!` macro requires deep recursion.
#![recursion_limit = "192"]

extern crate syn;
#[macro_use]
extern crate quote;

extern crate serde_derive_internals as internals;

extern crate proc_macro;
use proc_macro::TokenStream;

#[macro_use]
mod bound;
#[macro_use]
mod fragment;

mod ser;
mod de;

#[proc_macro_derive(Serialize, attributes(serde))]
pub fn derive_serialize(input: TokenStream) -> TokenStream {
    let input = syn::parse_derive_input(&input.to_string()).unwrap();
    match ser::expand_derive_serialize(&input) {
        Ok(expanded) => expanded.parse().unwrap(),
        Err(msg) => panic!(msg),
    }
}

#[proc_macro_derive(Deserialize, attributes(serde))]
pub fn derive_deserialize(input: TokenStream) -> TokenStream {
    let input = syn::parse_derive_input(&input.to_string()).unwrap();
    match de::expand_derive_deserialize(&input) {
        Ok(expanded) => expanded.parse().unwrap(),
        Err(msg) => panic!(msg),
    }
}
<|endoftext|>


<commit_before>use triangle::*;

#[test]
fn positive_length_sides_are_ok() {
    let sides = [2, 2, 2];
    let triangle = Triangle::build(sides);
    assert!(triangle.is_some());
}

#[test]
#[ignore]
fn zero_length_sides_are_illegal() {
    let sides = [0, 0, 0];
    let triangle = Triangle::build(sides);
    assert!(triangle.is_none());
}

#[test]
#[ignore]
fn equilateral_triangles_have_equal_sides() {
    let sides = [2, 2, 2];
    let triangle = Triangle::build(sides).unwrap();
    assert!(triangle.is_equilateral());
    assert!(!triangle.is_scalene());
}

#[test]
#[ignore]
fn larger_equilateral_triangles_have_equal_sides() {
    let sides = [10, 10, 10];
    let triangle = Triangle::build(sides).unwrap();
    assert!(triangle.is_equilateral());
    assert!(!triangle.is_scalene());
}

#[test]
#[ignore]
fn isosceles_triangles_have_two_equal_sides_one() {
    let sides = [3, 4, 4];
    let triangle = Triangle::build(sides).unwrap();
    assert!(!triangle.is_equilateral());
    assert!(triangle.is_isosceles());
    assert!(!triangle.is_scalene());
}

#[test]
#[ignore]
fn isosceles_triangles_have_two_equal_sides_two() {
    let sides = [4, 4, 3];
    let triangle = Triangle::build(sides).unwrap();
    assert!(!triangle.is_equilateral());
    assert!(triangle.is_isosceles());
    assert!(!triangle.is_scalene());
}

#[test]
#[ignore]
fn isosceles_triangles_have_two_equal_sides_three() {
    let sides = [4, 3, 4];
    let triangle = Triangle::build(sides).unwrap();
    assert!(!triangle.is_equilateral());
    assert!(triangle.is_isosceles());
    assert!(!triangle.is_scalene());
}

#[test]
#[ignore]
fn isosceles_triangles_have_two_equal_sides_four() {
    let sides = [4, 7, 4];
    let triangle = Triangle::build(sides).unwrap();
    assert!(!triangle.is_equilateral());
    assert!(triangle.is_isosceles());
    assert!(!triangle.is_scalene());
}

#[test]
#[ignore]
fn scalene_triangle_has_no_equal_sides_one() {
    let sides = [3, 4, 5];
    let triangle = Triangle::build(sides).unwrap();
    assert!(!triangle.is_equilateral());
    assert!(!triangle.is_isosceles());
    assert!(triangle.is_scalene());
}

#[test]
#[ignore]
fn scalene_triangle_has_no_equal_sides_two() {
    let sides = [5, 4, 6];
    let triangle = Triangle::build(sides).unwrap();
    assert!(!triangle.is_equilateral());
    assert!(!triangle.is_isosceles());
    assert!(triangle.is_scalene());
}

#[test]
#[ignore]
fn scalene_triangle_has_no_equal_sides_three() {
    let sides = [10, 11, 12];
    let triangle = Triangle::build(sides).unwrap();
    assert!(!triangle.is_equilateral());
    assert!(!triangle.is_isosceles());
    assert!(triangle.is_scalene());
}

#[test]
#[ignore]
fn scalene_triangle_has_no_equal_sides_four() {
    let sides = [5, 4, 2];
    let triangle = Triangle::build(sides).unwrap();
    assert!(!triangle.is_equilateral());
    assert!(!triangle.is_isosceles());
    assert!(triangle.is_scalene());
}

#[test]
#[ignore]
fn sum_of_two_sides_must_equal_or_exceed_the_remaining_side_one() {
    let sides = [7, 3, 2];
    let triangle = Triangle::build(sides);
    assert!(triangle.is_none());
}

#[test]
#[ignore]
fn sum_of_two_sides_must_equal_or_exceed_the_remaining_side_two() {
    let sides = [1, 1, 3];
    let triangle = Triangle::build(sides);
    assert!(triangle.is_none());
}

#[test]
#[ignore]
#[cfg(feature = "generic")]
fn scalene_triangle_with_floating_point_sides() {
    let sides = [0.4, 0.6, 0.3];
    let triangle = Triangle::build(sides).unwrap();
    assert!(!triangle.is_equilateral());
    assert!(!triangle.is_isosceles());
    assert!(triangle.is_scalene());
}

#[test]
#[ignore]
#[cfg(feature = "generic")]
fn equilateral_triangles_with_floating_point_sides() {
    let sides = [0.2, 0.2, 0.2];
    let triangle = Triangle::build(sides).unwrap();
    assert!(triangle.is_equilateral());
    assert!(!triangle.is_scalene());
}

#[test]
#[ignore]
#[cfg(feature = "generic")]
fn isosceles_triangle_with_floating_point_sides() {
    let sides = [0.3, 0.4, 0.4];
    let triangle = Triangle::build(sides).unwrap();
    assert!(!triangle.is_equilateral());
    assert!(triangle.is_isosceles());
    assert!(!triangle.is_scalene());
}
<commit_msg>Added tests for only one side being zero<commit_after>use triangle::*;

#[test]
fn positive_length_sides_are_ok() {
    let sides = [2, 2, 2];
    let triangle = Triangle::build(sides);
    assert!(triangle.is_some());
}

#[test]
#[ignore]
fn zero_length_sides_are_illegal() {
    let sides = [0, 0, 0];
    let triangle = Triangle::build(sides);
    assert!(triangle.is_none());
}

#[test]
#[ignore]
fn one_length_zero_side_first() {
    let sides = [0, 2, 2];
    let triangle = Triangle::build(sides);
    assert!(triangle.is_none());
}

#[test]
#[ignore]
fn one_length_zero_side_second() {
    let sides = [2, 0, 2];
    let triangle = Triangle::build(sides);
    assert!(triangle.is_none());
}

#[test]
#[ignore]
fn one_length_zero_side_third() {
    let sides = [2, 2, 0];
    let triangle = Triangle::build(sides);
    assert!(triangle.is_none());
}

#[test]
#[ignore]
fn equilateral_triangles_have_equal_sides() {
    let sides = [2, 2, 2];
    let triangle = Triangle::build(sides).unwrap();
    assert!(triangle.is_equilateral());
    assert!(!triangle.is_scalene());
}

#[test]
#[ignore]
fn larger_equilateral_triangles_have_equal_sides() {
    let sides = [10, 10, 10];
    let triangle = Triangle::build(sides).unwrap();
    assert!(triangle.is_equilateral());
    assert!(!triangle.is_scalene());
}

#[test]
#[ignore]
fn isosceles_triangles_have_two_equal_sides_one() {
    let sides = [3, 4, 4];
    let triangle = Triangle::build(sides).unwrap();
    assert!(!triangle.is_equilateral());
    assert!(triangle.is_isosceles());
    assert!(!triangle.is_scalene());
}

#[test]
#[ignore]
fn isosceles_triangles_have_two_equal_sides_two() {
    let sides = [4, 4, 3];
    let triangle = Triangle::build(sides).unwrap();
    assert!(!triangle.is_equilateral());
    assert!(triangle.is_isosceles());
    assert!(!triangle.is_scalene());
}

#[test]
#[ignore]
fn isosceles_triangles_have_two_equal_sides_three() {
    let sides = [4, 3, 4];
    let triangle = Triangle::build(sides).unwrap();
    assert!(!triangle.is_equilateral());
    assert!(triangle.is_isosceles());
    assert!(!triangle.is_scalene());
}

#[test]
#[ignore]
fn isosceles_triangles_have_two_equal_sides_four() {
    let sides = [4, 7, 4];
    let triangle = Triangle::build(sides).unwrap();
    assert!(!triangle.is_equilateral());
    assert!(triangle.is_isosceles());
    assert!(!triangle.is_scalene());
}

#[test]
#[ignore]
fn scalene_triangle_has_no_equal_sides_one() {
    let sides = [3, 4, 5];
    let triangle = Triangle::build(sides).unwrap();
    assert!(!triangle.is_equilateral());
    assert!(!triangle.is_isosceles());
    assert!(triangle.is_scalene());
}

#[test]
#[ignore]
fn scalene_triangle_has_no_equal_sides_two() {
    let sides = [5, 4, 6];
    let triangle = Triangle::build(sides).unwrap();
    assert!(!triangle.is_equilateral());
    assert!(!triangle.is_isosceles());
    assert!(triangle.is_scalene());
}

#[test]
#[ignore]
fn scalene_triangle_has_no_equal_sides_three() {
    let sides = [10, 11, 12];
    let triangle = Triangle::build(sides).unwrap();
    assert!(!triangle.is_equilateral());
    assert!(!triangle.is_isosceles());
    assert!(triangle.is_scalene());
}

#[test]
#[ignore]
fn scalene_triangle_has_no_equal_sides_four() {
    let sides = [5, 4, 2];
    let triangle = Triangle::build(sides).unwrap();
    assert!(!triangle.is_equilateral());
    assert!(!triangle.is_isosceles());
    assert!(triangle.is_scalene());
}

#[test]
#[ignore]
fn sum_of_two_sides_must_equal_or_exceed_the_remaining_side_one() {
    let sides = [7, 3, 2];
    let triangle = Triangle::build(sides);
    assert!(triangle.is_none());
}

#[test]
#[ignore]
fn sum_of_two_sides_must_equal_or_exceed_the_remaining_side_two() {
    let sides = [1, 1, 3];
    let triangle = Triangle::build(sides);
    assert!(triangle.is_none());
}

#[test]
#[ignore]
#[cfg(feature = "generic")]
fn scalene_triangle_with_floating_point_sides() {
    let sides = [0.4, 0.6, 0.3];
    let triangle = Triangle::build(sides).unwrap();
    assert!(!triangle.is_equilateral());
    assert!(!triangle.is_isosceles());
    assert!(triangle.is_scalene());
}

#[test]
#[ignore]
#[cfg(feature = "generic")]
fn equilateral_triangles_with_floating_point_sides() {
    let sides = [0.2, 0.2, 0.2];
    let triangle = Triangle::build(sides).unwrap();
    assert!(triangle.is_equilateral());
    assert!(!triangle.is_scalene());
}

#[test]
#[ignore]
#[cfg(feature = "generic")]
fn isosceles_triangle_with_floating_point_sides() {
    let sides = [0.3, 0.4, 0.4];
    let triangle = Triangle::build(sides).unwrap();
    assert!(!triangle.is_equilateral());
    assert!(triangle.is_isosceles());
    assert!(!triangle.is_scalene());
}
<|endoftext|>


<commit_before><commit_msg>Update codegen with Delimiter changes<commit_after><|endoftext|>


<commit_before>#![feature(proc_macro, proc_macro_lib)]
#![cfg(not(test))]

extern crate proc_macro;
extern crate serde_codegen;

use proc_macro::TokenStream;

#[proc_macro_derive(Serialize, attributes(serde))]
pub fn derive_serialize(input: TokenStream) -> TokenStream {
    match serde_codegen::expand_derive_serialize(&input.to_string()) {
        Ok(expanded) => expanded.parse().unwrap(),
        Err(msg) => panic!(msg),
    }
}

#[proc_macro_derive(Deserialize, attributes(serde))]
pub fn derive_deserialize(input: TokenStream) -> TokenStream {
    match serde_codegen::expand_derive_deserialize(&input.to_string()) {
        Ok(expanded) => expanded.parse().unwrap(),
        Err(msg) => panic!(msg),
    }
}
<commit_msg>Remove no-longer-necessary cfg<commit_after>#![feature(proc_macro, proc_macro_lib)]

extern crate proc_macro;
extern crate serde_codegen;

use proc_macro::TokenStream;

#[proc_macro_derive(Serialize, attributes(serde))]
pub fn derive_serialize(input: TokenStream) -> TokenStream {
    match serde_codegen::expand_derive_serialize(&input.to_string()) {
        Ok(expanded) => expanded.parse().unwrap(),
        Err(msg) => panic!(msg),
    }
}

#[proc_macro_derive(Deserialize, attributes(serde))]
pub fn derive_deserialize(input: TokenStream) -> TokenStream {
    match serde_codegen::expand_derive_deserialize(&input.to_string()) {
        Ok(expanded) => expanded.parse().unwrap(),
        Err(msg) => panic!(msg),
    }
}
<|endoftext|>


<commit_before>// P_2_1_1_03
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * changing number, color and strokeweight on diagonals in a grid
 *
 * MOUSE
 * position x          : diagonal strokeweight
 * position y          : number diagonals
 * left click          : new random layout
 *
 * KEYS
 * s                   : save png
 * 1                   : color left diagonal
 * 2                   : color right diagonal
 * 3                   : switch transparency left diagonal on/off
 * 4                   : switch transparency right diagonal on/off
 * 0                   : default
 */
use nannou::prelude::*;
use nannou::rand::rngs::StdRng;
use nannou::rand::{Rng, SeedableRng};

fn main() {
    nannou::app(model).update(update).run();
}

struct Model {
    tile_count: u32,
    act_random_seed: u64,
    color_left: Hsva,
    color_right: Hsva,
    alpha_left: f32,
    alpha_right: f32,
    transparent_left: bool,
    transparent_right: bool,
}

fn model(app: &App) -> Model {
    let _window = app
        .new_window()
        .size(600, 600)
        .view(view)
        .mouse_pressed(mouse_pressed)
        .key_released(key_released)
        .key_pressed(key_pressed)
        .build()
        .unwrap();

    let alpha_left = 0.0;
    let alpha_right = 1.0;

    Model {
        tile_count: 1,
        act_random_seed: 0,
        color_left: hsva(0.88, 1.0, 0.77, alpha_left),
        color_right: hsva(0.0, 0.0, 0.0, alpha_right),
        alpha_left,
        alpha_right,
        transparent_left: false,
        transparent_right: false,
    }
}

fn update(app: &App, model: &mut Model, _update: Update) {
    model.tile_count = (app.mouse.y + app.window_rect().top()) as u32 / 15;

    for grid_y in 0..model.tile_count {
        for _ in 0..model.tile_count {
            model.alpha_left = if model.transparent_left == true {
                1.0 / (grid_y * 10) as f32
            } else {
                1.0
            };

            model.color_left.alpha = model.alpha_left;

            model.alpha_right = if model.transparent_right == true {
                1.0 / (100 - grid_y * 10) as f32
            } else {
                1.0
            };

            model.color_right.alpha = model.alpha_right;
        }
    }
}

fn view(app: &App, model: &Model, frame: Frame) {
    // Prepare to draw.
    let draw = app.draw();
    draw.background().color(WHITE);
    let win = app.window_rect();

    let mut rng = StdRng::seed_from_u64(model.act_random_seed);

    for grid_y in 0..model.tile_count {
        for grid_x in 0..model.tile_count {
            let tile_w = win.w() / model.tile_count as f32;
            let tile_h = win.h() / model.tile_count as f32;
            let pos_x = win.left() + tile_w * grid_x as f32;
            let pos_y = (win.top() - tile_h) - tile_h * grid_y as f32;
            let mx = clamp(win.right() + app.mouse.x, 0.0, win.w());

            let toggle = rng.gen::<bool>();

            if toggle == false {
                draw.line()
                    .color(model.color_left)
                    .weight(mx / 15.0)
                    .points(
                        pt2(pos_x, pos_y),
                        pt2(
                            pos_x + (win.w() / model.tile_count as f32) / 2.0,
                            pos_y + win.h() / model.tile_count as f32,
                        ),
                    );
                draw.line()
                    .color(model.color_left)
                    .weight(mx / 15.0)
                    .points(
                        pt2(pos_x + (win.w() / model.tile_count as f32) / 2.0, pos_y),
                        pt2(
                            pos_x + (win.w() / model.tile_count as f32),
                            pos_y + win.h() / model.tile_count as f32,
                        ),
                    );
            }
            if toggle == true {
                draw.line()
                    .color(model.color_right)
                    .caps_round()
                    .weight(mx / 15.0)
                    .points(
                        pt2(pos_x, pos_y + win.w() / model.tile_count as f32),
                        pt2(pos_x + (win.h() / model.tile_count as f32) / 2.0, pos_y),
                    );
                draw.line()
                    .color(model.color_right)
                    .caps_round()
                    .weight(mx / 15.0)
                    .points(
                        pt2(
                            pos_x + (win.h() / model.tile_count as f32) / 2.0,
                            pos_y + win.w() / model.tile_count as f32,
                        ),
                        pt2(pos_x + win.h() / model.tile_count as f32, pos_y),
                    );
            }
        }
    }

    // Write to the window frame.
    draw.to_frame(app, &frame).unwrap();
}

fn mouse_pressed(_app: &App, model: &mut Model, _button: MouseButton) {
    model.act_random_seed = (random_f32() * 100000.0) as u64;
}

fn key_pressed(app: &App, _model: &mut Model, key: Key) {
    if key == Key::S {
        app.main_window()
            .capture_frame(app.exe_name().unwrap() + ".png");
    }
}

fn key_released(_app: &App, model: &mut Model, key: Key) {
    match key {
        Key::Key1 => {
            if model
                .color_left
                .eq(&hsva(0.75, 0.73, 0.51, model.alpha_left))
            {
                model.color_left = hsva(0.89, 1.0, 0.77, model.alpha_left);
            } else {
                model.color_left = hsva(0.75, 0.73, 0.51, model.alpha_left);
            }
        }
        Key::Key2 => {
            if model
                .color_right
                .eq(&hsva(0.0, 0.0, 0.0, model.alpha_right))
            {
                model.color_right = hsva(0.53, 1.0, 0.64, model.alpha_right);
            } else {
                model.color_right = hsva(0.0, 0.0, 0.0, model.alpha_right);
            }
        }
        Key::Key3 => {
            model.transparent_left = !model.transparent_left;
        }
        Key::Key4 => {
            model.transparent_right = !model.transparent_right;
        }
        Key::Key0 => {
            model.transparent_left = false;
            model.transparent_right = false;
            model.color_left = hsva(0.89, 1.0, 0.77, model.alpha_left);
            model.color_right = hsva(0.0, 0.0, 0.0, model.alpha_right);
        }
        _other_key => {}
    }
}
<commit_msg>Change p_2_1_1_03 alpha calculation and expand transparency behavior<commit_after>// P_2_1_1_03
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * changing number, color and strokeweight on diagonals in a grid
 *
 * MOUSE
 * position x          : diagonal strokeweight
 * position y          : number diagonals
 * left click          : new random layout
 *
 * KEYS
 * s                   : save png
 * 1                   : color left diagonal
 * 2                   : color right diagonal
 * 3                   : switch transparency left diagonal on/off
 * 4                   : switch transparency right diagonal on/off
 * 0                   : default
 */
use nannou::prelude::*;
use nannou::rand::rngs::StdRng;
use nannou::rand::{Rng, SeedableRng};

fn main() {
    nannou::app(model).update(update).run();
}

struct Model {
    tile_count: u32,
    act_random_seed: u64,
    color_left: Hsv,
    color_right: Hsv,
    transparent_left: bool,
    transparent_right: bool,
}

fn model(app: &App) -> Model {
    let _window = app
        .new_window()
        .size(600, 600)
        .view(view)
        .mouse_pressed(mouse_pressed)
        .key_released(key_released)
        .key_pressed(key_pressed)
        .build()
        .unwrap();

    Model {
        tile_count: 1,
        act_random_seed: 0,
        color_left: hsv(0.88, 1.0, 0.77),
        color_right: hsv(0.0, 0.0, 0.0),
        transparent_left: false,
        transparent_right: false,
    }
}

fn update(app: &App, model: &mut Model, _update: Update) {
    model.tile_count = (app.mouse.y + app.window_rect().top()) as u32 / 15;
}

fn view(app: &App, model: &Model, frame: Frame) {
    // Prepare to draw.
    let draw = app.draw();
    draw.background().color(WHITE);
    let win = app.window_rect();

    let mut rng = StdRng::seed_from_u64(model.act_random_seed);

    for grid_y in 0..model.tile_count {
        for grid_x in 0..model.tile_count {
            let tile_w = win.w() / model.tile_count as f32;
            let tile_h = win.h() / model.tile_count as f32;
            let pos_x = win.left() + tile_w * grid_x as f32;
            let pos_y = (win.top() - tile_h) - tile_h * grid_y as f32;
            let mx = clamp(win.right() + app.mouse.x, 0.0, win.w());

            let toggle = rng.gen::<bool>();

            if toggle == false {
                let (h, s, v) = model.color_left.into_components();
                let a = calculate_alpha_left(grid_y, model.transparent_left);

                draw.line()
                    .hsva(h.into(), s, v, a)
                    .caps_round()
                    .weight(mx / 15.0)
                    .points(
                        pt2(pos_x, pos_y),
                        pt2(
                            pos_x + (win.w() / model.tile_count as f32) / 2.0,
                            pos_y + win.h() / model.tile_count as f32,
                        ),
                    );
                draw.line()
                    .hsva(h.into(), s, v, a)
                    .caps_round()
                    .weight(mx / 15.0)
                    .points(
                        pt2(pos_x + (win.w() / model.tile_count as f32) / 2.0, pos_y),
                        pt2(
                            pos_x + (win.w() / model.tile_count as f32),
                            pos_y + win.h() / model.tile_count as f32,
                        ),
                    );
            }
            if toggle == true {
                let (h, s, v) = model.color_right.into_components();
                let a = calculate_alpha_right(grid_y, model.transparent_right);

                draw.line()
                    .hsva(h.into(), s, v, a)
                    .caps_round()
                    .weight(mx / 15.0)
                    .points(
                        pt2(pos_x, pos_y + win.w() / model.tile_count as f32),
                        pt2(pos_x + (win.h() / model.tile_count as f32) / 2.0, pos_y),
                    );
                draw.line()
                    .hsva(h.into(), s, v, a)
                    .caps_round()
                    .weight(mx / 15.0)
                    .points(
                        pt2(
                            pos_x + (win.h() / model.tile_count as f32) / 2.0,
                            pos_y + win.w() / model.tile_count as f32,
                        ),
                        pt2(pos_x + win.h() / model.tile_count as f32, pos_y),
                    );
            }
        }
    }

    // Write to the window frame.
    draw.to_frame(app, &frame).unwrap();
}

fn calculate_alpha_left(grid_y: u32, transparent_left: bool) -> f32 {
    let max_alpha = 100.0;
    let alpha_left = if transparent_left {
        let a = grid_y as f32 * 10.0;
        match a {
            _ if a > max_alpha => 1.0,
            _ if a < 0.0 => 0.0,
            _ => a / max_alpha,
        }
    } else {
        1.0
    };

    alpha_left
}

fn calculate_alpha_right(grid_y: u32, transparent_right: bool) -> f32 {
    let max_alpha = 100.0;
    let alpha_right = if transparent_right {
        let a = max_alpha - (grid_y as f32 * 10.0);
        match a {
            _ if a > max_alpha => 1.0,
            _ if a < 0.0 => 0.0,
            _ => a / max_alpha,
        }
    } else {
        1.0
    };

    alpha_right
}

fn mouse_pressed(_app: &App, model: &mut Model, _button: MouseButton) {
    model.act_random_seed = (random_f32() * 100000.0) as u64;
}

fn key_pressed(app: &App, _model: &mut Model, key: Key) {
    if key == Key::S {
        app.main_window()
            .capture_frame(app.exe_name().unwrap() + ".png");
    }
}

fn key_released(_app: &App, model: &mut Model, key: Key) {
    match key {
        Key::Key1 => {
            if model
                .color_left
                .eq(&hsv(0.75, 0.73, 0.51))
            {
                model.color_left = hsv(0.89, 1.0, 0.77);
            } else {
                model.color_left = hsv(0.75, 0.73, 0.51);
            }
        }
        Key::Key2 => {
            if model
                .color_right
                .eq(&hsv(0.0, 0.0, 0.0))
            {
                model.color_right = hsv(0.53, 1.0, 0.64);
            } else {
                model.color_right = hsv(0.0, 0.0, 0.0);
            }
        }
        Key::Key3 => {
            model.transparent_left = !model.transparent_left;
        }
        Key::Key4 => {
            model.transparent_right = !model.transparent_right;
        }
        Key::Key0 => {
            model.transparent_left = false;
            model.transparent_right = false;
            model.color_left = hsv(0.89, 1.0, 0.77);
            model.color_right = hsv(0.0, 0.0, 0.0);
        }
        _other_key => {}
    }
}
<|endoftext|>


<commit_before>extern crate tdo_core;

#[cfg(test)]
mod github {
    use tdo_core::tdo;

    #[test]
    fn handle_token() {
        let mut tdo = tdo::Tdo::new();
        let x = tdo.get_gh_token();
        assert_eq!(x, None);
        println!("{:?}", x);
        tdo.set_gh_token("ThisIsNoWorkingAuthTokenJustForTestingTheMethod");
        assert_eq!(tdo.get_gh_token().unwrap(),
                   "ThisIsNoWorkingAuthTokenJustForTestingTheMethod".to_string());
    }
}
<commit_msg>fix test<commit_after>extern crate tdo_core;

#[cfg(test)]
mod github {
    use tdo_core::tdo;

    #[test]
    fn handle_token() {
        let mut tdo = tdo::Tdo::new();
        let x = tdo.get_gh_token();
        assert_eq!(x, None);
        tdo.set_gh_token(Some("ThisIsNoWorkingAuthTokenJustForTestingTheMethod"));
        assert_eq!(tdo.get_gh_token().unwrap(),
                   "ThisIsNoWorkingAuthTokenJustForTestingTheMethod".to_string());
    }
}
<|endoftext|>


<commit_before>// This test uses procinfo, so can only be run on Linux.
extern crate libc;
extern crate ratelimit_meter;
#[macro_use]
extern crate nonzero_ext;

use ratelimit_meter::{DirectRateLimiter, LeakyBucket, GCRA};
use std::thread;

fn resident_memsize() -> i64 {
    let mut out: libc::rusage = unsafe { std::mem::zeroed() };
    assert!(unsafe { libc::getrusage(libc::RUSAGE_SELF, &mut out) } == 0);
    out.ru_maxrss
}

const LEAK_TOLERANCE: i64 = 1024 * 1024 * 10;

fn check_for_leaks(n_iter: usize, usage_before: i64) {
    let usage_after = resident_memsize();
    assert!(
        usage_after <= usage_before + LEAK_TOLERANCE,
        "Plausible memory leak!\nAfter {} iterations, usage before: {}, usage after: {}",
        n_iter,
        usage_before,
        usage_after
    );
}

#[test]
fn memleak_gcra() {
    const N_ITER: usize = 500_000;
    let mut bucket = DirectRateLimiter::<GCRA>::build_with_capacity(nonzero!(1_000_000u32))
        .build()
        .unwrap();
    let usage_before = resident_memsize();

    for _i in 0..N_ITER {
        drop(bucket.check());
    }
    check_for_leaks(N_ITER, usage_before);
}

#[test]
fn memleak_gcra_multi() {
    const N_ITER: usize = 500_000;
    let mut bucket = DirectRateLimiter::<GCRA>::build_with_capacity(nonzero!(1_000_000u32))
        .build()
        .unwrap();
    let usage_before = resident_memsize();

    for _i in 0..N_ITER {
        drop(bucket.check_n(2));
    }
    check_for_leaks(N_ITER, usage_before);
}

#[test]
fn memleak_gcra_threaded() {
    const N_ITER: usize = 5_000;
    let bucket = DirectRateLimiter::<GCRA>::build_with_capacity(nonzero!(1_000_000u32))
        .build()
        .unwrap();
    let usage_before = resident_memsize();

    for _i in 0..N_ITER {
        let mut bucket = bucket.clone();
        thread::spawn(move || drop(bucket.check())).join().unwrap();
    }
    check_for_leaks(N_ITER, usage_before);
}

#[test]
fn memleak_leakybucket() {
    const N_ITER: usize = 500_000;
    let mut bucket = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(1_000_000u32));
    let usage_before = resident_memsize();

    for _i in 0..N_ITER {
        drop(bucket.check());
    }
    check_for_leaks(N_ITER, usage_before);
}

#[test]
fn memleak_leakybucket_threaded() {
    const N_ITER: usize = 5_000;
    let bucket = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(1_000_000u32));
    let usage_before = resident_memsize();

    for _i in 0..N_ITER {
        let mut bucket = bucket.clone();
        thread::spawn(move || drop(bucket.check())).join().unwrap();
    }
    check_for_leaks(N_ITER, usage_before);
}
<commit_msg>Redo the memory leak tests with a RAII structure<commit_after>// This test uses procinfo, so can only be run on Linux.
extern crate libc;
extern crate ratelimit_meter;
#[macro_use]
extern crate nonzero_ext;

use ratelimit_meter::{DirectRateLimiter, LeakyBucket, GCRA};
use std::thread;

fn resident_memsize() -> i64 {
    let mut out: libc::rusage = unsafe { std::mem::zeroed() };
    assert!(unsafe { libc::getrusage(libc::RUSAGE_SELF, &mut out) } == 0);
    out.ru_maxrss
}

const LEAK_TOLERANCE: i64 = 1024 * 1024 * 10;

struct LeakCheck {
    usage_before: i64,
    n_iter: usize,
}

impl Drop for LeakCheck {
    fn drop(&mut self) {
        let usage_after = resident_memsize();
        assert!(
            usage_after <= self.usage_before + LEAK_TOLERANCE,
            "Plausible memory leak!\nAfter {} iterations, usage before: {}, usage after: {}",
            self.n_iter,
            self.usage_before,
            usage_after
        );
    }
}

impl LeakCheck {
    fn new(n_iter: usize) -> Self {
        LeakCheck {
            n_iter,
            usage_before: resident_memsize(),
        }
    }
}

#[test]
fn memleak_gcra() {
    let mut bucket = DirectRateLimiter::<GCRA>::build_with_capacity(nonzero!(1_000_000u32))
        .build()
        .unwrap();
    let leak_check = LeakCheck::new(500_000);

    for _i in 0..leak_check.n_iter {
        drop(bucket.check());
    }
}

#[test]
fn memleak_gcra_multi() {
    let mut bucket = DirectRateLimiter::<GCRA>::build_with_capacity(nonzero!(1_000_000u32))
        .build()
        .unwrap();
    let leak_check = LeakCheck::new(500_000);

    for _i in 0..leak_check.n_iter {
        drop(bucket.check_n(2));
    }
}

#[test]
fn memleak_gcra_threaded() {
    let bucket = DirectRateLimiter::<GCRA>::build_with_capacity(nonzero!(1_000_000u32))
        .build()
        .unwrap();
    let leak_check = LeakCheck::new(5_000);

    for _i in 0..leak_check.n_iter {
        let mut bucket = bucket.clone();
        thread::spawn(move || drop(bucket.check())).join().unwrap();
    }
}

#[test]
fn memleak_leakybucket() {
    let mut bucket = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(1_000_000u32));
    let leak_check = LeakCheck::new(500_000);

    for _i in 0..leak_check.n_iter {
        drop(bucket.check());
    }
}

#[test]
fn memleak_leakybucket_threaded() {
    let bucket = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(1_000_000u32));
    let leak_check = LeakCheck::new(5_000);

    for _i in 0..leak_check.n_iter {
        let mut bucket = bucket.clone();
        thread::spawn(move || drop(bucket.check())).join().unwrap();
    }
}
<|endoftext|>


<commit_before>use walkdir::WalkDir;
use std::path::PathBuf;
use std::{env, fs};

fn main() {
    // The src directory (we are in src/tools/error_index_generator)
    // Note that we could skip one of the .. but this ensures we at least loosely find the right
    // directory.
    let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
    let dest = out_dir.join("error_codes.rs");
    let mut idx = 0;
    for entry in WalkDir::new("../../../src") {
        let entry = entry.unwrap();
        if entry.file_name() == "error_codes.rs" {
            println!("cargo:rerun-if-changed={}", entry.path().to_str().unwrap());
            let file = fs::read_to_string(entry.path()).unwrap()
                .replace("syntax::register_diagnostics!", "register_diagnostics!");
            let contents = format!("(|| {{\n{}\n}})();", file);

            fs::write(&out_dir.join(&format!("error_{}.rs", idx)), &contents).unwrap();

            idx += 1;
        }
    }

    let mut all = String::new();
    all.push_str(r###"
fn register_all() -> Vec<(&'static str, Option<&'static str>)> {
    let mut long_codes: Vec<(&'static str, Option<&'static str>)> = Vec::new();
    macro_rules! register_diagnostics {
        ($($ecode:ident: $message:expr,)*) => (
            register_diagnostics!{$($ecode:$message,)* ;}
        );

        ($($ecode:ident: $message:expr,)* ; $($code:ident,)*) => (
            $(
                {long_codes.extend([
                    (stringify!($ecode), Some(stringify!($message))),
                ].iter());}
            )*
            $(
                {long_codes.extend([
                    stringify!($code),
                ].iter().cloned().map(|s| (s, None)).collect::<Vec<_>>());}
            )*
        )
    }
"###);
    for idx in 0..idx {
        all.push_str(&format!(r#"include!(concat!(env!("OUT_DIR"), "/error_{}.rs"));"#, idx));
        all.push_str("\n");
    }
    all.push_str("\nlong_codes\n");
    all.push_str("}\n");

    fs::write(&dest, all).unwrap();
}
<commit_msg>Rollup merge of #64422 - ollie27:error_index_generator_stringify, r=Mark-Simulacrum<commit_after>use walkdir::WalkDir;
use std::path::PathBuf;
use std::{env, fs};

fn main() {
    // The src directory (we are in src/tools/error_index_generator)
    // Note that we could skip one of the .. but this ensures we at least loosely find the right
    // directory.
    let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
    let dest = out_dir.join("error_codes.rs");
    let mut idx = 0;
    for entry in WalkDir::new("../../../src") {
        let entry = entry.unwrap();
        if entry.file_name() == "error_codes.rs" {
            println!("cargo:rerun-if-changed={}", entry.path().to_str().unwrap());
            let file = fs::read_to_string(entry.path()).unwrap()
                .replace("syntax::register_diagnostics!", "register_diagnostics!");
            let contents = format!("(|| {{\n{}\n}})();", file);

            fs::write(&out_dir.join(&format!("error_{}.rs", idx)), &contents).unwrap();

            idx += 1;
        }
    }

    let mut all = String::new();
    all.push_str(r###"
fn register_all() -> Vec<(&'static str, Option<&'static str>)> {
    let mut long_codes: Vec<(&'static str, Option<&'static str>)> = Vec::new();
    macro_rules! register_diagnostics {
        ($($ecode:ident: $message:expr,)*) => (
            register_diagnostics!{$($ecode:$message,)* ;}
        );

        ($($ecode:ident: $message:expr,)* ; $($code:ident,)*) => (
            $(
                {long_codes.extend([
                    (stringify!($ecode), Some($message)),
                ].iter());}
            )*
            $(
                {long_codes.extend([
                    stringify!($code),
                ].iter().cloned().map(|s| (s, None)).collect::<Vec<_>>());}
            )*
        )
    }
"###);
    for idx in 0..idx {
        all.push_str(&format!(r#"include!(concat!(env!("OUT_DIR"), "/error_{}.rs"));"#, idx));
        all.push_str("\n");
    }
    all.push_str("\nlong_codes\n");
    all.push_str("}\n");

    fs::write(&dest, all).unwrap();
}
<|endoftext|>


<commit_before>
use super::*;

/// Private namespace of the module.
mod private
{
}

TheModule::mod_interface!
{

  protected mod
  {
    // /// mod_protected1
    // #[ doc( inline ) ]
    mod_protected1,
    mod_protected2,
  };
  orphan mod
  {
    mod_orphan1,
    mod_orphan2,
  };
  exposed mod
  {
    mod_exposed1,
    mod_exposed2
  };
  prelude mod
  {
    mod_prelude1,
    mod_prelude2
  };

}

//

include!( "../../only_test/micro_modules_two_only_test.rs" );

<commit_msg>experiment<commit_after>
use super::*;

/// Private namespace of the module.
mod private
{
}

TheModule::mod_interface!
{

  protected mod
  {
    // /// mod_protected1
    // #[ doc( inline ) ]
    mod_protected1,
    mod_protected2,
  };
  orphan mod
  {
    mod_orphan1,
    mod_orphan2,
  };
  exposed mod
  {
    mod_exposed1,
    mod_exposed2
  };
  prelude mod
  {
    mod_prelude1,
    mod_prelude2
  };

}

//

include!( "../../only_test/micro_modules_two_only_test.rs" );
<|endoftext|>