summaryrefslogtreecommitdiff
path: root/meap/meap-code/ch2
diff options
context:
space:
mode:
authorAdam Carpenter <gitlab@53hor.net>2019-07-09 15:14:04 -0400
committerAdam Carpenter <gitlab@53hor.net>2019-07-09 15:14:04 -0400
commit7e8ee5ed9cad6484e9f13f81731b102ced58402e (patch)
tree5395402ab07bbb5a659dbd68c701e22a1227202f /meap/meap-code/ch2
downloadlearning-rust-7e8ee5ed9cad6484e9f13f81731b102ced58402e.tar.xz
learning-rust-7e8ee5ed9cad6484e9f13f81731b102ced58402e.zip
Init.
Diffstat (limited to 'meap/meap-code/ch2')
-rwxr-xr-xmeap/meap-code/ch2/ch2-3arrays.rs22
-rwxr-xr-xmeap/meap-code/ch2/ch2-add-with-lifetimes.rs8
-rwxr-xr-xmeap/meap-code/ch2/ch2-add-with-lifetimes_.rs8
-rwxr-xr-xmeap/meap-code/ch2/ch2-bufreader-lines.rs13
-rwxr-xr-xmeap/meap-code/ch2/ch2-define-type.rs22
-rwxr-xr-xmeap/meap-code/ch2/ch2-first-steps.rs11
-rwxr-xr-xmeap/meap-code/ch2/ch2-generic-add.rs16
-rwxr-xr-xmeap/meap-code/ch2/ch2-intro-to-numbers.rs8
-rwxr-xr-xmeap/meap-code/ch2/ch2-intro.rs18
-rwxr-xr-xmeap/meap-code/ch2/ch2-introducing-vec.rs52
-rwxr-xr-xmeap/meap-code/ch2/ch2-match-needles.rs17
-rwxr-xr-xmeap/meap-code/ch2/ch2-needle-in-haystack.rs15
-rwxr-xr-xmeap/meap-code/ch2/ch2-non-base2.rs10
-rwxr-xr-xmeap/meap-code/ch2/ch2-read-file-iter-lines.rs15
-rwxr-xr-xmeap/meap-code/ch2/ch2-read-file.rs21
-rwxr-xr-xmeap/meap-code/ch2/ch2-sensor-emulator.rs36
-rwxr-xr-xmeap/meap-code/ch2/ch2-simple-with-enumerate.rs13
-rwxr-xr-xmeap/meap-code/ch2/ch2-simple-with-linenumsbin0 -> 3714488 bytes
-rwxr-xr-xmeap/meap-code/ch2/ch2-simple-with-linenums.rs14
-rwxr-xr-xmeap/meap-code/ch2/ch2-sparse-matrix.rs20
-rwxr-xr-xmeap/meap-code/ch2/ch2-str-simple-pattern.rs12
21 files changed, 351 insertions, 0 deletions
diff --git a/meap/meap-code/ch2/ch2-3arrays.rs b/meap/meap-code/ch2/ch2-3arrays.rs
new file mode 100755
index 0000000..58d0ff2
--- /dev/null
+++ b/meap/meap-code/ch2/ch2-3arrays.rs
@@ -0,0 +1,22 @@
+fn main() {
+ let one = [1,2,3]; // <1>
+ let two: [u8; 3] = [1,2,3]; // <2>
+ let blank1 = [0; 3]; // <3>
+ let blank2: [u8; 3] = [0; 3]; // <4>
+
+ let arrays = [one, two, blank1, blank2]; // <5>
+
+ for a in &arrays { // <6>
+ print!("{:?}: ", a);
+ for n in a.iter() { // <7>
+ print!("\t{} + 10 = {}", n, n+10);
+ }
+
+ let mut sum = 0;
+ for i in 0..a.len() {
+ sum += a[i];
+ }
+ print!("\t(Σ{:?} = {})", a, sum);
+ println!("");
+ }
+}
diff --git a/meap/meap-code/ch2/ch2-add-with-lifetimes.rs b/meap/meap-code/ch2/ch2-add-with-lifetimes.rs
new file mode 100755
index 0000000..89c8bfe
--- /dev/null
+++ b/meap/meap-code/ch2/ch2-add-with-lifetimes.rs
@@ -0,0 +1,8 @@
+fn add_with_lifetimes<'a, 'b>(i: &'a i32, j: &'b i32) -> i32 {
+ *i + *j
+}
+
+fn main() {
+ let res = add_with_lifetimes(&10, &20);
+ println!("{}", res);
+}
diff --git a/meap/meap-code/ch2/ch2-add-with-lifetimes_.rs b/meap/meap-code/ch2/ch2-add-with-lifetimes_.rs
new file mode 100755
index 0000000..37b5c5f
--- /dev/null
+++ b/meap/meap-code/ch2/ch2-add-with-lifetimes_.rs
@@ -0,0 +1,8 @@
+fn add_with_lifetimes<'a, 'b>(i: &'a i32, j: &'b i32) -> i32 {
+ *i + *j // <1>
+}
+
+fn main() {
+ let res = add_with_lifetimes(&10, &20); // <2> <3>
+ println!("{}", res);
+} \ No newline at end of file
diff --git a/meap/meap-code/ch2/ch2-bufreader-lines.rs b/meap/meap-code/ch2/ch2-bufreader-lines.rs
new file mode 100755
index 0000000..24582af
--- /dev/null
+++ b/meap/meap-code/ch2/ch2-bufreader-lines.rs
@@ -0,0 +1,13 @@
+use std::fs::File;
+use std::io::BufReader;
+use std::io::prelude::*;
+
+fn main() {
+ let f = File::open("readme.md").unwrap();
+ let reader = BufReader::new(f);
+
+ for line_ in reader.lines() { // <1>
+ let line = line_.unwrap(); // <2>
+ println!("{} ({} bytes long)", line, line.len());
+ }
+} \ No newline at end of file
diff --git a/meap/meap-code/ch2/ch2-define-type.rs b/meap/meap-code/ch2/ch2-define-type.rs
new file mode 100755
index 0000000..45dbcda
--- /dev/null
+++ b/meap/meap-code/ch2/ch2-define-type.rs
@@ -0,0 +1,22 @@
+struct Counter {
+ value: u64, // <1>
+}
+
+impl Counter {
+ fn new() -> Self { // <2> <3>
+ Counter { value: 0 } // <4> <5>
+ }
+
+ fn incr(&mut self) { // <6>
+ self.value += 1;
+ }
+}
+
+fn main() {
+ let mut counter = Counter::new();
+
+ counter.incr();
+ counter.incr();
+
+ println!("{}", counter.value);
+}
diff --git a/meap/meap-code/ch2/ch2-first-steps.rs b/meap/meap-code/ch2/ch2-first-steps.rs
new file mode 100755
index 0000000..341b061
--- /dev/null
+++ b/meap/meap-code/ch2/ch2-first-steps.rs
@@ -0,0 +1,11 @@
+fn main() {
+ let a = 10; // <1>
+ let b: i32 = 20; // <2>
+
+ let c = add(a, b);
+ println!("a + b = {}", c);
+}
+
+fn add(i: i32, j: i32) -> i32 {
+ i + j
+}
diff --git a/meap/meap-code/ch2/ch2-generic-add.rs b/meap/meap-code/ch2/ch2-generic-add.rs
new file mode 100755
index 0000000..8f1a8a9
--- /dev/null
+++ b/meap/meap-code/ch2/ch2-generic-add.rs
@@ -0,0 +1,16 @@
+use std::ops::{Add};
+
+fn add<T: Add<Output = T>>(i: T, j: T) -> T {
+ i + j
+}
+
+fn main() {
+ let (a, b) = (1.2, 3.4);
+ let (x, y) = (10, 20);
+
+ let c = add(a,b);
+ let z = add(x,y);
+
+ println!("{} + {} = {}", a, b, c);
+ println!("{} + {} = {}", x, y, z);
+}
diff --git a/meap/meap-code/ch2/ch2-intro-to-numbers.rs b/meap/meap-code/ch2/ch2-intro-to-numbers.rs
new file mode 100755
index 0000000..db7b070
--- /dev/null
+++ b/meap/meap-code/ch2/ch2-intro-to-numbers.rs
@@ -0,0 +1,8 @@
+fn main() {
+ let twenty = 20; // <1>
+ let twenty_one: i32 = twenty + 1; // <2>
+ let floats_okay = 21.0; // <3>
+ let one_million = 1_000_000; // <4>
+
+ println!("{}; {}; {}; {}", twenty, twenty_one, floats_okay, one_million);
+} \ No newline at end of file
diff --git a/meap/meap-code/ch2/ch2-intro.rs b/meap/meap-code/ch2/ch2-intro.rs
new file mode 100755
index 0000000..5162fee
--- /dev/null
+++ b/meap/meap-code/ch2/ch2-intro.rs
@@ -0,0 +1,18 @@
+fn main() {
+ let start_at = 3;
+ let stop_at = 10;
+ let mut items = vec![];
+
+ for (i,x) in (start_at..stop_at).enumerate() {
+ let y = i as i64 * x;
+ items.push(y);
+ }
+
+ println!("{:?}", items);
+
+//let multiples_of_10 = items.iter().filter(|&y| y % 10 == 0).map(|&y| y.clone()).collect::<Vec<_>>();
+//let multiples_of_10: Vec<_> = items.iter().filter(|&y| y % 10 == 0).map(|&y| y.clone()).collect();
+ let multiples_of_10: Vec<_> = items.into_iter().filter(|y| y % 10 == 0).collect();
+ println!("{:?}", multiples_of_10);
+
+}
diff --git a/meap/meap-code/ch2/ch2-introducing-vec.rs b/meap/meap-code/ch2/ch2-introducing-vec.rs
new file mode 100755
index 0000000..0a3cf4b
--- /dev/null
+++ b/meap/meap-code/ch2/ch2-introducing-vec.rs
@@ -0,0 +1,52 @@
+fn main() {
+ // PARAMETERS
+ let context_lines = 2;
+ let needle = "oo";
+ let haystack = "Every face, every shop,
+bedroom window, public-house, and
+dark square is a picture
+feverishly turned--in search of what?
+It is the same with books.
+What do we seek
+through millions of pages?";
+
+ // INITIALIZATION
+ let mut tags: Vec<usize> = Vec::new(); // <1> `tags` holds line numbers where matches occur
+ let mut ctx: Vec<Vec<(usize, String)>> = Vec::new(); // <2> `ctx` contains a vector per match to hold that match's context lines
+
+ // PASS 1
+ for (i, line) in haystack.lines().enumerate() { // <3> iterate through the lines, recording line numbers where matches are encountered
+ if line.contains(needle) {
+ tags.push(i);
+
+ let v = Vec::with_capacity(2*context_lines + 1); // <4> <5> `Vec::with_capacity(_n_)` reserves space for _n_ items
+ ctx.push(v);
+ }
+ }
+
+ if tags.len() == 0 { // <6> When there are no matches, exit early
+ return;
+ }
+
+ // PASS 2
+ for (i, line) in haystack.lines().enumerate() { // <7> For each tag, at every line, check to see if we are nearby a match. When we are, add that line to the relevant `Vec<T>` within `ctx`.
+ for (j, tag) in tags.iter().enumerate() {
+ let lower_bound = tag.saturating_sub(context_lines); // <8> `usize.saturating_sub()` returns 0, rather than underflowing
+ let upper_bound = tag + context_lines;
+
+ if (i >= lower_bound) && (i <= upper_bound) {
+ let line_as_string = String::from(line); // <9> Copy `line` into a new `String` and store that locally for each match
+ let local_ctx = (i, line_as_string);
+ ctx[j].push(local_ctx);
+ }
+ }
+ }
+
+ // OUTPUT
+ for local_ctx in ctx.iter() {
+ for &(i, ref line) in local_ctx.iter() { // <10> `ref line` informs the compiler that we wish to borrow this value, rather than move it. These two terms are explained fully later in later chapters.
+ let line_num = i + 1;
+ println!("{}: {}", line_num, line);
+ }
+ }
+}
diff --git a/meap/meap-code/ch2/ch2-match-needles.rs b/meap/meap-code/ch2/ch2-match-needles.rs
new file mode 100755
index 0000000..ab999f3
--- /dev/null
+++ b/meap/meap-code/ch2/ch2-match-needles.rs
@@ -0,0 +1,17 @@
+fn main() {
+ // let needle = 42; // <1>
+ let haystack = [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862];
+
+ for reference in haystack.iter() {
+ let item = *reference;
+
+ let result = match item { // <2>
+ 42 | 132 => "hit!", // <3>
+ _ => "miss", // <4>
+ };
+
+ if result == "hit!" {
+ println!("{}: {}", item, result);
+ }
+ }
+} \ No newline at end of file
diff --git a/meap/meap-code/ch2/ch2-needle-in-haystack.rs b/meap/meap-code/ch2/ch2-needle-in-haystack.rs
new file mode 100755
index 0000000..45de1f0
--- /dev/null
+++ b/meap/meap-code/ch2/ch2-needle-in-haystack.rs
@@ -0,0 +1,15 @@
+fn main() {
+ let needle = 42;
+ let haystack = [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862]; // <1>
+
+ for reference in haystack.iter() { // <2>
+ let item = *reference; // <3>
+ if item == needle {
+ println!("{}", item);
+ }
+
+ // if reference == &needle { // <4>
+ // println!("{}", reference);
+ // }
+ }
+} \ No newline at end of file
diff --git a/meap/meap-code/ch2/ch2-non-base2.rs b/meap/meap-code/ch2/ch2-non-base2.rs
new file mode 100755
index 0000000..232c368
--- /dev/null
+++ b/meap/meap-code/ch2/ch2-non-base2.rs
@@ -0,0 +1,10 @@
+fn main() {
+ let three = 0b11; // <1>
+ let thirty = 0o36; // <2>
+ let three_hundred = 0x12C; // <3>
+
+ println!("{} {} {}", three, thirty, three_hundred);
+ println!("{:b} {:b} {:b}", three, thirty, three_hundred);
+ println!("{:o} {:o} {:o}", three, thirty, three_hundred);
+ println!("{:x} {:x} {:x}", three, thirty, three_hundred);
+}
diff --git a/meap/meap-code/ch2/ch2-read-file-iter-lines.rs b/meap/meap-code/ch2/ch2-read-file-iter-lines.rs
new file mode 100755
index 0000000..f59fa9e
--- /dev/null
+++ b/meap/meap-code/ch2/ch2-read-file-iter-lines.rs
@@ -0,0 +1,15 @@
+#[allow(unused_mut)]
+
+use std::fs::File;
+use std::io::BufReader;
+use std::io::prelude::*;
+
+fn main() {
+ let f = File::open("readme.md").unwrap(); // <1>
+ let reader = BufReader::new(f);
+
+ for line_ in reader.lines() {
+ let line = line_.unwrap();
+ println!("{} ({} bytes long)", line, line.len());
+ }
+}
diff --git a/meap/meap-code/ch2/ch2-read-file.rs b/meap/meap-code/ch2/ch2-read-file.rs
new file mode 100755
index 0000000..6114313
--- /dev/null
+++ b/meap/meap-code/ch2/ch2-read-file.rs
@@ -0,0 +1,21 @@
+use std::fs::File;
+use std::io::BufReader;
+use std::io::prelude::*;
+
+fn main() {
+ let mut f = File::open("readme.md").unwrap();
+ let mut reader = BufReader::new(f);
+
+ let mut line = String::new();
+ loop {
+ let len = reader.read_line(&mut line).unwrap();
+
+ if len == 0 {
+ break
+ }
+ println!("{} ({} bytes long)", line, len);
+
+ line.truncate(0);
+ }
+
+}
diff --git a/meap/meap-code/ch2/ch2-sensor-emulator.rs b/meap/meap-code/ch2/ch2-sensor-emulator.rs
new file mode 100755
index 0000000..afdc893
--- /dev/null
+++ b/meap/meap-code/ch2/ch2-sensor-emulator.rs
@@ -0,0 +1,36 @@
+use std::time;
+use std::f64::consts::PI;
+use std::thread;
+
+fn main() {
+ let mut sensor_array_state: f64 = 1.0;
+
+ for step in 1.. {
+ pause(step);
+ let reading = take_reading(sensor_array_state);
+ print_reading(reading);
+ sensor_array_state += 0.05;
+ }
+}
+
+fn pause(step: usize) {
+ let delay_ms = if step % 4 == 0 {
+ 500
+ } else if step % 7 == 0 {
+ 1000
+ } else {
+ 3
+ };
+
+ let delay = time::Duration::from_millis(delay_ms);
+ thread::sleep(delay);
+}
+
+fn take_reading(x: f64) -> f64 {
+ // sin(x) + sin(π / sin(πx))
+ x.sin() + (PI / (x*PI).sin()).sin()
+}
+
+fn print_reading(reading: f64) {
+ println!("{}", reading);
+}
diff --git a/meap/meap-code/ch2/ch2-simple-with-enumerate.rs b/meap/meap-code/ch2/ch2-simple-with-enumerate.rs
new file mode 100755
index 0000000..d43bf53
--- /dev/null
+++ b/meap/meap-code/ch2/ch2-simple-with-enumerate.rs
@@ -0,0 +1,13 @@
+fn main() {
+ let search_term = "picture";
+ let quote = "Every face, every shop, bedroom window, public-house, and
+dark square is a picture feverishly turned--in search of what?
+It is the same with books. What do we seek through millions of pages?";
+
+ for (idx, line) in quote.lines().enumerate() {
+ if line.contains(search_term) {
+ let line_num = idx + 1;
+ println!("{}: {}", line_num, line); // <2>
+ }
+ }
+}
diff --git a/meap/meap-code/ch2/ch2-simple-with-linenums b/meap/meap-code/ch2/ch2-simple-with-linenums
new file mode 100755
index 0000000..177f4c8
--- /dev/null
+++ b/meap/meap-code/ch2/ch2-simple-with-linenums
Binary files differ
diff --git a/meap/meap-code/ch2/ch2-simple-with-linenums.rs b/meap/meap-code/ch2/ch2-simple-with-linenums.rs
new file mode 100755
index 0000000..8da3c8c
--- /dev/null
+++ b/meap/meap-code/ch2/ch2-simple-with-linenums.rs
@@ -0,0 +1,14 @@
+fn main() {
+ let search_term = "picture";
+ let quote = "Every face, every shop, bedroom window, public-house, and
+dark square is a picture feverishly turned--in search of what?
+It is the same with books. What do we seek through millions of pages?";
+ let mut line_num: usize = 1; // <1>
+
+ for line in quote.lines() {
+ if line.contains(search_term) {
+ println!("{}: {}", line_num, line); // <2>
+ }
+ line_num += 1; // <3>
+ }
+}
diff --git a/meap/meap-code/ch2/ch2-sparse-matrix.rs b/meap/meap-code/ch2/ch2-sparse-matrix.rs
new file mode 100755
index 0000000..91e53f0
--- /dev/null
+++ b/meap/meap-code/ch2/ch2-sparse-matrix.rs
@@ -0,0 +1,20 @@
+#[derive(Debug)]
+struct Value<V>(usize, usize, V);
+
+struct SparseMatrix<V> {
+ values: Vec<Value<V>>
+}
+
+// impl SparseMatrix {
+// fn
+// }
+
+
+
+fn main () {
+ let val = Value(0, 1, 12.078);
+
+ println!("{:?}", val);
+}
+
+
diff --git a/meap/meap-code/ch2/ch2-str-simple-pattern.rs b/meap/meap-code/ch2/ch2-str-simple-pattern.rs
new file mode 100755
index 0000000..a1046bc
--- /dev/null
+++ b/meap/meap-code/ch2/ch2-str-simple-pattern.rs
@@ -0,0 +1,12 @@
+fn main() {
+ let search_term = "picture";
+ let quote = "Every face, every shop, bedroom window, public-house, and
+dark square is a picture feverishly turned--in search of what?
+It is the same with books. What do we seek through millions of pages?"; //<1>
+
+ for line in quote.lines() { // <2>
+ if line.contains(search_term) {
+ println!("{}", line);
+ }
+ }
+}