re-do deepaksirone's fix on the actual source file
[rust-101.git] / workspace / src / part14.rs
1 // Rust-101, Part 14: Slices, Arrays, External Dependencies
2 // ========================================================
3
4
5 // ## Slices
6
7 pub fn sort<T: PartialOrd>(data: &mut [T]) {
8     if data.len() < 2 { return; }
9
10     // We decide that the element at 0 is our pivot, and then we move our cursors through the rest of the slice,
11     // making sure that everything on the left is no larger than the pivot, and everything on the right is no smaller.
12     let mut lpos = 1;
13     let mut rpos = data.len();
14     /* Invariant: pivot is data[0]; everything with index (0,lpos) is <= pivot;
15        [rpos,len) is >= pivot; lpos < rpos */
16     loop {
17         // **Exercise 14.1**: Complete this Quicksort loop. You can use `swap` on slices to swap two elements. Write a
18         // test function for `sort`.
19         unimplemented!()
20     }
21
22     // Once our cursors met, we need to put the pivot in the right place.
23     data.swap(0, lpos-1);
24
25     // Finally, we split our slice to sort the two halves. The nice part about slices is that splitting them is cheap:
26     let (part1, part2) = data.split_at_mut(lpos);
27     unimplemented!()
28 }
29
30 // **Exercise 14.2**: Since `String` implements `PartialEq`, you can now change the function `output_lines` in the previous part
31 // to call the sort function above. If you did exercise 13.1, you will have slightly more work. Make sure you sort by the matched line
32 // only, not by filename or line number!
33
34 // Now, we can sort, e.g., an vector of numbers.
35 fn sort_nums(data: &mut Vec<i32>) {
36     sort(&mut data[..]);
37 }
38
39 // ## Arrays
40 fn sort_array() {
41     let mut array_of_data: [f64; 5] = [1.0, 3.4, 12.7, -9.12, 0.1];
42     sort(&mut array_of_data);
43 }
44
45 // ## External Dependencies
46
47
48 // I disabled the following module (using a rather bad hack), because it only compiles if `docopt` is linked.
49 // Remove the attribute of the `rgrep` module to enable compilation.
50 #[cfg(feature = "disabled")]
51 pub mod rgrep {
52     // Now that `docopt` is linked, we can first add it to the namespace with `extern crate` and then import shorter names with `use`.
53     // We also import some other pieces that we will need.
54     extern crate docopt;
55     use self::docopt::Docopt;
56     use part13::{run, Options, OutputMode};
57     use std::process;
58
59     // The `USAGE` string documents how the program is to be called. It's written in a format that `docopt` can parse.
60     static USAGE: &'static str = "
61 Usage: rgrep [-c] [-s] <pattern> <file>...
62
63 Options:
64     -c, --count  Count number of matching lines (rather than printing them).
65     -s, --sort   Sort the lines before printing.
66 ";
67
68     // This function extracts the rgrep options from the command-line arguments.
69     fn get_options() -> Options {
70         // This parses `argv` and exit the program with an error message if it fails. The code is taken from the [`docopt` documentation](http://burntsushi.net/rustdoc/docopt/). <br/>
71         let args = Docopt::new(USAGE).and_then(|d| d.parse()).unwrap_or_else(|e| e.exit());
72         // Now we can get all the values out.
73         let count = args.get_bool("-c");
74         let sort = args.get_bool("-s");
75         let pattern = args.get_str("<pattern>");
76         let files = args.get_vec("<file>");
77         if count && sort {
78             println!("Setting both '-c' and '-s' at the same time does not make any sense.");
79             process::exit(1);
80         }
81
82         // We need to make the strings owned to construct the `Options` instance.
83         let mode = if count {
84             OutputMode::Count
85         } else if sort {
86             OutputMode::SortAndPrint
87         } else {
88             OutputMode::Print
89         };
90         Options {
91             files: files.iter().map(|file| file.to_string()).collect(),
92             pattern: pattern.to_string(),
93             output_mode: mode,
94         }
95     }
96
97     // Finally, we can call the `run` function from the previous part on the options extracted using `get_options`. Edit `main.rs` to call this function.
98     // You can now use `cargo run -- <pattern> <files>` to call your program, and see the argument parser and the threads we wrote previously in action!
99     pub fn main() {
100         unimplemented!()
101     }
102 }
103
104 // **Exercise 14.3**: Wouldn't it be nice if rgrep supported regular expressions? There's already a crate that does all the parsing and matching on regular
105 // expression, it's called [regex](https://crates.io/crates/regex). Add this crate to the dependencies of your workspace, add an option ("-r") to switch
106 // the pattern to regular-expression mode, and change `filter_lines` to honor this option. The documentation of regex is available from its crates.io site.
107 // (You won't be able to use the `regex!` macro if you are on the stable or beta channel of Rust. But it wouldn't help for our use-case anyway.)
108