forked from hakimel/reveal.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
2016_10_20_introduction.html
629 lines (574 loc) · 20.4 KB
/
2016_10_20_introduction.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Rust Introduction</title>
<meta name="author" content="Sascha Grunert">
<link rel="stylesheet" href="css/reveal.css">
<link rel="stylesheet" href="css/theme/solarized.css">
<link rel="stylesheet" href="lib/css/zenburn.css">
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
</head>
<body>
<div class="reveal">
<div class="slides">
<section>
<h1>Rust</h1>
<h3>Fast, safe and productive — pick three</h3>
<small>First user group Meetup in Leipzig (2016-10-20)</small>
</section>
<section>
<section>
<h2>Common system programming problems:</h2>
<ul>
<li>Undefined behaviors</li>
<li>Iterator invalidation</li>
<li>Data races</li>
</ul>
</section>
<section>
<h2>Undefined behaviors</h2>
<pre><code class="c" data-trim contenteditable>
int arr[4] = {0, 1, 2, 3};
int *p = arr + 5; // undefined behavior
</code></pre>
<pre><code class="c" data-trim contenteditable>
int k, i;
for (i = 0; i < 10; i++) {
k = k + 1; // What is k?
}
</code></pre>
</section>
<section>
<h2>Iterator invalidation</h2>
<pre><code class="c" data-trim contenteditable>
vector<int> x = { 1, 2, 3 };
int j = 0;
for (auto it = x.begin(); it != x.end(); ++it) {
x.push_back(j); // Makes iterator invalid.
j++;
cout << j << " .. ";
}
</code></pre>
Iterators are invalidated by some operations that modify a std::vector.
</section>
<section>
<h2>Data races</h2>
<pre><code class="c" data-trim contenteditable>
if (x == 5) { // The "Check"
y = x * 2; // The "Act"
// If another thread changed x
// in between "if (x == 5)" and
// "y = x * 2" above, y will not be
// equal to 10.
}
</code></pre>
</section>
<section>
<h2>Why is this a problem?</h2>
<ul>
<li>Runtime failures like segfaults are not recoverable.</li>
<li>Extremely common source of security bugs.</li>
<li>Existing solutions for safety are slow and usually require a garbage collection.</li>
<li>Non type safety leads into common pitfalls (void pointers, wrong casts).</li>
<li>Code Review for such corner cases slows down the development.</li>
</ul>
</section>
<section>
<img class="plain" src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/Rust_programming_language_black_logo.svg/480px-Rust_programming_language_black_logo.svg.png">
</section>
</section>
<section>
<section>
<h1>Some basics</h1>
</section>
<section>
<h2>If, loops, functions</h2>
<pre><code class="rust" data-trim contenteditable>
if a > 1 {
println!("{:?}", a);
}
let k = 0; // u32
let mut i: i32 = 0; // Same: let mut i = 0i32;
loop {
if i > 10 { break; }
i += 1;
println!("{:?}", i);
}
fn multiply(x: i32, y: i32) -> i32 {
x * y
}
</code></pre>
</section>
<section>
<h2>Expression based language</h2>
<pre><code class="rust" data-trim contenteditable>
let b = 3i32;
let a = if b > 1 {
let mut c = b - 5;
c = c * b;
c
} else {
1i32
};
fn greater(a: i32, b: i32) -> i32 {
if a > b {
a
} else {
b
}
}
</code></pre>
</section>
<section>
<h2>Pattern matching</h2>
<pre><code class="rust" data-trim contenteditable>
let number = 5u32;
let size = match number {
0 => "none",
2 | 3 => "tiny",
4...7 => "small",
8...20 => "medium",
_ => "large"
};
match number {
2 | 8 | 9 => {
let mut c = 1;
c += number;
println!("The incremented number is {}", c);
},
_ => println!("Sorry! :(")
}
</code></pre>
</section>
<section>
<h2>Destructuring</h2>
<pre><code class="rust" data-trim contenteditable>
let pair = (4u32, 5u32);
let (a, b) = pair;
let (b, a) = (a, b);
let smaller = match pair {
(x, y) if x < y => x,
(_, y) => y
};
match pair {
(0, 0) => println!("Origin"),
(0, y) => println!("Y-axis, coordinate {}", y),
(x, 0) => println!("X-axis, coordinate {}", x),
(x, y) => {
let distance = ((x*x + y*y) as f32).sqrt();
println!("Point is ({}, {}), and {} units from origin",
x, y, distance);
}
};
</code></pre>
</section>
</section>
<section>
<section>
<h1>Data types</h1>
</section>
<section>
<h2>Structures</h2>
<pre><code class="rust" data-trim contenteditable>
struct Point {
x: i32,
y: i32
}
let p = Point {x: 0, y: 0};
println!("X coordinate is {}", p.x)
</code></pre>
</section>
<section>
<h2>Enums</h2>
<pre><code class="rust" data-trim contenteditable>
enum Shape {
Circle(Point, u32),
Rectangle(Point, Point),
}
enum Option<T> {
Some(T),
None,
}
let origin = Point {x: 0, y: 0};
let circ = Shape::Circle(origin, 10);
</code></pre>
</section>
<section>
<h2>Extended pattern matching</h2>
<pre><code class="rust" data-trim contenteditable>
let perimeter = match shape {
Circle(_, r) => 2*pi*r,
Rectangle(p1, p2) => 2*abs(p2.x - p1.x) + 2*abs(p2.y - p1.y)
}
let perimeter = match shape {
Circle(_, r) => 2*pi*r,
Rectangle(Point {x: x1, y: y1}, Point {x: x2, y: y2}) =>
2*abs(x2 - x1) + 2*abs(y2 - y1)
}
match point {
Point {x: 2...6, y: -1...5} => println!("I like this point"),
_ => println!("I do not like this point"),
}
</code></pre>
</section>
<section>
<h2>Generics</h2>
<pre><code class="rust" data-trim contenteditable>
enum Option<T> {
Some(T),
None
}
fn maybe_sqrt(x: i32) -> Option<u32> {
if x >= 0 {
Some(sqrt(x) as u32)
} else {
None
}
}
</code></pre>
</section>
<section>
<h2>Implementations</h2>
<pre><code class="rust" data-trim contenteditable>
impl Point {
fn distance(&self) -> f32 { // point.distance()
((self.x*self.x + self.y*self.y) as f32).sqrt()
}
fn random() -> Point { // Point::random()
Point {
x: 4, // Chosen by fair dice roll
y: 4, // Guaranteed to be random
}
}
}
</code></pre>
</section>
<section>
<h2>Traits</h2>
<pre><code class="rust" data-trim contenteditable>
trait Pointy {
fn poke(&self, at: &str);
fn hello(&self) {
println!("Hello world");
}
}
impl Pointy for Point {
fn poke(&self, at: &str) {
println!("Poked {}", at);
}
}
fn poke_forever<T>(pointy: T, at: &str) where T: Pointy {
loop {
pointy.poke(at)
}
}
</code></pre>
</section>
</section>
<section>
<section>
<h1>Memory management</h1>
</section>
<section>
<h2>Moves and copies</h2>
<pre><code class="rust" data-trim contenteditable>
let x = 5i8;
let y = x;
println!("x is {:?}", x); // y was copied from x
let x = vec![1u8, 2u8, 3u8];
let y = x; // the vector was "moved"
println!("y is {:?}", y);
// Will not work, the vector is "owned" by y
// println!("x is {}", x)
fn abc(x: Vec<u8>) {
// do something
}
let vec = vec![1u8, 2u8, 3u8];
abc(vec); // 'abc' consumes vec
</code></pre>
</section>
<section>
<h2>Borrowing</h2>
<pre><code class="rust" data-trim contenteditable>
let x = vec![1, 2, 3];
let y = &x; // the vector was "borrowed"
let c = x.clone(); // Explicit copy
println!("x is {:?}", x);
println!("y is {:?}", *y);
fn abc(x: &Vec<u8>) {
// do something
}
let vec = vec![1u8,2u8,3u8];
abc(&vec); // Passes a borrowed reference
// Still can use vec here
</code></pre>
</section>
<section>
<h2>Borrowing & mutability</h2>
<pre><code class="rust" data-trim contenteditable>
let mut x = vec![1u8, 2u8, 3u8];
{
let y = &x; // the pointer was "borrowed"
// Not allowed, x is currently borrowed and cannot be mutated
// x.push(1);
// Not allowed, y is not a mutable reference
// y.push(1);
}
x.push(1); // The borrow was "returned", we can mutate now
let mut x = vec![1u8, 2u8, 3u8];
{
let y = &mut x; // the pointer was "borrowed", mutably
// Still not allowed, x is currently borrowed and cannot be mutated
// x.push(1);
// also not allowed, y is mutating this
// println!("x is {}", x)
// Allowed, y is a mutable reference
y.push(1);
}
x.push(1) // The borrow was "returned", we can mutate now
</code></pre>
</section>
<section>
<h2>Ownership and implementations</h2>
<pre><code class="rust" data-trim contenteditable>
struct Polygon {points: Vec<Point>};
impl Point {
// This one moves
fn draw_move(self) {
// ...
}
// This one borrows
fn draw_borrow(&self) {
// ...
// after calling p.draw_borrow() I can still use p
}
// This one borrows mutably
fn draw_borrow_mut(&mut self) {
// ...
// I can mutate self here
}
}
// (*polygon).draw_borrow() dereference not necessary
</code></pre>
</section>
<section>
<h2>The heap</h2>
<pre><code class="rust" data-trim contenteditable>
let mut x = Box::new(1); // On the heap
*x = 2;
// Type Box<u32>
// Also gets moved, not copied
fn abc() {
let x = Box::new(1); // malloc() happened
// do stuff with x or *x
// free() happened
}
fn def() -> Box<u32>{
let x = Box::new(1); // malloc() happened
// do stuff with x or *x
x // x returned to outer owner
}
</code></pre>
</section>
<section>
<h2>Destructuring and binding by reference</h2>
<pre><code class="rust" data-trim contenteditable>
let pair = (Box::new(1), Box::new(2));
let (a, b) = pair;
// The boxes were moved out of `pair`, cannot use it anymore
let pair = (Box::new(1), Box::new(2));
{
let (ref a, ref b) = pair;
// a, b are borrowed references now, so everything is fine
// use `ref mut` for mutable references
}
// Works in match statements too!
let maybe_heap = Some(Box::new(1));
match maybe_heap {
Some(ref x) => println!("{}", x),
None => println!("No variable")
}
</code></pre>
</section>
<section>
<h2>Strings and arrays</h2>
<pre><code class="rust" data-trim contenteditable>
let mut fixed_len_vec = [1,2,3]; // type [u32, 3]
fixed_len_vec[1] = 2;
let mut buffer = vec![1,2,3]; // type Vec<u32>
buffer.push(20); // Now it is of length 4!
let slice = &buffer[0..2]; // type &[u32]
let slice = &[1,2,3]; // Same
let owned = "Manish".to_string(); // type String
let static_slice = "Manish"; // type `&'static str`
let slice = &owned[0..3]; // type &str
</code></pre>
</section>
<section>
<h2>Some unsafe Rust</h2>
<pre><code class="rust" data-trim contenteditable>
extern crate core;
use std::{mem, ptr};
fn main() {
let y = *dangle() + 1;
// Segfault.
}
fn dangle() -> Box<u32> {
unsafe {
// Null pointer
let mut p: *mut int = ptr::null_mut();
// Heap memory, will be freed at the end of this function
let b = Box::new(1u32);
ptr::write(p, *b);
mem::transmute(p) // Converts to box and returns
}
}
</code></pre>
</section>
</section>
<section>
<section>
<h1>Concurrency</h1>
</section>
<section>
<h2>Thread safety #1</h2>
<pre><code class="rust" data-trim contenteditable>
use std::sync::mpsc::*;
use std::thread::spawn;
let (tx, rx) = channel();
spawn(move || {
tx.send(1); // works!
});
let x = rx.recv();
</code></pre>
</section>
<section>
<h2>Thread safety #2</h2>
<pre><code class="rust" data-trim contenteditable>
use std::sync::mpsc::*;
use std::thread::spawn;
let (tx, rx) = channel();
spawn(move || {
let x = Box::new(1);
tx.send(x); // works!
});
let x = rx.recv();
</code></pre>
</section>
<section>
<h2>Thread safety #3</h2>
<pre><code class="rust" data-trim contenteditable>
use std::sync::mpsc::*;
use std::thread::spawn;
let (tx, rx) = channel();
spawn(move || {
let x = Box::new(1);
tx.send(&x); // x does not live long enough
});
let x = rx.recv();
</code></pre>
</section>
<section>
<h2>Thread safety #4</h2>
<pre><code class="rust" data-trim contenteditable>
use std::sync::mpsc::*;
use std::thread::spawn;
use std::rc::Rc;
// use std::sync::Arc;
let (tx, rx) = channel();
spawn(move || {
let x = Rc::new(1); // smart pointer
tx.send(x.clone()); // cannot send between thread safely
});
let x = rx.recv();
</code></pre>
</section>
</section>
<section>
<section>
<h1>More features</h1>
</section>
<section>
<h2>Further topics #1</h2>
<ul>
<li class="fragment fade-up">General thread safety due to borrow checker</li>
<li class="fragment fade-up">Powerful zero cost abstractions without garbage collection</li>
<li class="fragment fade-up">Error handling via result types</li>
<li class="fragment fade-up">Associated types and constants</li>
<li class="fragment fade-up">Buddy traits, associated trait types, trait objects vs generics</li>
<li class="fragment fade-up">Error Handling</li>
<li class="fragment fade-up">Lifetimes</li>
<li class="fragment fade-up">Documentation</li>
</ul>
</section>
<section>
<h2>Further topics #2</h2>
<ul>
<li class="fragment fade-up">Iterators</li>
<li class="fragment fade-up">Closures</li>
<li class="fragment fade-up">Futures</li>
<li class="fragment fade-up">I/O Streams</li>
<li class="fragment fade-up">Macros</li>
<li class="fragment fade-up">Unsafe Code</li>
<li class="fragment fade-up">Program Structure, Modules, Crates</li>
<li class="fragment fade-up"><a href="https://crates.io" target"_blank">External crates</a></li>
</ul>
</section>
<section>
<h2>Resources</h2>
<ul>
<li><a href="http://doc.rust-lang.org/book">http://doc.rust-lang.org/book</a></li>
<li><a href="http://rustbyexample.com/">http://rustbyexample.com/</a></li>
<li><a href="http://doc.rust-lang.org/">http://doc.rust-lang.org/</a></li>
<li><a href="https://blog.rust-lang.org/">https://blog.rust-lang.org/</a></li>
<li><a href="https://play.rust-lang.org/">https://play.rust-lang.org/</a></li>
<li><a href="http://users.rust-lang.org/">http://users.rust-lang.org/</a></li>
<li><a href="https://www.rust-lang.org/en-US/community.html">https://www.rust-lang.org/en-US/community.html</a></li>
<li><a href="http://reddit.com/r/rust/">http://reddit.com/r/rust/</a></li>
</ul>
</section>
<section>
<a href="https://rust-leipzig.github.io/" target="_blank">We have a blog.</a>
</section>
<section>
<p>Two good books, one free:</p>
<img height="300px" class="plain" src="http://akamaicovers.oreilly.com/images/0636920040385/rc_cat.gif">
<img height="300px" class="plain" src="http://covers.oreillystatic.com/images/0636920040446/cat.gif">
</section>
</section>
<section>
<h1>Thank you!</h1>
</section>
</div>
</div>
<script src="lib/js/head.min.js"></script>
<script src="js/reveal.js"></script>
<script>
// More info https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
backgroundTransition: 'zoom',
center: true,
controls: true,
history: true,
progress: true,
transition: 'zoom',
// More info https://github.com/hakimel/reveal.js#dependencies
dependencies: [
{ src: 'plugin/markdown/marked.js' },
{ src: 'plugin/markdown/markdown.js' },
{ src: 'plugin/notes/notes.js', async: true },
{ src: 'plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } },
{ src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }
]
});
</script>
</body>
</html>