Merge pull request #42 from zdyxry/master
[rust-101.git] / src / part14.rs
1 // Rust-101, Part 14: Slices, Arrays, External Dependencies
2 // ========================================================
3
4 //@ To complete rgrep, there are two pieces we still need to implement: Sorting, and taking the job
5 //@ options as argument to the program, rather than hard-coding them. Let's start with sorting.
6
7 // ## Slices
8 //@ Again, we first have to think about the type we want to give to our sorting function. We may be
9 //@ inclined to pass it a `Vec<T>`. Of course, sorting does not actually consume the argument, so
10 //@ we should make that a `&mut Vec<T>`. But there's a problem with that: If we want to implement
11 //@ some divide-and-conquer sorting algorithm (say, Quicksort), then we will have to *split* our
12 //@ argument at some point, and operate recursively on the two parts. But we can't split a `Vec`!
13 //@ We could now extend the function signature to also take some indices, marking the part of the
14 //@ vector we are supposed to sort, but that's all rather clumsy. Rust offers a nicer solution.
15
16 //@ `[T]` is the type of an (unsized) *array*, with elements of type `T`. All this means is that
17 //@ there's a contiguous region of memory, where a bunch of `T` are stored. How many? We can't
18 //@ tell! This is an unsized type. Just like for trait objects, this means we can only operate on
19 //@ pointers to that type, and these pointers will carry the missing information - namely, the
20 //@ length (they will be *fat pointers*). Such a reference to an array is called a *slice*. As we
21 //@ will see, a slice can be split. Our function can thus take a mutable slice, and promise to sort
22 //@ all elements in there.
23 pub fn sort<T: PartialOrd>(data: &mut [T]) {
24     if data.len() < 2 { return; }
25
26     // We decide that the element at 0 is our pivot, and then we move our cursors through the rest
27     // of the slice, making sure that everything on the left is no larger than the pivot, and
28     // everything on the right is no smaller.
29     let mut lpos = 1;
30     let mut rpos = data.len();
31     /* Invariant: pivot is data[0]; everything with index (0,lpos) is <= pivot;
32        [rpos,len) is >= pivot; lpos < rpos */
33     loop {
34         // **Exercise 14.1**: Complete this Quicksort loop. You can use `swap` on slices to swap
35         // two elements. Write a test function for `sort`.
36         unimplemented!()
37     }
38
39     // Once our cursors met, we need to put the pivot in the right place.
40     data.swap(0, lpos-1);
41
42     // Finally, we split our slice to sort the two halves. The nice part about slices is that
43     // splitting them is cheap:
44     //@ They are just a pointer to a start address, and a length. We can thus get two pointers, one
45     //@ at the beginning and one in the middle, and set the lengths appropriately such that they
46     //@ don't overlap. This is what `split_at_mut` does. Since the two slices don't overlap, there
47     //@ is no aliasing and we can have both of them as unique, mutable slices.
48     let (part1, part2) = data.split_at_mut(lpos);
49     //@ The index operation can not only be used to address certain elements, it can also be used
50     //@ for *slicing*: Giving a range of indices, and obtaining an appropriate part of the slice we
51     //@ started with. Here, we remove the last element from `part1`, which is the pivot. This makes
52     //@ sure both recursive calls work on strictly smaller slices.
53     sort(&mut part1[..lpos-1]);                                     /*@*/
54     sort(part2);                                                    /*@*/
55 }
56
57 // **Exercise 14.2**: Since `String` implements `PartialEq`, you can now change the function
58 // `output_lines` in the previous part to call the sort function above. If you did exercise 13.1,
59 // you will have slightly more work. Make sure you sort by the matched line only, not by filename
60 // or line number!
61
62 // Now, we can sort, e.g., an vector of numbers.
63 fn sort_nums(data: &mut Vec<i32>) {
64     //@ Vectors support slicing, just like slices do. Here, `..` denotes the full range, which
65     //@ means we want to slice the entire vector. It is then passed to the `sort` function, which
66     //@ doesn't even know that it is working on data inside a vector.
67     sort(&mut data[..]);
68 }
69
70 // ## Arrays
71 //@ An *array* in Rust is given by the type `[T; n]`, where `n` is some *fixed* number. So, `[f64;
72 //@ 10]` is an array of 10 floating-point numbers, all one right next to the other in memory.
73 //@ Arrays are sized, and hence can be used like any other type. But we can also borrow them as
74 //@ slices, e.g., to sort them.
75 fn sort_array() {
76     let mut array_of_data: [f64; 5] = [1.0, 3.4, 12.7, -9.12, 0.1];
77     sort(&mut array_of_data);
78 }
79
80 // ## External Dependencies
81 //@ This leaves us with just one more piece to complete rgrep: Taking arguments from the command-
82 //@ line. We could now directly work on [`std::env::args`](https://doc.rust-
83 //@ lang.org/stable/std/env/fn.args.html) to gain access to those arguments, and this would become
84 //@ a pretty boring lesson in string manipulation. Instead, I want to use this opportunity to show
85 //@ how easy it is to benefit from other people's work in your program.
86 //@ 
87 //@ For sure, we are not the first to equip a Rust program with support for command-line arguments.
88 //@ Someone must have written a library for the job, right? Indeed, someone has. Rust has a central
89 //@ repository of published libraries, called [crates.io](https://crates.io/).
90 //@ It's a bit like [PyPI](https://pypi.python.org/pypi) or the [Ruby Gems](https://rubygems.org/):
91 //@ Everybody can upload their code, and there's tooling for importing that code into your project.
92 //@ This tooling is provided by `cargo`, the tool we are already using to build this tutorial.
93 //@ (`cargo` also has support for *publishing* your crate on crates.io, I refer you to [the
94 //@ documentation](http://doc.crates.io/crates-io.html) for more details.)
95 //@ In this case, we are going to use the [`docopt` crate](https://crates.io/crates/docopt), which
96 //@ creates a parser for command-line arguments based on the usage string. External dependencies
97 //@ are declared in the `Cargo.toml` file.
98
99 //@ I already prepared that file, but the declaration of the dependency is still commented out. So
100 //@ please open `Cargo.toml` of your workspace now, and enable the two commented-out lines. Then do
101 //@ `cargo build`. Cargo will now download the crate from crates.io, compile it, and link it to
102 //@ your program. In the future, you can do `cargo update` to make it download new versions of
103 //@ crates you depend on.
104 //@ Note that crates.io is only the default location for dependencies, you can also give it the URL
105 //@ of a git repository or some local path. All of this is explained in the
106 //@ [Cargo Guide](http://doc.crates.io/guide.html).
107
108 // I disabled the following module (using a rather bad hack), because it only compiles if `docopt`
109 // is linked. Remove the attribute of the `rgrep` module to enable compilation.
110 #[cfg(feature = "disabled")]
111 pub mod rgrep {
112     // Now that `docopt` is linked, we can first add it to the namespace with `extern crate` and
113     // then import shorter names with `use`. We also import some other pieces that we will need.
114     extern crate docopt;
115     use self::docopt::Docopt;
116     use part13::{run, Options, OutputMode};
117     use std::process;
118
119     // The `USAGE` string documents how the program is to be called. It's written in a format that
120     // `docopt` can parse.
121     static USAGE: &'static str = "
122 Usage: rgrep [-c] [-s] <pattern> <file>...
123
124 Options:
125     -c, --count  Count number of matching lines (rather than printing them).
126     -s, --sort   Sort the lines before printing.
127 ";
128
129     // This function extracts the rgrep options from the command-line arguments.
130     fn get_options() -> Options {
131         // This parses `argv` and exit the program with an error message if it fails. The code is
132         // taken from the [`docopt` documentation](http://burntsushi.net/rustdoc/docopt/). <br/>
133         //@ The function `and_then` takes a closure from `T` to `Result<U, E>`, and uses it to
134         //@ transform a `Result<T, E>` to a `Result<U, E>`. This way, we can chain computations
135         //@ that only happen if the previous one succeeded (and the error type has to stay the
136         //@ same). In case you know about monads, this style of programming will be familiar to
137         //@ you.
138         //@ There's a similar function for `Option`. `unwrap_or_else` is a bit like `unwrap`, but
139         //@ rather than panicking in case of an `Err`, it calls the closure.
140         let args = Docopt::new(USAGE).and_then(|d| d.parse()).unwrap_or_else(|e| e.exit());
141         // Now we can get all the values out.
142         let count = args.get_bool("-c");
143         let sort = args.get_bool("-s");
144         let pattern = args.get_str("<pattern>");
145         let files = args.get_vec("<file>");
146         if count && sort {
147             println!("Setting both '-c' and '-s' at the same time does not make any sense.");
148             process::exit(1);
149         }
150
151         // We need to make the strings owned to construct the `Options` instance.
152         //@ If you check all the types carefully, you will notice that `pattern` above is of type
153         //@ `&str`. `str` is the type of a UTF-8 encoded string, that is, a bunch of bytes in
154         //@ memory (`[u8]`) that are valid according of UTF-8. `str` is unsized. `&str` stores the
155         //@ address of the character data, and their length.
156         //@ String literals like "this one" are of type `&'static str`: They point right to the
157         //@ constant section of the binary, so  the reference is valid for the entire program. The
158         //@ bytes pointed to by `pattern`, on the other hand, are owned by someone else,  and we
159         //@ call `to_string` on it to copy the string data into a buffer on the heap that we own.
160         let mode = if count {
161             OutputMode::Count
162         } else if sort {
163             OutputMode::SortAndPrint
164         } else {
165             OutputMode::Print
166         };
167         Options {
168             files: files.iter().map(|file| file.to_string()).collect(),
169             pattern: pattern.to_string(),
170             output_mode: mode,
171         }
172     }
173
174     // Finally, we can call the `run` function from the previous part on the options extracted using
175     // `get_options`. Edit `main.rs` to call this function.
176     // You can now use `cargo run -- <pattern> <files>` to call your program, and see the argument
177     // parser and the threads we wrote previously in action!
178     pub fn main() {
179         run(get_options());                                         /*@*/
180     }
181 }
182
183 // **Exercise 14.3**: Wouldn't it be nice if rgrep supported regular expressions? There's already a
184 // crate that does all the parsing and matching on regular expression, it's called
185 // [regex](https://crates.io/crates/regex). Add this crate to the dependencies of your workspace,
186 // add an option ("-r") to switch the pattern to regular-expression mode, and change `filter_lines`
187 // to honor this option. The documentation of regex is available from its crates.io site.
188 // (You won't be able to use the `regex!` macro if you are on the stable or beta channel of Rust.
189 // But it wouldn't help for our use-case anyway.)
190
191 //@ [index](main.html) | [previous](part13.html) | [raw source](workspace/src/part14.rs) |
192 //@ [next](part15.html)