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

//! Command-line interface of the rustbuild build system.
//!
//! This module implements the command-line parsing of the build system which
//! has various flags to configure how it's run.

use std::env;
use std::fs;
use std::path::PathBuf;
use std::process;

use getopts::Options;

use Build;
use config::Config;
use metadata;
use step;

/// Deserialized version of all flags for this compile.
pub struct Flags {
    pub verbose: usize, // verbosity level: 0 == not verbose, 1 == verbose, 2 == very verbose
    pub on_fail: Option<String>,
    pub stage: Option<u32>,
    pub keep_stage: Option<u32>,
    pub build: String,
    pub host: Vec<String>,
    pub target: Vec<String>,
    pub config: Option<PathBuf>,
    pub src: Option<PathBuf>,
    pub jobs: Option<u32>,
    pub cmd: Subcommand,
    pub incremental: bool,
}

impl Flags {
    pub fn verbose(&self) -> bool {
        self.verbose > 0
    }

    pub fn very_verbose(&self) -> bool {
        self.verbose > 1
    }
}

pub enum Subcommand {
    Build {
        paths: Vec<PathBuf>,
    },
    Doc {
        paths: Vec<PathBuf>,
    },
    Test {
        paths: Vec<PathBuf>,
        test_args: Vec<String>,
        no_fail_fast: bool,
    },
    Bench {
        paths: Vec<PathBuf>,
        test_args: Vec<String>,
    },
    Clean,
    Dist {
        paths: Vec<PathBuf>,
    },
    Install {
        paths: Vec<PathBuf>,
    },
}

impl Flags {
    pub fn parse(args: &[String]) -> Flags {
        let mut extra_help = String::new();
        let mut subcommand_help = format!("\
Usage: x.py <subcommand> [options] [<paths>...]

Subcommands:
    build       Compile either the compiler or libraries
    test        Build and run some test suites
    bench       Build and run some benchmarks
    doc         Build documentation
    clean       Clean out build directories
    dist        Build distribution artifacts
    install     Install distribution artifacts

To learn more about a subcommand, run `./x.py <subcommand> -h`");

        let mut opts = Options::new();
        // Options common to all subcommands
        opts.optflagmulti("v", "verbose", "use verbose output (-vv for very verbose)");
        opts.optflag("i", "incremental", "use incremental compilation");
        opts.optopt("", "config", "TOML configuration file for build", "FILE");
        opts.optopt("", "build", "build target of the stage0 compiler", "BUILD");
        opts.optmulti("", "host", "host targets to build", "HOST");
        opts.optmulti("", "target", "target targets to build", "TARGET");
        opts.optopt("", "on-fail", "command to run on failure", "CMD");
        opts.optopt("", "stage", "stage to build", "N");
        opts.optopt("", "keep-stage", "stage to keep without recompiling", "N");
        opts.optopt("", "src", "path to the root of the rust checkout", "DIR");
        opts.optopt("j", "jobs", "number of jobs to run in parallel", "JOBS");
        opts.optflag("h", "help", "print this help message");

        // fn usage()
        let usage = |exit_code: i32, opts: &Options, subcommand_help: &str, extra_help: &str| -> ! {
            println!("{}", opts.usage(subcommand_help));
            if !extra_help.is_empty() {
                println!("{}", extra_help);
            }
            process::exit(exit_code);
        };

        // We can't use getopt to parse the options until we have completed specifying which
        // options are valid, but under the current implementation, some options are conditional on
        // the subcommand. Therefore we must manually identify the subcommand first, so that we can
        // complete the definition of the options.  Then we can use the getopt::Matches object from
        // there on out.
        let mut possible_subcommands = args.iter().collect::<Vec<_>>();
        possible_subcommands.retain(|&s|
                                           (s == "build")
                                        || (s == "test")
                                        || (s == "bench")
                                        || (s == "doc")
                                        || (s == "clean")
                                        || (s == "dist")
                                        || (s == "install"));
        let subcommand = match possible_subcommands.first() {
            Some(s) => s,
            None => {
                // No subcommand -- show the general usage and subcommand help
                println!("{}\n", subcommand_help);
                process::exit(0);
            }
        };

        // Some subcommands get extra options
        match subcommand.as_str() {
            "test"  => {
                opts.optflag("", "no-fail-fast", "Run all tests regardless of failure");
                opts.optmulti("", "test-args", "extra arguments", "ARGS");
            },
            "bench" => { opts.optmulti("", "test-args", "extra arguments", "ARGS"); },
            _ => { },
        };

        // Done specifying what options are possible, so do the getopts parsing
        let matches = opts.parse(&args[..]).unwrap_or_else(|e| {
            // Invalid argument/option format
            println!("\n{}\n", e);
            usage(1, &opts, &subcommand_help, &extra_help);
        });
        // Extra sanity check to make sure we didn't hit this crazy corner case:
        //
        //     ./x.py --frobulate clean build
        //            ^-- option  ^     ^- actual subcommand
        //                        \_ arg to option could be mistaken as subcommand
        let mut pass_sanity_check = true;
        match matches.free.get(0) {
            Some(check_subcommand) => {
                if &check_subcommand != subcommand {
                    pass_sanity_check = false;
                }
            },
            None => {
                pass_sanity_check = false;
            }
        }
        if !pass_sanity_check {
            println!("{}\n", subcommand_help);
            println!("Sorry, I couldn't figure out which subcommand you were trying to specify.\n\
                      You may need to move some options to after the subcommand.\n");
            process::exit(1);
        }
        // Extra help text for some commands
        match subcommand.as_str() {
            "build" => {
                subcommand_help.push_str("\n
Arguments:
    This subcommand accepts a number of paths to directories to the crates
    and/or artifacts to compile. For example:

        ./x.py build src/libcore
        ./x.py build src/libcore src/libproc_macro
        ./x.py build src/libstd --stage 1

    If no arguments are passed then the complete artifacts for that stage are
    also compiled.

        ./x.py build
        ./x.py build --stage 1

    For a quick build with a usable compile, you can pass:

        ./x.py build --stage 1 src/libtest

    This will first build everything once (like --stage 0 without further
    arguments would), and then use the compiler built in stage 0 to build
    src/libtest and its dependencies.");
            }
            "test" => {
                subcommand_help.push_str("\n
Arguments:
    This subcommand accepts a number of paths to directories to tests that
    should be compiled and run. For example:

        ./x.py test src/test/run-pass
        ./x.py test src/libstd --test-args hash_map
        ./x.py test src/libstd --stage 0

    If no arguments are passed then the complete artifacts for that stage are
    compiled and tested.

        ./x.py test
        ./x.py test --stage 1");
            }
            "doc" => {
                subcommand_help.push_str("\n
Arguments:
    This subcommand accepts a number of paths to directories of documentation
    to build. For example:

        ./x.py doc src/doc/book
        ./x.py doc src/doc/nomicon
        ./x.py doc src/doc/book src/libstd

    If no arguments are passed then everything is documented:

        ./x.py doc
        ./x.py doc --stage 1");
            }
            _ => { }
        };
        // Get any optional paths which occur after the subcommand
        let cwd = t!(env::current_dir());
        let paths = matches.free[1..].iter().map(|p| cwd.join(p)).collect::<Vec<_>>();

        // All subcommands can have an optional "Available paths" section
        if matches.opt_present("verbose") {
            let flags = Flags::parse(&["build".to_string()]);
            let mut config = Config::default();
            config.build = flags.build.clone();
            let mut build = Build::new(flags, config);
            metadata::build(&mut build);
            let maybe_rules_help = step::build_rules(&build).get_help(subcommand);
            if maybe_rules_help.is_some() {
                extra_help.push_str(maybe_rules_help.unwrap().as_str());
            }
        } else {
            extra_help.push_str(format!("Run `./x.py {} -h -v` to see a list of available paths.",
                     subcommand).as_str());
        }

        // User passed in -h/--help?
        if matches.opt_present("help") {
            usage(0, &opts, &subcommand_help, &extra_help);
        }

        let cmd = match subcommand.as_str() {
            "build" => {
                Subcommand::Build { paths: paths }
            }
            "test" => {
                Subcommand::Test {
                    paths: paths,
                    test_args: matches.opt_strs("test-args"),
                    no_fail_fast: matches.opt_present("no-fail-fast"),
                }
            }
            "bench" => {
                Subcommand::Bench {
                    paths: paths,
                    test_args: matches.opt_strs("test-args"),
                }
            }
            "doc" => {
                Subcommand::Doc { paths: paths }
            }
            "clean" => {
                if paths.len() > 0 {
                    println!("\nclean takes no arguments\n");
                    usage(1, &opts, &subcommand_help, &extra_help);
                }
                Subcommand::Clean
            }
            "dist" => {
                Subcommand::Dist {
                    paths: paths,
                }
            }
            "install" => {
                Subcommand::Install {
                    paths: paths,
                }
            }
            _ => {
                usage(1, &opts, &subcommand_help, &extra_help);
            }
        };

        let cfg_file = matches.opt_str("config").map(PathBuf::from).or_else(|| {
            if fs::metadata("config.toml").is_ok() {
                Some(PathBuf::from("config.toml"))
            } else {
                None
            }
        });

        let mut stage = matches.opt_str("stage").map(|j| j.parse().unwrap());

        if matches.opt_present("incremental") {
            if stage.is_none() {
                stage = Some(1);
            }
        }

        Flags {
            verbose: matches.opt_count("verbose"),
            stage: stage,
            on_fail: matches.opt_str("on-fail"),
            keep_stage: matches.opt_str("keep-stage").map(|j| j.parse().unwrap()),
            build: matches.opt_str("build").unwrap_or_else(|| {
                env::var("BUILD").unwrap()
            }),
            host: split(matches.opt_strs("host")),
            target: split(matches.opt_strs("target")),
            config: cfg_file,
            src: matches.opt_str("src").map(PathBuf::from),
            jobs: matches.opt_str("jobs").map(|j| j.parse().unwrap()),
            cmd: cmd,
            incremental: matches.opt_present("incremental"),
        }
    }
}

impl Subcommand {
    pub fn test_args(&self) -> Vec<&str> {
        match *self {
            Subcommand::Test { ref test_args, .. } |
            Subcommand::Bench { ref test_args, .. } => {
                test_args.iter().flat_map(|s| s.split_whitespace()).collect()
            }
            _ => Vec::new(),
        }
    }

    pub fn no_fail_fast(&self) -> bool {
        match *self {
            Subcommand::Test { no_fail_fast, .. } => no_fail_fast,
            _ => false,
        }
    }
}

fn split(s: Vec<String>) -> Vec<String> {
    s.iter().flat_map(|s| s.split(',')).map(|s| s.to_string()).collect()
}
<commit_msg>bootstrap: further clarify build --help<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Command-line interface of the rustbuild build system.
//!
//! This module implements the command-line parsing of the build system which
//! has various flags to configure how it's run.

use std::env;
use std::fs;
use std::path::PathBuf;
use std::process;

use getopts::Options;

use Build;
use config::Config;
use metadata;
use step;

/// Deserialized version of all flags for this compile.
pub struct Flags {
    pub verbose: usize, // verbosity level: 0 == not verbose, 1 == verbose, 2 == very verbose
    pub on_fail: Option<String>,
    pub stage: Option<u32>,
    pub keep_stage: Option<u32>,
    pub build: String,
    pub host: Vec<String>,
    pub target: Vec<String>,
    pub config: Option<PathBuf>,
    pub src: Option<PathBuf>,
    pub jobs: Option<u32>,
    pub cmd: Subcommand,
    pub incremental: bool,
}

impl Flags {
    pub fn verbose(&self) -> bool {
        self.verbose > 0
    }

    pub fn very_verbose(&self) -> bool {
        self.verbose > 1
    }
}

pub enum Subcommand {
    Build {
        paths: Vec<PathBuf>,
    },
    Doc {
        paths: Vec<PathBuf>,
    },
    Test {
        paths: Vec<PathBuf>,
        test_args: Vec<String>,
        no_fail_fast: bool,
    },
    Bench {
        paths: Vec<PathBuf>,
        test_args: Vec<String>,
    },
    Clean,
    Dist {
        paths: Vec<PathBuf>,
    },
    Install {
        paths: Vec<PathBuf>,
    },
}

impl Flags {
    pub fn parse(args: &[String]) -> Flags {
        let mut extra_help = String::new();
        let mut subcommand_help = format!("\
Usage: x.py <subcommand> [options] [<paths>...]

Subcommands:
    build       Compile either the compiler or libraries
    test        Build and run some test suites
    bench       Build and run some benchmarks
    doc         Build documentation
    clean       Clean out build directories
    dist        Build distribution artifacts
    install     Install distribution artifacts

To learn more about a subcommand, run `./x.py <subcommand> -h`");

        let mut opts = Options::new();
        // Options common to all subcommands
        opts.optflagmulti("v", "verbose", "use verbose output (-vv for very verbose)");
        opts.optflag("i", "incremental", "use incremental compilation");
        opts.optopt("", "config", "TOML configuration file for build", "FILE");
        opts.optopt("", "build", "build target of the stage0 compiler", "BUILD");
        opts.optmulti("", "host", "host targets to build", "HOST");
        opts.optmulti("", "target", "target targets to build", "TARGET");
        opts.optopt("", "on-fail", "command to run on failure", "CMD");
        opts.optopt("", "stage", "stage to build", "N");
        opts.optopt("", "keep-stage", "stage to keep without recompiling", "N");
        opts.optopt("", "src", "path to the root of the rust checkout", "DIR");
        opts.optopt("j", "jobs", "number of jobs to run in parallel", "JOBS");
        opts.optflag("h", "help", "print this help message");

        // fn usage()
        let usage = |exit_code: i32, opts: &Options, subcommand_help: &str, extra_help: &str| -> ! {
            println!("{}", opts.usage(subcommand_help));
            if !extra_help.is_empty() {
                println!("{}", extra_help);
            }
            process::exit(exit_code);
        };

        // We can't use getopt to parse the options until we have completed specifying which
        // options are valid, but under the current implementation, some options are conditional on
        // the subcommand. Therefore we must manually identify the subcommand first, so that we can
        // complete the definition of the options.  Then we can use the getopt::Matches object from
        // there on out.
        let mut possible_subcommands = args.iter().collect::<Vec<_>>();
        possible_subcommands.retain(|&s|
                                           (s == "build")
                                        || (s == "test")
                                        || (s == "bench")
                                        || (s == "doc")
                                        || (s == "clean")
                                        || (s == "dist")
                                        || (s == "install"));
        let subcommand = match possible_subcommands.first() {
            Some(s) => s,
            None => {
                // No subcommand -- show the general usage and subcommand help
                println!("{}\n", subcommand_help);
                process::exit(0);
            }
        };

        // Some subcommands get extra options
        match subcommand.as_str() {
            "test"  => {
                opts.optflag("", "no-fail-fast", "Run all tests regardless of failure");
                opts.optmulti("", "test-args", "extra arguments", "ARGS");
            },
            "bench" => { opts.optmulti("", "test-args", "extra arguments", "ARGS"); },
            _ => { },
        };

        // Done specifying what options are possible, so do the getopts parsing
        let matches = opts.parse(&args[..]).unwrap_or_else(|e| {
            // Invalid argument/option format
            println!("\n{}\n", e);
            usage(1, &opts, &subcommand_help, &extra_help);
        });
        // Extra sanity check to make sure we didn't hit this crazy corner case:
        //
        //     ./x.py --frobulate clean build
        //            ^-- option  ^     ^- actual subcommand
        //                        \_ arg to option could be mistaken as subcommand
        let mut pass_sanity_check = true;
        match matches.free.get(0) {
            Some(check_subcommand) => {
                if &check_subcommand != subcommand {
                    pass_sanity_check = false;
                }
            },
            None => {
                pass_sanity_check = false;
            }
        }
        if !pass_sanity_check {
            println!("{}\n", subcommand_help);
            println!("Sorry, I couldn't figure out which subcommand you were trying to specify.\n\
                      You may need to move some options to after the subcommand.\n");
            process::exit(1);
        }
        // Extra help text for some commands
        match subcommand.as_str() {
            "build" => {
                subcommand_help.push_str("\n
Arguments:
    This subcommand accepts a number of paths to directories to the crates
    and/or artifacts to compile. For example:

        ./x.py build src/libcore
        ./x.py build src/libcore src/libproc_macro
        ./x.py build src/libstd --stage 1

    If no arguments are passed then the complete artifacts for that stage are
    also compiled.

        ./x.py build
        ./x.py build --stage 1

    For a quick build of a usable compiler, you can pass:

        ./x.py build --stage 1 src/libtest

    This will first build everything once (like --stage 0 without further
    arguments would), and then use the compiler built in stage 0 to build
    src/libtest and its dependencies.
    Once this is done, build/$ARCH/stage1 contains a usable compiler.");
            }
            "test" => {
                subcommand_help.push_str("\n
Arguments:
    This subcommand accepts a number of paths to directories to tests that
    should be compiled and run. For example:

        ./x.py test src/test/run-pass
        ./x.py test src/libstd --test-args hash_map
        ./x.py test src/libstd --stage 0

    If no arguments are passed then the complete artifacts for that stage are
    compiled and tested.

        ./x.py test
        ./x.py test --stage 1");
            }
            "doc" => {
                subcommand_help.push_str("\n
Arguments:
    This subcommand accepts a number of paths to directories of documentation
    to build. For example:

        ./x.py doc src/doc/book
        ./x.py doc src/doc/nomicon
        ./x.py doc src/doc/book src/libstd

    If no arguments are passed then everything is documented:

        ./x.py doc
        ./x.py doc --stage 1");
            }
            _ => { }
        };
        // Get any optional paths which occur after the subcommand
        let cwd = t!(env::current_dir());
        let paths = matches.free[1..].iter().map(|p| cwd.join(p)).collect::<Vec<_>>();

        // All subcommands can have an optional "Available paths" section
        if matches.opt_present("verbose") {
            let flags = Flags::parse(&["build".to_string()]);
            let mut config = Config::default();
            config.build = flags.build.clone();
            let mut build = Build::new(flags, config);
            metadata::build(&mut build);
            let maybe_rules_help = step::build_rules(&build).get_help(subcommand);
            if maybe_rules_help.is_some() {
                extra_help.push_str(maybe_rules_help.unwrap().as_str());
            }
        } else {
            extra_help.push_str(format!("Run `./x.py {} -h -v` to see a list of available paths.",
                     subcommand).as_str());
        }

        // User passed in -h/--help?
        if matches.opt_present("help") {
            usage(0, &opts, &subcommand_help, &extra_help);
        }

        let cmd = match subcommand.as_str() {
            "build" => {
                Subcommand::Build { paths: paths }
            }
            "test" => {
                Subcommand::Test {
                    paths: paths,
                    test_args: matches.opt_strs("test-args"),
                    no_fail_fast: matches.opt_present("no-fail-fast"),
                }
            }
            "bench" => {
                Subcommand::Bench {
                    paths: paths,
                    test_args: matches.opt_strs("test-args"),
                }
            }
            "doc" => {
                Subcommand::Doc { paths: paths }
            }
            "clean" => {
                if paths.len() > 0 {
                    println!("\nclean takes no arguments\n");
                    usage(1, &opts, &subcommand_help, &extra_help);
                }
                Subcommand::Clean
            }
            "dist" => {
                Subcommand::Dist {
                    paths: paths,
                }
            }
            "install" => {
                Subcommand::Install {
                    paths: paths,
                }
            }
            _ => {
                usage(1, &opts, &subcommand_help, &extra_help);
            }
        };

        let cfg_file = matches.opt_str("config").map(PathBuf::from).or_else(|| {
            if fs::metadata("config.toml").is_ok() {
                Some(PathBuf::from("config.toml"))
            } else {
                None
            }
        });

        let mut stage = matches.opt_str("stage").map(|j| j.parse().unwrap());

        if matches.opt_present("incremental") {
            if stage.is_none() {
                stage = Some(1);
            }
        }

        Flags {
            verbose: matches.opt_count("verbose"),
            stage: stage,
            on_fail: matches.opt_str("on-fail"),
            keep_stage: matches.opt_str("keep-stage").map(|j| j.parse().unwrap()),
            build: matches.opt_str("build").unwrap_or_else(|| {
                env::var("BUILD").unwrap()
            }),
            host: split(matches.opt_strs("host")),
            target: split(matches.opt_strs("target")),
            config: cfg_file,
            src: matches.opt_str("src").map(PathBuf::from),
            jobs: matches.opt_str("jobs").map(|j| j.parse().unwrap()),
            cmd: cmd,
            incremental: matches.opt_present("incremental"),
        }
    }
}

impl Subcommand {
    pub fn test_args(&self) -> Vec<&str> {
        match *self {
            Subcommand::Test { ref test_args, .. } |
            Subcommand::Bench { ref test_args, .. } => {
                test_args.iter().flat_map(|s| s.split_whitespace()).collect()
            }
            _ => Vec::new(),
        }
    }

    pub fn no_fail_fast(&self) -> bool {
        match *self {
            Subcommand::Test { no_fail_fast, .. } => no_fail_fast,
            _ => false,
        }
    }
}

fn split(s: Vec<String>) -> Vec<String> {
    s.iter().flat_map(|s| s.split(',')).map(|s| s.to_string()).collect()
}
<|endoftext|>


<commit_before>// rustfmt-normalize_comments: true
// rustfmt-indent_style: Visual
// Test chain formatting.

fn main() {
    // Don't put chains on a single line if it wasn't so in source.
    let a = b.c.d.1.foo(|x| x + 1);

    bbbbbbbbbbbbbbbbbbb.ccccccccccccccccccccccccccccccccccccc
                       .ddddddddddddddddddddddddddd();

    bbbbbbbbbbbbbbbbbbb.ccccccccccccccccccccccccccccccccccccc
                       .ddddddddddddddddddddddddddd
                       .eeeeeeee();

    // Test case where first chain element isn't a path, but is shorter than
    // the size of a tab.
    x().y(|| match cond() {
              true => (),
              false => (),
          });

    loong_func().quux(move || if true { 1 } else { 2 });

    some_fuuuuuuuuunction().method_call_a(aaaaa, bbbbb, |c| {
        let x = c;
        x
    });

    some_fuuuuuuuuunction().method_call_a(aaaaa, bbbbb, |c| {
                               let x = c;
                               x
                           })
                           .method_call_b(aaaaa, bbbbb, |c| {
                               let x = c;
                               x
                           });

    fffffffffffffffffffffffffffffffffff(a, {
        SCRIPT_TASK_ROOT.with(|root| {
                                  *root.borrow_mut() = Some(&script_task);
                              });
    });

    let suuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuum =
        xxxxxxx.map(|x| x + 5)
               .map(|x| x / 2)
               .fold(0, |acc, x| acc + x);

    aaaaaaaaaaaaaaaa.map(|x| {
                             x += 1;
                             x
                         })
                    .filter(some_mod::some_filter)
}

fn floaters() {
    let z = Foo { field1: val1,
                  field2: val2, };

    let x = Foo { field1: val1,
                  field2: val2, }.method_call()
            .method_call();

    let y = if cond { val1 } else { val2 }.method_call();

    {
        match x {
            PushParam => {
                // params are 1-indexed
                stack.push(mparams[match cur.to_digit(10) {
                                       Some(d) => d as usize - 1,
                                       None => return Err("bad param number".to_owned()),
                                   }].clone());
            }
        }
    }

    if cond {
        some();
    } else {
        none();
    }.bar()
    .baz();

    Foo { x: val }.baz(|| {
                           force();
                           multiline();
                       })
                  .quux();

    Foo { y: i_am_multi_line,
          z: ok, }.baz(|| {
             force();
             multiline();
         })
    .quux();

    a + match x {
            true => "yay!",
            false => "boo!",
        }.bar()
}

fn is_replaced_content() -> bool {
    constellat.send(ConstellationMsg::ViewportConstrained(self.id, constraints))
              .unwrap();
}

fn issue587() {
    a.b::<()>(c);

    std::mem::transmute(dl.symbol::<()>("init").unwrap())
}

fn issue_1389() {
    let names = String::from_utf8(names)?.split('|')
                                         .map(str::to_owned)
                                         .collect();
}

fn issue1217() -> Result<Mnemonic, Error> {
    let random_chars: String = OsRng::new()?.gen_ascii_chars()
                                            .take(self.bit_length)
                                            .collect();

    Ok(Mnemonic::new(&random_chars))
}

fn issue1236(options: Vec<String>) -> Result<Option<String>> {
    let process = Command::new("dmenu").stdin(Stdio::piped())
                                       .stdout(Stdio::piped())
                                       .spawn()
                                       .chain_err(|| "failed to spawn dmenu")?;
}

fn issue1434() {
    for _ in 0..100 {
        let prototype_id =
            PrototypeIdData::from_reader::<_, B>(&mut self.file_cursor).chain_err(|| {
                format!("could not read prototype ID at offset {:#010x}",
                        current_offset)
            })?;
    }
}
<commit_msg>Update a test<commit_after>// rustfmt-normalize_comments: true
// rustfmt-indent_style: Visual
// Test chain formatting.

fn main() {
    // Don't put chains on a single line if it wasn't so in source.
    let a = b.c.d.1.foo(|x| x + 1);

    bbbbbbbbbbbbbbbbbbb.ccccccccccccccccccccccccccccccccccccc
                       .ddddddddddddddddddddddddddd();

    bbbbbbbbbbbbbbbbbbb.ccccccccccccccccccccccccccccccccccccc
                       .ddddddddddddddddddddddddddd
                       .eeeeeeee();

    // Test case where first chain element isn't a path, but is shorter than
    // the size of a tab.
    x().y(|| match cond() {
        true => (),
        false => (),
    });

    loong_func().quux(move || if true { 1 } else { 2 });

    some_fuuuuuuuuunction().method_call_a(aaaaa, bbbbb, |c| {
        let x = c;
        x
    });

    some_fuuuuuuuuunction().method_call_a(aaaaa, bbbbb, |c| {
                               let x = c;
                               x
                           })
                           .method_call_b(aaaaa, bbbbb, |c| {
                               let x = c;
                               x
                           });

    fffffffffffffffffffffffffffffffffff(a, {
        SCRIPT_TASK_ROOT.with(|root| {
                                  *root.borrow_mut() = Some(&script_task);
                              });
    });

    let suuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuum =
        xxxxxxx.map(|x| x + 5)
               .map(|x| x / 2)
               .fold(0, |acc, x| acc + x);

    aaaaaaaaaaaaaaaa.map(|x| {
                             x += 1;
                             x
                         })
                    .filter(some_mod::some_filter)
}

fn floaters() {
    let z = Foo { field1: val1,
                  field2: val2, };

    let x = Foo { field1: val1,
                  field2: val2, }.method_call()
            .method_call();

    let y = if cond { val1 } else { val2 }.method_call();

    {
        match x {
            PushParam => {
                // params are 1-indexed
                stack.push(mparams[match cur.to_digit(10) {
                                       Some(d) => d as usize - 1,
                                       None => return Err("bad param number".to_owned()),
                                   }].clone());
            }
        }
    }

    if cond {
        some();
    } else {
        none();
    }.bar()
    .baz();

    Foo { x: val }.baz(|| {
                           force();
                           multiline();
                       })
                  .quux();

    Foo { y: i_am_multi_line,
          z: ok, }.baz(|| {
             force();
             multiline();
         })
    .quux();

    a + match x {
            true => "yay!",
            false => "boo!",
        }.bar()
}

fn is_replaced_content() -> bool {
    constellat.send(ConstellationMsg::ViewportConstrained(self.id, constraints))
              .unwrap();
}

fn issue587() {
    a.b::<()>(c);

    std::mem::transmute(dl.symbol::<()>("init").unwrap())
}

fn issue_1389() {
    let names = String::from_utf8(names)?.split('|')
                                         .map(str::to_owned)
                                         .collect();
}

fn issue1217() -> Result<Mnemonic, Error> {
    let random_chars: String = OsRng::new()?.gen_ascii_chars()
                                            .take(self.bit_length)
                                            .collect();

    Ok(Mnemonic::new(&random_chars))
}

fn issue1236(options: Vec<String>) -> Result<Option<String>> {
    let process = Command::new("dmenu").stdin(Stdio::piped())
                                       .stdout(Stdio::piped())
                                       .spawn()
                                       .chain_err(|| "failed to spawn dmenu")?;
}

fn issue1434() {
    for _ in 0..100 {
        let prototype_id =
            PrototypeIdData::from_reader::<_, B>(&mut self.file_cursor).chain_err(|| {
                format!("could not read prototype ID at offset {:#010x}",
                        current_offset)
            })?;
    }
}
<|endoftext|>


<commit_before>/// TWIM Driver for the SAM4L
///
/// The implementation, especially of repeated starts, is quite sensitive to the
/// ordering of operations (e.g. setup DMA, then set command register, then next
/// command register, then enable, then start the DMA transfer). The placement
/// of writes to interrupt enable/disable registers is also significant, but not
/// refactored in such a way that's very logical right now.
///
/// The point is that until this changes, and this notice is taken away: IF YOU
/// CHANGE THIS DRIVER, TEST RIGOROUSLY!!!
///

use helpers::*;
use core::mem;

use common::take_cell::TakeCell;

use hil;
use pm;
use dma::{DMAChannel, DMAClient, DMAPeripheral};
use nvic;

// Listing of all registers related to the TWIM peripheral.
// Section 27.9 of the datasheet
#[repr(C, packed)]
#[allow(dead_code)]
struct Registers {
    control:                         usize,
    clock_waveform_generator:        usize,
    smbus_timing:                    usize,
    command:                         usize,
    next_command:                    usize,
    receive_holding:                 usize,
    transmit_holding:                usize,
    status:                          usize,
    interrupt_enable:                usize,
    interrupt_disable:               usize,
    interrupt_mask:                  usize,
    status_clear:                    usize,
    parameter:                       usize,
    version:                         usize,
    hsmode_clock_waveform_generator: usize,
    slew_rate:                       usize,
    hsmod_slew_rate:                 usize
}

// The addresses in memory (7.1 of manual) of the TWIM peripherals
const I2C_BASE_ADDRS: [*mut Registers; 4] =
    [ 0x40018000 as *mut Registers
    , 0x4001C000 as *mut Registers
    , 0x40078000 as *mut Registers
    , 0x4007C000 as *mut Registers];

// There are four TWIM (two wire master interface) peripherals on the SAM4L.
// These likely won't all be used for I2C, but we let the platform decide
// which one to use.
#[derive(Clone,Copy)]
pub enum Location {
    I2C00,  // TWIMS0
    I2C01,  // TWIMS1
    I2C02,  // TWIM2
    I2C03   // TWIM3
}

// Three main I2C speeds
#[derive(Clone,Copy)]
pub enum Speed {
    Standard100k,
    Fast400k,
    FastPlus1M
}

// This is instantiated when an I2C device is created by the device tree.
// This represents an abstraction of the peripheral hardware.
pub struct I2CDevice {
    registers: *mut Registers,  // Pointer to the I2C registers in memory
    clock: pm::Clock,
    dma: TakeCell<&'static DMAChannel>,
    dma_pids: (DMAPeripheral, DMAPeripheral),
    nvic: nvic::NvicIdx,
    client: TakeCell<&'static hil::i2c::I2CClient>,
    on_deck: TakeCell<(DMAPeripheral, usize)>,
}

pub static mut I2C0 : I2CDevice =
    I2CDevice::new(I2C_BASE_ADDRS[0], pm::PBAClock::TWIM0, nvic::NvicIdx::TWIM0,
                   DMAPeripheral::TWIM0_RX, DMAPeripheral::TWIM0_TX);
pub static mut I2C1 : I2CDevice =
    I2CDevice::new(I2C_BASE_ADDRS[1], pm::PBAClock::TWIM1, nvic::NvicIdx::TWIM1,
                   DMAPeripheral::TWIM1_RX, DMAPeripheral::TWIM1_TX);
pub static mut I2C2 : I2CDevice =
    I2CDevice::new(I2C_BASE_ADDRS[2], pm::PBAClock::TWIM2, nvic::NvicIdx::TWIM2,
                   DMAPeripheral::TWIM2_RX, DMAPeripheral::TWIM2_TX);
pub static mut I2C3 : I2CDevice =
    I2CDevice::new(I2C_BASE_ADDRS[3], pm::PBAClock::TWIM3, nvic::NvicIdx::TWIM3,
                   DMAPeripheral::TWIM3_RX, DMAPeripheral::TWIM3_TX);

pub const START : usize = 1 << 13;
pub const STOP : usize = 1 << 14;
pub const ACKLAST : usize = 1 << 24;

// Need to implement the `new` function on the I2C device as a constructor.
// This gets called from the device tree.
impl I2CDevice {
    const fn new(base_addr: *mut Registers, clock: pm::PBAClock,
                 nvic: nvic::NvicIdx,
                 dma_rx: DMAPeripheral, dma_tx: DMAPeripheral) -> I2CDevice {
        I2CDevice {
            registers: base_addr as *mut Registers,
            clock: pm::Clock::PBA(clock),
            dma: TakeCell::empty(),
            dma_pids: (dma_rx, dma_tx),
            nvic: nvic,
            client: TakeCell::empty(),
            on_deck: TakeCell::empty()
        }
    }

    /// Set the clock prescaler and the time widths of the I2C signals
    /// in the CWGR register to make the bus run at a particular I2C speed.
    fn set_bus_speed (&self) {

        // Set the clock speed parameters. This could be made smarter, but for
        // now we just use precomputed constants based on a 48MHz clock.
        // See line 320 in asf-2.31.0/sam/drivers/twim/twim.c for where I
        // got these values.
        // clock_speed / bus_speed / 2
        let (exp, data, stasto, high, low) = (7, 10, 200, 100, 100);

        let cwgr = ((exp & 0x7) << 28) |
                   ((data & 0xF) << 24) |
                   ((stasto & 0xFF) << 16) |
                   ((high & 0xFF) << 8) |
                   ((low & 0xFF) << 0);
        let regs : &mut Registers = unsafe {mem::transmute(self.registers)};
        volatile_store(&mut regs.clock_waveform_generator, cwgr);
    }

    pub fn set_dma(&self, dma: &'static DMAChannel) {
        self.dma.replace(dma);
    }

    pub fn set_client(&self, client: &'static hil::i2c::I2CClient) {
        self.client.replace(client);
    }

    pub fn handle_interrupt(&self) {
        use hil::i2c::Error;
        let regs : &mut Registers = unsafe {mem::transmute(self.registers)};

        let old_status = volatile_load(&regs.status);

        volatile_store(&mut regs.status_clear, !0);

        let err = match old_status {
            x if x & (1 <<  8) != 0 /*ANACK*/  => Some(Error::AddressNak),
            x if x & (1 <<  9) != 0 /*DNACK*/  => Some(Error::DataNak),
            x if x & (1 << 10) != 0 /*ARBLST*/ => Some(Error::ArbitrationLost),
            x if x & (1 <<  3) != 0 /*CCOMP*/   => Some(Error::CommandComplete),
            _ => None
        };

        match self.on_deck.take() {
            None => {
                volatile_store(&mut regs.command, 0);
                volatile_store(&mut regs.next_command, 0);

                err.map(|err| {
                    // enable, reset, disable
                    volatile_store(&mut regs.control, 0x1 << 0);
                    volatile_store(&mut regs.control, 0x1 << 7);
                    volatile_store(&mut regs.control, 0x1 << 1);

                    self.client.map(|client| {
                        let buf = match self.dma.take() {
                            Some(dma) => {
                                let b = dma.abort_xfer();
                                self.dma.replace(dma);
                                b
                            },
                            None => None
                        };
                        buf.map(|buf| {
                            client.command_complete(buf, err);
                        });
                    });
                });
            },
            Some((dma_periph, len)) => {
                // Enable transaction error interrupts
                volatile_store(&mut regs.interrupt_enable,
                                 (1 << 3)    // CCOMP   - Command completed
                               | (1 << 8)    // ANAK   - Address not ACKd
                               | (1 << 9)    // DNAK   - Data not ACKd
                               | (1 << 10)); // ARBLST - Abitration lost
                self.dma.map(|dma| {
                    let buf = dma.abort_xfer().unwrap();
                    dma.prepare_xfer(dma_periph, buf, len);
                    dma.start_xfer();
                });
            }
        }
    }

    fn setup_xfer(&self, chip: u8, flags: usize, read: bool, len: u8) {
        let regs : &mut Registers = unsafe {mem::transmute(self.registers)};

        // disable before configuring
        volatile_store(&mut regs.control, 0x1 << 1);

        let read = if read { 1 } else { 0 };
        let command = ((chip as usize) << 1) // 7 bit address at offset 1 (8th
                                             // bit is ignored anyway)
                    | flags  // START, STOP & ACKLAST flags
                    | (1 << 15) // VALID
                    | (len as usize) << 16 // NBYTES (at most 255)
                    | read;
        volatile_store(&mut regs.command, command);
        volatile_store(&mut regs.next_command, 0);

        // Enable transaction error interrupts
        volatile_store(&mut regs.interrupt_enable,
                         (1 << 3)    // CCOMP   - Command completed
                       | (1 << 8)    // ANAK   - Address not ACKd
                       | (1 << 9)    // DNAK   - Data not ACKd
                       | (1 << 10)); // ARBLST - Abitration lost
    }

    fn setup_nextfer(&self, chip: u8, flags: usize, read: bool, len: u8) {
        let regs : &mut Registers = unsafe {mem::transmute(self.registers)};

        // disable before configuring
        volatile_store(&mut regs.control, 0x1 << 1);

        let read = if read { 1 } else { 0 };
        let command = ((chip as usize) << 1) // 7 bit address at offset 1 (8th
                                             // bit is ignored anyway)
                    | flags  // START, STOP & ACKLAST flags
                    | (1 << 15) // VALID
                    | (len as usize) << 16 // NBYTES (at most 255)
                    | read;
        volatile_store(&mut regs.next_command, command);

        // Enable
        volatile_store(&mut regs.control, 0x1 << 0);
    }

    fn master_enable(&self) {
        let regs : &mut Registers = unsafe {mem::transmute(self.registers)};

        // Enable to begin transfer
        volatile_store(&mut regs.control, 0x1 << 0);

    }

    pub fn write(&self, chip: u8, flags: usize, data: &'static mut [u8], len: u8) {
        self.dma.map(move |dma| {
            dma.enable();
            dma.prepare_xfer(self.dma_pids.1, data, len as usize);
            self.setup_xfer(chip, flags, false, len);
            self.master_enable();
            dma.start_xfer();
        });
    }

    pub fn read(&self, chip: u8, flags: usize, data: &'static mut [u8], len: u8) {
        self.dma.map(move |dma| {
            dma.enable();
            dma.prepare_xfer(self.dma_pids.0, data, len as usize);
            self.setup_xfer(chip, flags, true, len);
            self.master_enable();
            dma.start_xfer();
        });
    }

    pub fn write_read(&self, chip: u8, data: &'static mut [u8], split: u8, read_len: u8) {
        self.dma.map(move |dma| {
           dma.enable();
           dma.prepare_xfer(self.dma_pids.1, data, split as usize);
           self.setup_xfer(chip, START, false, split);
           self.setup_nextfer(chip, START | STOP, true, read_len);
           self.on_deck.replace(
               (self.dma_pids.0, read_len as usize)
           );
           dma.start_xfer();
        });
    }

    fn enable_interrupts(&self) {
        unsafe {
            nvic::enable(self.nvic);
        }
    }

    fn disable_interrupts(&self) {
        let regs : &mut Registers = unsafe {mem::transmute(self.registers)};
        volatile_store(&mut regs.interrupt_disable, !0);
        unsafe {
            nvic::disable(self.nvic);
        }
    }
}

impl DMAClient for I2CDevice {
    fn xfer_done(&mut self, _pid: usize) {
        self.on_deck.take().map(|(dma_periph, len)| {
            self.dma.map(|dma| {
                let buf = dma.abort_xfer().unwrap();
                dma.prepare_xfer(dma_periph, buf, len);
                dma.start_xfer();
            });
        });
    }
}

impl hil::i2c::I2C for I2CDevice {

    /// This enables the entire I2C peripheral
    fn enable(&self) {
        // Enable the clock for the TWIM module
        unsafe {
            pm::enable_clock(self.clock);
        }

        let regs : &mut Registers = unsafe {mem::transmute(self.registers)};

        // enable, reset, disable
        volatile_store(&mut regs.control, 0x1 << 0);
        volatile_store(&mut regs.control, 0x1 << 7);
        volatile_store(&mut regs.control, 0x1 << 1);

        // Init the bus speed
        self.set_bus_speed();

        // slew
        volatile_store(&mut regs.slew_rate, (0x2 << 28) | (7<<16) | (7<<0));

        // clear interrupts
        volatile_store(&mut regs.status_clear, !0);

        self.enable_interrupts();
    }

    /// This disables the entire I2C peripheral
    fn disable (&self) {
        let regs : &mut Registers = unsafe {mem::transmute(self.registers)};
        volatile_store(&mut regs.control, 0x1 << 1);
        unsafe {
            pm::disable_clock(self.clock);
        }
        self.disable_interrupts();
    }

    fn write(&self, addr: u8, data: &'static mut [u8], len: u8) {
        I2CDevice::write(self, addr, START | STOP, data, len);
    }

    fn read(&self, addr: u8, data: &'static mut [u8], len: u8) {
        I2CDevice::read(self, addr, START | STOP, data, len);
    }
}

pub unsafe extern "C" fn twim2_interrupt() {
    use chip;
    use common::Queue;

    let dev = &I2C2;
    dev.disable_interrupts();
    chip::INTERRUPT_QUEUE.as_mut().unwrap().enqueue(dev.nvic);
}

<commit_msg>SAM4L: I2C working after fixing clock params<commit_after>/// TWIM Driver for the SAM4L
///
/// The implementation, especially of repeated starts, is quite sensitive to the
/// ordering of operations (e.g. setup DMA, then set command register, then next
/// command register, then enable, then start the DMA transfer). The placement
/// of writes to interrupt enable/disable registers is also significant, but not
/// refactored in such a way that's very logical right now.
///
/// The point is that until this changes, and this notice is taken away: IF YOU
/// CHANGE THIS DRIVER, TEST RIGOROUSLY!!!
///

use helpers::*;
use core::mem;

use common::take_cell::TakeCell;

use hil;
use pm;
use dma::{DMAChannel, DMAClient, DMAPeripheral};
use nvic;

// Listing of all registers related to the TWIM peripheral.
// Section 27.9 of the datasheet
#[repr(C, packed)]
#[allow(dead_code)]
struct Registers {
    control:                         usize,
    clock_waveform_generator:        usize,
    smbus_timing:                    usize,
    command:                         usize,
    next_command:                    usize,
    receive_holding:                 usize,
    transmit_holding:                usize,
    status:                          usize,
    interrupt_enable:                usize,
    interrupt_disable:               usize,
    interrupt_mask:                  usize,
    status_clear:                    usize,
    parameter:                       usize,
    version:                         usize,
    hsmode_clock_waveform_generator: usize,
    slew_rate:                       usize,
    hsmod_slew_rate:                 usize
}

// The addresses in memory (7.1 of manual) of the TWIM peripherals
const I2C_BASE_ADDRS: [*mut Registers; 4] =
    [ 0x40018000 as *mut Registers
    , 0x4001C000 as *mut Registers
    , 0x40078000 as *mut Registers
    , 0x4007C000 as *mut Registers];

// There are four TWIM (two wire master interface) peripherals on the SAM4L.
// These likely won't all be used for I2C, but we let the platform decide
// which one to use.
#[derive(Clone,Copy)]
pub enum Location {
    I2C00,  // TWIMS0
    I2C01,  // TWIMS1
    I2C02,  // TWIM2
    I2C03   // TWIM3
}

// Three main I2C speeds
#[derive(Clone,Copy)]
pub enum Speed {
    Standard100k,
    Fast400k,
    FastPlus1M
}

// This is instantiated when an I2C device is created by the device tree.
// This represents an abstraction of the peripheral hardware.
pub struct I2CDevice {
    registers: *mut Registers,  // Pointer to the I2C registers in memory
    clock: pm::Clock,
    dma: TakeCell<&'static DMAChannel>,
    dma_pids: (DMAPeripheral, DMAPeripheral),
    nvic: nvic::NvicIdx,
    client: TakeCell<&'static hil::i2c::I2CClient>,
    on_deck: TakeCell<(DMAPeripheral, usize)>,
}

pub static mut I2C0 : I2CDevice =
    I2CDevice::new(I2C_BASE_ADDRS[0], pm::PBAClock::TWIM0, nvic::NvicIdx::TWIM0,
                   DMAPeripheral::TWIM0_RX, DMAPeripheral::TWIM0_TX);
pub static mut I2C1 : I2CDevice =
    I2CDevice::new(I2C_BASE_ADDRS[1], pm::PBAClock::TWIM1, nvic::NvicIdx::TWIM1,
                   DMAPeripheral::TWIM1_RX, DMAPeripheral::TWIM1_TX);
pub static mut I2C2 : I2CDevice =
    I2CDevice::new(I2C_BASE_ADDRS[2], pm::PBAClock::TWIM2, nvic::NvicIdx::TWIM2,
                   DMAPeripheral::TWIM2_RX, DMAPeripheral::TWIM2_TX);
pub static mut I2C3 : I2CDevice =
    I2CDevice::new(I2C_BASE_ADDRS[3], pm::PBAClock::TWIM3, nvic::NvicIdx::TWIM3,
                   DMAPeripheral::TWIM3_RX, DMAPeripheral::TWIM3_TX);

pub const START : usize = 1 << 13;
pub const STOP : usize = 1 << 14;
pub const ACKLAST : usize = 1 << 24;

// Need to implement the `new` function on the I2C device as a constructor.
// This gets called from the device tree.
impl I2CDevice {
    const fn new(base_addr: *mut Registers, clock: pm::PBAClock,
                 nvic: nvic::NvicIdx,
                 dma_rx: DMAPeripheral, dma_tx: DMAPeripheral) -> I2CDevice {
        I2CDevice {
            registers: base_addr as *mut Registers,
            clock: pm::Clock::PBA(clock),
            dma: TakeCell::empty(),
            dma_pids: (dma_rx, dma_tx),
            nvic: nvic,
            client: TakeCell::empty(),
            on_deck: TakeCell::empty()
        }
    }

    /// Set the clock prescaler and the time widths of the I2C signals
    /// in the CWGR register to make the bus run at a particular I2C speed.
    fn set_bus_speed (&self) {

        // These parameters are copied from the Michael's TinyOS implementation. Are they correct?
        // Who knows... Michael probably knows. We were originally copying the parameters from the
        // Atmel Software Framework, but those parameters didn't agree with the accelerometer and
        // nearly burned my fingers. Michael's parameters seem to work without danger of injury.
        //
        // Ultimately we should understand what the heck these parameters actually mean and either
        // confirm them or replace them. They almost certainly depend on the clock speed of the
        // CPU, so we'll need to change them if we change the CPU clock speed.
        let (exp, data, stasto, high, low) = (3, 4, 10, 10, 10);

        let cwgr = ((exp & 0x7) << 28) |
                   ((data & 0xF) << 24) |
                   ((stasto & 0xFF) << 16) |
                   ((high & 0xFF) << 8) |
                   ((low & 0xFF) << 0);
        let regs : &mut Registers = unsafe {mem::transmute(self.registers)};
        volatile_store(&mut regs.clock_waveform_generator, cwgr);
    }

    pub fn set_dma(&self, dma: &'static DMAChannel) {
        self.dma.replace(dma);
    }

    pub fn set_client(&self, client: &'static hil::i2c::I2CClient) {
        self.client.replace(client);
    }

    pub fn handle_interrupt(&self) {
        use hil::i2c::Error;
        let regs : &mut Registers = unsafe {mem::transmute(self.registers)};

        let old_status = volatile_load(&regs.status);

        volatile_store(&mut regs.status_clear, !0);

        let err = match old_status {
            x if x & (1 <<  8) != 0 /*ANACK*/  => Some(Error::AddressNak),
            x if x & (1 <<  9) != 0 /*DNACK*/  => Some(Error::DataNak),
            x if x & (1 << 10) != 0 /*ARBLST*/ => Some(Error::ArbitrationLost),
            x if x & (1 <<  3) != 0 /*CCOMP*/   => Some(Error::CommandComplete),
            _ => None
        };

        match self.on_deck.take() {
            None => {
                volatile_store(&mut regs.command, 0);
                volatile_store(&mut regs.next_command, 0);

                err.map(|err| {
                    // enable, reset, disable
                    volatile_store(&mut regs.control, 0x1 << 0);
                    volatile_store(&mut regs.control, 0x1 << 7);
                    volatile_store(&mut regs.control, 0x1 << 1);

                    self.client.map(|client| {
                        let buf = match self.dma.take() {
                            Some(dma) => {
                                let b = dma.abort_xfer();
                                self.dma.replace(dma);
                                b
                            },
                            None => None
                        };
                        buf.map(|buf| {
                            client.command_complete(buf, err);
                        });
                    });
                });
            },
            Some((dma_periph, len)) => {
                // Enable transaction error interrupts
                volatile_store(&mut regs.interrupt_enable,
                                 (1 << 3)    // CCOMP   - Command completed
                               | (1 << 8)    // ANAK   - Address not ACKd
                               | (1 << 9)    // DNAK   - Data not ACKd
                               | (1 << 10)); // ARBLST - Abitration lost
                self.dma.map(|dma| {
                    let buf = dma.abort_xfer().unwrap();
                    dma.prepare_xfer(dma_periph, buf, len);
                    dma.start_xfer();
                });
            }
        }
    }

    fn setup_xfer(&self, chip: u8, flags: usize, read: bool, len: u8) {
        let regs : &mut Registers = unsafe {mem::transmute(self.registers)};

        // disable before configuring
        volatile_store(&mut regs.control, 0x1 << 1);

        let read = if read { 1 } else { 0 };
        let command = ((chip as usize) << 1) // 7 bit address at offset 1 (8th
                                             // bit is ignored anyway)
                    | flags  // START, STOP & ACKLAST flags
                    | (1 << 15) // VALID
                    | (len as usize) << 16 // NBYTES (at most 255)
                    | read;
        volatile_store(&mut regs.command, command);
        volatile_store(&mut regs.next_command, 0);

        // Enable transaction error interrupts
        volatile_store(&mut regs.interrupt_enable,
                         (1 << 3)    // CCOMP   - Command completed
                       | (1 << 8)    // ANAK   - Address not ACKd
                       | (1 << 9)    // DNAK   - Data not ACKd
                       | (1 << 10)); // ARBLST - Abitration lost
    }

    fn setup_nextfer(&self, chip: u8, flags: usize, read: bool, len: u8) {
        let regs : &mut Registers = unsafe {mem::transmute(self.registers)};

        // disable before configuring
        volatile_store(&mut regs.control, 0x1 << 1);

        let read = if read { 1 } else { 0 };
        let command = ((chip as usize) << 1) // 7 bit address at offset 1 (8th
                                             // bit is ignored anyway)
                    | flags  // START, STOP & ACKLAST flags
                    | (1 << 15) // VALID
                    | (len as usize) << 16 // NBYTES (at most 255)
                    | read;
        volatile_store(&mut regs.next_command, command);

        // Enable
        volatile_store(&mut regs.control, 0x1 << 0);
    }

    fn master_enable(&self) {
        let regs : &mut Registers = unsafe {mem::transmute(self.registers)};

        // Enable to begin transfer
        volatile_store(&mut regs.control, 0x1 << 0);

    }

    pub fn write(&self, chip: u8, flags: usize, data: &'static mut [u8], len: u8) {
        self.dma.map(move |dma| {
            dma.enable();
            dma.prepare_xfer(self.dma_pids.1, data, len as usize);
            self.setup_xfer(chip, flags, false, len);
            self.master_enable();
            dma.start_xfer();
        });
    }

    pub fn read(&self, chip: u8, flags: usize, data: &'static mut [u8], len: u8) {
        self.dma.map(move |dma| {
            dma.enable();
            dma.prepare_xfer(self.dma_pids.0, data, len as usize);
            self.setup_xfer(chip, flags, true, len);
            self.master_enable();
            dma.start_xfer();
        });
    }

    pub fn write_read(&self, chip: u8, data: &'static mut [u8], split: u8, read_len: u8) {
        self.dma.map(move |dma| {
           dma.enable();
           dma.prepare_xfer(self.dma_pids.1, data, split as usize);
           self.setup_xfer(chip, START, false, split);
           self.setup_nextfer(chip, START | STOP, true, read_len);
           self.on_deck.replace(
               (self.dma_pids.0, read_len as usize)
           );
           dma.start_xfer();
        });
    }

    fn enable_interrupts(&self) {
        unsafe {
            nvic::enable(self.nvic);
        }
    }

    fn disable_interrupts(&self) {
        let regs : &mut Registers = unsafe {mem::transmute(self.registers)};
        volatile_store(&mut regs.interrupt_disable, !0);
        unsafe {
            nvic::disable(self.nvic);
        }
    }
}

impl DMAClient for I2CDevice {
    fn xfer_done(&mut self, _pid: usize) {
        self.on_deck.take().map(|(dma_periph, len)| {
            self.dma.map(|dma| {
                let buf = dma.abort_xfer().unwrap();
                dma.prepare_xfer(dma_periph, buf, len);
                dma.start_xfer();
            });
        });
    }
}

impl hil::i2c::I2C for I2CDevice {

    /// This enables the entire I2C peripheral
    fn enable(&self) {
        // Enable the clock for the TWIM module
        unsafe {
            pm::enable_clock(self.clock);
        }

        let regs : &mut Registers = unsafe {mem::transmute(self.registers)};

        // enable, reset, disable
        volatile_store(&mut regs.control, 0x1 << 0);
        volatile_store(&mut regs.control, 0x1 << 7);
        volatile_store(&mut regs.control, 0x1 << 1);

        // Init the bus speed
        self.set_bus_speed();

        // slew
        volatile_store(&mut regs.slew_rate, (0x2 << 28) | (7<<16) | (7<<0));

        // clear interrupts
        volatile_store(&mut regs.status_clear, !0);

        self.enable_interrupts();
    }

    /// This disables the entire I2C peripheral
    fn disable (&self) {
        let regs : &mut Registers = unsafe {mem::transmute(self.registers)};
        volatile_store(&mut regs.control, 0x1 << 1);
        unsafe {
            pm::disable_clock(self.clock);
        }
        self.disable_interrupts();
    }

    fn write(&self, addr: u8, data: &'static mut [u8], len: u8) {
        I2CDevice::write(self, addr, START | STOP, data, len);
    }

    fn read(&self, addr: u8, data: &'static mut [u8], len: u8) {
        I2CDevice::read(self, addr, START | STOP, data, len);
    }
}

pub unsafe extern "C" fn twim2_interrupt() {
    use chip;
    use common::Queue;

    let dev = &I2C2;
    dev.disable_interrupts();
    chip::INTERRUPT_QUEUE.as_mut().unwrap().enqueue(dev.nvic);
}

<|endoftext|>


<commit_before>use crate::airport_data::{Airport, AirportType, Position, Runway};
use rand::seq::SliceRandom;
use rocket::State;
use rocket_contrib::json::{Json, JsonValue};
use serde_derive::{Deserialize, Serialize};
use std::fmt;
use std::ptr;

const MAX_AIRPORTS_TO_GET: usize = 2000;
const MAX_AIRPORTS_TO_RETURN: usize = 100;

#[post("/search_routes", format = "json", data = "<filters>")]
pub fn search_routes<'a>(filters: Json<Filters>, airports: State<'a, Vec<Airport>>) -> JsonValue {
    let departures = filters
        .departure
        .as_ref()
        .map(|filters| filters.matching_airports(&airports))
        .unwrap_or_else(|| random_airport_set(&airports));

    let arrivals = filters
        .arrival
        .as_ref()
        .map(|filters| filters.matching_airports(&airports))
        .unwrap_or_else(|| random_airport_set(&airports));

    let mut routes = Vec::with_capacity(MAX_AIRPORTS_TO_RETURN / 2);

    for departure in departures {
        for arrival in &arrivals {
            if ptr::eq(departure, *arrival) {
                continue;
            }

            let route = Route::new(departure, arrival, filters.speed);

            match &filters.time_or_dist {
                Some(TimeOrDistance::Time(time_range)) => {
                    if !time_range.within(&route.time) {
                        continue;
                    }
                }
                Some(TimeOrDistance::Distance(dist_range)) => {
                    if !dist_range.within(&route.distance) {
                        continue;
                    }
                }
                None => (),
            }

            routes.push(route);
        }
    }

    let mut routes = routes.as_mut_slice();

    if routes.len() > 1 {
        let (shuffled, _) = routes.partial_shuffle(&mut rand::thread_rng(), MAX_AIRPORTS_TO_RETURN);
        routes = shuffled;
    }

    json!({ "routes": routes })
}

#[inline(always)]
fn random_airport_set(airports: &[Airport]) -> Vec<&Airport> {
    airports
        .choose_multiple(&mut rand::thread_rng(), MAX_AIRPORTS_TO_GET)
        .collect()
}

#[derive(Debug, Serialize)]
struct Route<'a> {
    from: &'a Airport,
    to: &'a Airport,
    distance: f32,
    time: Time,
}

impl<'a> Route<'a> {
    #[inline(always)]
    fn new(from: &'a Airport, to: &'a Airport, speed: Speed) -> Self {
        let distance = Self::calculate_distance(from.position, to.position);
        let time = Time::from_distance(distance, speed);

        Self {
            from,
            to,
            distance,
            time,
        }
    }

    /// Get the distance in nautical miles between two longitude and latitude points
    /// using the Haversine formula.
    fn calculate_distance(from: Position, to: Position) -> f32 {
        // Radius of Earth in nautical miles
        const RADIUS_NM: f32 = 3440.0;

        let from_lat = from.latitude_deg.to_radians();
        let to_lat = to.latitude_deg.to_radians();
        let lat = to_lat - from_lat;

        let lon = (to.longitude_deg - from.longitude_deg).to_radians();

        let a =
            (lat / 2.0).sin().powi(2) + from_lat.cos() * to_lat.cos() * (lon / 2.0).sin().powi(2);
        let c = 2.0 * a.sqrt().atan2((1.0 - a).sqrt());

        RADIUS_NM * c
    }
}

#[derive(Copy, Clone, Debug, Default, Deserialize, Serialize, PartialEq, PartialOrd)]
struct Time {
    hour: u8,
    minutes: u8,
}

impl Time {
    fn from_distance(distance: f32, speed: Speed) -> Self {
        let total_hours = distance / speed.as_knots();

        let hour = total_hours.floor().min(99.0);
        let minutes = ((total_hours - hour) * 60.0).floor().min(59.0);

        Self {
            hour: hour as u8,
            minutes: minutes as u8,
        }
    }
}

#[derive(Copy, Clone, Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
#[serde(tag = "type", content = "value")]
pub enum Speed {
    Mach(f32),
    Knots(f32),
}

impl Speed {
    #[inline(always)]
    fn as_knots(self) -> f32 {
        const KNOTS_PER_MACH: f32 = 666.739;

        match self {
            Self::Mach(mach) => mach * KNOTS_PER_MACH,
            Self::Knots(knots) => knots,
        }
    }
}

#[derive(Debug, Deserialize)]
pub struct Filters {
    speed: Speed,
    departure: Option<AirportFilters>,
    arrival: Option<AirportFilters>,
    #[serde(rename = "timeDist", default)]
    time_or_dist: Option<TimeOrDistance>,
}

#[derive(Debug, Deserialize)]
struct AirportFilters {
    icao: Option<String>,
    #[serde(rename = "airportType", default)]
    airport_type: AirportType,
    #[serde(rename = "runwayLength")]
    runway_length: Option<RunwayLength>,
    #[serde(default)]
    countries: Vec<String>,
}

impl AirportFilters {
    fn matching_airports<'a>(&self, airports: &'a [Airport]) -> Vec<&'a Airport> {
        if let Some(icao) = &self.icao {
            let index = airports
                .binary_search_by(|arpt| arpt.icao.as_str().cmp(icao.as_str()))
                .ok();

            let index = match index {
                Some(index) => index,
                None => return Vec::new(),
            };

            return vec![&airports[index]];
        }

        type MatchClosure<'a> = Box<dyn Fn(&Airport) -> bool + 'a>;

        let type_matches: MatchClosure = match self.airport_type {
            AirportType::Unknown => Box::new(|_| true),
            kind => Box::new(move |arpt| arpt.class == kind),
        };

        let runway_len_matches: MatchClosure = match self.runway_length {
            Some(len) => Box::new(move |arpt| len.fits_any(&arpt.runways)),
            None => Box::new(|_| true),
        };

        let country_matches: MatchClosure = match self.countries.as_slice() {
            [] => Box::new(|_| true),
            countries => Box::new(move |arpt| Self::list_has_any(&arpt.country_name, countries)),
        };

        Self::airport_matches(
            |arpt| type_matches(arpt) && runway_len_matches(arpt) && country_matches(arpt),
            airports,
        )
    }

    fn airport_matches<F>(matcher: F, airports: &[Airport]) -> Vec<&Airport>
    where
        F: Fn(&Airport) -> bool,
    {
        let mut results = Vec::new();

        for airport in airports {
            if !matcher(airport) {
                continue;
            }

            results.push(airport);

            if results.len() >= MAX_AIRPORTS_TO_GET {
                break;
            }
        }

        results
    }

    #[inline(always)]
    fn list_has_any(name: &str, list: &[String]) -> bool {
        list.iter().any(|x| x.eq_ignore_ascii_case(name))
    }
}

#[derive(Copy, Clone, Debug, Deserialize)]
#[serde(tag = "selector", content = "length")]
pub enum RunwayLength {
    #[serde(rename = "eq")]
    Equal(u32),
    #[serde(rename = "gt")]
    GreaterThan(u32),
    #[serde(rename = "lt")]
    LessThan(u32),
}

impl RunwayLength {
    #[inline(always)]
    pub fn fits(self, length: u32) -> bool {
        match self {
            Self::Equal(len) => len == length,
            Self::GreaterThan(len) => length > len,
            Self::LessThan(len) => length < len,
        }
    }

    #[inline(always)]
    pub fn fits_any(self, runways: &[Runway]) -> bool {
        runways.iter().any(|runway| match runway.length_ft {
            Some(len) => self.fits(len),
            None => false,
        })
    }
}

#[derive(Debug, Default, Deserialize)]
pub struct Range<T>
where
    T: fmt::Debug + Default + PartialOrd,
{
    pub min: Option<T>,
    pub max: Option<T>,
}

impl<T> Range<T>
where
    T: fmt::Debug + Default + PartialOrd,
{
    fn within(&self, value: &T) -> bool {
        if let Some(true) = self.min.as_ref().map(|min| value < min) {
            return false;
        }

        if let Some(true) = self.max.as_ref().map(|max| value > max) {
            return false;
        }

        true
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
#[serde(tag = "type", content = "value")]
enum TimeOrDistance {
    #[serde(rename = "time")]
    Time(Range<Time>),
    #[serde(rename = "dist")]
    Distance(Range<f32>),
}

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

    #[test]
    fn range_within() {
        macro_rules! within {
            ($min:expr => $max:expr, $value:expr) => {
                Range::within(
                    &Range {
                        min: $min,
                        max: $max,
                    },
                    &$value,
                )
            };
        }

        assert_eq!(within!(Some(1) => Some(3), 2), true);
        assert_eq!(within!(Some(2) => Some(3), 2), true);
        assert_eq!(within!(Some(2) => Some(3), 3), true);

        assert_eq!(within!(Some(1) => Some(5), 10), false);
        assert_eq!(within!(Some(10) => Some(100), 9), false);
    }

    #[test]
    fn runway_length_fits() {
        assert_eq!(RunwayLength::Equal(12345).fits(12345), true);
        assert_eq!(RunwayLength::Equal(12345).fits(12346), false);

        assert_eq!(RunwayLength::GreaterThan(1000).fits(1001), true);
        assert_eq!(RunwayLength::GreaterThan(1000).fits(1000), false);

        assert_eq!(RunwayLength::LessThan(1000).fits(999), true);
        assert_eq!(RunwayLength::LessThan(1000).fits(1000), false);
    }
}
<commit_msg>backend: Add test cases for route filtering<commit_after>use crate::airport_data::{Airport, AirportType, Position, Runway};
use rand::seq::SliceRandom;
use rocket::State;
use rocket_contrib::json::{Json, JsonValue};
use serde_derive::{Deserialize, Serialize};
use std::fmt;
use std::ptr;

const MAX_AIRPORTS_TO_GET: usize = 2000;
const MAX_AIRPORTS_TO_RETURN: usize = 100;

#[post("/search_routes", format = "json", data = "<filters>")]
pub fn search_routes<'a>(filters: Json<Filters>, airports: State<'a, Vec<Airport>>) -> JsonValue {
    let departures = filters
        .departure
        .as_ref()
        .map(|filters| filters.matching_airports(&airports))
        .unwrap_or_else(|| random_airport_set(&airports));

    let arrivals = filters
        .arrival
        .as_ref()
        .map(|filters| filters.matching_airports(&airports))
        .unwrap_or_else(|| random_airport_set(&airports));

    let mut routes = Vec::with_capacity(MAX_AIRPORTS_TO_RETURN / 2);

    for departure in departures {
        for arrival in &arrivals {
            if ptr::eq(departure, *arrival) {
                continue;
            }

            let route = Route::new(departure, arrival, filters.speed);

            match &filters.time_or_dist {
                Some(TimeOrDistance::Time(time_range)) => {
                    if !time_range.within(&route.time) {
                        continue;
                    }
                }
                Some(TimeOrDistance::Distance(dist_range)) => {
                    if !dist_range.within(&route.distance) {
                        continue;
                    }
                }
                None => (),
            }

            routes.push(route);
        }
    }

    let mut routes = routes.as_mut_slice();

    if routes.len() > 1 {
        let (shuffled, _) = routes.partial_shuffle(&mut rand::thread_rng(), MAX_AIRPORTS_TO_RETURN);
        routes = shuffled;
    }

    json!({ "routes": routes })
}

#[inline(always)]
fn random_airport_set(airports: &[Airport]) -> Vec<&Airport> {
    airports
        .choose_multiple(&mut rand::thread_rng(), MAX_AIRPORTS_TO_GET)
        .collect()
}

#[derive(Debug, Serialize)]
struct Route<'a> {
    from: &'a Airport,
    to: &'a Airport,
    distance: f32,
    time: Time,
}

impl<'a> Route<'a> {
    #[inline(always)]
    fn new(from: &'a Airport, to: &'a Airport, speed: Speed) -> Self {
        let distance = Self::calculate_distance(from.position, to.position);
        let time = Time::from_distance(distance, speed);

        Self {
            from,
            to,
            distance,
            time,
        }
    }

    /// Get the distance in nautical miles between two longitude and latitude points
    /// using the Haversine formula.
    fn calculate_distance(from: Position, to: Position) -> f32 {
        // Radius of Earth in nautical miles
        const RADIUS_NM: f32 = 3440.0;

        let from_lat = from.latitude_deg.to_radians();
        let to_lat = to.latitude_deg.to_radians();
        let lat = to_lat - from_lat;

        let lon = (to.longitude_deg - from.longitude_deg).to_radians();

        let a =
            (lat / 2.0).sin().powi(2) + from_lat.cos() * to_lat.cos() * (lon / 2.0).sin().powi(2);
        let c = 2.0 * a.sqrt().atan2((1.0 - a).sqrt());

        RADIUS_NM * c
    }
}

#[derive(Copy, Clone, Debug, Default, Deserialize, Serialize, PartialEq, PartialOrd)]
struct Time {
    hour: u8,
    minutes: u8,
}

impl Time {
    fn from_distance(distance: f32, speed: Speed) -> Self {
        let total_hours = distance / speed.as_knots();

        let hour = total_hours.floor().min(99.0);
        let minutes = ((total_hours - hour) * 60.0).floor().min(59.0);

        Self {
            hour: hour as u8,
            minutes: minutes as u8,
        }
    }
}

#[derive(Copy, Clone, Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
#[serde(tag = "type", content = "value")]
pub enum Speed {
    Mach(f32),
    Knots(f32),
}

impl Speed {
    #[inline(always)]
    fn as_knots(self) -> f32 {
        const KNOTS_PER_MACH: f32 = 666.739;

        match self {
            Self::Mach(mach) => mach * KNOTS_PER_MACH,
            Self::Knots(knots) => knots,
        }
    }
}

#[derive(Debug, Deserialize)]
pub struct Filters {
    speed: Speed,
    departure: Option<AirportFilters>,
    arrival: Option<AirportFilters>,
    #[serde(rename = "timeDist", default)]
    time_or_dist: Option<TimeOrDistance>,
}

#[derive(Debug, Deserialize)]
struct AirportFilters {
    icao: Option<String>,
    #[serde(rename = "airportType", default)]
    airport_type: AirportType,
    #[serde(rename = "runwayLength")]
    runway_length: Option<RunwayLength>,
    #[serde(default)]
    countries: Vec<String>,
}

impl AirportFilters {
    fn matching_airports<'a>(&self, airports: &'a [Airport]) -> Vec<&'a Airport> {
        if let Some(icao) = &self.icao {
            let index = airports
                .binary_search_by(|arpt| arpt.icao.as_str().cmp(icao.as_str()))
                .ok();

            let index = match index {
                Some(index) => index,
                None => return Vec::new(),
            };

            return vec![&airports[index]];
        }

        type MatchClosure<'a> = Box<dyn Fn(&Airport) -> bool + 'a>;

        let type_matches: MatchClosure = match self.airport_type {
            AirportType::Unknown => Box::new(|_| true),
            kind => Box::new(move |arpt| arpt.class == kind),
        };

        let runway_len_matches: MatchClosure = match self.runway_length {
            Some(len) => Box::new(move |arpt| len.fits_any(&arpt.runways)),
            None => Box::new(|_| true),
        };

        let country_matches: MatchClosure = match self.countries.as_slice() {
            [] => Box::new(|_| true),
            countries => Box::new(move |arpt| Self::list_has_any(&arpt.country_name, countries)),
        };

        Self::airport_matches(
            |arpt| type_matches(arpt) && runway_len_matches(arpt) && country_matches(arpt),
            airports,
        )
    }

    fn airport_matches<F>(matcher: F, airports: &[Airport]) -> Vec<&Airport>
    where
        F: Fn(&Airport) -> bool,
    {
        let mut results = Vec::new();

        for airport in airports {
            if !matcher(airport) {
                continue;
            }

            results.push(airport);

            if results.len() >= MAX_AIRPORTS_TO_GET {
                break;
            }
        }

        results
    }

    #[inline(always)]
    fn list_has_any(name: &str, list: &[String]) -> bool {
        list.iter().any(|x| x.eq_ignore_ascii_case(name))
    }
}

#[derive(Copy, Clone, Debug, Deserialize)]
#[serde(tag = "selector", content = "length")]
pub enum RunwayLength {
    #[serde(rename = "eq")]
    Equal(u32),
    #[serde(rename = "gt")]
    GreaterThan(u32),
    #[serde(rename = "lt")]
    LessThan(u32),
}

impl RunwayLength {
    #[inline(always)]
    pub fn fits(self, length: u32) -> bool {
        match self {
            Self::Equal(len) => len == length,
            Self::GreaterThan(len) => length > len,
            Self::LessThan(len) => length < len,
        }
    }

    #[inline(always)]
    pub fn fits_any(self, runways: &[Runway]) -> bool {
        runways.iter().any(|runway| match runway.length_ft {
            Some(len) => self.fits(len),
            None => false,
        })
    }
}

#[derive(Debug, Default, Deserialize)]
pub struct Range<T>
where
    T: fmt::Debug + Default + PartialOrd,
{
    pub min: Option<T>,
    pub max: Option<T>,
}

impl<T> Range<T>
where
    T: fmt::Debug + Default + PartialOrd,
{
    fn within(&self, value: &T) -> bool {
        if let Some(true) = self.min.as_ref().map(|min| value < min) {
            return false;
        }

        if let Some(true) = self.max.as_ref().map(|max| value > max) {
            return false;
        }

        true
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
#[serde(tag = "type", content = "value")]
enum TimeOrDistance {
    #[serde(rename = "time")]
    Time(Range<Time>),
    #[serde(rename = "dist")]
    Distance(Range<f32>),
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::airport_data::RunwayMarker;
    use std::collections::HashMap;

    #[test]
    fn range_within() {
        macro_rules! within {
            ($min:expr => $max:expr, $value:expr) => {
                Range::within(
                    &Range {
                        min: $min,
                        max: $max,
                    },
                    &$value,
                )
            };
        }

        assert_eq!(within!(Some(1) => Some(3), 2), true);
        assert_eq!(within!(Some(2) => Some(3), 2), true);
        assert_eq!(within!(Some(2) => Some(3), 3), true);

        assert_eq!(within!(Some(1) => Some(5), 10), false);
        assert_eq!(within!(Some(10) => Some(100), 9), false);
    }

    #[test]
    fn runway_length_fits() {
        assert_eq!(RunwayLength::Equal(12345).fits(12345), true);
        assert_eq!(RunwayLength::Equal(12345).fits(12346), false);

        assert_eq!(RunwayLength::GreaterThan(1000).fits(1001), true);
        assert_eq!(RunwayLength::GreaterThan(1000).fits(1000), false);

        assert_eq!(RunwayLength::LessThan(1000).fits(999), true);
        assert_eq!(RunwayLength::LessThan(1000).fits(1000), false);
    }

    fn get_airports() -> Vec<Airport> {
        // San Francisco
        let ksfo = Airport {
            icao: "KSFO".into(),
            class: AirportType::Large,
            position: Position::new(37.618, -122.375),
            runways: vec![Runway {
                length_ft: Some(7500),
                width_ft: Some(200),
                he_marker: Some(RunwayMarker::new("01L".into(), 0.0, 0.0)),
                le_marker: Some(RunwayMarker::new("19R".into(), 0.0, 0.0)),
            }],
            frequencies: HashMap::new(),
            country_name: "United States".into(),
        };

        // Sacramento Executive
        let ksac = Airport {
            icao: "KSAC".into(),
            class: AirportType::Medium,
            position: Position::new(38.512, -121.492),
            runways: vec![Runway {
                length_ft: Some(3836),
                width_ft: Some(100),
                he_marker: Some(RunwayMarker::new("12".into(), 0.0, 0.0)),
                le_marker: Some(RunwayMarker::new("30".into(), 0.0, 0.0)),
            }],
            frequencies: HashMap::new(),
            country_name: "United States".into(),
        };

        // Narita
        let rjaa = Airport {
            icao: "RJAA".into(),
            class: AirportType::Large,
            position: Position::new(35.764, 140.386),
            runways: vec![Runway {
                length_ft: Some(8202),
                width_ft: Some(196),
                he_marker: Some(RunwayMarker::new("16L".into(), 0.0, 0.0)),
                le_marker: Some(RunwayMarker::new("34R".into(), 0.0, 0.0)),
            }],
            frequencies: HashMap::new(),
            country_name: "Japan".into(),
        };

        vec![ksfo, ksac, rjaa]
    }

    fn display_airports(airports: Vec<&Airport>) -> Vec<&String> {
        airports.into_iter().map(|arpt| &arpt.icao).collect()
    }

    macro_rules! assert_expected_icaos {
        ($result:expr, $expected:expr) => {
            let result = $result;

            assert!(
                !result.is_empty(),
                "expected to get airports {:?}, got nothing",
                $expected
            );

            assert_eq!(
                $expected.len(),
                result.len(),
                "expected to get {} airport(s) ({:?}), got {} ({:?})",
                $expected.len(),
                $expected,
                result.len(),
                display_airports(result)
            );

            let has_expected_arpts = result
                .iter()
                .all(|found| $expected.contains(&found.icao.as_str()));

            assert!(
                has_expected_arpts,
                "expected to get airports {:?}, got {:?}",
                $expected,
                display_airports(result)
            );
        };
    }

    #[test]
    fn filter_icao() {
        const EXPECTED_ICAO: &'static str = "KSAC";

        let airports = get_airports();

        let filter = AirportFilters {
            icao: Some(EXPECTED_ICAO.into()),
            airport_type: AirportType::Unknown,
            runway_length: None,
            countries: vec![],
        };

        assert_expected_icaos!(filter.matching_airports(&airports[..]), [EXPECTED_ICAO]);
    }

    #[test]
    fn filter_airport_type() {
        const EXPECTED_TYPE: AirportType = AirportType::Large;
        const EXPECTED_ICAOS: [&'static str; 2] = ["KSFO", "RJAA"];

        let airports = get_airports();

        let filter = AirportFilters {
            icao: None,
            airport_type: EXPECTED_TYPE,
            runway_length: None,
            countries: vec![],
        };

        assert_expected_icaos!(filter.matching_airports(&airports[..]), EXPECTED_ICAOS);
    }

    #[test]
    fn filter_runway_length_gt() {
        const EXPECTED_ICAOS: [&'static str; 2] = ["KSFO", "RJAA"];

        let airports = get_airports();

        let filter = AirportFilters {
            icao: None,
            airport_type: AirportType::Unknown,
            runway_length: Some(RunwayLength::GreaterThan(7000)),
            countries: vec![],
        };

        assert_expected_icaos!(filter.matching_airports(&airports[..]), EXPECTED_ICAOS);
    }

    #[test]
    fn filter_runway_length_eq() {
        const EXPECTED_ICAOS: [&'static str; 1] = ["KSAC"];

        let airports = get_airports();

        let filter = AirportFilters {
            icao: None,
            airport_type: AirportType::Unknown,
            runway_length: Some(RunwayLength::Equal(3836)),
            countries: vec![],
        };

        assert_expected_icaos!(filter.matching_airports(&airports[..]), EXPECTED_ICAOS);
    }

    #[test]
    fn filter_runway_length_lt() {
        const EXPECTED_ICAOS: [&'static str; 2] = ["KSFO", "KSAC"];

        let airports = get_airports();

        let filter = AirportFilters {
            icao: None,
            airport_type: AirportType::Unknown,
            runway_length: Some(RunwayLength::LessThan(7501)),
            countries: vec![],
        };

        assert_expected_icaos!(filter.matching_airports(&airports[..]), EXPECTED_ICAOS);
    }

    #[test]
    fn filter_countries() {
        let airports = get_airports();

        let mut filter = AirportFilters {
            icao: None,
            airport_type: AirportType::Unknown,
            runway_length: None,
            countries: vec!["United States".into()],
        };

        assert_expected_icaos!(filter.matching_airports(&airports[..]), ["KSFO", "KSAC"]);

        filter.countries = vec!["Japan".into()];
        assert_expected_icaos!(filter.matching_airports(&airports[..]), ["RJAA"]);

        filter.countries = vec!["United States".into(), "Japan".into()];

        assert_expected_icaos!(
            filter.matching_airports(&airports[..]),
            ["KSFO", "KSAC", "RJAA"]
        );
    }
}
<|endoftext|>