diff --git a/po/tr.po b/po/tr.po index ef2ea105183..989b5ef8d70 100644 --- a/po/tr.po +++ b/po/tr.po @@ -2,136 +2,137 @@ msgid "" msgstr "" "Project-Id-Version: Comprehensive Rust 🦀\n" "POT-Creation-Date: \n" -"PO-Revision-Date: 2023-05-25 14:15+0300\n" -"Last-Translator: \n" +"PO-Revision-Date: 2023-08-25 14:48-0700\n" +"Last-Translator: akerem@protonmail.com\n" "Language-Team: Turkish \n" +"Language: tr\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: tr\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" +"X-Generator: Poedit 3.3.2\n" -#: src/SUMMARY.md:3 src/welcome.md:1 +#: src/SUMMARY.md:4 src/index.md:1 msgid "Welcome to Comprehensive Rust 🦀" msgstr "Comprehensive Rust'a Hoşgeldiniz 🦀" -#: src/SUMMARY.md:4 src/running-the-course.md:1 +#: src/SUMMARY.md:5 src/running-the-course.md:1 msgid "Running the Course" msgstr "TODO:" -#: src/SUMMARY.md:5 src/running-the-course/course-structure.md:1 +#: src/SUMMARY.md:6 src/running-the-course/course-structure.md:1 msgid "Course Structure" msgstr "Kurs Yapısı" -#: src/SUMMARY.md:6 src/running-the-course/keyboard-shortcuts.md:1 +#: src/SUMMARY.md:7 src/running-the-course/keyboard-shortcuts.md:1 msgid "Keyboard Shortcuts" msgstr "Klavye Kısayolları" -#: src/SUMMARY.md:7 src/running-the-course/translations.md:1 +#: src/SUMMARY.md:8 src/running-the-course/translations.md:1 msgid "Translations" msgstr "Çeviriler" -#: src/SUMMARY.md:8 src/cargo.md:1 +#: src/SUMMARY.md:9 src/cargo.md:1 msgid "Using Cargo" msgstr "Cargo'yu Kullanmak" -#: src/SUMMARY.md:9 +#: src/SUMMARY.md:10 msgid "Rust Ecosystem" msgstr "Rust Ekosistemi" -#: src/SUMMARY.md:10 +#: src/SUMMARY.md:11 msgid "Code Samples" msgstr "Kod Örnekleri" -#: src/SUMMARY.md:11 +#: src/SUMMARY.md:12 msgid "Running Cargo Locally" msgstr "Cargo'yu Bilgisayarınızda Çalıştırmak" -#: src/SUMMARY.md:14 +#: src/SUMMARY.md:15 msgid "Day 1: Morning" msgstr "Gün 1: Sabah" -#: src/SUMMARY.md:18 src/SUMMARY.md:75 src/SUMMARY.md:128 src/SUMMARY.md:185 -#: src/SUMMARY.md:211 src/SUMMARY.md:259 +#: src/SUMMARY.md:19 src/SUMMARY.md:79 src/SUMMARY.md:137 src/SUMMARY.md:195 +#: src/SUMMARY.md:221 src/SUMMARY.md:271 msgid "Welcome" msgstr "Hoşgeldiniz" -#: src/SUMMARY.md:19 src/welcome-day-1/what-is-rust.md:1 +#: src/SUMMARY.md:20 src/welcome-day-1/what-is-rust.md:1 msgid "What is Rust?" msgstr "Rust Nedir?" -#: src/SUMMARY.md:20 src/hello-world.md:1 +#: src/SUMMARY.md:21 src/hello-world.md:1 msgid "Hello World!" msgstr "Merhaba Dünya!" -#: src/SUMMARY.md:21 src/hello-world/small-example.md:1 +#: src/SUMMARY.md:22 src/hello-world/small-example.md:1 msgid "Small Example" msgstr "Basit Örnek" -#: src/SUMMARY.md:22 src/why-rust.md:1 +#: src/SUMMARY.md:23 src/why-rust.md:1 msgid "Why Rust?" msgstr "Neden Rust?" -#: src/SUMMARY.md:23 src/why-rust/compile-time.md:1 +#: src/SUMMARY.md:24 src/why-rust/compile-time.md:1 msgid "Compile Time Guarantees" msgstr "Derleme Zamanı Garantileri" -#: src/SUMMARY.md:24 src/why-rust/runtime.md:1 +#: src/SUMMARY.md:25 src/why-rust/runtime.md:1 msgid "Runtime Guarantees" msgstr "Çalışma Zamanı Garantileri" -#: src/SUMMARY.md:25 src/why-rust/modern.md:1 +#: src/SUMMARY.md:26 src/why-rust/modern.md:1 msgid "Modern Features" msgstr "Modern Özellikler" -#: src/SUMMARY.md:26 src/basic-syntax.md:1 +#: src/SUMMARY.md:27 src/basic-syntax.md:1 msgid "Basic Syntax" msgstr "Sözdizimi" -#: src/SUMMARY.md:27 src/basic-syntax/scalar-types.md:1 +#: src/SUMMARY.md:28 src/basic-syntax/scalar-types.md:1 msgid "Scalar Types" msgstr "Skaler Tipler" -#: src/SUMMARY.md:28 src/basic-syntax/compound-types.md:1 +#: src/SUMMARY.md:29 src/basic-syntax/compound-types.md:1 msgid "Compound Types" msgstr "Bileşik Tipler" -#: src/SUMMARY.md:29 src/basic-syntax/references.md:1 +#: src/SUMMARY.md:30 src/basic-syntax/references.md:1 msgid "References" msgstr "Referanslar" -#: src/SUMMARY.md:30 src/basic-syntax/references-dangling.md:1 +#: src/SUMMARY.md:31 src/basic-syntax/references-dangling.md:1 msgid "Dangling References" msgstr "Askılı Referanslar" -#: src/SUMMARY.md:31 src/basic-syntax/slices.md:1 +#: src/SUMMARY.md:32 src/basic-syntax/slices.md:1 msgid "Slices" msgstr "Dilimler" -#: src/SUMMARY.md:32 +#: src/SUMMARY.md:33 msgid "String vs str" msgstr "String vs str" -#: src/SUMMARY.md:33 src/basic-syntax/functions.md:1 +#: src/SUMMARY.md:34 src/basic-syntax/functions.md:1 msgid "Functions" msgstr "Fonksiyonlar" -#: src/SUMMARY.md:34 src/basic-syntax/rustdoc.md:1 +#: src/SUMMARY.md:35 src/basic-syntax/rustdoc.md:1 msgid "Rustdoc" msgstr "Rustdoc" -#: src/SUMMARY.md:35 src/SUMMARY.md:82 src/basic-syntax/methods.md:1 +#: src/SUMMARY.md:36 src/SUMMARY.md:107 src/basic-syntax/methods.md:1 #: src/methods.md:1 msgid "Methods" msgstr "Metotlar" -#: src/SUMMARY.md:36 +#: src/SUMMARY.md:37 msgid "Overloading" msgstr "Aşırı Yükleme" -#: src/SUMMARY.md:37 src/SUMMARY.md:66 src/SUMMARY.md:90 src/SUMMARY.md:119 -#: src/SUMMARY.md:148 src/SUMMARY.md:177 src/SUMMARY.md:204 src/SUMMARY.md:225 -#: src/SUMMARY.md:251 src/SUMMARY.md:273 src/SUMMARY.md:293 +#: src/SUMMARY.md:38 src/SUMMARY.md:71 src/SUMMARY.md:100 src/SUMMARY.md:110 +#: src/SUMMARY.md:129 src/SUMMARY.md:157 src/SUMMARY.md:187 src/SUMMARY.md:214 +#: src/SUMMARY.md:235 src/SUMMARY.md:263 src/SUMMARY.md:285 src/SUMMARY.md:306 #: src/exercises/android/morning.md:1 src/exercises/bare-metal/morning.md:1 #: src/exercises/bare-metal/afternoon.md:1 #: src/exercises/concurrency/morning.md:1 @@ -139,1009 +140,1005 @@ msgstr "Aşırı Yükleme" msgid "Exercises" msgstr "Egzersizler" -#: src/SUMMARY.md:38 src/exercises/day-1/implicit-conversions.md:1 +#: src/SUMMARY.md:39 src/exercises/day-1/implicit-conversions.md:1 msgid "Implicit Conversions" msgstr "Örtülü Dönüşümler" -#: src/SUMMARY.md:39 +#: src/SUMMARY.md:40 msgid "Arrays and for Loops" msgstr "Diziler ve for Döngüleri" -#: src/SUMMARY.md:41 +#: src/SUMMARY.md:42 msgid "Day 1: Afternoon" msgstr "Gün 2: Öğleden Sonra" -#: src/SUMMARY.md:43 src/basic-syntax/variables.md:1 +#: src/SUMMARY.md:44 src/SUMMARY.md:298 src/control-flow.md:1 +msgid "Control Flow" +msgstr "Kontrol Akışı" + +#: src/SUMMARY.md:45 src/control-flow/blocks.md:1 +msgid "Blocks" +msgstr "Bloklar" + +#: src/SUMMARY.md:46 +msgid "if expressions" +msgstr "if İfadelesi" + +#: src/SUMMARY.md:47 +msgid "for expressions" +msgstr "for İfadesi" + +#: src/SUMMARY.md:48 +msgid "while expressions" +msgstr "while İfadesi" + +#: src/SUMMARY.md:49 +msgid "break & continue" +msgstr "break & continue" + +#: src/SUMMARY.md:50 +msgid "loop expressions" +msgstr "loop İfadesi" + +#: src/SUMMARY.md:52 src/basic-syntax/variables.md:1 msgid "Variables" msgstr "Değişkenler" -#: src/SUMMARY.md:44 src/basic-syntax/type-inference.md:1 +#: src/SUMMARY.md:53 src/basic-syntax/type-inference.md:1 msgid "Type Inference" msgstr "Tür Çıkarımı" -#: src/SUMMARY.md:45 +#: src/SUMMARY.md:54 msgid "static & const" msgstr "static & const" -#: src/SUMMARY.md:46 src/basic-syntax/scopes-shadowing.md:1 +#: src/SUMMARY.md:55 src/basic-syntax/scopes-shadowing.md:1 msgid "Scopes and Shadowing" msgstr "Kapsamlar ve Gölgeleme" -#: src/SUMMARY.md:47 src/memory-management.md:1 +#: src/SUMMARY.md:56 src/enums.md:1 +msgid "Enums" +msgstr "Enumlar" + +#: src/SUMMARY.md:57 src/enums/variant-payloads.md:1 +msgid "Variant Payloads" +msgstr "Değişken Yükler" + +#: src/SUMMARY.md:58 src/enums/sizes.md:1 +msgid "Enum Sizes" +msgstr "Enum Büyüklükleri" + +#: src/SUMMARY.md:60 src/control-flow/novel.md:1 +#, fuzzy +msgid "Novel Control Flow" +msgstr "Kontrol Akışı" + +#: src/SUMMARY.md:61 +msgid "if let expressions" +msgstr "if let İfadesi" + +#: src/SUMMARY.md:62 +msgid "while let expressions" +msgstr "while let İfadesi" + +#: src/SUMMARY.md:63 +msgid "match expressions" +msgstr "match İfadesi" + +#: src/SUMMARY.md:65 src/pattern-matching.md:1 +msgid "Pattern Matching" +msgstr "Şablon Eşleştirme" + +#: src/SUMMARY.md:66 src/pattern-matching/destructuring-enums.md:1 +msgid "Destructuring Enums" +msgstr "Enumları Yok Etme" + +#: src/SUMMARY.md:67 src/pattern-matching/destructuring-structs.md:1 +msgid "Destructuring Structs" +msgstr "Veri Yapılarını Yok Etme" + +#: src/SUMMARY.md:68 src/pattern-matching/destructuring-arrays.md:1 +msgid "Destructuring Arrays" +msgstr "Dizileri Yok Etme" + +#: src/SUMMARY.md:69 src/pattern-matching/match-guards.md:1 +msgid "Match Guards" +msgstr "Eşleştirme Muhafızları" + +#: src/SUMMARY.md:72 src/exercises/day-1/luhn.md:1 +#: src/exercises/day-1/solutions-afternoon.md:3 +msgid "Luhn Algorithm" +msgstr "Luhn Algrotiması" + +#: src/SUMMARY.md:73 +#, fuzzy +msgid "Pattern Matching (TBD)" +msgstr "Şablon Eşleştirme" + +#: src/SUMMARY.md:75 +msgid "Day 2: Morning" +msgstr "Gün 2: Sabah" + +#: src/SUMMARY.md:81 src/memory-management.md:1 msgid "Memory Management" msgstr "Bellek Yönetimi" -#: src/SUMMARY.md:48 +#: src/SUMMARY.md:82 msgid "Stack vs Heap" msgstr "Stack vs Heap" -#: src/SUMMARY.md:49 src/memory-management/stack.md:1 +#: src/SUMMARY.md:83 msgid "Stack Memory" msgstr "Stack Belleği" -#: src/SUMMARY.md:50 src/memory-management/manual.md:1 +#: src/SUMMARY.md:84 src/memory-management/manual.md:1 msgid "Manual Memory Management" msgstr "Manuel Bellek Yönetimi" -#: src/SUMMARY.md:51 src/memory-management/scope-based.md:1 +#: src/SUMMARY.md:85 src/memory-management/scope-based.md:1 msgid "Scope-Based Memory Management" msgstr "Kapsam Tabanlı Bellek Yönetimi" -#: src/SUMMARY.md:52 +#: src/SUMMARY.md:86 msgid "Garbage Collection" msgstr "Çöp Toplama" -#: src/SUMMARY.md:53 +#: src/SUMMARY.md:87 msgid "Rust Memory Management" msgstr "Rust Bellek Yönetimi" -#: src/SUMMARY.md:54 src/memory-management/comparison.md:1 +#: src/SUMMARY.md:88 src/memory-management/comparison.md:1 msgid "Comparison" msgstr "Karşılaştırma" -#: src/SUMMARY.md:55 src/ownership.md:1 +#: src/SUMMARY.md:89 src/ownership.md:1 msgid "Ownership" msgstr "Sahiplik" -#: src/SUMMARY.md:56 src/ownership/move-semantics.md:1 +#: src/SUMMARY.md:90 src/ownership/move-semantics.md:1 msgid "Move Semantics" msgstr "Taşıma Şematiği" -#: src/SUMMARY.md:57 src/ownership/moved-strings-rust.md:1 +#: src/SUMMARY.md:91 src/ownership/moved-strings-rust.md:1 msgid "Moved Strings in Rust" msgstr "Rust'da Taşınmış Stringler" -#: src/SUMMARY.md:58 src/ownership/double-free-modern-cpp.md:1 +#: src/SUMMARY.md:92 msgid "Double Frees in Modern C++" msgstr "Modern C++'da Çifte Serbestlik" -#: src/SUMMARY.md:59 src/ownership/moves-function-calls.md:1 +#: src/SUMMARY.md:93 src/ownership/moves-function-calls.md:1 msgid "Moves in Function Calls" msgstr "Fonksiyon Çağrılarında Taşımalar" -#: src/SUMMARY.md:60 src/ownership/copy-clone.md:1 +#: src/SUMMARY.md:94 src/ownership/copy-clone.md:1 msgid "Copying and Cloning" msgstr "Kopyalama ve Klonlama" -#: src/SUMMARY.md:61 src/ownership/borrowing.md:1 +#: src/SUMMARY.md:95 src/ownership/borrowing.md:1 msgid "Borrowing" msgstr "Ödünç Alma" -#: src/SUMMARY.md:62 src/ownership/shared-unique-borrows.md:1 +#: src/SUMMARY.md:96 src/ownership/shared-unique-borrows.md:1 msgid "Shared and Unique Borrows" msgstr "Paylaşılan ve Eşsiz Ödünç Almalar" -#: src/SUMMARY.md:63 src/ownership/lifetimes.md:1 +#: src/SUMMARY.md:97 src/ownership/lifetimes.md:1 msgid "Lifetimes" msgstr "Ömürler" -#: src/SUMMARY.md:64 src/ownership/lifetimes-function-calls.md:1 +#: src/SUMMARY.md:98 src/ownership/lifetimes-function-calls.md:1 msgid "Lifetimes in Function Calls" msgstr "Fonksiyon Çağrılarında Ömürler" -#: src/SUMMARY.md:65 src/ownership/lifetimes-data-structures.md:1 +#: src/SUMMARY.md:99 src/ownership/lifetimes-data-structures.md:1 msgid "Lifetimes in Data Structures" msgstr "Veri Yapılarında Ömürler" -#: src/SUMMARY.md:67 src/exercises/day-1/book-library.md:1 -#: src/exercises/day-1/solutions-afternoon.md:3 -msgid "Designing a Library" -msgstr "Kütüphane Tasarlama" +#: src/SUMMARY.md:101 src/exercises/day-2/book-library.md:1 +#, fuzzy +msgid "Storing Books" +msgstr "String" -#: src/SUMMARY.md:68 src/exercises/day-1/iterators-and-ownership.md:1 +#: src/SUMMARY.md:102 src/exercises/day-2/iterators-and-ownership.md:1 msgid "Iterators and Ownership" msgstr "Yineleyiciler ve Sahiplik" -#: src/SUMMARY.md:71 -msgid "Day 2: Morning" -msgstr "Gün 2: Sabah" - -#: src/SUMMARY.md:76 src/structs.md:1 +#: src/SUMMARY.md:104 src/structs.md:1 msgid "Structs" msgstr "Veri Yapıları" -#: src/SUMMARY.md:77 src/structs/tuple-structs.md:1 +#: src/SUMMARY.md:105 src/structs/tuple-structs.md:1 msgid "Tuple Structs" msgstr "Tuple Veri Yapısı" -#: src/SUMMARY.md:78 src/structs/field-shorthand.md:1 +#: src/SUMMARY.md:106 src/structs/field-shorthand.md:1 msgid "Field Shorthand Syntax" msgstr "TODO:" -#: src/SUMMARY.md:79 src/enums.md:1 -msgid "Enums" -msgstr "Enumlar" - -#: src/SUMMARY.md:80 src/enums/variant-payloads.md:1 -msgid "Variant Payloads" -msgstr "Değişken Yükler" - -#: src/SUMMARY.md:81 src/enums/sizes.md:1 -msgid "Enum Sizes" -msgstr "Enum Büyüklükleri" - -#: src/SUMMARY.md:83 src/methods/receiver.md:1 +#: src/SUMMARY.md:108 src/methods/receiver.md:1 msgid "Method Receiver" msgstr "Metot Alıcısı" -#: src/SUMMARY.md:84 src/SUMMARY.md:159 src/SUMMARY.md:272 +#: src/SUMMARY.md:109 src/SUMMARY.md:169 src/SUMMARY.md:284 #: src/methods/example.md:1 src/concurrency/shared_state/example.md:1 msgid "Example" msgstr "Örnek" -#: src/SUMMARY.md:85 src/pattern-matching.md:1 -msgid "Pattern Matching" -msgstr "Şablon Eşleştirme" - -#: src/SUMMARY.md:86 src/pattern-matching/destructuring-enums.md:1 -msgid "Destructuring Enums" -msgstr "Enumları Yok Etme" - -#: src/SUMMARY.md:87 src/pattern-matching/destructuring-structs.md:1 -msgid "Destructuring Structs" -msgstr "Veri Yapılarını Yok Etme" - -#: src/SUMMARY.md:88 src/pattern-matching/destructuring-arrays.md:1 -msgid "Destructuring Arrays" -msgstr "Dizileri Yok Etme" - -#: src/SUMMARY.md:89 src/pattern-matching/match-guards.md:1 -msgid "Match Guards" -msgstr "Eşleştirme Muhafızları" - -#: src/SUMMARY.md:91 src/exercises/day-2/health-statistics.md:1 +#: src/SUMMARY.md:111 src/exercises/day-2/health-statistics.md:1 msgid "Health Statistics" msgstr "Sağlık İstatistikleri" -#: src/SUMMARY.md:92 src/exercises/day-2/solutions-morning.md:3 -msgid "Points and Polygons" -msgstr "Noktalar ve Çokgenler" - -#: src/SUMMARY.md:94 +#: src/SUMMARY.md:113 msgid "Day 2: Afternoon" msgstr "Gün 2: Öğleden Sonra" -#: src/SUMMARY.md:96 src/SUMMARY.md:286 src/control-flow.md:1 -msgid "Control Flow" -msgstr "Kontrol Akışı" - -#: src/SUMMARY.md:97 src/control-flow/blocks.md:1 -msgid "Blocks" -msgstr "Bloklar" - -#: src/SUMMARY.md:98 -msgid "if expressions" -msgstr "if İfadelesi" - -#: src/SUMMARY.md:99 -msgid "if let expressions" -msgstr "if let İfadesi" - -#: src/SUMMARY.md:100 -msgid "while expressions" -msgstr "while İfadesi" - -#: src/SUMMARY.md:101 -msgid "while let expressions" -msgstr "while let İfadesi" - -#: src/SUMMARY.md:102 -msgid "for expressions" -msgstr "for İfadesi" - -#: src/SUMMARY.md:103 -msgid "loop expressions" -msgstr "loop İfadesi" - -#: src/SUMMARY.md:104 -msgid "match expressions" -msgstr "match İfadesi" - -#: src/SUMMARY.md:105 -msgid "break & continue" -msgstr "break & continue" - -#: src/SUMMARY.md:106 src/std.md:1 +#: src/SUMMARY.md:115 src/std.md:1 msgid "Standard Library" msgstr "Standart Kütüphane" -#: src/SUMMARY.md:107 +#: src/SUMMARY.md:116 msgid "Option and Result" msgstr "Option ve Result" -#: src/SUMMARY.md:108 src/std/string.md:1 +#: src/SUMMARY.md:117 src/std/string.md:1 msgid "String" msgstr "String" -#: src/SUMMARY.md:109 +#: src/SUMMARY.md:118 msgid "Vec" msgstr "Vec" -#: src/SUMMARY.md:110 +#: src/SUMMARY.md:119 msgid "HashMap" msgstr "HashMap" -#: src/SUMMARY.md:111 +#: src/SUMMARY.md:120 msgid "Box" msgstr "Box" -#: src/SUMMARY.md:112 +#: src/SUMMARY.md:121 msgid "Recursive Data Types" msgstr "Özyinelemeli Veri Türleri" -#: src/SUMMARY.md:113 src/std/box-niche.md:1 +#: src/SUMMARY.md:122 src/std/box-niche.md:1 msgid "Niche Optimization" msgstr "Niche Optimizasyonu" -#: src/SUMMARY.md:114 +#: src/SUMMARY.md:123 msgid "Rc" msgstr "Rc" -#: src/SUMMARY.md:115 src/modules.md:1 +#: src/SUMMARY.md:124 +msgid "Cell/RefCell" +msgstr "" + +#: src/SUMMARY.md:125 src/modules.md:1 msgid "Modules" msgstr "Modüller" -#: src/SUMMARY.md:116 src/modules/visibility.md:1 +#: src/SUMMARY.md:126 src/modules/visibility.md:1 msgid "Visibility" msgstr "Görünebilirlik" -#: src/SUMMARY.md:117 src/modules/paths.md:1 +#: src/SUMMARY.md:127 src/modules/paths.md:1 msgid "Paths" msgstr "Yollar" -#: src/SUMMARY.md:118 src/modules/filesystem.md:1 +#: src/SUMMARY.md:128 src/modules/filesystem.md:1 msgid "Filesystem Hierarchy" msgstr "Dosya Sistemi Hiyerarşisi" -#: src/SUMMARY.md:120 src/exercises/day-2/luhn.md:1 +#: src/SUMMARY.md:130 src/exercises/day-2/strings-iterators.md:1 #: src/exercises/day-2/solutions-afternoon.md:3 -msgid "Luhn Algorithm" -msgstr "Luhn Algrotiması" - -#: src/SUMMARY.md:121 src/exercises/day-2/strings-iterators.md:1 -#: src/exercises/day-2/solutions-afternoon.md:97 msgid "Strings and Iterators" msgstr "Stringler ve Yineleyiciler" -#: src/SUMMARY.md:124 +#: src/SUMMARY.md:133 msgid "Day 3: Morning" msgstr "Gün 3: Sabah" -#: src/SUMMARY.md:129 src/generics.md:1 +#: src/SUMMARY.md:138 src/generics.md:1 msgid "Generics" msgstr "Jenerikler" -#: src/SUMMARY.md:130 src/generics/data-types.md:1 +#: src/SUMMARY.md:139 src/generics/data-types.md:1 msgid "Generic Data Types" msgstr "Jenerik Veri Türleri" -#: src/SUMMARY.md:131 src/generics/methods.md:1 +#: src/SUMMARY.md:140 src/generics/methods.md:1 msgid "Generic Methods" msgstr "Jenerik Metotlar" -#: src/SUMMARY.md:132 src/generics/monomorphization.md:1 +#: src/SUMMARY.md:141 src/generics/monomorphization.md:1 msgid "Monomorphization" msgstr "Monomorfizasyon" -#: src/SUMMARY.md:133 src/traits.md:1 +#: src/SUMMARY.md:142 src/traits.md:1 msgid "Traits" msgstr "Traitler" -#: src/SUMMARY.md:134 src/traits/trait-objects.md:1 +#: src/SUMMARY.md:143 src/traits/trait-objects.md:1 msgid "Trait Objects" msgstr "Trait Nesneleri" -#: src/SUMMARY.md:135 src/traits/deriving-traits.md:1 +#: src/SUMMARY.md:144 src/traits/deriving-traits.md:1 msgid "Deriving Traits" msgstr "Türeyen Traitler" -#: src/SUMMARY.md:136 src/traits/default-methods.md:1 +#: src/SUMMARY.md:145 src/traits/default-methods.md:1 msgid "Default Methods" msgstr "Varsayılan Metotlar" -#: src/SUMMARY.md:137 src/traits/trait-bounds.md:1 +#: src/SUMMARY.md:146 src/traits/trait-bounds.md:1 msgid "Trait Bounds" msgstr "Trait Sınırları" -#: src/SUMMARY.md:138 +#: src/SUMMARY.md:147 msgid "impl Trait" msgstr "impl Trait" -#: src/SUMMARY.md:139 src/traits/important-traits.md:1 +#: src/SUMMARY.md:148 src/traits/important-traits.md:1 msgid "Important Traits" msgstr "Önemli Traitler" -#: src/SUMMARY.md:140 +#: src/SUMMARY.md:149 msgid "Iterator" msgstr "Iterator" -#: src/SUMMARY.md:141 src/traits/from-iterator.md:1 +#: src/SUMMARY.md:150 src/traits/from-iterator.md:1 msgid "FromIterator" msgstr "FromIterator" -#: src/SUMMARY.md:142 +#: src/SUMMARY.md:151 msgid "From and Into" msgstr "From ve Into" -#: src/SUMMARY.md:143 +#: src/SUMMARY.md:152 msgid "Read and Write" msgstr "Read ve Write" -#: src/SUMMARY.md:144 +#: src/SUMMARY.md:153 msgid "Drop" msgstr "Drop" -#: src/SUMMARY.md:145 +#: src/SUMMARY.md:154 msgid "Default" msgstr "Default" -#: src/SUMMARY.md:146 +#: src/SUMMARY.md:155 msgid "Operators: Add, Mul, ..." msgstr "Operatörler: Add, Mul, ..." -#: src/SUMMARY.md:147 +#: src/SUMMARY.md:156 msgid "Closures: Fn, FnMut, FnOnce" msgstr "TODO:" -#: src/SUMMARY.md:149 src/exercises/day-3/simple-gui.md:1 +#: src/SUMMARY.md:158 src/exercises/day-3/simple-gui.md:1 #: src/exercises/day-3/solutions-morning.md:3 msgid "A Simple GUI Library" msgstr "Basit bir GUI Kütüphanesi" -#: src/SUMMARY.md:151 +#: src/SUMMARY.md:159 src/exercises/day-3/solutions-morning.md:175 +msgid "Points and Polygons" +msgstr "Noktalar ve Çokgenler" + +#: src/SUMMARY.md:161 msgid "Day 3: Afternoon" msgstr "Gün 3: Öğleden Sonra" -#: src/SUMMARY.md:153 src/error-handling.md:1 +#: src/SUMMARY.md:163 src/error-handling.md:1 msgid "Error Handling" msgstr "Hata Yönetimi" -#: src/SUMMARY.md:154 src/error-handling/panics.md:1 +#: src/SUMMARY.md:164 src/error-handling/panics.md:1 msgid "Panics" msgstr "Panikler" -#: src/SUMMARY.md:155 +#: src/SUMMARY.md:165 msgid "Catching Stack Unwinding" msgstr "TODO:" -#: src/SUMMARY.md:156 +#: src/SUMMARY.md:166 msgid "Structured Error Handling" msgstr "Yapılandırılmış Hata Yönetimi" -#: src/SUMMARY.md:157 +#: src/SUMMARY.md:167 msgid "Propagating Errors with ?" msgstr "? ile Hata Döndürme" -#: src/SUMMARY.md:158 src/error-handling/converting-error-types.md:1 +#: src/SUMMARY.md:168 src/error-handling/converting-error-types.md:1 #: src/error-handling/converting-error-types-example.md:1 msgid "Converting Error Types" msgstr "Hata Türlerini Dönüştürme" -#: src/SUMMARY.md:160 src/error-handling/deriving-error-enums.md:1 +#: src/SUMMARY.md:170 src/error-handling/deriving-error-enums.md:1 msgid "Deriving Error Enums" msgstr "Hata Enumlarını Türetme" -#: src/SUMMARY.md:161 src/error-handling/dynamic-errors.md:1 +#: src/SUMMARY.md:171 src/error-handling/dynamic-errors.md:1 msgid "Dynamic Error Types" msgstr "Dinamik Hata Türleri" -#: src/SUMMARY.md:162 src/error-handling/error-contexts.md:1 +#: src/SUMMARY.md:172 src/error-handling/error-contexts.md:1 msgid "Adding Context to Errors" msgstr "Hatalara Bağlam Ekleme" -#: src/SUMMARY.md:163 src/testing.md:1 +#: src/SUMMARY.md:173 src/testing.md:1 msgid "Testing" msgstr "Test Etme" -#: src/SUMMARY.md:164 src/testing/unit-tests.md:1 +#: src/SUMMARY.md:174 src/testing/unit-tests.md:1 msgid "Unit Tests" msgstr "Birim Testleri" -#: src/SUMMARY.md:165 src/testing/test-modules.md:1 +#: src/SUMMARY.md:175 src/testing/test-modules.md:1 msgid "Test Modules" msgstr "Test Modülleri" -#: src/SUMMARY.md:166 src/testing/doc-tests.md:1 +#: src/SUMMARY.md:176 src/testing/doc-tests.md:1 msgid "Documentation Tests" msgstr "Dokümantasyon Testleri" -#: src/SUMMARY.md:167 src/testing/integration-tests.md:1 +#: src/SUMMARY.md:177 src/testing/integration-tests.md:1 msgid "Integration Tests" msgstr "Entegrasyon Testleri" -#: src/SUMMARY.md:168 src/bare-metal/useful-crates.md:1 +#: src/SUMMARY.md:178 src/bare-metal/useful-crates.md:1 msgid "Useful crates" msgstr "Yararlı crateler" -#: src/SUMMARY.md:169 src/unsafe.md:1 +#: src/SUMMARY.md:179 src/unsafe.md:1 msgid "Unsafe Rust" msgstr "Güvensiz Rust" -#: src/SUMMARY.md:170 src/unsafe/raw-pointers.md:1 +#: src/SUMMARY.md:180 src/unsafe/raw-pointers.md:1 msgid "Dereferencing Raw Pointers" msgstr "Saf İşaretçilerin Referansını Kaldırma" -#: src/SUMMARY.md:171 src/unsafe/mutable-static-variables.md:1 +#: src/SUMMARY.md:181 src/unsafe/mutable-static-variables.md:1 msgid "Mutable Static Variables" msgstr "Değişebilir Statik Değişlenler" -#: src/SUMMARY.md:172 src/unsafe/unions.md:1 +#: src/SUMMARY.md:182 src/unsafe/unions.md:1 msgid "Unions" msgstr "Unionlar" -#: src/SUMMARY.md:173 src/unsafe/calling-unsafe-functions.md:1 +#: src/SUMMARY.md:183 src/unsafe/calling-unsafe-functions.md:1 msgid "Calling Unsafe Functions" msgstr "Güvensiz Fonksiyonları Çağırma" -#: src/SUMMARY.md:174 src/unsafe/writing-unsafe-functions.md:1 +#: src/SUMMARY.md:184 src/unsafe/writing-unsafe-functions.md:1 msgid "Writing Unsafe Functions" msgstr "Güvensiz Fonksiyonlar Yazma" -#: src/SUMMARY.md:175 +#: src/SUMMARY.md:185 msgid "Extern Functions" msgstr "Dış Fonksiyonlar" -#: src/SUMMARY.md:176 src/unsafe/unsafe-traits.md:1 +#: src/SUMMARY.md:186 src/unsafe/unsafe-traits.md:1 msgid "Implementing Unsafe Traits" msgstr "Güvensiz Traitleri Ekleme" -#: src/SUMMARY.md:178 src/exercises/day-3/safe-ffi-wrapper.md:1 +#: src/SUMMARY.md:188 src/exercises/day-3/safe-ffi-wrapper.md:1 #: src/exercises/day-3/solutions-afternoon.md:3 msgid "Safe FFI Wrapper" msgstr "Güvenli FFI Sarıcı" -#: src/SUMMARY.md:181 src/SUMMARY.md:249 -#: src/running-the-course/course-structure.md:16 src/bare-metal/android.md:1 +#: src/SUMMARY.md:191 src/SUMMARY.md:261 src/bare-metal/android.md:1 msgid "Android" msgstr "Android" -#: src/SUMMARY.md:186 src/android/setup.md:1 +#: src/SUMMARY.md:196 src/android/setup.md:1 msgid "Setup" msgstr "Kurulum" -#: src/SUMMARY.md:187 src/android/build-rules.md:1 +#: src/SUMMARY.md:197 src/android/build-rules.md:1 msgid "Build Rules" msgstr "Oluşturma Kuralları" -#: src/SUMMARY.md:188 +#: src/SUMMARY.md:198 msgid "Binary" msgstr "Çalıştırılabilir Dosya" -#: src/SUMMARY.md:189 +#: src/SUMMARY.md:199 msgid "Library" msgstr "Kütüphane" -#: src/SUMMARY.md:190 src/android/aidl.md:1 +#: src/SUMMARY.md:200 src/android/aidl.md:1 msgid "AIDL" msgstr "AIDL" -#: src/SUMMARY.md:191 +#: src/SUMMARY.md:201 msgid "Interface" msgstr "Arayüz" -#: src/SUMMARY.md:192 +#: src/SUMMARY.md:202 msgid "Implementation" msgstr "Ekleme" -#: src/SUMMARY.md:193 +#: src/SUMMARY.md:203 msgid "Server" msgstr "Sunucu" -#: src/SUMMARY.md:194 src/android/aidl/deploy.md:1 +#: src/SUMMARY.md:204 src/android/aidl/deploy.md:1 msgid "Deploy" msgstr "Başlatma" -#: src/SUMMARY.md:195 +#: src/SUMMARY.md:205 msgid "Client" msgstr "Alıcı" -#: src/SUMMARY.md:196 src/android/aidl/changing.md:1 +#: src/SUMMARY.md:206 src/android/aidl/changing.md:1 msgid "Changing API" msgstr "API'yi Değiştirme" -#: src/SUMMARY.md:197 src/SUMMARY.md:240 src/android/logging.md:1 +#: src/SUMMARY.md:207 src/SUMMARY.md:251 src/android/logging.md:1 #: src/bare-metal/aps/logging.md:1 msgid "Logging" msgstr "TODO: NOTE:Günlükleme Olabilir" -#: src/SUMMARY.md:198 src/android/interoperability.md:1 +#: src/SUMMARY.md:208 src/android/interoperability.md:1 msgid "Interoperability" msgstr "Birlikte Çalışabilirlik" -#: src/SUMMARY.md:199 +#: src/SUMMARY.md:209 msgid "With C" msgstr "C ile" -#: src/SUMMARY.md:200 +#: src/SUMMARY.md:210 msgid "Calling C with Bindgen" msgstr "Bindgen ile C Kullanma" -#: src/SUMMARY.md:201 +#: src/SUMMARY.md:211 msgid "Calling Rust from C" msgstr "C ile Rust Kullanma" -#: src/SUMMARY.md:202 src/android/interoperability/cpp.md:1 +#: src/SUMMARY.md:212 src/android/interoperability/cpp.md:1 msgid "With C++" msgstr "C++ ile" -#: src/SUMMARY.md:203 +#: src/SUMMARY.md:213 msgid "With Java" msgstr "Java ile" -#: src/SUMMARY.md:207 +#: src/SUMMARY.md:217 msgid "Bare Metal: Morning" msgstr "" -#: src/SUMMARY.md:212 +#: src/SUMMARY.md:222 msgid "no_std" msgstr "" -#: src/SUMMARY.md:213 +#: src/SUMMARY.md:223 msgid "A Minimal Example" msgstr "" -#: src/SUMMARY.md:214 +#: src/SUMMARY.md:224 msgid "alloc" msgstr "" -#: src/SUMMARY.md:215 src/bare-metal/microcontrollers.md:1 +#: src/SUMMARY.md:225 src/bare-metal/microcontrollers.md:1 msgid "Microcontrollers" msgstr "" -#: src/SUMMARY.md:216 src/bare-metal/microcontrollers/mmio.md:1 +#: src/SUMMARY.md:226 src/bare-metal/microcontrollers/mmio.md:1 msgid "Raw MMIO" msgstr "" -#: src/SUMMARY.md:217 +#: src/SUMMARY.md:227 msgid "PACs" msgstr "" -#: src/SUMMARY.md:218 +#: src/SUMMARY.md:228 msgid "HAL Crates" msgstr "" -#: src/SUMMARY.md:219 +#: src/SUMMARY.md:229 msgid "Board Support Crates" msgstr "" -#: src/SUMMARY.md:220 +#: src/SUMMARY.md:230 msgid "The Type State Pattern" msgstr "" -#: src/SUMMARY.md:221 +#: src/SUMMARY.md:231 msgid "embedded-hal" msgstr "" -#: src/SUMMARY.md:222 +#: src/SUMMARY.md:232 msgid "probe-rs, cargo-embed" msgstr "" -#: src/SUMMARY.md:223 src/bare-metal/microcontrollers/debugging.md:1 +#: src/SUMMARY.md:233 src/bare-metal/microcontrollers/debugging.md:1 msgid "Debugging" msgstr "" -#: src/SUMMARY.md:224 src/SUMMARY.md:242 +#: src/SUMMARY.md:234 src/SUMMARY.md:254 msgid "Other Projects" msgstr "" -#: src/SUMMARY.md:226 src/exercises/bare-metal/compass.md:1 +#: src/SUMMARY.md:236 src/exercises/bare-metal/compass.md:1 #: src/exercises/bare-metal/solutions-morning.md:3 msgid "Compass" msgstr "" -#: src/SUMMARY.md:228 +#: src/SUMMARY.md:238 msgid "Bare Metal: Afternoon" msgstr "" -#: src/SUMMARY.md:230 +#: src/SUMMARY.md:240 msgid "Application Processors" msgstr "" -#: src/SUMMARY.md:231 +#: src/SUMMARY.md:241 src/bare-metal/aps/entry-point.md:1 +msgid "Getting Ready to Rust" +msgstr "" + +#: src/SUMMARY.md:242 msgid "Inline Assembly" msgstr "" -#: src/SUMMARY.md:232 +#: src/SUMMARY.md:243 msgid "MMIO" msgstr "" -#: src/SUMMARY.md:233 +#: src/SUMMARY.md:244 msgid "Let's Write a UART Driver" msgstr "" -#: src/SUMMARY.md:234 +#: src/SUMMARY.md:245 msgid "More Traits" msgstr "" -#: src/SUMMARY.md:235 +#: src/SUMMARY.md:246 msgid "A Better UART Driver" msgstr "" -#: src/SUMMARY.md:236 src/bare-metal/aps/better-uart/bitflags.md:1 +#: src/SUMMARY.md:247 src/bare-metal/aps/better-uart/bitflags.md:1 msgid "Bitflags" msgstr "" -#: src/SUMMARY.md:237 +#: src/SUMMARY.md:248 msgid "Multiple Registers" msgstr "" -#: src/SUMMARY.md:238 src/bare-metal/aps/better-uart/driver.md:1 +#: src/SUMMARY.md:249 src/bare-metal/aps/better-uart/driver.md:1 msgid "Driver" msgstr "" -#: src/SUMMARY.md:239 src/SUMMARY.md:241 +#: src/SUMMARY.md:250 src/SUMMARY.md:252 msgid "Using It" msgstr "" -#: src/SUMMARY.md:243 +#: src/SUMMARY.md:253 src/bare-metal/aps/exceptions.md:1 +#, fuzzy +msgid "Exceptions" +msgstr "Fonksiyonlar" + +#: src/SUMMARY.md:255 msgid "Useful Crates" msgstr "" -#: src/SUMMARY.md:244 +#: src/SUMMARY.md:256 msgid "zerocopy" msgstr "" -#: src/SUMMARY.md:245 +#: src/SUMMARY.md:257 msgid "aarch64-paging" msgstr "" -#: src/SUMMARY.md:246 +#: src/SUMMARY.md:258 msgid "buddy_system_allocator" msgstr "" -#: src/SUMMARY.md:247 +#: src/SUMMARY.md:259 msgid "tinyvec" msgstr "" -#: src/SUMMARY.md:248 +#: src/SUMMARY.md:260 msgid "spin" msgstr "" -#: src/SUMMARY.md:250 src/bare-metal/android/vmbase.md:1 +#: src/SUMMARY.md:262 src/bare-metal/android/vmbase.md:1 msgid "vmbase" msgstr "" -#: src/SUMMARY.md:252 +#: src/SUMMARY.md:264 msgid "RTC Driver" msgstr "" -#: src/SUMMARY.md:255 +#: src/SUMMARY.md:267 msgid "Concurrency: Morning" msgstr "" -#: src/SUMMARY.md:260 src/concurrency/threads.md:1 +#: src/SUMMARY.md:272 src/concurrency/threads.md:1 msgid "Threads" msgstr "" -#: src/SUMMARY.md:261 src/concurrency/scoped-threads.md:1 +#: src/SUMMARY.md:273 src/concurrency/scoped-threads.md:1 msgid "Scoped Threads" msgstr "" -#: src/SUMMARY.md:262 src/concurrency/channels.md:1 +#: src/SUMMARY.md:274 src/concurrency/channels.md:1 msgid "Channels" msgstr "" -#: src/SUMMARY.md:263 src/concurrency/channels/unbounded.md:1 +#: src/SUMMARY.md:275 src/concurrency/channels/unbounded.md:1 msgid "Unbounded Channels" msgstr "" -#: src/SUMMARY.md:264 src/concurrency/channels/bounded.md:1 +#: src/SUMMARY.md:276 src/concurrency/channels/bounded.md:1 msgid "Bounded Channels" msgstr "" -#: src/SUMMARY.md:265 +#: src/SUMMARY.md:277 msgid "Send and Sync" msgstr "" -#: src/SUMMARY.md:265 +#: src/SUMMARY.md:277 msgid "Send" msgstr "" -#: src/SUMMARY.md:265 +#: src/SUMMARY.md:277 msgid "Sync" msgstr "" -#: src/SUMMARY.md:268 src/concurrency/send-sync/examples.md:1 +#: src/SUMMARY.md:280 src/concurrency/send-sync/examples.md:1 msgid "Examples" msgstr "" -#: src/SUMMARY.md:269 src/concurrency/shared_state.md:1 +#: src/SUMMARY.md:281 src/concurrency/shared_state.md:1 msgid "Shared State" msgstr "" -#: src/SUMMARY.md:270 +#: src/SUMMARY.md:282 msgid "Arc" msgstr "" -#: src/SUMMARY.md:271 +#: src/SUMMARY.md:283 msgid "Mutex" msgstr "" -#: src/SUMMARY.md:274 src/SUMMARY.md:294 +#: src/SUMMARY.md:286 src/SUMMARY.md:307 #: src/exercises/concurrency/dining-philosophers.md:1 #: src/exercises/concurrency/solutions-morning.md:3 msgid "Dining Philosophers" msgstr "" -#: src/SUMMARY.md:275 src/exercises/concurrency/link-checker.md:1 +#: src/SUMMARY.md:287 src/exercises/concurrency/link-checker.md:1 msgid "Multi-threaded Link Checker" msgstr "" -#: src/SUMMARY.md:277 +#: src/SUMMARY.md:289 msgid "Concurrency: Afternoon" msgstr "" -#: src/SUMMARY.md:279 +#: src/SUMMARY.md:291 msgid "Async Basics" msgstr "" -#: src/SUMMARY.md:280 +#: src/SUMMARY.md:292 msgid "async/await" msgstr "" -#: src/SUMMARY.md:281 src/async/futures.md:1 +#: src/SUMMARY.md:293 src/async/futures.md:1 msgid "Futures" msgstr "" -#: src/SUMMARY.md:282 src/async/runtimes.md:1 +#: src/SUMMARY.md:294 src/async/runtimes.md:1 msgid "Runtimes" msgstr "" -#: src/SUMMARY.md:283 src/async/runtimes/tokio.md:1 +#: src/SUMMARY.md:295 src/async/runtimes/tokio.md:1 msgid "Tokio" msgstr "" -#: src/SUMMARY.md:284 src/exercises/concurrency/link-checker.md:106 -#: src/exercises/concurrency/chat-app.md:140 src/async/tasks.md:1 +#: src/SUMMARY.md:296 src/exercises/concurrency/link-checker.md:126 +#: src/async/tasks.md:1 src/exercises/concurrency/chat-app.md:140 msgid "Tasks" msgstr "" -#: src/SUMMARY.md:285 src/async/channels.md:1 +#: src/SUMMARY.md:297 src/async/channels.md:1 msgid "Async Channels" msgstr "" -#: src/SUMMARY.md:287 src/async/control-flow/join.md:1 +#: src/SUMMARY.md:299 src/async/control-flow/join.md:1 msgid "Join" msgstr "" -#: src/SUMMARY.md:288 src/async/control-flow/select.md:1 +#: src/SUMMARY.md:300 src/async/control-flow/select.md:1 msgid "Select" msgstr "" -#: src/SUMMARY.md:289 +#: src/SUMMARY.md:301 msgid "Pitfalls" msgstr "" -#: src/SUMMARY.md:290 +#: src/SUMMARY.md:302 msgid "Blocking the Executor" msgstr "" -#: src/SUMMARY.md:291 src/async/pitfalls/pin.md:1 +#: src/SUMMARY.md:303 src/async/pitfalls/pin.md:1 msgid "Pin" msgstr "" -#: src/SUMMARY.md:292 src/async/pitfalls/async-traits.md:1 +#: src/SUMMARY.md:304 src/async/pitfalls/async-traits.md:1 msgid "Async Traits" msgstr "" -#: src/SUMMARY.md:295 src/exercises/concurrency/chat-app.md:1 -#: src/exercises/concurrency/solutions-afternoon.md:113 +#: src/SUMMARY.md:305 src/async/pitfalls/cancellation.md:1 +#, fuzzy +msgid "Cancellation" +msgstr "Çeviriler" + +#: src/SUMMARY.md:308 src/exercises/concurrency/chat-app.md:1 +#: src/exercises/concurrency/solutions-afternoon.md:119 msgid "Broadcast Chat Application" msgstr "" -#: src/SUMMARY.md:298 +#: src/SUMMARY.md:311 msgid "Final Words" msgstr "" -#: src/SUMMARY.md:302 src/thanks.md:1 +#: src/SUMMARY.md:315 src/thanks.md:1 msgid "Thanks!" msgstr "" -#: src/SUMMARY.md:303 +#: src/SUMMARY.md:316 msgid "Other Resources" msgstr "" -#: src/SUMMARY.md:304 src/credits.md:1 +#: src/SUMMARY.md:317 src/credits.md:1 msgid "Credits" msgstr "" -#: src/SUMMARY.md:307 src/exercises/solutions.md:1 +#: src/SUMMARY.md:320 src/exercises/solutions.md:1 msgid "Solutions" msgstr "" -#: src/SUMMARY.md:312 +#: src/SUMMARY.md:325 msgid "Day 1 Morning" msgstr "" -#: src/SUMMARY.md:313 +#: src/SUMMARY.md:326 msgid "Day 1 Afternoon" msgstr "" -#: src/SUMMARY.md:314 +#: src/SUMMARY.md:327 msgid "Day 2 Morning" msgstr "" -#: src/SUMMARY.md:315 +#: src/SUMMARY.md:328 msgid "Day 2 Afternoon" msgstr "" -#: src/SUMMARY.md:316 +#: src/SUMMARY.md:329 msgid "Day 3 Morning" msgstr "" -#: src/SUMMARY.md:317 +#: src/SUMMARY.md:330 msgid "Day 3 Afternoon" msgstr "" -#: src/SUMMARY.md:318 +#: src/SUMMARY.md:331 msgid "Bare Metal Rust Morning" msgstr "" -#: src/SUMMARY.md:319 src/exercises/bare-metal/solutions-afternoon.md:1 +#: src/SUMMARY.md:332 src/exercises/bare-metal/solutions-afternoon.md:1 msgid "Bare Metal Rust Afternoon" msgstr "" -#: src/SUMMARY.md:320 +#: src/SUMMARY.md:333 msgid "Concurrency Morning" msgstr "" -#: src/SUMMARY.md:321 +#: src/SUMMARY.md:334 msgid "Concurrency Afternoon" msgstr "" -#: src/welcome.md:3 -msgid "" -"[![Build workflow](https://img.shields.io/github/actions/workflow/status/" -"google/comprehensive-rust/build.yml?style=flat-square)](https://github.com/" -"google/comprehensive-rust/actions/workflows/build.yml?query=branch%3Amain)" -msgstr "" - -#: src/welcome.md:3 -msgid "Build workflow" -msgstr "" - -#: src/welcome.md:3 +#: src/index.md:3 msgid "" "[![Build workflow](https://img.shields.io/github/actions/workflow/status/" "google/comprehensive-rust/build.yml?style=flat-square)](https://github.com/" "google/comprehensive-rust/actions/workflows/build.yml?query=branch%3Amain) [!" "[GitHub contributors](https://img.shields.io/github/contributors/google/" "comprehensive-rust?style=flat-square)](https://github.com/google/" -"comprehensive-rust/graphs/contributors)" -msgstr "" - -#: src/welcome.md:4 -msgid "GitHub contributors" -msgstr "" - -#: src/welcome.md:4 -msgid "" -"[![GitHub contributors](https://img.shields.io/github/contributors/google/" -"comprehensive-rust?style=flat-square)](https://github.com/google/" "comprehensive-rust/graphs/contributors) [![GitHub stars](https://img.shields." "io/github/stars/google/comprehensive-rust?style=flat-square)](https://github." "com/google/comprehensive-rust/stargazers)" msgstr "" -#: src/welcome.md:5 -msgid "GitHub stars" -msgstr "" - -#: src/welcome.md:5 -msgid "" -"[![GitHub stars](https://img.shields.io/github/stars/google/comprehensive-" -"rust?style=flat-square)](https://github.com/google/comprehensive-rust/" -"stargazers)" -msgstr "" - -#: src/welcome.md:7 +#: src/index.md:7 msgid "" -"This is a three day Rust course developed by the Android team. The course " -"covers the full spectrum of Rust, from basic syntax to advanced topics like " -"generics and error handling. It also includes Android-specific content on " -"the last day." +"This is a free Rust course developed by the Android team at Google. The " +"course covers the full spectrum of Rust, from basic syntax to advanced " +"topics like generics and error handling." msgstr "" -#: src/welcome.md:11 +#: src/index.md:11 msgid "" "The goal of the course is to teach you Rust. We assume you don't know " "anything about Rust and hope to:" msgstr "" -#: src/welcome.md:14 +#: src/index.md:14 msgid "Give you a comprehensive understanding of the Rust syntax and language." msgstr "" -#: src/welcome.md:15 +#: src/index.md:15 msgid "Enable you to modify existing programs and write new programs in Rust." msgstr "" -#: src/welcome.md:16 +#: src/index.md:16 msgid "Show you common Rust idioms." msgstr "" -#: src/welcome.md:18 +#: src/index.md:18 +msgid "We call the first three course days Rust Fundamentals." +msgstr "" + +#: src/index.md:20 msgid "" -"The first three days show you the fundamentals of Rust. Following this, " -"you're invited to dive into one or more specialized topics:" +"Building on this, you're invited to dive into one or more specialized topics:" msgstr "" -#: src/welcome.md:21 +#: src/index.md:22 msgid "" "[Android](android.md): a half-day course on using Rust for Android platform " "development (AOSP). This includes interoperability with C, C++, and Java." msgstr "" -#: src/welcome.md:23 +#: src/index.md:24 msgid "" -"[Bare-metal](bare-metal.md): a full day class on using Rust for bare-metal " +"[Bare-metal](bare-metal.md): a whole-day class on using Rust for bare-metal " "(embedded) development. Both microcontrollers and application processors are " "covered." msgstr "" -#: src/welcome.md:26 +#: src/index.md:27 msgid "" -"[Concurrency](concurrency.md): a full day class on concurrency in Rust. We " +"[Concurrency](concurrency.md): a whole-day class on concurrency in Rust. We " "cover both classical concurrency (preemptively scheduling using threads and " "mutexes) and async/await concurrency (cooperative multitasking using " "futures)." msgstr "" -#: src/welcome.md:32 +#: src/index.md:33 msgid "Non-Goals" msgstr "" -#: src/welcome.md:34 +#: src/index.md:35 msgid "" "Rust is a large language and we won't be able to cover all of it in a few " "days. Some non-goals of this course are:" msgstr "" -#: src/welcome.md:37 +#: src/index.md:38 msgid "" -"Learn how to develop macros, please see [Chapter 19.5 in the Rust Book]" +"Learning how to develop macros: please see [Chapter 19.5 in the Rust Book]" "(https://doc.rust-lang.org/book/ch19-06-macros.html) and [Rust by Example]" "(https://doc.rust-lang.org/rust-by-example/macros.html) instead." msgstr "" -#: src/welcome.md:41 +#: src/index.md:42 msgid "Assumptions" msgstr "" -#: src/welcome.md:43 +#: src/index.md:44 msgid "" "The course assumes that you already know how to program. Rust is a " -"statically typed language and we will sometimes make comparisons with C and " +"statically-typed language and we will sometimes make comparisons with C and " "C++ to better explain or contrast the Rust approach." msgstr "" -#: src/welcome.md:47 +#: src/index.md:48 msgid "" -"If you know how to program in a dynamically typed language such as Python or " +"If you know how to program in a dynamically-typed language such as Python or " "JavaScript, then you will be able to follow along just fine too." msgstr "" -#: src/welcome.md:52 +#: src/index.md:53 msgid "" "This is an example of a _speaker note_. We will use these to add additional " "information to the slides. This could be key points which the instructor " @@ -1231,15 +1228,17 @@ msgid "The course is fast paced and covers a lot of ground:" msgstr "" #: src/running-the-course/course-structure.md:7 -msgid "Day 1: Basic Rust, ownership and the borrow checker." +msgid "Day 1: Basic Rust, syntax, control flow, creating and consuming values." msgstr "" #: src/running-the-course/course-structure.md:8 -msgid "Day 2: Compound data types, pattern matching, the standard library." +msgid "" +"Day 2: Memory management, ownership, compound data types, and the standard " +"library." msgstr "" #: src/running-the-course/course-structure.md:9 -msgid "Day 3: Traits and generics, error handling, testing, unsafe Rust." +msgid "Day 3: Generics, traits, error handling, testing, and unsafe Rust." msgstr "" #: src/running-the-course/course-structure.md:11 @@ -1252,11 +1251,16 @@ msgid "" "specialized topics:" msgstr "" +#: src/running-the-course/course-structure.md:16 +#, fuzzy +msgid "Rust in Android" +msgstr "Android" + #: src/running-the-course/course-structure.md:18 msgid "" -"The [Android Deep Dive](../android.md) is a half-day course on using Rust " -"for Android platform development. This includes interoperability with C, C+" -"+, and Java." +"The [Rust in Android](../android.md) deep dive is a half-day course on using " +"Rust for Android platform development. This includes interoperability with " +"C, C++, and Java." msgstr "" #: src/running-the-course/course-structure.md:22 @@ -1276,14 +1280,14 @@ msgid "" msgstr "" #: src/running-the-course/course-structure.md:34 -msgid "Bare-Metal" +msgid "Bare-Metal Rust" msgstr "" #: src/running-the-course/course-structure.md:36 msgid "" -"The [Bare-Metal Deep Dive](../bare-metal.md): a full day class on using Rust " -"for bare-metal (embedded) development. Both microcontrollers and application " -"processors are covered." +"The [Bare-Metal Rust](../bare-metal.md) deep dive is a full day class on " +"using Rust for bare-metal (embedded) development. Both microcontrollers and " +"application processors are covered." msgstr "" #: src/running-the-course/course-structure.md:40 @@ -1295,13 +1299,13 @@ msgid "" msgstr "" #: src/running-the-course/course-structure.md:45 -msgid "Concurrency" +msgid "Concurrency in Rust" msgstr "" #: src/running-the-course/course-structure.md:47 msgid "" -"The [Concurrency Deep Dive](../concurrency.md) is a full day class on " -"classical as well as `async`/`await` concurrency." +"The [Concurrency in Rust](../concurrency.md) deep dive is a full day class " +"on classical as well as `async`/`await` concurrency." msgstr "" #: src/running-the-course/course-structure.md:50 @@ -1376,8 +1380,9 @@ msgstr "" #: src/running-the-course/translations.md:6 msgid "" "[Brazilian Portuguese](https://google.github.io/comprehensive-rust/pt-BR/) " -"by [@rastringer](https://github.com/rastringer) and [@hugojacob](https://" -"github.com/hugojacob)." +"by [@rastringer](https://github.com/rastringer), [@hugojacob](https://github." +"com/hugojacob), [@joaovicmendes](https://github.com/joaovicmendes) and " +"[@henrif75](https://github.com/henrif75)." msgstr "" #: src/running-the-course/translations.md:7 @@ -1393,6 +1398,42 @@ msgid "" msgstr "" #: src/running-the-course/translations.md:11 +#, fuzzy +msgid "Incomplete Translations" +msgstr "Çeviriler" + +#: src/running-the-course/translations.md:13 +msgid "" +"There is a large number of in-progress translations. We link to the most " +"recently updated translations:" +msgstr "" + +#: src/running-the-course/translations.md:16 +msgid "" +"[Bengali](https://google.github.io/comprehensive-rust/bn/) by [@raselmandol]" +"(https://github.com/raselmandol)." +msgstr "" + +#: src/running-the-course/translations.md:17 +msgid "" +"[French](https://google.github.io/comprehensive-rust/fr/) by [@KookaS]" +"(https://github.com/KookaS) and [@vcaen](https://github.com/vcaen)." +msgstr "" + +#: src/running-the-course/translations.md:18 +msgid "" +"[German](https://google.github.io/comprehensive-rust/de/) by [@Throvn]" +"(https://github.com/Throvn) and [@ronaldfw](https://github.com/ronaldfw)." +msgstr "" + +#: src/running-the-course/translations.md:19 +msgid "" +"[Japanese](https://google.github.io/comprehensive-rust/ja/) by [@CoinEZ-JPN]" +"(https://github.com/CoinEZ) and [@momotaro1105](https://github.com/" +"momotaro1105)." +msgstr "" + +#: src/running-the-course/translations.md:21 msgid "" "If you want to help with this effort, please see [our instructions](https://" "github.com/google/comprehensive-rust/blob/main/TRANSLATIONS.md) for how to " @@ -1414,52 +1455,39 @@ msgid "Installation" msgstr "" #: src/cargo.md:10 -msgid "Rustup (Recommended)" +msgid "**Please follow the instructions on .**" msgstr "" #: src/cargo.md:12 msgid "" -"You can follow the instructions to install cargo and rust compiler, among " -"other standard ecosystem tools with the [rustup](https://rust-analyzer." -"github.io/) tool, which is maintained by the Rust Foundation." -msgstr "" - -#: src/cargo.md:14 -msgid "" -"Along with cargo and rustc, Rustup will install itself as a command line " -"utility that you can use to install/switch toolchains, setup cross " -"compilation, etc." +"This will give you the Cargo build tool (`cargo`) and the Rust compiler " +"(`rustc`). You will also get `rustup`, a command line utility that you can " +"use to install/switch toolchains, setup cross compilation, etc." msgstr "" #: src/cargo.md:16 -msgid "Package Managers" -msgstr "" - -#: src/cargo.md:18 -msgid "Debian" -msgstr "" - -#: src/cargo.md:20 msgid "" -"On Debian/Ubuntu, you can install Cargo, the Rust source and the [Rust " -"formatter](https://github.com/rust-lang/rustfmt) with" +"On Debian/Ubuntu, you can also install Cargo, the Rust source and the [Rust " +"formatter](https://github.com/rust-lang/rustfmt) via `apt`. However, this " +"gets you an outdated rust version and may lead to unexpected behavior. The " +"command would be:" msgstr "" -#: src/cargo.md:22 +#: src/cargo.md:18 msgid "" "```shell\n" -"$ sudo apt install cargo rust-src rustfmt\n" +"sudo apt install cargo rust-src rustfmt\n" "```" msgstr "" -#: src/cargo.md:26 +#: src/cargo.md:22 msgid "" -"This will allow \\[rust-analyzer\\]\\[1\\] to jump to the definitions. We " -"suggest using [VS Code](https://code.visualstudio.com/) to edit the code " -"(but any LSP compatible editor works)." +"We suggest using [VS Code](https://code.visualstudio.com/) to edit the code " +"(but any LSP compatible editor works with rust-analyzer[3](https://rust-" +"analyzer.github.io/))." msgstr "" -#: src/cargo.md:29 +#: src/cargo.md:24 msgid "" "Some folks also like to use the [JetBrains](https://www.jetbrains.com/" "clion/) family of IDEs, which do their own analysis but have their own " @@ -1486,9 +1514,9 @@ msgstr "" #: src/cargo/rust-ecosystem.md:8 msgid "" "`cargo`: the Rust dependency manager and build tool. Cargo knows how to " -"download dependencies hosted on and it will pass them to " -"`rustc` when building your project. Cargo also comes with a built-in test " -"runner which is used to execute unit tests." +"download dependencies, usually hosted on , and it will " +"pass them to `rustc` when building your project. Cargo also comes with a " +"built-in test runner which is used to execute unit tests." msgstr "" #: src/cargo/rust-ecosystem.md:13 @@ -1531,72 +1559,78 @@ msgstr "" #: src/cargo/rust-ecosystem.md:32 msgid "" +"Dependencies can also be resolved from alternative [registries](https://doc." +"rust-lang.org/cargo/reference/registries.html), git, folders, and more." +msgstr "" + +#: src/cargo/rust-ecosystem.md:34 +msgid "" "Rust also has [editions](https://doc.rust-lang.org/edition-guide/): the " "current edition is Rust 2021. Previous editions were Rust 2015 and Rust 2018." msgstr "" -#: src/cargo/rust-ecosystem.md:35 +#: src/cargo/rust-ecosystem.md:37 msgid "" "The editions are allowed to make backwards incompatible changes to the " "language." msgstr "" -#: src/cargo/rust-ecosystem.md:38 +#: src/cargo/rust-ecosystem.md:40 msgid "" "To prevent breaking code, editions are opt-in: you select the edition for " "your crate via the `Cargo.toml` file." msgstr "" -#: src/cargo/rust-ecosystem.md:41 +#: src/cargo/rust-ecosystem.md:43 msgid "" "To avoid splitting the ecosystem, Rust compilers can mix code written for " "different editions." msgstr "" -#: src/cargo/rust-ecosystem.md:44 +#: src/cargo/rust-ecosystem.md:46 msgid "" "Mention that it is quite rare to ever use the compiler directly not through " "`cargo` (most users never do)." msgstr "" -#: src/cargo/rust-ecosystem.md:46 +#: src/cargo/rust-ecosystem.md:48 msgid "" "It might be worth alluding that Cargo itself is an extremely powerful and " "comprehensive tool. It is capable of many advanced features including but " "not limited to: " msgstr "" -#: src/cargo/rust-ecosystem.md:47 +#: src/cargo/rust-ecosystem.md:49 msgid "Project/package structure" msgstr "" -#: src/cargo/rust-ecosystem.md:48 +#: src/cargo/rust-ecosystem.md:50 msgid "[workspaces](https://doc.rust-lang.org/cargo/reference/workspaces.html)" msgstr "" -#: src/cargo/rust-ecosystem.md:49 +#: src/cargo/rust-ecosystem.md:51 msgid "Dev Dependencies and Runtime Dependency management/caching" msgstr "" -#: src/cargo/rust-ecosystem.md:50 +#: src/cargo/rust-ecosystem.md:52 msgid "" "[build scripting](https://doc.rust-lang.org/cargo/reference/build-scripts." "html)" msgstr "" -#: src/cargo/rust-ecosystem.md:51 +#: src/cargo/rust-ecosystem.md:53 msgid "" "[global installation](https://doc.rust-lang.org/cargo/commands/cargo-install." "html)" msgstr "" -#: src/cargo/rust-ecosystem.md:52 +#: src/cargo/rust-ecosystem.md:54 msgid "" "It is also extensible with sub command plugins as well (such as [cargo " "clippy](https://github.com/rust-lang/rust-clippy))." msgstr "" -#: src/cargo/rust-ecosystem.md:53 +#: src/cargo/rust-ecosystem.md:55 msgid "" "Read more from the [official Cargo Book](https://doc.rust-lang.org/cargo/)" msgstr "" @@ -1684,20 +1718,26 @@ msgstr "" #: src/cargo/running-locally.md:15 msgid "" +"You can use any later version too since Rust maintains backwards " +"compatibility." +msgstr "" + +#: src/cargo/running-locally.md:17 +msgid "" "With this in place, follow these steps to build a Rust binary from one of " "the examples in this training:" msgstr "" -#: src/cargo/running-locally.md:18 +#: src/cargo/running-locally.md:20 msgid "Click the \"Copy to clipboard\" button on the example you want to copy." msgstr "" -#: src/cargo/running-locally.md:20 +#: src/cargo/running-locally.md:22 msgid "" "Use `cargo new exercise` to create a new `exercise/` directory for your code:" msgstr "" -#: src/cargo/running-locally.md:22 +#: src/cargo/running-locally.md:24 msgid "" "```shell\n" "$ cargo new exercise\n" @@ -1705,12 +1745,12 @@ msgid "" "```" msgstr "" -#: src/cargo/running-locally.md:27 +#: src/cargo/running-locally.md:29 msgid "" "Navigate into `exercise/` and use `cargo run` to build and run your binary:" msgstr "" -#: src/cargo/running-locally.md:29 +#: src/cargo/running-locally.md:31 msgid "" "```shell\n" "$ cd exercise\n" @@ -1722,13 +1762,13 @@ msgid "" "```" msgstr "" -#: src/cargo/running-locally.md:38 +#: src/cargo/running-locally.md:40 msgid "" "Replace the boiler-plate code in `src/main.rs` with your own code. For " "example, using the example on the previous page, make `src/main.rs` look like" msgstr "" -#: src/cargo/running-locally.md:41 +#: src/cargo/running-locally.md:43 msgid "" "```rust\n" "fn main() {\n" @@ -1737,11 +1777,11 @@ msgid "" "```" msgstr "" -#: src/cargo/running-locally.md:47 +#: src/cargo/running-locally.md:49 msgid "Use `cargo run` to build and run your updated binary:" msgstr "" -#: src/cargo/running-locally.md:49 +#: src/cargo/running-locally.md:51 msgid "" "```shell\n" "$ cargo run\n" @@ -1752,7 +1792,7 @@ msgid "" "```" msgstr "" -#: src/cargo/running-locally.md:57 +#: src/cargo/running-locally.md:59 msgid "" "Use `cargo check` to quickly check your project for errors, use `cargo " "build` to compile it without running it. You will find the output in `target/" @@ -1760,14 +1800,14 @@ msgid "" "optimized release build in `target/release/`." msgstr "" -#: src/cargo/running-locally.md:62 +#: src/cargo/running-locally.md:64 msgid "" "You can add dependencies for your project by editing `Cargo.toml`. When you " "run `cargo` commands, it will automatically download and compile missing " "dependencies for you." msgstr "" -#: src/cargo/running-locally.md:70 +#: src/cargo/running-locally.md:72 msgid "" "Try to encourage the class participants to install Cargo and use a local " "editor. It will make their life easier since they will have a normal " @@ -1780,7 +1820,7 @@ msgstr "" #: src/welcome-day-1.md:3 msgid "" -"This is the first day of Comprehensive Rust. We will cover a lot of ground " +"This is the first day of Rust Fundamentals. We will cover a lot of ground " "today:" msgstr "" @@ -1792,13 +1832,12 @@ msgstr "" #: src/welcome-day-1.md:9 msgid "" -"Memory management: stack vs heap, manual memory management, scope-based " -"memory management, and garbage collection." +"Control flow constructs: `if`, `if let`, `while`, `while let`, `break`, and " +"`continue`." msgstr "" #: src/welcome-day-1.md:12 -msgid "" -"Ownership: move semantics, copying and cloning, borrowing, and lifetimes." +msgid "Pattern matching: destructuring enums, structs, and arrays." msgstr "" #: src/welcome-day-1.md:16 @@ -1929,7 +1968,8 @@ msgid "High level of control." msgstr "" #: src/welcome-day-1/what-is-rust.md:25 -msgid "Can be scaled down to very constrained devices like mobile phones." +msgid "" +"Can be scaled down to very constrained devices such as microcontrollers." msgstr "" #: src/welcome-day-1/what-is-rust.md:26 @@ -1982,15 +2022,14 @@ msgstr "" #: src/hello-world.md:22 msgid "" "This slide tries to make the students comfortable with Rust code. They will " -"see a ton of it over the next four days so we start small with something " +"see a ton of it over the next three days so we start small with something " "familiar." msgstr "" #: src/hello-world.md:27 msgid "" "Rust is very much like other languages in the C/C++/Java tradition. It is " -"imperative (not functional) and it doesn't try to reinvent things unless " -"absolutely necessary." +"imperative and it doesn't try to reinvent things unless absolutely necessary." msgstr "" #: src/hello-world.md:31 @@ -2011,6 +2050,14 @@ msgid "" "html)." msgstr "" +#: src/hello-world.md:40 +msgid "" +"Rust is multi-paradigm. For example, it has powerful [object-oriented " +"programming features](https://doc.rust-lang.org/book/ch17-00-oop.html), and, " +"while it is not a functional language, it includes a range of [functional " +"concepts](https://doc.rust-lang.org/book/ch13-00-functional-features.html)." +msgstr "" + #: src/hello-world/small-example.md:3 msgid "Here is a small example program in Rust:" msgstr "" @@ -2071,6 +2118,12 @@ msgid "" "that the students become familiar with searching in the standard library." msgstr "" +#: src/hello-world/small-example.md:44 +msgid "" +"In a shell `rustup doc std::fmt` will open a browser on the local std::fmt " +"documentation" +msgstr "" + #: src/why-rust.md:3 msgid "Some unique selling points of Rust:" msgstr "" @@ -2191,18 +2244,20 @@ msgid "Array access is bounds checked." msgstr "" #: src/why-rust/runtime.md:6 -msgid "Integer overflow is defined." +msgid "Integer overflow is defined (panic or wrap-around)." msgstr "" #: src/why-rust/runtime.md:12 msgid "" -"Integer overflow is defined via a compile-time flag. The options are either " -"a panic (a controlled crash of the program) or wrap-around semantics. By " -"default, you get panics in debug mode (`cargo build`) and wrap-around in " -"release mode (`cargo build --release`)." +"Integer overflow is defined via the [`overflow-checks`](https://doc.rust-" +"lang.org/rustc/codegen-options/index.html#overflow-checks) compile-time " +"flag. If enabled, the program will panic (a controlled crash of the " +"program), otherwise you get wrap-around semantics. By default, you get " +"panics in debug mode (`cargo build`) and wrap-around in release mode (`cargo " +"build --release`)." msgstr "" -#: src/why-rust/runtime.md:17 +#: src/why-rust/runtime.md:18 msgid "" "Bounds checking cannot be disabled with a compiler flag. It can also not be " "disabled directly with the `unsafe` keyword. However, `unsafe` allows you to " @@ -2211,7 +2266,7 @@ msgid "" msgstr "" #: src/why-rust/modern.md:3 -msgid "Rust is built with all the experience gained in the last 40 years." +msgid "Rust is built with all the experience gained in the last decades." msgstr "" #: src/why-rust/modern.md:5 @@ -2364,7 +2419,7 @@ msgid "`i8`, `i16`, `i32`, `i64`, `i128`, `isize`" msgstr "" #: src/basic-syntax/scalar-types.md:5 -msgid "`-10`, `0`, `1_000`, `123i64`" +msgid "`-10`, `0`, `1_000`, `123_i64`" msgstr "" #: src/basic-syntax/scalar-types.md:6 @@ -2376,7 +2431,7 @@ msgid "`u8`, `u16`, `u32`, `u64`, `u128`, `usize`" msgstr "" #: src/basic-syntax/scalar-types.md:6 -msgid "`0`, `123`, `10u16`" +msgid "`0`, `123`, `10_u16`" msgstr "" #: src/basic-syntax/scalar-types.md:7 @@ -2388,7 +2443,7 @@ msgid "`f32`, `f64`" msgstr "" #: src/basic-syntax/scalar-types.md:7 -msgid "`3.14`, `-10.0e20`, `2f32`" +msgid "`3.14`, `-10.0e20`, `2_f32`" msgstr "" #: src/basic-syntax/scalar-types.md:8 @@ -2440,11 +2495,11 @@ msgid "`isize` and `usize` are the width of a pointer," msgstr "" #: src/basic-syntax/scalar-types.md:16 -msgid "`char` is 32 bit wide," +msgid "`char` is 32 bits wide," msgstr "" #: src/basic-syntax/scalar-types.md:17 -msgid "`bool` is 8 bit wide." +msgid "`bool` is 8 bits wide." msgstr "" #: src/basic-syntax/scalar-types.md:21 @@ -2482,6 +2537,13 @@ msgid "" "```" msgstr "" +#: src/basic-syntax/scalar-types.md:43 +msgid "" +"All underscores in numbers can be left out, they are for legibility only. So " +"`1_000` can be written as `1000` (or `10_00`), and `123_i64` can be written " +"as `123i64`." +msgstr "" + #: src/basic-syntax/compound-types.md:5 msgid "Arrays" msgstr "" @@ -2542,10 +2604,10 @@ msgstr "" #: src/basic-syntax/compound-types.md:34 msgid "" -"Arrays have elements of the same type, `T`, and length, `N`, which is a " -"compile-time constant. Note that the length of the array is _part of its " -"type_, which means that `[u8; 3]` and `[u8; 4]` are considered two different " -"types." +"A value of the array type `[T; N]` holds `N` (a compile-time constant) " +"elements of the same type `T`. Note that the length of the array is _part of " +"its type_, which means that `[u8; 3]` and `[u8; 4]` are considered two " +"different types." msgstr "" #: src/basic-syntax/compound-types.md:38 @@ -2684,66 +2746,69 @@ msgstr "" msgid "" "```rust,editable\n" "fn main() {\n" -" let a: [i32; 6] = [10, 20, 30, 40, 50, 60];\n" +" let mut a: [i32; 6] = [10, 20, 30, 40, 50, 60];\n" " println!(\"a: {a:?}\");\n" "\n" " let s: &[i32] = &a[2..4];\n" +"\n" " println!(\"s: {s:?}\");\n" "}\n" "```" msgstr "" -#: src/basic-syntax/slices.md:15 +#: src/basic-syntax/slices.md:16 msgid "Slices borrow data from the sliced type." msgstr "" -#: src/basic-syntax/slices.md:16 -msgid "Question: What happens if you modify `a[3]`?" +#: src/basic-syntax/slices.md:17 +msgid "Question: What happens if you modify `a[3]` right before printing `s`?" msgstr "" -#: src/basic-syntax/slices.md:20 +#: src/basic-syntax/slices.md:21 msgid "" "We create a slice by borrowing `a` and specifying the starting and ending " "indexes in brackets." msgstr "" -#: src/basic-syntax/slices.md:22 +#: src/basic-syntax/slices.md:23 msgid "" "If the slice starts at index 0, Rust’s range syntax allows us to drop the " "starting index, meaning that `&a[0..a.len()]` and `&a[..a.len()]` are " "identical." msgstr "" -#: src/basic-syntax/slices.md:24 +#: src/basic-syntax/slices.md:25 msgid "" "The same is true for the last index, so `&a[2..a.len()]` and `&a[2..]` are " "identical." msgstr "" -#: src/basic-syntax/slices.md:26 +#: src/basic-syntax/slices.md:27 msgid "" "To easily create a slice of the full array, we can therefore use `&a[..]`." msgstr "" -#: src/basic-syntax/slices.md:28 +#: src/basic-syntax/slices.md:29 msgid "" "`s` is a reference to a slice of `i32`s. Notice that the type of `s` " "(`&[i32]`) no longer mentions the array length. This allows us to perform " "computation on slices of different sizes." msgstr "" -#: src/basic-syntax/slices.md:30 +#: src/basic-syntax/slices.md:31 msgid "" "Slices always borrow from another object. In this example, `a` has to remain " "'alive' (in scope) for at least as long as our slice. " msgstr "" -#: src/basic-syntax/slices.md:32 +#: src/basic-syntax/slices.md:33 msgid "" "The question about modifying `a[3]` can spark an interesting discussion, but " -"the answer is that for memory safety reasons you cannot do it through `a` " -"after you created a slice, but you can read the data from both `a` and `s` " -"safely. More details will be explained in the borrow checker section." +"the answer is that for memory safety reasons you cannot do it through `a` at " +"this point in the execution, but you can read the data from both `a` and `s` " +"safely. It works before you created the slice, and again after the " +"`println`, when the slice is no longer used. More details will be explained " +"in the borrow checker section." msgstr "" #: src/basic-syntax/string-slices.md:1 @@ -2939,6 +3004,13 @@ msgid "" "be addressed here." msgstr "" +#: src/basic-syntax/rustdoc.md:33 +msgid "" +"Rustdoc comments can contain code snippets that we can run and test using " +"`cargo test`. We will discuss these tests in the [Testing section](../" +"testing/doc-tests.html)." +msgstr "" + #: src/basic-syntax/methods.md:3 msgid "" "Methods are functions associated with a type. The `self` argument of a " @@ -2979,7 +3051,7 @@ msgid "" msgstr "" #: src/basic-syntax/methods.md:34 -msgid "Add a `Rectangle::new` constructor and call this from `main`:" +msgid "Add a static method called `Rectangle::new` and call this from `main`:" msgstr "" #: src/basic-syntax/methods.md:36 @@ -2993,8 +3065,16 @@ msgstr "" #: src/basic-syntax/methods.md:42 msgid "" -"Add a `Rectangle::new_square(width: u32)` constructor to illustrate that " -"constructors can take arbitrary parameters." +"While _technically_, Rust does not have custom constructors, static methods " +"are commonly used to initialize structs (but don't have to). The actual " +"constructor, `Rectangle { width, height }`, could be called directly. See " +"the [Rustnomicon](https://doc.rust-lang.org/nomicon/constructors.html)." +msgstr "" + +#: src/basic-syntax/methods.md:45 +msgid "" +"Add a `Rectangle::square(width: u32)` constructor to illustrate that such " +"static methods can take arbitrary parameters." msgstr "" #: src/basic-syntax/functions-interlude.md:1 @@ -3091,14 +3171,12 @@ msgid "" "their state if you navigate away from the page." msgstr "" -#: src/exercises/day-1/morning.md:22 src/exercises/day-1/afternoon.md:11 -#: src/exercises/day-2/morning.md:11 src/exercises/day-2/afternoon.md:7 -#: src/exercises/day-3/morning.md:7 src/exercises/bare-metal/morning.md:7 -#: src/exercises/bare-metal/afternoon.md:7 +#: src/exercises/day-1/morning.md:22 src/exercises/day-2/morning.md:11 +#: src/exercises/day-3/morning.md:9 src/exercises/bare-metal/morning.md:7 #: src/exercises/concurrency/morning.md:12 -#: src/exercises/concurrency/afternoon.md:13 msgid "" -"After looking at the exercises, you can look at the \\[solutions\\] provided." +"After looking at the exercises, you can look at the [solutions](solutions-" +"morning.md) provided." msgstr "" #: src/exercises/day-1/implicit-conversions.md:3 @@ -3211,7 +3289,7 @@ msgid "" "fn main() {\n" " let array = [10, 20, 30];\n" " print!(\"Iterating over array:\");\n" -" for n in array {\n" +" for n in &array {\n" " print!(\" {n}\");\n" " }\n" " println!();\n" @@ -3305,1369 +3383,1500 @@ msgid "" "[Solution](solutions-morning.md#arrays-and-for-loops) section." msgstr "" -#: src/basic-syntax/variables.md:3 +#: src/exercises/day-1/for-loops.md:95 msgid "" -"Rust provides type safety via static typing. Variable bindings are immutable " -"by default:" +"The use of the reference `&array` within `for n in &array` is a subtle " +"preview of issues of ownership that will come later in the afternoon." msgstr "" -#: src/basic-syntax/variables.md:6 +#: src/exercises/day-1/for-loops.md:98 +msgid "Without the `&`..." +msgstr "" + +#: src/exercises/day-1/for-loops.md:99 msgid "" -"```rust,editable\n" -"fn main() {\n" -" let x: i32 = 10;\n" -" println!(\"x: {x}\");\n" -" // x = 20;\n" -" // println!(\"x: {x}\");\n" -"}\n" -"```" +"The loop would have been one that consumes the array. This is a change " +"[introduced in the 2021 Edition](https://doc.rust-lang.org/edition-guide/" +"rust-2021/IntoIterator-for-arrays.html)." msgstr "" -#: src/basic-syntax/variables.md:17 +#: src/exercises/day-1/for-loops.md:102 msgid "" -"Due to type inference the `i32` is optional. We will gradually show the " -"types less and less as the course progresses." +"An implicit array copy would have occured. Since `i32` is a copy type, then " +"`[i32; 3]` is also a copy type." msgstr "" -#: src/basic-syntax/variables.md:18 +#: src/control-flow.md:3 msgid "" -"Note that since `println!` is a macro, `x` is not moved, even using the " -"function like syntax of `println!(\"x: {}\", x)`" +"As we have seen, `if` is an expression in Rust. It is used to conditionally " +"evaluate one of two blocks, but the blocks can have a value which then " +"becomes the value of the `if` expression. Other control flow expressions " +"work similarly in Rust." msgstr "" -#: src/basic-syntax/type-inference.md:3 -msgid "Rust will look at how the variable is _used_ to determine the type:" +#: src/control-flow/blocks.md:3 +msgid "" +"A block in Rust contains a sequence of expressions. Each block has a value " +"and a type, which are those of the last expression of the block:" msgstr "" -#: src/basic-syntax/type-inference.md:5 +#: src/control-flow/blocks.md:7 msgid "" "```rust,editable\n" -"fn takes_u32(x: u32) {\n" -" println!(\"u32: {x}\");\n" -"}\n" -"\n" -"fn takes_i8(y: i8) {\n" -" println!(\"i8: {y}\");\n" -"}\n" -"\n" "fn main() {\n" -" let x = 10;\n" -" let y = 20;\n" -"\n" -" takes_u32(x);\n" -" takes_i8(y);\n" -" // takes_u32(y);\n" +" let x = {\n" +" let y = 10;\n" +" println!(\"y: {y}\");\n" +" let z = {\n" +" let w = {\n" +" 3 + 4\n" +" };\n" +" println!(\"w: {w}\");\n" +" y * w\n" +" };\n" +" println!(\"z: {z}\");\n" +" z - y\n" +" };\n" +" println!(\"x: {x}\");\n" "}\n" "```" msgstr "" -#: src/basic-syntax/type-inference.md:26 -msgid "" -"This slide demonstrates how the Rust compiler infers types based on " -"constraints given by variable declarations and usages." -msgstr "" - -#: src/basic-syntax/type-inference.md:28 +#: src/control-flow/blocks.md:26 msgid "" -"It is very important to emphasize that variables declared like this are not " -"of some sort of dynamic \"any type\" that can hold any data. The machine " -"code generated by such declaration is identical to the explicit declaration " -"of a type. The compiler does the job for us and helps us write more concise " -"code." +"If the last expression ends with `;`, then the resulting value and type is " +"`()`." msgstr "" -#: src/basic-syntax/type-inference.md:32 +#: src/control-flow/blocks.md:28 msgid "" -"The following code tells the compiler to copy into a certain generic " -"container without the code ever explicitly specifying the contained type, " -"using `_` as a placeholder:" +"The same rule is used for functions: the value of the function body is the " +"return value:" msgstr "" -#: src/basic-syntax/type-inference.md:34 +#: src/control-flow/blocks.md:31 msgid "" "```rust,editable\n" -"fn main() {\n" -" let mut v = Vec::new();\n" -" v.push((10, false));\n" -" v.push((20, true));\n" -" println!(\"v: {v:?}\");\n" +"fn double(x: i32) -> i32 {\n" +" x + x\n" +"}\n" "\n" -" let vv = v.iter().collect::>();\n" -" println!(\"vv: {vv:?}\");\n" +"fn main() {\n" +" println!(\"doubled: {}\", double(7));\n" "}\n" "```" msgstr "" -#: src/basic-syntax/type-inference.md:46 -msgid "" -"[`collect`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator." -"html#method.collect) relies on `FromIterator`, which [`HashSet`](https://doc." -"rust-lang.org/std/iter/trait.FromIterator.html) implements." +#: src/control-flow/blocks.md:43 src/enums.md:34 src/enums/sizes.md:28 +#: src/pattern-matching.md:25 src/pattern-matching/match-guards.md:22 +#: src/structs.md:31 src/methods.md:30 src/methods/example.md:46 +msgid "Key Points:" msgstr "" -#: src/basic-syntax/static-and-const.md:1 -msgid "Static and Constant Variables" +#: src/control-flow/blocks.md:44 +msgid "" +"The point of this slide is to show that blocks have a type and value in " +"Rust. " msgstr "" -#: src/basic-syntax/static-and-const.md:3 -msgid "Global state is managed with static and constant variables." +#: src/control-flow/blocks.md:45 +msgid "" +"You can show how the value of the block changes by changing the last line in " +"the block. For instance, adding/removing a semicolon or using a `return`." msgstr "" -#: src/basic-syntax/static-and-const.md:5 -msgid "`const`" +#: src/control-flow/if-expressions.md:1 +msgid "`if` expressions" msgstr "" -#: src/basic-syntax/static-and-const.md:7 -msgid "You can declare compile-time constants:" +#: src/control-flow/if-expressions.md:3 +msgid "" +"You use [`if` expressions](https://doc.rust-lang.org/reference/expressions/" +"if-expr.html#if-expressions) exactly like `if` statements in other languages:" msgstr "" -#: src/basic-syntax/static-and-const.md:9 +#: src/control-flow/if-expressions.md:7 msgid "" "```rust,editable\n" -"const DIGEST_SIZE: usize = 3;\n" -"const ZERO: Option = Some(42);\n" -"\n" -"fn compute_digest(text: &str) -> [u8; DIGEST_SIZE] {\n" -" let mut digest = [ZERO.unwrap_or(0); DIGEST_SIZE];\n" -" for (idx, &b) in text.as_bytes().iter().enumerate() {\n" -" digest[idx % DIGEST_SIZE] = digest[idx % DIGEST_SIZE]." -"wrapping_add(b);\n" +"fn main() {\n" +" let mut x = 10;\n" +" if x % 2 == 0 {\n" +" x = x / 2;\n" +" } else {\n" +" x = 3 * x + 1;\n" " }\n" -" digest\n" "}\n" -"\n" +"```" +msgstr "" + +#: src/control-flow/if-expressions.md:18 +msgid "" +"In addition, you can use `if` as an expression. The last expression of each " +"block becomes the value of the `if` expression:" +msgstr "" + +#: src/control-flow/if-expressions.md:22 +msgid "" +"```rust,editable\n" "fn main() {\n" -" let digest = compute_digest(\"Hello\");\n" -" println!(\"Digest: {digest:?}\");\n" +" let mut x = 10;\n" +" x = if x % 2 == 0 {\n" +" x / 2\n" +" } else {\n" +" 3 * x + 1\n" +" };\n" "}\n" "```" msgstr "" -#: src/basic-syntax/static-and-const.md:27 +#: src/control-flow/if-expressions.md:35 msgid "" -"According to the [Rust RFC Book](https://rust-lang.github.io/rfcs/0246-const-" -"vs-static.html) these are inlined upon use." +"Because `if` is an expression and must have a particular type, both of its " +"branch blocks must have the same type. Consider showing what happens if you " +"add `;` after `x / 2` in the second example." msgstr "" -#: src/basic-syntax/static-and-const.md:29 -msgid "`static`" +#: src/control-flow/for-expressions.md:1 +msgid "`for` loops" msgstr "" -#: src/basic-syntax/static-and-const.md:31 -msgid "You can also declare static variables:" +#: src/control-flow/for-expressions.md:3 +msgid "" +"The [`for` loop](https://doc.rust-lang.org/std/keyword.for.html) is closely " +"related to the [`while let` loop](while-let-expressions.md). It will " +"automatically call `into_iter()` on the expression and then iterate over it:" msgstr "" -#: src/basic-syntax/static-and-const.md:33 +#: src/control-flow/for-expressions.md:7 msgid "" "```rust,editable\n" -"static BANNER: &str = \"Welcome to RustOS 3.14\";\n" -"\n" "fn main() {\n" -" println!(\"{BANNER}\");\n" +" let v = vec![10, 20, 30];\n" +"\n" +" for x in v {\n" +" println!(\"x: {x}\");\n" +" }\n" +" \n" +" for i in (0..10).step_by(2) {\n" +" println!(\"i: {i}\");\n" +" }\n" "}\n" "```" msgstr "" -#: src/basic-syntax/static-and-const.md:41 -msgid "" -"As noted in the [Rust RFC Book](https://rust-lang.github.io/rfcs/0246-const-" -"vs-static.html), these are not inlined upon use and have an actual " -"associated memory location. This is useful for unsafe and embedded code, " -"and the variable lives through the entirety of the program execution." +#: src/control-flow/for-expressions.md:21 +msgid "You can use `break` and `continue` here as usual." msgstr "" -#: src/basic-syntax/static-and-const.md:44 -msgid "" -"We will look at mutating static data in the [chapter on Unsafe Rust](../" -"unsafe.md)." +#: src/control-flow/for-expressions.md:25 +msgid "Index iteration is not a special syntax in Rust for just that case." msgstr "" -#: src/basic-syntax/static-and-const.md:48 -msgid "Mention that `const` behaves semantically similar to C++'s `constexpr`." +#: src/control-flow/for-expressions.md:26 +msgid "`(0..10)` is a range that implements an `Iterator` trait. " msgstr "" -#: src/basic-syntax/static-and-const.md:49 +#: src/control-flow/for-expressions.md:27 msgid "" -"`static`, on the other hand, is much more similar to a `const` or mutable " -"global variable in C++." +"`step_by` is a method that returns another `Iterator` that skips every other " +"element. " msgstr "" -#: src/basic-syntax/static-and-const.md:50 +#: src/control-flow/for-expressions.md:28 msgid "" -"It isn't super common that one would need a runtime evaluated constant, but " -"it is helpful and safer than using a static." +"Modify the elements in the vector and explain the compiler errors. Change " +"vector `v` to be mutable and the for loop to `for x in v.iter_mut()`." msgstr "" -#: src/basic-syntax/scopes-shadowing.md:3 -msgid "" -"You can shadow variables, both those from outer scopes and variables from " -"the same scope:" +#: src/control-flow/while-expressions.md:1 +msgid "`while` loops" msgstr "" -#: src/basic-syntax/scopes-shadowing.md:6 +#: src/control-flow/while-expressions.md:3 +msgid "" +"The [`while` keyword](https://doc.rust-lang.org/reference/expressions/loop-" +"expr.html#predicate-loops) works very similar to other languages:" +msgstr "" + +#: src/control-flow/while-expressions.md:6 msgid "" "```rust,editable\n" "fn main() {\n" -" let a = 10;\n" -" println!(\"before: {a}\");\n" -"\n" -" {\n" -" let a = \"hello\";\n" -" println!(\"inner scope: {a}\");\n" -"\n" -" let a = true;\n" -" println!(\"shadowed in inner scope: {a}\");\n" +" let mut x = 10;\n" +" while x != 1 {\n" +" x = if x % 2 == 0 {\n" +" x / 2\n" +" } else {\n" +" 3 * x + 1\n" +" };\n" " }\n" -"\n" -" println!(\"after: {a}\");\n" +" println!(\"Final x: {x}\");\n" "}\n" "```" msgstr "" -#: src/basic-syntax/scopes-shadowing.md:25 -msgid "" -"Definition: Shadowing is different from mutation, because after shadowing " -"both variable's memory locations exist at the same time. Both are available " -"under the same name, depending where you use it in the code. " +#: src/control-flow/break-continue.md:1 +msgid "`break` and `continue`" msgstr "" -#: src/basic-syntax/scopes-shadowing.md:26 -msgid "A shadowing variable can have a different type. " +#: src/control-flow/break-continue.md:3 +msgid "" +"If you want to exit a loop early, use [`break`](https://doc.rust-lang.org/" +"reference/expressions/loop-expr.html#break-expressions)," msgstr "" -#: src/basic-syntax/scopes-shadowing.md:27 +#: src/control-flow/break-continue.md:4 msgid "" -"Shadowing looks obscure at first, but is convenient for holding on to values " -"after `.unwrap()`." +"If you want to immediately start the next iteration use [`continue`](https://" +"doc.rust-lang.org/reference/expressions/loop-expr.html#continue-expressions)." msgstr "" -#: src/basic-syntax/scopes-shadowing.md:28 +#: src/control-flow/break-continue.md:7 msgid "" -"The following code demonstrates why the compiler can't simply reuse memory " -"locations when shadowing an immutable variable in a scope, even if the type " -"does not change." +"Both `continue` and `break` can optionally take a label argument which is " +"used to break out of nested loops:" msgstr "" -#: src/basic-syntax/scopes-shadowing.md:30 +#: src/control-flow/break-continue.md:10 msgid "" "```rust,editable\n" "fn main() {\n" -" let a = 1;\n" -" let b = &a;\n" -" let a = a + 1;\n" -" println!(\"{a} {b}\");\n" +" let v = vec![10, 20, 30];\n" +" let mut iter = v.into_iter();\n" +" 'outer: while let Some(x) = iter.next() {\n" +" println!(\"x: {x}\");\n" +" let mut i = 0;\n" +" while i < x {\n" +" println!(\"x: {x}, i: {i}\");\n" +" i += 1;\n" +" if i == 3 {\n" +" break 'outer;\n" +" }\n" +" }\n" +" }\n" "}\n" "```" msgstr "" -#: src/memory-management.md:3 -msgid "Traditionally, languages have fallen into two broad categories:" -msgstr "" - -#: src/memory-management.md:5 -msgid "Full control via manual memory management: C, C++, Pascal, ..." -msgstr "" - -#: src/memory-management.md:6 +#: src/control-flow/break-continue.md:28 msgid "" -"Full safety via automatic memory management at runtime: Java, Python, Go, " -"Haskell, ..." +"In this case we break the outer loop after 3 iterations of the inner loop." msgstr "" -#: src/memory-management.md:8 -msgid "Rust offers a new mix:" +#: src/control-flow/loop-expressions.md:1 +msgid "`loop` expressions" msgstr "" -#: src/memory-management.md:10 +#: src/control-flow/loop-expressions.md:3 msgid "" -"Full control _and_ safety via compile time enforcement of correct memory " -"management." -msgstr "" - -#: src/memory-management.md:13 -msgid "It does this with an explicit ownership concept." +"Finally, there is a [`loop` keyword](https://doc.rust-lang.org/reference/" +"expressions/loop-expr.html#infinite-loops) which creates an endless loop." msgstr "" -#: src/memory-management.md:15 -msgid "First, let's refresh how memory management works." +#: src/control-flow/loop-expressions.md:6 +msgid "Here you must either `break` or `return` to stop the loop:" msgstr "" -#: src/memory-management/stack-vs-heap.md:1 -msgid "The Stack vs The Heap" +#: src/control-flow/loop-expressions.md:8 +msgid "" +"```rust,editable\n" +"fn main() {\n" +" let mut x = 10;\n" +" loop {\n" +" x = if x % 2 == 0 {\n" +" x / 2\n" +" } else {\n" +" 3 * x + 1\n" +" };\n" +" if x == 1 {\n" +" break;\n" +" }\n" +" }\n" +" println!(\"Final x: {x}\");\n" +"}\n" +"```" msgstr "" -#: src/memory-management/stack-vs-heap.md:3 -msgid "Stack: Continuous area of memory for local variables." +#: src/control-flow/loop-expressions.md:27 +msgid "Break the `loop` with a value (e.g. `break 8`) and print it out." msgstr "" -#: src/memory-management/stack-vs-heap.md:4 -msgid "Values have fixed sizes known at compile time." +#: src/control-flow/loop-expressions.md:28 +msgid "" +"Note that `loop` is the only looping construct which returns a non-trivial " +"value. This is because it's guaranteed to be entered at least once (unlike " +"`while` and `for` loops)." msgstr "" -#: src/memory-management/stack-vs-heap.md:5 -msgid "Extremely fast: just move a stack pointer." +#: src/basic-syntax/variables.md:3 +msgid "" +"Rust provides type safety via static typing. Variable bindings are immutable " +"by default:" msgstr "" -#: src/memory-management/stack-vs-heap.md:6 -msgid "Easy to manage: follows function calls." +#: src/basic-syntax/variables.md:6 +msgid "" +"```rust,editable\n" +"fn main() {\n" +" let x: i32 = 10;\n" +" println!(\"x: {x}\");\n" +" // x = 20;\n" +" // println!(\"x: {x}\");\n" +"}\n" +"```" msgstr "" -#: src/memory-management/stack-vs-heap.md:7 -msgid "Great memory locality." +#: src/basic-syntax/variables.md:17 +msgid "" +"Due to type inference the `i32` is optional. We will gradually show the " +"types less and less as the course progresses." msgstr "" -#: src/memory-management/stack-vs-heap.md:9 -msgid "Heap: Storage of values outside of function calls." +#: src/basic-syntax/type-inference.md:3 +msgid "Rust will look at how the variable is _used_ to determine the type:" msgstr "" -#: src/memory-management/stack-vs-heap.md:10 -msgid "Values have dynamic sizes determined at runtime." +#: src/basic-syntax/type-inference.md:5 +msgid "" +"```rust,editable\n" +"fn takes_u32(x: u32) {\n" +" println!(\"u32: {x}\");\n" +"}\n" +"\n" +"fn takes_i8(y: i8) {\n" +" println!(\"i8: {y}\");\n" +"}\n" +"\n" +"fn main() {\n" +" let x = 10;\n" +" let y = 20;\n" +"\n" +" takes_u32(x);\n" +" takes_i8(y);\n" +" // takes_u32(y);\n" +"}\n" +"```" msgstr "" -#: src/memory-management/stack-vs-heap.md:11 -msgid "Slightly slower than the stack: some book-keeping needed." +#: src/basic-syntax/type-inference.md:26 +msgid "" +"This slide demonstrates how the Rust compiler infers types based on " +"constraints given by variable declarations and usages." msgstr "" -#: src/memory-management/stack-vs-heap.md:12 -msgid "No guarantee of memory locality." +#: src/basic-syntax/type-inference.md:28 +msgid "" +"It is very important to emphasize that variables declared like this are not " +"of some sort of dynamic \"any type\" that can hold any data. The machine " +"code generated by such declaration is identical to the explicit declaration " +"of a type. The compiler does the job for us and helps us write more concise " +"code." msgstr "" -#: src/memory-management/stack.md:3 +#: src/basic-syntax/type-inference.md:32 msgid "" -"Creating a `String` puts fixed-sized data on the stack and dynamically sized " -"data on the heap:" +"The following code tells the compiler to copy into a certain generic " +"container without the code ever explicitly specifying the contained type, " +"using `_` as a placeholder:" msgstr "" -#: src/memory-management/stack.md:6 +#: src/basic-syntax/type-inference.md:34 msgid "" "```rust,editable\n" "fn main() {\n" -" let s1 = String::from(\"Hello\");\n" +" let mut v = Vec::new();\n" +" v.push((10, false));\n" +" v.push((20, true));\n" +" println!(\"v: {v:?}\");\n" +"\n" +" let vv = v.iter().collect::>();\n" +" println!(\"vv: {vv:?}\");\n" "}\n" "```" msgstr "" -#: src/memory-management/stack.md:12 +#: src/basic-syntax/type-inference.md:46 msgid "" -"```bob\n" -" Stack Heap\n" -".- - - - - - - - - - - - - -. .- - - - - - - - - - - - - - - -.\n" -": : : :\n" -": s1 : : :\n" -": +-----------+-------+ : : +----+----+----+----+----+ :\n" -": | ptr | o---+---+-----+-->| H | e | l | l | o | :\n" -": | len | 5 | : : +----+----+----+----+----+ :\n" -": | capacity | 5 | : : :\n" -": +-----------+-------+ : : :\n" -": : `- - - - - - - - - - - - - - - -'\n" -"`- - - - - - - - - - - - - -'\n" -"```" +"[`collect`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator." +"html#method.collect) relies on [`FromIterator`](https://doc.rust-lang.org/" +"std/iter/trait.FromIterator.html), which [`HashSet`](https://doc.rust-lang." +"org/std/collections/struct.HashSet.html#impl-FromIterator%3CT%3E-for-" +"HashSet%3CT,+S%3E) implements." msgstr "" -#: src/memory-management/stack.md:28 -msgid "" -"Mention that a `String` is backed by a `Vec`, so it has a capacity and " -"length and can grow if mutable via reallocation on the heap." +#: src/basic-syntax/static-and-const.md:1 +msgid "Static and Constant Variables" msgstr "" -#: src/memory-management/stack.md:30 +#: src/basic-syntax/static-and-const.md:3 msgid "" -"If students ask about it, you can mention that the underlying memory is heap " -"allocated using the [System Allocator](https://doc.rust-lang.org/std/alloc/" -"struct.System.html) and custom allocators can be implemented using the " -"[Allocator API](https://doc.rust-lang.org/std/alloc/index.html)" +"Static and constant variables are two different ways to create globally-" +"scoped values that cannot be moved or reallocated during the execution of " +"the program. " msgstr "" -#: src/memory-management/stack.md:32 +#: src/basic-syntax/static-and-const.md:6 +msgid "`const`" +msgstr "" + +#: src/basic-syntax/static-and-const.md:8 msgid "" -"We can inspect the memory layout with `unsafe` code. However, you should " -"point out that this is rightfully unsafe!" +"Constant variables are evaluated at compile time and their values are " +"inlined wherever they are used:" msgstr "" -#: src/memory-management/stack.md:34 +#: src/basic-syntax/static-and-const.md:11 msgid "" "```rust,editable\n" -"fn main() {\n" -" let mut s1 = String::from(\"Hello\");\n" -" s1.push(' ');\n" -" s1.push_str(\"world\");\n" -" // DON'T DO THIS AT HOME! For educational purposes only.\n" -" // String provides no guarantees about its layout, so this could lead " -"to\n" -" // undefined behavior.\n" -" unsafe {\n" -" let (capacity, ptr, len): (usize, usize, usize) = std::mem::" -"transmute(s1);\n" -" println!(\"ptr = {ptr:#x}, len = {len}, capacity = {capacity}\");\n" +"const DIGEST_SIZE: usize = 3;\n" +"const ZERO: Option = Some(42);\n" +"\n" +"fn compute_digest(text: &str) -> [u8; DIGEST_SIZE] {\n" +" let mut digest = [ZERO.unwrap_or(0); DIGEST_SIZE];\n" +" for (idx, &b) in text.as_bytes().iter().enumerate() {\n" +" digest[idx % DIGEST_SIZE] = digest[idx % DIGEST_SIZE]." +"wrapping_add(b);\n" " }\n" +" digest\n" +"}\n" +"\n" +"fn main() {\n" +" let digest = compute_digest(\"Hello\");\n" +" println!(\"Digest: {digest:?}\");\n" "}\n" "```" msgstr "" -#: src/memory-management/manual.md:3 -msgid "You allocate and deallocate heap memory yourself." +#: src/basic-syntax/static-and-const.md:29 +msgid "" +"According to the [Rust RFC Book](https://rust-lang.github.io/rfcs/0246-const-" +"vs-static.html) these are inlined upon use." msgstr "" -#: src/memory-management/manual.md:5 +#: src/basic-syntax/static-and-const.md:31 msgid "" -"If not done with care, this can lead to crashes, bugs, security " -"vulnerabilities, and memory leaks." +"Only functions marked `const` can be called at compile time to generate " +"`const` values. `const` functions can however be called at runtime." msgstr "" -#: src/memory-management/manual.md:7 -msgid "C Example" +#: src/basic-syntax/static-and-const.md:33 +msgid "`static`" msgstr "" -#: src/memory-management/manual.md:9 -msgid "You must call `free` on every pointer you allocate with `malloc`:" +#: src/basic-syntax/static-and-const.md:35 +msgid "" +"Static variables will live during the whole execution of the program, and " +"therefore will not move:" msgstr "" -#: src/memory-management/manual.md:11 +#: src/basic-syntax/static-and-const.md:37 msgid "" -"```c\n" -"void foo(size_t n) {\n" -" int* int_array = (int*)malloc(n * sizeof(int));\n" -" //\n" -" // ... lots of code\n" -" //\n" -" free(int_array);\n" +"```rust,editable\n" +"static BANNER: &str = \"Welcome to RustOS 3.14\";\n" +"\n" +"fn main() {\n" +" println!(\"{BANNER}\");\n" "}\n" "```" msgstr "" -#: src/memory-management/manual.md:21 +#: src/basic-syntax/static-and-const.md:45 msgid "" -"Memory is leaked if the function returns early between `malloc` and `free`: " -"the pointer is lost and we cannot deallocate the memory." +"As noted in the [Rust RFC Book](https://rust-lang.github.io/rfcs/0246-const-" +"vs-static.html), these are not inlined upon use and have an actual " +"associated memory location. This is useful for unsafe and embedded code, " +"and the variable lives through the entirety of the program execution. When a " +"globally-scoped value does not have a reason to need object identity, " +"`const` is generally preferred." msgstr "" -#: src/memory-management/scope-based.md:3 +#: src/basic-syntax/static-and-const.md:49 msgid "" -"Constructors and destructors let you hook into the lifetime of an object." +"Because `static` variables are accessible from any thread, they must be " +"`Sync`. Interior mutability is possible through a [`Mutex`](https://doc.rust-" +"lang.org/std/sync/struct.Mutex.html), atomic or similar. It is also possible " +"to have mutable statics, but they require manual synchronisation so any " +"access to them requires `unsafe` code. We will look at [mutable statics](../" +"unsafe/mutable-static-variables.md) in the chapter on Unsafe Rust." msgstr "" -#: src/memory-management/scope-based.md:5 -msgid "" -"By wrapping a pointer in an object, you can free memory when the object is " -"destroyed. The compiler guarantees that this happens, even if an exception " -"is raised." +#: src/basic-syntax/static-and-const.md:57 +msgid "Mention that `const` behaves semantically similar to C++'s `constexpr`." msgstr "" -#: src/memory-management/scope-based.md:9 +#: src/basic-syntax/static-and-const.md:58 msgid "" -"This is often called _resource acquisition is initialization_ (RAII) and " -"gives you smart pointers." +"`static`, on the other hand, is much more similar to a `const` or mutable " +"global variable in C++." msgstr "" -#: src/memory-management/scope-based.md:12 -msgid "C++ Example" +#: src/basic-syntax/static-and-const.md:59 +msgid "" +"`static` provides object identity: an address in memory and state as " +"required by types with interior mutability such as `Mutex`." msgstr "" -#: src/memory-management/scope-based.md:14 +#: src/basic-syntax/static-and-const.md:60 msgid "" -"```c++\n" -"void say_hello(std::unique_ptr person) {\n" -" std::cout << \"Hello \" << person->name << std::endl;\n" -"}\n" -"```" +"It isn't super common that one would need a runtime evaluated constant, but " +"it is helpful and safer than using a static." msgstr "" -#: src/memory-management/scope-based.md:20 -msgid "" -"The `std::unique_ptr` object is allocated on the stack, and points to memory " -"allocated on the heap." +#: src/basic-syntax/static-and-const.md:61 +msgid "`thread_local` data can be created with the macro `std::thread_local`." msgstr "" -#: src/memory-management/scope-based.md:22 -msgid "At the end of `say_hello`, the `std::unique_ptr` destructor will run." +#: src/basic-syntax/static-and-const.md:63 +msgid "Properties table:" msgstr "" -#: src/memory-management/scope-based.md:23 -msgid "The destructor frees the `Person` object it points to." +#: src/basic-syntax/static-and-const.md:65 +msgid "Property" msgstr "" -#: src/memory-management/scope-based.md:25 -msgid "" -"Special move constructors are used when passing ownership to a function:" +#: src/basic-syntax/static-and-const.md:65 +msgid "Static" msgstr "" -#: src/memory-management/scope-based.md:27 -msgid "" -"```c++\n" -"std::unique_ptr person = find_person(\"Carla\");\n" -"say_hello(std::move(person));\n" -"```" +#: src/basic-syntax/static-and-const.md:65 +msgid "Constant" msgstr "" -#: src/memory-management/garbage-collection.md:1 -msgid "Automatic Memory Management" +#: src/basic-syntax/static-and-const.md:67 +msgid "Has an address in memory" msgstr "" -#: src/memory-management/garbage-collection.md:3 -msgid "" -"An alternative to manual and scope-based memory management is automatic " -"memory management:" +#: src/basic-syntax/static-and-const.md:67 +#: src/basic-syntax/static-and-const.md:68 +#: src/basic-syntax/static-and-const.md:70 +#: src/basic-syntax/static-and-const.md:71 +msgid "Yes" msgstr "" -#: src/memory-management/garbage-collection.md:6 -msgid "The programmer never allocates or deallocates memory explicitly." +#: src/basic-syntax/static-and-const.md:67 +msgid "No (inlined)" msgstr "" -#: src/memory-management/garbage-collection.md:7 -msgid "" -"A garbage collector finds unused memory and deallocates it for the " -"programmer." +#: src/basic-syntax/static-and-const.md:68 +msgid "Lives for the entire duration of the program" msgstr "" -#: src/memory-management/garbage-collection.md:9 -msgid "Java Example" +#: src/basic-syntax/static-and-const.md:68 +#: src/basic-syntax/static-and-const.md:69 +#: src/basic-syntax/static-and-const.md:71 +msgid "No" msgstr "" -#: src/memory-management/garbage-collection.md:11 -msgid "The `person` object is not deallocated after `sayHello` returns:" +#: src/basic-syntax/static-and-const.md:69 +msgid "Can be mutable" msgstr "" -#: src/memory-management/garbage-collection.md:13 -msgid "" -"```java\n" -"void sayHello(Person person) {\n" -" System.out.println(\"Hello \" + person.getName());\n" -"}\n" -"```" +#: src/basic-syntax/static-and-const.md:69 +msgid "Yes (unsafe)" msgstr "" -#: src/memory-management/rust.md:1 -msgid "Memory Management in Rust" +#: src/basic-syntax/static-and-const.md:70 +msgid "Evaluated at compile time" msgstr "" -#: src/memory-management/rust.md:3 -msgid "Memory management in Rust is a mix:" +#: src/basic-syntax/static-and-const.md:70 +msgid "Yes (initialised at compile time)" msgstr "" -#: src/memory-management/rust.md:5 -msgid "Safe and correct like Java, but without a garbage collector." +#: src/basic-syntax/static-and-const.md:71 +msgid "Inlined wherever it is used" msgstr "" -#: src/memory-management/rust.md:6 +#: src/basic-syntax/scopes-shadowing.md:3 msgid "" -"Depending on which abstraction (or combination of abstractions) you choose, " -"can be a single unique pointer, reference counted, or atomically reference " -"counted." +"You can shadow variables, both those from outer scopes and variables from " +"the same scope:" msgstr "" -#: src/memory-management/rust.md:7 -msgid "Scope-based like C++, but the compiler enforces full adherence." +#: src/basic-syntax/scopes-shadowing.md:6 +msgid "" +"```rust,editable\n" +"fn main() {\n" +" let a = 10;\n" +" println!(\"before: {a}\");\n" +"\n" +" {\n" +" let a = \"hello\";\n" +" println!(\"inner scope: {a}\");\n" +"\n" +" let a = true;\n" +" println!(\"shadowed in inner scope: {a}\");\n" +" }\n" +"\n" +" println!(\"after: {a}\");\n" +"}\n" +"```" msgstr "" -#: src/memory-management/rust.md:8 +#: src/basic-syntax/scopes-shadowing.md:25 msgid "" -"A Rust user can choose the right abstraction for the situation, some even " -"have no cost at runtime like C." +"Definition: Shadowing is different from mutation, because after shadowing " +"both variable's memory locations exist at the same time. Both are available " +"under the same name, depending where you use it in the code. " msgstr "" -#: src/memory-management/rust.md:10 -msgid "It achieves this by modeling _ownership_ explicitly." +#: src/basic-syntax/scopes-shadowing.md:26 +msgid "A shadowing variable can have a different type. " msgstr "" -#: src/memory-management/rust.md:14 +#: src/basic-syntax/scopes-shadowing.md:27 msgid "" -"If asked how at this point, you can mention that in Rust this is usually " -"handled by RAII wrapper types such as [Box](https://doc.rust-lang.org/std/" -"boxed/struct.Box.html), [Vec](https://doc.rust-lang.org/std/vec/struct.Vec." -"html), [Rc](https://doc.rust-lang.org/std/rc/struct.Rc.html), or [Arc]" -"(https://doc.rust-lang.org/std/sync/struct.Arc.html). These encapsulate " -"ownership and memory allocation via various means, and prevent the potential " -"errors in C." +"Shadowing looks obscure at first, but is convenient for holding on to values " +"after `.unwrap()`." msgstr "" -#: src/memory-management/rust.md:16 +#: src/basic-syntax/scopes-shadowing.md:28 msgid "" -"You may be asked about destructors here, the [Drop](https://doc.rust-lang." -"org/std/ops/trait.Drop.html) trait is the Rust equivalent." +"The following code demonstrates why the compiler can't simply reuse memory " +"locations when shadowing an immutable variable in a scope, even if the type " +"does not change." msgstr "" -#: src/memory-management/comparison.md:3 -msgid "Here is a rough comparison of the memory management techniques." +#: src/basic-syntax/scopes-shadowing.md:30 +msgid "" +"```rust,editable\n" +"fn main() {\n" +" let a = 1;\n" +" let b = &a;\n" +" let a = a + 1;\n" +" println!(\"{a} {b}\");\n" +"}\n" +"```" msgstr "" -#: src/memory-management/comparison.md:5 -msgid "Pros of Different Memory Management Techniques" +#: src/enums.md:3 +msgid "" +"The `enum` keyword allows the creation of a type which has a few different " +"variants:" msgstr "" -#: src/memory-management/comparison.md:7 src/memory-management/comparison.md:22 -msgid "Manual like C:" +#: src/enums.md:6 +msgid "" +"```rust,editable\n" +"fn generate_random_number() -> i32 {\n" +" // Implementation based on https://xkcd.com/221/\n" +" 4 // Chosen by fair dice roll. Guaranteed to be random.\n" +"}\n" +"\n" +"#[derive(Debug)]\n" +"enum CoinFlip {\n" +" Heads,\n" +" Tails,\n" +"}\n" +"\n" +"fn flip_coin() -> CoinFlip {\n" +" let random_number = generate_random_number();\n" +" if random_number % 2 == 0 {\n" +" return CoinFlip::Heads;\n" +" } else {\n" +" return CoinFlip::Tails;\n" +" }\n" +"}\n" +"\n" +"fn main() {\n" +" println!(\"You got: {:?}\", flip_coin());\n" +"}\n" +"```" msgstr "" -#: src/memory-management/comparison.md:8 src/memory-management/comparison.md:14 -#: src/memory-management/comparison.md:17 -msgid "No runtime overhead." +#: src/enums.md:36 +msgid "Enumerations allow you to collect a set of values under one type" msgstr "" -#: src/memory-management/comparison.md:9 src/memory-management/comparison.md:26 -msgid "Automatic like Java:" +#: src/enums.md:37 +msgid "" +"This page offers an enum type `CoinFlip` with two variants `Heads` and " +"`Tails`. You might note the namespace when using variants." msgstr "" -#: src/memory-management/comparison.md:10 -msgid "Fully automatic." +#: src/enums.md:38 +msgid "This might be a good time to compare Structs and Enums:" msgstr "" -#: src/memory-management/comparison.md:11 -#: src/memory-management/comparison.md:18 -msgid "Safe and correct." +#: src/enums.md:39 +msgid "" +"In both, you can have a simple version without fields (unit struct) or one " +"with different types of fields (variant payloads). " msgstr "" -#: src/memory-management/comparison.md:12 -#: src/memory-management/comparison.md:29 -msgid "Scope-based like C++:" +#: src/enums.md:40 +msgid "In both, associated functions are defined within an `impl` block." msgstr "" -#: src/memory-management/comparison.md:13 -msgid "Partially automatic." +#: src/enums.md:41 +msgid "" +"You could even implement the different variants of an enum with separate " +"structs but then they wouldn’t be the same type as they would if they were " +"all defined in an enum. " msgstr "" -#: src/memory-management/comparison.md:15 -msgid "Compiler-enforced scope-based like Rust:" -msgstr "" - -#: src/memory-management/comparison.md:16 -msgid "Enforced by compiler." -msgstr "" - -#: src/memory-management/comparison.md:20 -msgid "Cons of Different Memory Management Techniques" +#: src/enums/variant-payloads.md:3 +msgid "" +"You can define richer enums where the variants carry data. You can then use " +"the `match` statement to extract the data from each variant:" msgstr "" -#: src/memory-management/comparison.md:23 -msgid "Use-after-free." +#: src/enums/variant-payloads.md:6 +msgid "" +"```rust,editable\n" +"enum WebEvent {\n" +" PageLoad, // Variant without payload\n" +" KeyPress(char), // Tuple struct variant\n" +" Click { x: i64, y: i64 }, // Full struct variant\n" +"}\n" +"\n" +"#[rustfmt::skip]\n" +"fn inspect(event: WebEvent) {\n" +" match event {\n" +" WebEvent::PageLoad => println!(\"page loaded\"),\n" +" WebEvent::KeyPress(c) => println!(\"pressed '{c}'\"),\n" +" WebEvent::Click { x, y } => println!(\"clicked at x={x}, y={y}\"),\n" +" }\n" +"}\n" +"\n" +"fn main() {\n" +" let load = WebEvent::PageLoad;\n" +" let press = WebEvent::KeyPress('x');\n" +" let click = WebEvent::Click { x: 20, y: 80 };\n" +"\n" +" inspect(load);\n" +" inspect(press);\n" +" inspect(click);\n" +"}\n" +"```" msgstr "" -#: src/memory-management/comparison.md:24 -msgid "Double-frees." +#: src/enums/variant-payloads.md:35 +msgid "" +"The values in the enum variants can only be accessed after being pattern " +"matched. The pattern binds references to the fields in the \"match arm\" " +"after the `=>`." msgstr "" -#: src/memory-management/comparison.md:25 -msgid "Memory leaks." +#: src/enums/variant-payloads.md:36 +msgid "" +"The expression is matched against the patterns from top to bottom. There is " +"no fall-through like in C or C++." msgstr "" -#: src/memory-management/comparison.md:27 -msgid "Garbage collection pauses." +#: src/enums/variant-payloads.md:37 +msgid "" +"The match expression has a value. The value is the last expression in the " +"match arm which was executed." msgstr "" -#: src/memory-management/comparison.md:28 -msgid "Destructor delays." +#: src/enums/variant-payloads.md:38 +msgid "" +"Starting from the top we look for what pattern matches the value then run " +"the code following the arrow. Once we find a match, we stop. " msgstr "" -#: src/memory-management/comparison.md:30 -msgid "Complex, opt-in by programmer." +#: src/enums/variant-payloads.md:39 +msgid "" +"Demonstrate what happens when the search is inexhaustive. Note the advantage " +"the Rust compiler provides by confirming when all cases are handled. " msgstr "" -#: src/memory-management/comparison.md:31 -msgid "Potential for use-after-free." +#: src/enums/variant-payloads.md:40 +msgid "`match` inspects a hidden discriminant field in the `enum`." msgstr "" -#: src/memory-management/comparison.md:32 -msgid "Compiler-enforced and scope-based like Rust:" +#: src/enums/variant-payloads.md:41 +msgid "" +"It is possible to retrieve the discriminant by calling `std::mem::" +"discriminant()`" msgstr "" -#: src/memory-management/comparison.md:33 -msgid "Some upfront complexity." +#: src/enums/variant-payloads.md:42 +msgid "" +"This is useful, for example, if implementing `PartialEq` for structs where " +"comparing field values doesn't affect equality." msgstr "" -#: src/memory-management/comparison.md:34 -msgid "Can reject valid programs." +#: src/enums/variant-payloads.md:43 +msgid "" +"`WebEvent::Click { ... }` is not exactly the same as `WebEvent::" +"Click(Click)` with a top level `struct Click { ... }`. The inlined version " +"cannot implement traits, for example." msgstr "" -#: src/ownership.md:3 +#: src/enums/sizes.md:3 msgid "" -"All variable bindings have a _scope_ where they are valid and it is an error " -"to use a variable outside its scope:" +"Rust enums are packed tightly, taking constraints due to alignment into " +"account:" msgstr "" -#: src/ownership.md:6 +#: src/enums/sizes.md:5 msgid "" -"```rust,editable,compile_fail\n" -"struct Point(i32, i32);\n" +"```rust,editable\n" +"use std::any::type_name;\n" +"use std::mem::{align_of, size_of};\n" +"\n" +"fn dbg_size() {\n" +" println!(\"{}: size {} bytes, align: {} bytes\",\n" +" type_name::(), size_of::(), align_of::());\n" +"}\n" +"\n" +"enum Foo {\n" +" A,\n" +" B,\n" +"}\n" "\n" "fn main() {\n" -" {\n" -" let p = Point(3, 4);\n" -" println!(\"x: {}\", p.0);\n" -" }\n" -" println!(\"y: {}\", p.1);\n" +" dbg_size::();\n" "}\n" "```" msgstr "" -#: src/ownership.md:18 +#: src/enums/sizes.md:24 msgid "" -"At the end of the scope, the variable is _dropped_ and the data is freed." -msgstr "" - -#: src/ownership.md:19 -msgid "A destructor can run here to free up resources." +"See the [Rust Reference](https://doc.rust-lang.org/reference/type-layout." +"html)." msgstr "" -#: src/ownership.md:20 -msgid "We say that the variable _owns_ the value." +#: src/enums/sizes.md:30 +msgid "" +"Internally Rust is using a field (discriminant) to keep track of the enum " +"variant." msgstr "" -#: src/ownership/move-semantics.md:3 -msgid "An assignment will transfer ownership between variables:" +#: src/enums/sizes.md:32 +msgid "" +"You can control the discriminant if needed (e.g., for compatibility with C):" msgstr "" -#: src/ownership/move-semantics.md:5 +#: src/enums/sizes.md:34 msgid "" "```rust,editable\n" +"#[repr(u32)]\n" +"enum Bar {\n" +" A, // 0\n" +" B = 10000,\n" +" C, // 10001\n" +"}\n" +"\n" "fn main() {\n" -" let s1: String = String::from(\"Hello!\");\n" -" let s2: String = s1;\n" -" println!(\"s2: {s2}\");\n" -" // println!(\"s1: {s1}\");\n" +" println!(\"A: {}\", Bar::A as u32);\n" +" println!(\"B: {}\", Bar::B as u32);\n" +" println!(\"C: {}\", Bar::C as u32);\n" "}\n" "```" msgstr "" -#: src/ownership/move-semantics.md:14 -msgid "The assignment of `s1` to `s2` transfers ownership." -msgstr "" - -#: src/ownership/move-semantics.md:15 -msgid "The data was _moved_ from `s1` and `s1` is no longer accessible." -msgstr "" - -#: src/ownership/move-semantics.md:16 -msgid "When `s1` goes out of scope, nothing happens: it has no ownership." +#: src/enums/sizes.md:49 +msgid "" +"Without `repr`, the discriminant type takes 2 bytes, because 10001 fits 2 " +"bytes." msgstr "" -#: src/ownership/move-semantics.md:17 -msgid "When `s2` goes out of scope, the string data is freed." +#: src/enums/sizes.md:53 +msgid "Try out other types such as" msgstr "" -#: src/ownership/move-semantics.md:18 -msgid "There is always _exactly_ one variable binding which owns a value." +#: src/enums/sizes.md:55 +msgid "`dbg_size!(bool)`: size 1 bytes, align: 1 bytes," msgstr "" -#: src/ownership/move-semantics.md:22 +#: src/enums/sizes.md:56 msgid "" -"Mention that this is the opposite of the defaults in C++, which copies by " -"value unless you use `std::move` (and the move constructor is defined!)." +"`dbg_size!(Option)`: size 1 bytes, align: 1 bytes (niche optimization, " +"see below)," msgstr "" -#: src/ownership/move-semantics.md:24 -msgid "In Rust, clones are explicit (by using `clone`)." +#: src/enums/sizes.md:57 +msgid "`dbg_size!(&i32)`: size 8 bytes, align: 8 bytes (on a 64-bit machine)," msgstr "" -#: src/ownership/moved-strings-rust.md:3 +#: src/enums/sizes.md:58 msgid "" -"```rust,editable\n" -"fn main() {\n" -" let s1: String = String::from(\"Rust\");\n" -" let s2: String = s1;\n" -"}\n" -"```" +"`dbg_size!(Option<&i32>)`: size 8 bytes, align: 8 bytes (null pointer " +"optimization, see below)." msgstr "" -#: src/ownership/moved-strings-rust.md:10 -msgid "The heap data from `s1` is reused for `s2`." +#: src/enums/sizes.md:60 +msgid "" +"Niche optimization: Rust will merge unused bit patterns for the enum " +"discriminant." msgstr "" -#: src/ownership/moved-strings-rust.md:11 -msgid "When `s1` goes out of scope, nothing happens (it has been moved from)." +#: src/enums/sizes.md:63 +msgid "" +"Null pointer optimization: For [some types](https://doc.rust-lang.org/std/" +"option/#representation), Rust guarantees that `size_of::()` equals " +"`size_of::>()`." msgstr "" -#: src/ownership/moved-strings-rust.md:13 -msgid "Before move to `s2`:" +#: src/enums/sizes.md:67 +msgid "" +"Example code if you want to show how the bitwise representation _may_ look " +"like in practice. It's important to note that the compiler provides no " +"guarantees regarding this representation, therefore this is totally unsafe." msgstr "" -#: src/ownership/moved-strings-rust.md:15 +#: src/enums/sizes.md:70 msgid "" -"```bob\n" -" Stack Heap\n" -".- - - - - - - - - - - - - -. .- - - - - - - - - - - - - -.\n" -": : : :\n" -": s1 : : :\n" -": +-----------+-------+ : : +----+----+----+----+ :\n" -": | ptr | o---+---+-----+-->| R | u | s | t | :\n" -": | len | 4 | : : +----+----+----+----+ :\n" -": | capacity | 4 | : : :\n" -": +-----------+-------+ : : :\n" -": : `- - - - - - - - - - - - - -'\n" -": :\n" -"`- - - - - - - - - - - - - -'\n" +"```rust,editable\n" +"use std::mem::transmute;\n" +"\n" +"macro_rules! dbg_bits {\n" +" ($e:expr, $bit_type:ty) => {\n" +" println!(\"- {}: {:#x}\", stringify!($e), transmute::<_, " +"$bit_type>($e));\n" +" };\n" +"}\n" +"\n" +"fn main() {\n" +" // TOTALLY UNSAFE. Rust provides no guarantees about the bitwise\n" +" // representation of types.\n" +" unsafe {\n" +" println!(\"Bitwise representation of bool\");\n" +" dbg_bits!(false, u8);\n" +" dbg_bits!(true, u8);\n" +"\n" +" println!(\"Bitwise representation of Option\");\n" +" dbg_bits!(None::, u8);\n" +" dbg_bits!(Some(false), u8);\n" +" dbg_bits!(Some(true), u8);\n" +"\n" +" println!(\"Bitwise representation of Option>\");\n" +" dbg_bits!(Some(Some(false)), u8);\n" +" dbg_bits!(Some(Some(true)), u8);\n" +" dbg_bits!(Some(None::), u8);\n" +" dbg_bits!(None::>, u8);\n" +"\n" +" println!(\"Bitwise representation of Option<&i32>\");\n" +" dbg_bits!(None::<&i32>, usize);\n" +" dbg_bits!(Some(&0i32), usize);\n" +" }\n" +"}\n" "```" msgstr "" -#: src/ownership/moved-strings-rust.md:30 -msgid "After move to `s2`:" +#: src/enums/sizes.md:105 +msgid "" +"More complex example if you want to discuss what happens when we chain more " +"than 256 `Option`s together." msgstr "" -#: src/ownership/moved-strings-rust.md:32 +#: src/enums/sizes.md:107 msgid "" -"```bob\n" -" Stack Heap\n" -".- - - - - - - - - - - - - -. .- - - - - - - - - - - - - -.\n" -": : : :\n" -": s1 \"(inaccessible)\" : : :\n" -": +-----------+-------+ : : +----+----+----+----+ :\n" -": | ptr | o---+---+--+--+-->| R | u | s | t | :\n" -": | len | 4 | : | : +----+----+----+----+ :\n" -": | capacity | 4 | : | : :\n" -": +-----------+-------+ : | : :\n" -": : | `- - - - - - - - - - - - - -'\n" -": s2 : |\n" -": +-----------+-------+ : |\n" -": | ptr | o---+---+--'\n" -": | len | 4 | :\n" -": | capacity | 4 | :\n" -": +-----------+-------+ :\n" -": :\n" -"`- - - - - - - - - - - - - -'\n" -"```" -msgstr "" - -#: src/ownership/double-free-modern-cpp.md:3 -msgid "Modern C++ solves this differently:" -msgstr "" - -#: src/ownership/double-free-modern-cpp.md:5 -msgid "" -"```c++\n" -"std::string s1 = \"Cpp\";\n" -"std::string s2 = s1; // Duplicate the data in s1.\n" +"```rust,editable\n" +"#![recursion_limit = \"1000\"]\n" +"\n" +"use std::mem::transmute;\n" +"\n" +"macro_rules! dbg_bits {\n" +" ($e:expr, $bit_type:ty) => {\n" +" println!(\"- {}: {:#x}\", stringify!($e), transmute::<_, " +"$bit_type>($e));\n" +" };\n" +"}\n" +"\n" +"// Macro to wrap a value in 2^n Some() where n is the number of \"@\" " +"signs.\n" +"// Increasing the recursion limit is required to evaluate this macro.\n" +"macro_rules! many_options {\n" +" ($value:expr) => { Some($value) };\n" +" ($value:expr, @) => {\n" +" Some(Some($value))\n" +" };\n" +" ($value:expr, @ $($more:tt)+) => {\n" +" many_options!(many_options!($value, $($more)+), $($more)+)\n" +" };\n" +"}\n" +"\n" +"fn main() {\n" +" // TOTALLY UNSAFE. Rust provides no guarantees about the bitwise\n" +" // representation of types.\n" +" unsafe {\n" +" assert_eq!(many_options!(false), Some(false));\n" +" assert_eq!(many_options!(false, @), Some(Some(false)));\n" +" assert_eq!(many_options!(false, @@), " +"Some(Some(Some(Some(false)))));\n" +"\n" +" println!(\"Bitwise representation of a chain of 128 Option's.\");\n" +" dbg_bits!(many_options!(false, @@@@@@@), u8);\n" +" dbg_bits!(many_options!(true, @@@@@@@), u8);\n" +"\n" +" println!(\"Bitwise representation of a chain of 256 Option's.\");\n" +" dbg_bits!(many_options!(false, @@@@@@@@), u16);\n" +" dbg_bits!(many_options!(true, @@@@@@@@), u16);\n" +"\n" +" println!(\"Bitwise representation of a chain of 257 Option's.\");\n" +" dbg_bits!(many_options!(Some(false), @@@@@@@@), u16);\n" +" dbg_bits!(many_options!(Some(true), @@@@@@@@), u16);\n" +" dbg_bits!(many_options!(None::, @@@@@@@@), u16);\n" +" }\n" +"}\n" "```" msgstr "" -#: src/ownership/double-free-modern-cpp.md:10 +#: src/control-flow/novel.md:3 msgid "" -"The heap data from `s1` is duplicated and `s2` gets its own independent copy." -msgstr "" - -#: src/ownership/double-free-modern-cpp.md:11 -msgid "When `s1` and `s2` go out of scope, they each free their own memory." -msgstr "" - -#: src/ownership/double-free-modern-cpp.md:13 -msgid "Before copy-assignment:" +"Rust has a few control flow constructs which differ from other languages. " +"They are used for pattern matching:" msgstr "" -#: src/ownership/double-free-modern-cpp.md:16 -msgid "" -"```bob\n" -" Stack Heap\n" -".- - - - - - - - - - - - - -. .- - - - - - - - - - - -.\n" -": : : :\n" -": s1 : : :\n" -": +-----------+-------+ : : +----+----+----+ :\n" -": | ptr | o---+---+--+--+-->| C | p | p | :\n" -": | len | 3 | : : +----+----+----+ :\n" -": | capacity | 3 | : : :\n" -": +-----------+-------+ : : :\n" -": : `- - - - - - - - - - - -'\n" -"`- - - - - - - - - - - - - -'\n" -"```" +#: src/control-flow/novel.md:6 src/control-flow/if-let-expressions.md:1 +msgid "`if let` expressions" msgstr "" -#: src/ownership/double-free-modern-cpp.md:30 -msgid "After copy-assignment:" -msgstr "" +#: src/control-flow/novel.md:7 +#, fuzzy +msgid "`while let` expressions" +msgstr "while let İfadesi" -#: src/ownership/double-free-modern-cpp.md:32 -msgid "" -"```bob\n" -" Stack Heap\n" -".- - - - - - - - - - - - - -. .- - - - - - - - - - - -.\n" -": : : :\n" -": s1 : : :\n" -": +-----------+-------+ : : +----+----+----+ :\n" -": | ptr | o---+---+--+--+-->| C | p | p | :\n" -": | len | 3 | : : +----+----+----+ :\n" -": | capacity | 3 | : : :\n" -": +-----------+-------+ : : :\n" -": : : :\n" -": s2 : : :\n" -": +-----------+-------+ : : +----+----+----+ :\n" -": | ptr | o---+---+-----+-->| C | p | p | :\n" -": | len | 3 | : : +----+----+----+ :\n" -": | capacity | 3 | : : :\n" -": +-----------+-------+ : : :\n" -": : `- - - - - - - - - - - -'\n" -"`- - - - - - - - - - - - - -'\n" -"```" +#: src/control-flow/novel.md:8 src/control-flow/match-expressions.md:1 +msgid "`match` expressions" msgstr "" -#: src/ownership/moves-function-calls.md:3 +#: src/control-flow/if-let-expressions.md:3 msgid "" -"When you pass a value to a function, the value is assigned to the function " -"parameter. This transfers ownership:" +"The [`if let` expression](https://doc.rust-lang.org/reference/expressions/if-" +"expr.html#if-let-expressions) lets you execute different code depending on " +"whether a value matches a pattern:" msgstr "" -#: src/ownership/moves-function-calls.md:6 +#: src/control-flow/if-let-expressions.md:7 msgid "" "```rust,editable\n" -"fn say_hello(name: String) {\n" -" println!(\"Hello {name}\")\n" -"}\n" -"\n" "fn main() {\n" -" let name = String::from(\"Alice\");\n" -" say_hello(name);\n" -" // say_hello(name);\n" +" let arg = std::env::args().next();\n" +" if let Some(value) = arg {\n" +" println!(\"Program name: {value}\");\n" +" } else {\n" +" println!(\"Missing name?\");\n" +" }\n" "}\n" "```" msgstr "" -#: src/ownership/moves-function-calls.md:20 -msgid "" -"With the first call to `say_hello`, `main` gives up ownership of `name`. " -"Afterwards, `name` cannot be used anymore within `main`." -msgstr "" - -#: src/ownership/moves-function-calls.md:21 +#: src/control-flow/if-let-expressions.md:18 +#: src/control-flow/while-let-expressions.md:21 +#: src/control-flow/match-expressions.md:23 msgid "" -"The heap memory allocated for `name` will be freed at the end of the " -"`say_hello` function." +"See [pattern matching](../pattern-matching.md) for more details on patterns " +"in Rust." msgstr "" -#: src/ownership/moves-function-calls.md:22 +#: src/control-flow/if-let-expressions.md:23 msgid "" -"`main` can retain ownership if it passes `name` as a reference (`&name`) and " -"if `say_hello` accepts a reference as a parameter." +"Unlike `match`, `if let` does not have to cover all branches. This can make " +"it more concise than `match`." msgstr "" -#: src/ownership/moves-function-calls.md:23 -msgid "" -"Alternatively, `main` can pass a clone of `name` in the first call (`name." -"clone()`)." +#: src/control-flow/if-let-expressions.md:24 +msgid "A common usage is handling `Some` values when working with `Option`." msgstr "" -#: src/ownership/moves-function-calls.md:24 +#: src/control-flow/if-let-expressions.md:25 msgid "" -"Rust makes it harder than C++ to inadvertently create copies by making move " -"semantics the default, and by forcing programmers to make clones explicit." +"Unlike `match`, `if let` does not support guard clauses for pattern matching." msgstr "" -#: src/ownership/copy-clone.md:3 +#: src/control-flow/if-let-expressions.md:26 msgid "" -"While move semantics are the default, certain types are copied by default:" +"Since 1.65, a similar [let-else](https://doc.rust-lang.org/rust-by-example/" +"flow_control/let_else.html) construct allows to do a destructuring " +"assignment, or if it fails, execute a block which is required to abort " +"normal control flow (with `panic`/`return`/`break`/`continue`):" msgstr "" -#: src/ownership/copy-clone.md:5 +#: src/control-flow/if-let-expressions.md:28 msgid "" "```rust,editable\n" "fn main() {\n" -" let x = 42;\n" -" let y = x;\n" -" println!(\"x: {x}\");\n" -" println!(\"y: {y}\");\n" +" println!(\"{:?}\", second_word_to_upper(\"foo bar\"));\n" +"}\n" +" \n" +"fn second_word_to_upper(s: &str) -> Option {\n" +" let mut it = s.split(' ');\n" +" let (Some(_), Some(item)) = (it.next(), it.next()) else {\n" +" return None;\n" +" };\n" +" Some(item.to_uppercase())\n" "}\n" +"\n" "```" msgstr "" -#: src/ownership/copy-clone.md:14 -msgid "These types implement the `Copy` trait." +#: src/control-flow/while-let-expressions.md:1 +msgid "`while let` loops" msgstr "" -#: src/ownership/copy-clone.md:16 -msgid "You can opt-in your own types to use copy semantics:" +#: src/control-flow/while-let-expressions.md:3 +msgid "" +"Like with `if let`, there is a [`while let`](https://doc.rust-lang.org/" +"reference/expressions/loop-expr.html#predicate-pattern-loops) variant which " +"repeatedly tests a value against a pattern:" msgstr "" -#: src/ownership/copy-clone.md:18 +#: src/control-flow/while-let-expressions.md:6 msgid "" "```rust,editable\n" -"#[derive(Copy, Clone, Debug)]\n" -"struct Point(i32, i32);\n" -"\n" "fn main() {\n" -" let p1 = Point(3, 4);\n" -" let p2 = p1;\n" -" println!(\"p1: {p1:?}\");\n" -" println!(\"p2: {p2:?}\");\n" +" let v = vec![10, 20, 30];\n" +" let mut iter = v.into_iter();\n" +"\n" +" while let Some(x) = iter.next() {\n" +" println!(\"x: {x}\");\n" +" }\n" "}\n" "```" msgstr "" -#: src/ownership/copy-clone.md:30 -msgid "After the assignment, both `p1` and `p2` own their own data." +#: src/control-flow/while-let-expressions.md:17 +msgid "" +"Here the iterator returned by `v.into_iter()` will return a `Option` on " +"every call to `next()`. It returns `Some(x)` until it is done, after which " +"it will return `None`. The `while let` lets us keep iterating through all " +"items." msgstr "" -#: src/ownership/copy-clone.md:31 -msgid "We can also use `p1.clone()` to explicitly copy the data." +#: src/control-flow/while-let-expressions.md:26 +msgid "" +"Point out that the `while let` loop will keep going as long as the value " +"matches the pattern." msgstr "" -#: src/ownership/copy-clone.md:35 -msgid "Copying and cloning are not the same thing:" +#: src/control-flow/while-let-expressions.md:27 +msgid "" +"You could rewrite the `while let` loop as an infinite loop with an if " +"statement that breaks when there is no value to unwrap for `iter.next()`. " +"The `while let` provides syntactic sugar for the above scenario." msgstr "" -#: src/ownership/copy-clone.md:37 +#: src/control-flow/match-expressions.md:3 msgid "" -"Copying refers to bitwise copies of memory regions and does not work on " -"arbitrary objects." +"The [`match` keyword](https://doc.rust-lang.org/reference/expressions/match-" +"expr.html) is used to match a value against one or more patterns. In that " +"sense, it works like a series of `if let` expressions:" msgstr "" -#: src/ownership/copy-clone.md:38 +#: src/control-flow/match-expressions.md:7 msgid "" -"Copying does not allow for custom logic (unlike copy constructors in C++)." +"```rust,editable\n" +"fn main() {\n" +" match std::env::args().next().as_deref() {\n" +" Some(\"cat\") => println!(\"Will do cat things\"),\n" +" Some(\"ls\") => println!(\"Will ls some files\"),\n" +" Some(\"mv\") => println!(\"Let's move some files\"),\n" +" Some(\"rm\") => println!(\"Uh, dangerous!\"),\n" +" None => println!(\"Hmm, no program name?\"),\n" +" _ => println!(\"Unknown program name!\"),\n" +" }\n" +"}\n" +"```" msgstr "" -#: src/ownership/copy-clone.md:39 +#: src/control-flow/match-expressions.md:20 msgid "" -"Cloning is a more general operation and also allows for custom behavior by " -"implementing the `Clone` trait." +"Like `if let`, each match arm must have the same type. The type is the last " +"expression of the block, if any. In the example above, the type is `()`." msgstr "" -#: src/ownership/copy-clone.md:40 -msgid "Copying does not work on types that implement the `Drop` trait." +#: src/control-flow/match-expressions.md:28 +msgid "Save the match expression to a variable and print it out." msgstr "" -#: src/ownership/copy-clone.md:42 src/ownership/lifetimes-function-calls.md:29 -msgid "In the above example, try the following:" +#: src/control-flow/match-expressions.md:29 +msgid "Remove `.as_deref()` and explain the error." msgstr "" -#: src/ownership/copy-clone.md:44 +#: src/control-flow/match-expressions.md:30 msgid "" -"Add a `String` field to `struct Point`. It will not compile because `String` " -"is not a `Copy` type." +"`std::env::args().next()` returns an `Option`, but we cannot match " +"against `String`." msgstr "" -#: src/ownership/copy-clone.md:45 +#: src/control-flow/match-expressions.md:31 msgid "" -"Remove `Copy` from the `derive` attribute. The compiler error is now in the " -"`println!` for `p1`." +"`as_deref()` transforms an `Option` to `Option<&T::Target>`. In our case, " +"this turns `Option` into `Option<&str>`." msgstr "" -#: src/ownership/copy-clone.md:46 -msgid "Show that it works if you clone `p1` instead." +#: src/control-flow/match-expressions.md:32 +msgid "" +"We can now use pattern matching to match against the `&str` inside `Option`." msgstr "" -#: src/ownership/copy-clone.md:48 +#: src/pattern-matching.md:3 msgid "" -"If students ask about `derive`, it is sufficient to say that this is a way " -"to generate code in Rust at compile time. In this case the default " -"implementations of `Copy` and `Clone` traits are generated." +"The `match` keyword let you match a value against one or more _patterns_. " +"The comparisons are done from top to bottom and the first match wins." msgstr "" -#: src/ownership/borrowing.md:3 -msgid "" -"Instead of transferring ownership when calling a function, you can let a " -"function _borrow_ the value:" +#: src/pattern-matching.md:6 +msgid "The patterns can be simple values, similarly to `switch` in C and C++:" msgstr "" -#: src/ownership/borrowing.md:6 +#: src/pattern-matching.md:8 msgid "" "```rust,editable\n" -"#[derive(Debug)]\n" -"struct Point(i32, i32);\n" -"\n" -"fn add(p1: &Point, p2: &Point) -> Point {\n" -" Point(p1.0 + p2.0, p1.1 + p2.1)\n" -"}\n" -"\n" "fn main() {\n" -" let p1 = Point(3, 4);\n" -" let p2 = Point(10, 20);\n" -" let p3 = add(&p1, &p2);\n" -" println!(\"{p1:?} + {p2:?} = {p3:?}\");\n" +" let input = 'x';\n" +"\n" +" match input {\n" +" 'q' => println!(\"Quitting\"),\n" +" 'a' | 's' | 'w' | 'd' => println!(\"Moving around\"),\n" +" '0'..='9' => println!(\"Number input\"),\n" +" _ => println!(\"Something else\"),\n" +" }\n" "}\n" "```" msgstr "" -#: src/ownership/borrowing.md:22 -msgid "The `add` function _borrows_ two points and returns a new point." +#: src/pattern-matching.md:21 +msgid "The `_` pattern is a wildcard pattern which matches any value." msgstr "" -#: src/ownership/borrowing.md:23 -msgid "The caller retains ownership of the inputs." +#: src/pattern-matching.md:26 +msgid "" +"You might point out how some specific characters are being used when in a " +"pattern" msgstr "" -#: src/ownership/borrowing.md:27 -msgid "Notes on stack returns:" +#: src/pattern-matching.md:27 +msgid "`|` as an `or`" msgstr "" -#: src/ownership/borrowing.md:28 -msgid "" -"Demonstrate that the return from `add` is cheap because the compiler can " -"eliminate the copy operation. Change the above code to print stack addresses " -"and run it on the [Playground](https://play.rust-lang.org/). In the " -"\"DEBUG\" optimization level, the addresses should change, while they stay " -"the same when changing to the \"RELEASE\" setting:" +#: src/pattern-matching.md:28 +msgid "`..` can expand as much as it needs to be" msgstr "" -#: src/ownership/borrowing.md:30 -msgid "" -"```rust,editable\n" -"#[derive(Debug)]\n" -"struct Point(i32, i32);\n" -"\n" -"fn add(p1: &Point, p2: &Point) -> Point {\n" -" let p = Point(p1.0 + p2.0, p1.1 + p2.1);\n" -" println!(\"&p.0: {:p}\", &p.0);\n" -" p\n" -"}\n" -"\n" -"fn main() {\n" -" let p1 = Point(3, 4);\n" -" let p2 = Point(10, 20);\n" -" let p3 = add(&p1, &p2);\n" -" println!(\"&p3.0: {:p}\", &p3.0);\n" -" println!(\"{p1:?} + {p2:?} = {p3:?}\");\n" -"}\n" -"```" +#: src/pattern-matching.md:29 +msgid "`1..=5` represents an inclusive range" msgstr "" -#: src/ownership/borrowing.md:48 -msgid "The Rust compiler can do return value optimization (RVO)." +#: src/pattern-matching.md:30 +msgid "`_` is a wild card" msgstr "" -#: src/ownership/borrowing.md:49 +#: src/pattern-matching.md:31 msgid "" -"In C++, copy elision has to be defined in the language specification because " -"constructors can have side effects. In Rust, this is not an issue at all. If " -"RVO did not happen, Rust will always performs a simple and efficient " -"`memcpy` copy." +"It can be useful to show how binding works, by for instance replacing a " +"wildcard character with a variable, or removing the quotes around `q`." msgstr "" -#: src/ownership/shared-unique-borrows.md:3 -msgid "Rust puts constraints on the ways you can borrow values:" +#: src/pattern-matching.md:32 +msgid "You can demonstrate matching on a reference." msgstr "" -#: src/ownership/shared-unique-borrows.md:5 -msgid "You can have one or more `&T` values at any given time, _or_" +#: src/pattern-matching.md:33 +msgid "" +"This might be a good time to bring up the concept of irrefutable patterns, " +"as the term can show up in error messages." msgstr "" -#: src/ownership/shared-unique-borrows.md:6 -msgid "You can have exactly one `&mut T` value." +#: src/pattern-matching/destructuring-enums.md:3 +msgid "" +"Patterns can also be used to bind variables to parts of your values. This is " +"how you inspect the structure of your types. Let us start with a simple " +"`enum` type:" msgstr "" -#: src/ownership/shared-unique-borrows.md:8 +#: src/pattern-matching/destructuring-enums.md:6 msgid "" -"```rust,editable,compile_fail\n" -"fn main() {\n" -" let mut a: i32 = 10;\n" -" let b: &i32 = &a;\n" +"```rust,editable\n" +"enum Result {\n" +" Ok(i32),\n" +" Err(String),\n" +"}\n" "\n" -" {\n" -" let c: &mut i32 = &mut a;\n" -" *c = 20;\n" +"fn divide_in_two(n: i32) -> Result {\n" +" if n % 2 == 0 {\n" +" Result::Ok(n / 2)\n" +" } else {\n" +" Result::Err(format!(\"cannot divide {n} into two equal parts\"))\n" " }\n" +"}\n" "\n" -" println!(\"a: {a}\");\n" -" println!(\"b: {b}\");\n" +"fn main() {\n" +" let n = 100;\n" +" match divide_in_two(n) {\n" +" Result::Ok(half) => println!(\"{n} divided in two is {half}\"),\n" +" Result::Err(msg) => println!(\"sorry, an error happened: {msg}\"),\n" +" }\n" "}\n" "```" msgstr "" -#: src/ownership/shared-unique-borrows.md:25 +#: src/pattern-matching/destructuring-enums.md:29 msgid "" -"The above code does not compile because `a` is borrowed as mutable (through " -"`c`) and as immutable (through `b`) at the same time." +"Here we have used the arms to _destructure_ the `Result` value. In the first " +"arm, `half` is bound to the value inside the `Ok` variant. In the second " +"arm, `msg` is bound to the error message." msgstr "" -#: src/ownership/shared-unique-borrows.md:26 +#: src/pattern-matching/destructuring-enums.md:36 msgid "" -"Move the `println!` statement for `b` before the scope that introduces `c` " -"to make the code compile." +"The `if`/`else` expression is returning an enum that is later unpacked with " +"a `match`." msgstr "" -#: src/ownership/shared-unique-borrows.md:27 +#: src/pattern-matching/destructuring-enums.md:37 msgid "" -"After that change, the compiler realizes that `b` is only ever used before " -"the new mutable borrow of `a` through `c`. This is a feature of the borrow " -"checker called \"non-lexical lifetimes\"." -msgstr "" - -#: src/ownership/lifetimes.md:3 -msgid "A borrowed value has a _lifetime_:" -msgstr "" - -#: src/ownership/lifetimes.md:5 -msgid "The lifetime can be implicit: `add(p1: &Point, p2: &Point) -> Point`." +"You can try adding a third variant to the enum definition and displaying the " +"errors when running the code. Point out the places where your code is now " +"inexhaustive and how the compiler tries to give you hints." msgstr "" -#: src/ownership/lifetimes.md:6 -msgid "Lifetimes can also be explicit: `&'a Point`, `&'document str`." +#: src/pattern-matching/destructuring-structs.md:3 +msgid "You can also destructure `structs`:" msgstr "" -#: src/ownership/lifetimes.md:7 src/ownership/lifetimes-function-calls.md:23 +#: src/pattern-matching/destructuring-structs.md:5 msgid "" -"Read `&'a Point` as \"a borrowed `Point` which is valid for at least the " -"lifetime `a`\"." +"```rust,editable\n" +"struct Foo {\n" +" x: (u32, u32),\n" +" y: u32,\n" +"}\n" +"\n" +"#[rustfmt::skip]\n" +"fn main() {\n" +" let foo = Foo { x: (1, 2), y: 3 };\n" +" match foo {\n" +" Foo { x: (1, b), y } => println!(\"x.0 = 1, b = {b}, y = {y}\"),\n" +" Foo { y: 2, x: i } => println!(\"y = 2, x = {i:?}\"),\n" +" Foo { y, .. } => println!(\"y = {y}, other fields were " +"ignored\"),\n" +" }\n" +"}\n" +"```" msgstr "" -#: src/ownership/lifetimes.md:9 -msgid "" -"Lifetimes are always inferred by the compiler: you cannot assign a lifetime " -"yourself." +#: src/pattern-matching/destructuring-structs.md:23 +msgid "Change the literal values in `foo` to match with the other patterns." msgstr "" -#: src/ownership/lifetimes.md:11 -msgid "" -"Lifetime annotations create constraints; the compiler verifies that there is " -"a valid solution." +#: src/pattern-matching/destructuring-structs.md:24 +msgid "Add a new field to `Foo` and make changes to the pattern as needed." msgstr "" -#: src/ownership/lifetimes.md:13 +#: src/pattern-matching/destructuring-structs.md:25 msgid "" -"Lifetimes for function arguments and return values must be fully specified, " -"but Rust allows these to be elidied in most cases with [a few simple rules]" -"(https://doc.rust-lang.org/nomicon/lifetime-elision.html)." +"The distinction between a capture and a constant expression can be hard to " +"spot. Try changing the `2` in the second arm to a variable, and see that it " +"subtly doesn't work. Change it to a `const` and see it working again." msgstr "" -#: src/ownership/lifetimes-function-calls.md:3 +#: src/pattern-matching/destructuring-arrays.md:3 msgid "" -"In addition to borrowing its arguments, a function can return a borrowed " -"value:" +"You can destructure arrays, tuples, and slices by matching on their elements:" msgstr "" -#: src/ownership/lifetimes-function-calls.md:5 +#: src/pattern-matching/destructuring-arrays.md:5 msgid "" "```rust,editable\n" -"#[derive(Debug)]\n" -"struct Point(i32, i32);\n" -"\n" -"fn left_most<'a>(p1: &'a Point, p2: &'a Point) -> &'a Point {\n" -" if p1.0 < p2.0 { p1 } else { p2 }\n" -"}\n" -"\n" +"#[rustfmt::skip]\n" "fn main() {\n" -" let p1: Point = Point(10, 10);\n" -" let p2: Point = Point(20, 20);\n" -" let p3: &Point = left_most(&p1, &p2);\n" -" println!(\"left-most point: {:?}\", p3);\n" +" let triple = [0, -2, 3];\n" +" println!(\"Tell me about {triple:?}\");\n" +" match triple {\n" +" [0, y, z] => println!(\"First is 0, y = {y}, and z = {z}\"),\n" +" [1, ..] => println!(\"First is 1 and the rest were ignored\"),\n" +" _ => println!(\"All elements were ignored\"),\n" +" }\n" "}\n" "```" msgstr "" -#: src/ownership/lifetimes-function-calls.md:21 -msgid "`'a` is a generic parameter, it is inferred by the compiler." -msgstr "" - -#: src/ownership/lifetimes-function-calls.md:22 -msgid "Lifetimes start with `'` and `'a` is a typical default name." -msgstr "" - -#: src/ownership/lifetimes-function-calls.md:25 -msgid "" -"The _at least_ part is important when parameters are in different scopes." -msgstr "" - -#: src/ownership/lifetimes-function-calls.md:31 +#: src/pattern-matching/destructuring-arrays.md:21 msgid "" -"Move the declaration of `p2` and `p3` into a a new scope (`{ ... }`), " -"resulting in the following code:" +"Destructuring of slices of unknown length also works with patterns of fixed " +"length." msgstr "" -#: src/ownership/lifetimes-function-calls.md:32 +#: src/pattern-matching/destructuring-arrays.md:24 msgid "" -"```rust,ignore\n" -"#[derive(Debug)]\n" -"struct Point(i32, i32);\n" -"\n" -"fn left_most<'a>(p1: &'a Point, p2: &'a Point) -> &'a Point {\n" -" if p1.0 < p2.0 { p1 } else { p2 }\n" +"```rust,editable\n" +"fn main() {\n" +" inspect(&[0, -2, 3]);\n" +" inspect(&[0, -2, 3, 4]);\n" "}\n" "\n" -"fn main() {\n" -" let p1: Point = Point(10, 10);\n" -" let p3: &Point;\n" -" {\n" -" let p2: Point = Point(20, 20);\n" -" p3 = left_most(&p1, &p2);\n" +"#[rustfmt::skip]\n" +"fn inspect(slice: &[i32]) {\n" +" println!(\"Tell me about {slice:?}\");\n" +" match slice {\n" +" &[0, y, z] => println!(\"First is 0, y = {y}, and z = {z}\"),\n" +" &[1, ..] => println!(\"First is 1 and the rest were ignored\"),\n" +" _ => println!(\"All elements were ignored\"),\n" " }\n" -" println!(\"left-most point: {:?}\", p3);\n" "}\n" "```" msgstr "" -#: src/ownership/lifetimes-function-calls.md:50 -msgid "Note how this does not compile since `p3` outlives `p2`." -msgstr "" - -#: src/ownership/lifetimes-function-calls.md:52 -msgid "" -"Reset the workspace and change the function signature to `fn left_most<'a, " -"'b>(p1: &'a Point, p2: &'a Point) -> &'b Point`. This will not compile " -"because the relationship between the lifetimes `'a` and `'b` is unclear." -msgstr "" - -#: src/ownership/lifetimes-function-calls.md:53 -msgid "Another way to explain it:" +#: src/pattern-matching/destructuring-arrays.md:41 +msgid "Create a new pattern using `_` to represent an element. " msgstr "" -#: src/ownership/lifetimes-function-calls.md:54 -msgid "" -"Two references to two values are borrowed by a function and the function " -"returns another reference." +#: src/pattern-matching/destructuring-arrays.md:42 +msgid "Add more values to the array." msgstr "" -#: src/ownership/lifetimes-function-calls.md:56 +#: src/pattern-matching/destructuring-arrays.md:43 msgid "" -"It must have come from one of those two inputs (or from a global variable)." +"Point out that how `..` will expand to account for different number of " +"elements." msgstr "" -#: src/ownership/lifetimes-function-calls.md:57 -msgid "" -"Which one is it? The compiler needs to to know, so at the call site the " -"returned reference is not used for longer than a variable from where the " -"reference came from." +#: src/pattern-matching/destructuring-arrays.md:44 +msgid "Show matching against the tail with patterns `[.., b]` and `[a@..,b]`" msgstr "" -#: src/ownership/lifetimes-data-structures.md:3 +#: src/pattern-matching/match-guards.md:3 msgid "" -"If a data type stores borrowed data, it must be annotated with a lifetime:" +"When matching, you can add a _guard_ to a pattern. This is an arbitrary " +"Boolean expression which will be executed if the pattern matches:" msgstr "" -#: src/ownership/lifetimes-data-structures.md:5 +#: src/pattern-matching/match-guards.md:6 msgid "" "```rust,editable\n" -"#[derive(Debug)]\n" -"struct Highlight<'doc>(&'doc str);\n" -"\n" -"fn erase(text: String) {\n" -" println!(\"Bye {text}!\");\n" -"}\n" -"\n" +"#[rustfmt::skip]\n" "fn main() {\n" -" let text = String::from(\"The quick brown fox jumps over the lazy dog." -"\");\n" -" let fox = Highlight(&text[4..19]);\n" -" let dog = Highlight(&text[35..43]);\n" -" // erase(text);\n" -" println!(\"{fox:?}\");\n" -" println!(\"{dog:?}\");\n" +" let pair = (2, -2);\n" +" println!(\"Tell me about {pair:?}\");\n" +" match pair {\n" +" (x, y) if x == y => println!(\"These are twins\"),\n" +" (x, y) if x + y == 0 => println!(\"Antimatter, kaboom!\"),\n" +" (x, _) if x % 2 == 1 => println!(\"The first one is odd\"),\n" +" _ => println!(\"No correlation...\"),\n" +" }\n" "}\n" "```" msgstr "" -#: src/ownership/lifetimes-data-structures.md:25 -msgid "" -"In the above example, the annotation on `Highlight` enforces that the data " -"underlying the contained `&str` lives at least as long as any instance of " -"`Highlight` that uses that data." -msgstr "" - -#: src/ownership/lifetimes-data-structures.md:26 +#: src/pattern-matching/match-guards.md:23 msgid "" -"If `text` is consumed before the end of the lifetime of `fox` (or `dog`), " -"the borrow checker throws an error." +"Match guards as a separate syntax feature are important and necessary when " +"we wish to concisely express more complex ideas than patterns alone would " +"allow." msgstr "" -#: src/ownership/lifetimes-data-structures.md:27 +#: src/pattern-matching/match-guards.md:24 msgid "" -"Types with borrowed data force users to hold on to the original data. This " -"can be useful for creating lightweight views, but it generally makes them " -"somewhat harder to use." +"They are not the same as separate `if` expression inside of the match arm. " +"An `if` expression inside of the branch block (after `=>`) happens after the " +"match arm is selected. Failing the `if` condition inside of that block won't " +"result in other arms of the original `match` expression being considered." msgstr "" -#: src/ownership/lifetimes-data-structures.md:28 -msgid "When possible, make data structures own their data directly." +#: src/pattern-matching/match-guards.md:26 +msgid "You can use the variables defined in the pattern in your if expression." msgstr "" -#: src/ownership/lifetimes-data-structures.md:29 +#: src/pattern-matching/match-guards.md:27 msgid "" -"Some structs with multiple references inside can have more than one lifetime " -"annotation. This can be necessary if there is a need to describe lifetime " -"relationships between the references themselves, in addition to the lifetime " -"of the struct itself. Those are very advanced use cases." +"The condition defined in the guard applies to every expression in a pattern " +"with an `|`." msgstr "" #: src/exercises/day-1/afternoon.md:1 @@ -4679,8781 +4888,8837 @@ msgid "We will look at two things:" msgstr "" #: src/exercises/day-1/afternoon.md:5 -msgid "A small book library," -msgstr "" +#, fuzzy +msgid "The Luhn algorithm," +msgstr "Luhn Algrotiması" #: src/exercises/day-1/afternoon.md:7 -msgid "Iterators and ownership (hard)." +msgid "An exercise on pattern matching." msgstr "" -#: src/exercises/day-1/book-library.md:3 +#: src/exercises/day-1/afternoon.md:11 src/exercises/day-2/afternoon.md:7 +#: src/exercises/bare-metal/afternoon.md:7 +#: src/exercises/concurrency/afternoon.md:13 msgid "" -"We will learn much more about structs and the `Vec` type tomorrow. For " -"now, you just need to know part of its API:" +"After looking at the exercises, you can look at the [solutions](solutions-" +"afternoon.md) provided." msgstr "" -#: src/exercises/day-1/book-library.md:6 +#: src/exercises/day-1/luhn.md:3 msgid "" -"```rust,editable\n" -"fn main() {\n" -" let mut vec = vec![10, 20];\n" -" vec.push(30);\n" -" let midpoint = vec.len() / 2;\n" -" println!(\"middle value: {}\", vec[midpoint]);\n" -" for item in &vec {\n" -" println!(\"item: {item}\");\n" -" }\n" -"}\n" -"```" +"The [Luhn algorithm](https://en.wikipedia.org/wiki/Luhn_algorithm) is used " +"to validate credit card numbers. The algorithm takes a string as input and " +"does the following to validate the credit card number:" msgstr "" -#: src/exercises/day-1/book-library.md:18 +#: src/exercises/day-1/luhn.md:7 +msgid "Ignore all spaces. Reject number with less than two digits." +msgstr "" + +#: src/exercises/day-1/luhn.md:9 msgid "" -"Use this to create a library application. Copy the code below to and update the types to make it compile:" +"Moving from **right to left**, double every second digit: for the number " +"`1234`, we double `3` and `1`. For the number `98765`, we double `6` and `8`." msgstr "" -#: src/exercises/day-1/book-library.md:21 +#: src/exercises/day-1/luhn.md:12 msgid "" -"```rust,should_panic\n" -"struct Library {\n" -" books: Vec,\n" -"}\n" +"After doubling a digit, sum the digits. So doubling `7` becomes `14` which " +"becomes `5`." +msgstr "" + +#: src/exercises/day-1/luhn.md:15 +msgid "Sum all the undoubled and doubled digits." +msgstr "" + +#: src/exercises/day-1/luhn.md:17 +msgid "The credit card number is valid if the sum ends with `0`." +msgstr "" + +#: src/exercises/day-1/luhn.md:19 +msgid "" +"Copy the code below to and implement the " +"function." +msgstr "" + +#: src/exercises/day-1/luhn.md:21 +msgid "" +"Try to solve the problem the \"simple\" way first, using `for` loops and " +"integers. Then, revisit the solution and try to implement it with iterators." +msgstr "" + +#: src/exercises/day-1/luhn.md:25 +msgid "" +"```rust\n" +"// TODO: remove this when you're done with your implementation.\n" +"#![allow(unused_variables, dead_code)]\n" "\n" -"struct Book {\n" -" title: String,\n" -" year: u16,\n" +"pub fn luhn(cc_number: &str) -> bool {\n" +" unimplemented!()\n" "}\n" "\n" -"impl Book {\n" -" // This is a constructor, used below.\n" -" fn new(title: &str, year: u16) -> Book {\n" -" Book {\n" -" title: String::from(title),\n" -" year,\n" -" }\n" -" }\n" +"#[test]\n" +"fn test_non_digit_cc_number() {\n" +" assert!(!luhn(\"foo\"));\n" "}\n" "\n" -"// Implement the methods below. Update the `self` parameter to\n" -"// indicate the method's required level of ownership over the object:\n" -"//\n" -"// - `&self` for shared read-only access,\n" -"// - `&mut self` for unique and mutable access,\n" -"// - `self` for unique access by value.\n" -"impl Library {\n" -" fn new() -> Library {\n" -" todo!(\"Initialize and return a `Library` value\")\n" -" }\n" +"#[test]\n" +"fn test_empty_cc_number() {\n" +" assert!(!luhn(\"\"));\n" +" assert!(!luhn(\" \"));\n" +" assert!(!luhn(\" \"));\n" +" assert!(!luhn(\" \"));\n" +"}\n" "\n" -" //fn len(self) -> usize {\n" -" // todo!(\"Return the length of `self.books`\")\n" -" //}\n" +"#[test]\n" +"fn test_single_digit_cc_number() {\n" +" assert!(!luhn(\"0\"));\n" +"}\n" "\n" -" //fn is_empty(self) -> bool {\n" -" // todo!(\"Return `true` if `self.books` is empty\")\n" -" //}\n" +"#[test]\n" +"fn test_two_digit_cc_number() {\n" +" assert!(luhn(\" 0 0 \"));\n" +"}\n" "\n" -" //fn add_book(self, book: Book) {\n" -" // todo!(\"Add a new book to `self.books`\")\n" -" //}\n" -"\n" -" //fn print_books(self) {\n" -" // todo!(\"Iterate over `self.books` and each book's title and " -"year\")\n" -" //}\n" -"\n" -" //fn oldest_book(self) -> Option<&Book> {\n" -" // todo!(\"Return a reference to the oldest book (if any)\")\n" -" //}\n" +"#[test]\n" +"fn test_valid_cc_number() {\n" +" assert!(luhn(\"4263 9826 4026 9299\"));\n" +" assert!(luhn(\"4539 3195 0343 6467\"));\n" +" assert!(luhn(\"7992 7398 713\"));\n" "}\n" "\n" -"// This shows the desired behavior. Uncomment the code below and\n" -"// implement the missing methods. You will need to update the\n" -"// method signatures, including the \"self\" parameter! You may\n" -"// also need to update the variable bindings within main.\n" -"fn main() {\n" -" let library = Library::new();\n" -"\n" -" //println!(\"The library is empty: {}\", library.is_empty());\n" -" //\n" -" //library.add_book(Book::new(\"Lord of the Rings\", 1954));\n" -" //library.add_book(Book::new(\"Alice's Adventures in Wonderland\", " -"1865));\n" -" //\n" -" //println!(\"The library is no longer empty: {}\", library.is_empty());\n" -" //\n" -" //\n" -" //library.print_books();\n" -" //\n" -" //match library.oldest_book() {\n" -" // Some(book) => println!(\"The oldest book is {}\", book.title),\n" -" // None => println!(\"The library is empty!\"),\n" -" //}\n" -" //\n" -" //println!(\"The library has {} books\", library.len());\n" -" //library.print_books();\n" +"#[test]\n" +"fn test_invalid_cc_number() {\n" +" assert!(!luhn(\"4223 9826 4026 9299\"));\n" +" assert!(!luhn(\"4539 3195 0343 6476\"));\n" +" assert!(!luhn(\"8273 1232 7352 0569\"));\n" "}\n" +"\n" +"#[allow(dead_code)]\n" +"fn main() {}\n" "```" msgstr "" -#: src/exercises/day-1/book-library.md:102 -msgid "[Solution](solutions-afternoon.md#designing-a-library)" -msgstr "" - -#: src/exercises/day-1/iterators-and-ownership.md:3 -msgid "" -"The ownership model of Rust affects many APIs. An example of this is the " -"[`Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html) and " -"[`IntoIterator`](https://doc.rust-lang.org/std/iter/trait.IntoIterator.html) " -"traits." +#: src/welcome-day-2.md:1 +msgid "Welcome to Day 2" msgstr "" -#: src/exercises/day-1/iterators-and-ownership.md:8 src/bare-metal/no_std.md:28 -msgid "`Iterator`" +#: src/welcome-day-2.md:3 +msgid "Now that we have seen a fair amount of Rust, we will continue with:" msgstr "" -#: src/exercises/day-1/iterators-and-ownership.md:10 +#: src/welcome-day-2.md:5 msgid "" -"Traits are like interfaces: they describe behavior (methods) for a type. The " -"`Iterator` trait simply says that you can call `next` until you get `None` " -"back:" +"Memory management: stack vs heap, manual memory management, scope-based " +"memory management, and garbage collection." msgstr "" -#: src/exercises/day-1/iterators-and-ownership.md:13 +#: src/welcome-day-2.md:8 msgid "" -"```rust\n" -"pub trait Iterator {\n" -" type Item;\n" -" fn next(&mut self) -> Option;\n" -"}\n" -"```" +"Ownership: move semantics, copying and cloning, borrowing, and lifetimes." msgstr "" -#: src/exercises/day-1/iterators-and-ownership.md:20 -msgid "You use this trait like this:" -msgstr "" +#: src/welcome-day-2.md:10 +#, fuzzy +msgid "Structs and methods." +msgstr "Stringler ve Yineleyiciler" -#: src/exercises/day-1/iterators-and-ownership.md:22 +#: src/welcome-day-2.md:12 msgid "" -"```rust,editable\n" -"fn main() {\n" -" let v: Vec = vec![10, 20, 30];\n" -" let mut iter = v.iter();\n" -"\n" -" println!(\"v[0]: {:?}\", iter.next());\n" -" println!(\"v[1]: {:?}\", iter.next());\n" -" println!(\"v[2]: {:?}\", iter.next());\n" -" println!(\"No more items: {:?}\", iter.next());\n" -"}\n" -"```" -msgstr "" - -#: src/exercises/day-1/iterators-and-ownership.md:34 -msgid "What is the type returned by the iterator? Test your answer here:" +"The Standard Library: `String`, `Option` and `Result`, `Vec`, `HashMap`, " +"`Rc` and `Arc`." msgstr "" -#: src/exercises/day-1/iterators-and-ownership.md:36 -msgid "" -"```rust,editable,compile_fail\n" -"fn main() {\n" -" let v: Vec = vec![10, 20, 30];\n" -" let mut iter = v.iter();\n" -"\n" -" let v0: Option<..> = iter.next();\n" -" println!(\"v0: {v0:?}\");\n" -"}\n" -"```" +#: src/welcome-day-2.md:15 +msgid "Modules: visibility, paths, and filesystem hierarchy." msgstr "" -#: src/exercises/day-1/iterators-and-ownership.md:46 -msgid "Why is this type used?" +#: src/memory-management.md:3 +msgid "Traditionally, languages have fallen into two broad categories:" msgstr "" -#: src/exercises/day-1/iterators-and-ownership.md:48 -msgid "`IntoIterator`" +#: src/memory-management.md:5 +msgid "Full control via manual memory management: C, C++, Pascal, ..." msgstr "" -#: src/exercises/day-1/iterators-and-ownership.md:50 +#: src/memory-management.md:6 msgid "" -"The `Iterator` trait tells you how to _iterate_ once you have created an " -"iterator. The related trait `IntoIterator` tells you how to create the " -"iterator:" +"Full safety via automatic memory management at runtime: Java, Python, Go, " +"Haskell, ..." msgstr "" -#: src/exercises/day-1/iterators-and-ownership.md:53 -msgid "" -"```rust\n" -"pub trait IntoIterator {\n" -" type Item;\n" -" type IntoIter: Iterator;\n" -"\n" -" fn into_iter(self) -> Self::IntoIter;\n" -"}\n" -"```" +#: src/memory-management.md:8 +msgid "Rust offers a new mix:" msgstr "" -#: src/exercises/day-1/iterators-and-ownership.md:62 +#: src/memory-management.md:10 msgid "" -"The syntax here means that every implementation of `IntoIterator` must " -"declare two types:" +"Full control _and_ safety via compile time enforcement of correct memory " +"management." msgstr "" -#: src/exercises/day-1/iterators-and-ownership.md:65 -msgid "`Item`: the type we iterate over, such as `i8`," +#: src/memory-management.md:13 +msgid "It does this with an explicit ownership concept." msgstr "" -#: src/exercises/day-1/iterators-and-ownership.md:66 -msgid "`IntoIter`: the `Iterator` type returned by the `into_iter` method." +#: src/memory-management.md:15 +msgid "First, let's refresh how memory management works." msgstr "" -#: src/exercises/day-1/iterators-and-ownership.md:68 -msgid "" -"Note that `IntoIter` and `Item` are linked: the iterator must have the same " -"`Item` type, which means that it returns `Option`" +#: src/memory-management/stack-vs-heap.md:1 +msgid "The Stack vs The Heap" msgstr "" -#: src/exercises/day-1/iterators-and-ownership.md:71 -msgid "Like before, what is the type returned by the iterator?" +#: src/memory-management/stack-vs-heap.md:3 +msgid "Stack: Continuous area of memory for local variables." msgstr "" -#: src/exercises/day-1/iterators-and-ownership.md:73 -msgid "" -"```rust,editable,compile_fail\n" -"fn main() {\n" -" let v: Vec = vec![String::from(\"foo\"), String::" -"from(\"bar\")];\n" -" let mut iter = v.into_iter();\n" -"\n" -" let v0: Option<..> = iter.next();\n" -" println!(\"v0: {v0:?}\");\n" -"}\n" -"```" +#: src/memory-management/stack-vs-heap.md:4 +msgid "Values have fixed sizes known at compile time." msgstr "" -#: src/exercises/day-1/iterators-and-ownership.md:83 -msgid "`for` Loops" +#: src/memory-management/stack-vs-heap.md:5 +msgid "Extremely fast: just move a stack pointer." msgstr "" -#: src/exercises/day-1/iterators-and-ownership.md:85 -msgid "" -"Now that we know both `Iterator` and `IntoIterator`, we can build `for` " -"loops. They call `into_iter()` on an expression and iterates over the " -"resulting iterator:" +#: src/memory-management/stack-vs-heap.md:6 +msgid "Easy to manage: follows function calls." msgstr "" -#: src/exercises/day-1/iterators-and-ownership.md:89 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let v: Vec = vec![String::from(\"foo\"), String::" -"from(\"bar\")];\n" -"\n" -" for word in &v {\n" -" println!(\"word: {word}\");\n" -" }\n" -"\n" -" for word in v {\n" -" println!(\"word: {word}\");\n" -" }\n" -"}\n" -"```" +#: src/memory-management/stack-vs-heap.md:7 +msgid "Great memory locality." msgstr "" -#: src/exercises/day-1/iterators-and-ownership.md:103 -msgid "What is the type of `word` in each loop?" +#: src/memory-management/stack-vs-heap.md:9 +msgid "Heap: Storage of values outside of function calls." msgstr "" -#: src/exercises/day-1/iterators-and-ownership.md:105 -msgid "" -"Experiment with the code above and then consult the documentation for [`impl " -"IntoIterator for &Vec`](https://doc.rust-lang.org/std/vec/struct.Vec." -"html#impl-IntoIterator-for-%26%27a%20Vec%3CT%2C%20A%3E) and [`impl " -"IntoIterator for Vec`](https://doc.rust-lang.org/std/vec/struct.Vec." -"html#impl-IntoIterator-for-Vec%3CT%2C%20A%3E) to check your answers." +#: src/memory-management/stack-vs-heap.md:10 +msgid "Values have dynamic sizes determined at runtime." msgstr "" -#: src/welcome-day-2.md:1 -msgid "Welcome to Day 2" +#: src/memory-management/stack-vs-heap.md:11 +msgid "Slightly slower than the stack: some book-keeping needed." msgstr "" -#: src/welcome-day-2.md:3 -msgid "Now that we have seen a fair amount of Rust, we will continue with:" +#: src/memory-management/stack-vs-heap.md:12 +msgid "No guarantee of memory locality." msgstr "" -#: src/welcome-day-2.md:5 -msgid "Structs, enums, methods." +#: src/memory-management/stack.md:1 +#, fuzzy +msgid "Stack and Heap Example" +msgstr "Stack vs Heap" + +#: src/memory-management/stack.md:3 +msgid "" +"Creating a `String` puts fixed-sized metadata on the stack and dynamically " +"sized data, the actual string, on the heap:" msgstr "" -#: src/welcome-day-2.md:7 -msgid "Pattern matching: destructuring enums, structs, and arrays." +#: src/memory-management/stack.md:6 +msgid "" +"```rust,editable\n" +"fn main() {\n" +" let s1 = String::from(\"Hello\");\n" +"}\n" +"```" msgstr "" -#: src/welcome-day-2.md:9 +#: src/memory-management/stack.md:12 msgid "" -"Control flow constructs: `if`, `if let`, `while`, `while let`, `break`, and " -"`continue`." +"```bob\n" +" Stack Heap\n" +".- - - - - - - - - - - - - -. .- - - - - - - - - - - - - - - -.\n" +": : : :\n" +": s1 : : :\n" +": +-----------+-------+ : : +----+----+----+----+----+ :\n" +": | ptr | o---+---+-----+-->| H | e | l | l | o | :\n" +": | len | 5 | : : +----+----+----+----+----+ :\n" +": | capacity | 5 | : : :\n" +": +-----------+-------+ : : :\n" +": : `- - - - - - - - - - - - - - - -'\n" +"`- - - - - - - - - - - - - -'\n" +"```" msgstr "" -#: src/welcome-day-2.md:12 +#: src/memory-management/stack.md:28 msgid "" -"The Standard Library: `String`, `Option` and `Result`, `Vec`, `HashMap`, " -"`Rc` and `Arc`." +"Mention that a `String` is backed by a `Vec`, so it has a capacity and " +"length and can grow if mutable via reallocation on the heap." msgstr "" -#: src/welcome-day-2.md:15 -msgid "Modules: visibility, paths, and filesystem hierarchy." +#: src/memory-management/stack.md:30 +msgid "" +"If students ask about it, you can mention that the underlying memory is heap " +"allocated using the [System Allocator](https://doc.rust-lang.org/std/alloc/" +"struct.System.html) and custom allocators can be implemented using the " +"[Allocator API](https://doc.rust-lang.org/std/alloc/index.html)" msgstr "" -#: src/structs.md:3 -msgid "Like C and C++, Rust has support for custom structs:" +#: src/memory-management/stack.md:32 +msgid "" +"We can inspect the memory layout with `unsafe` code. However, you should " +"point out that this is rightfully unsafe!" msgstr "" -#: src/structs.md:5 +#: src/memory-management/stack.md:34 msgid "" "```rust,editable\n" -"struct Person {\n" -" name: String,\n" -" age: u8,\n" -"}\n" -"\n" "fn main() {\n" -" let mut peter = Person {\n" -" name: String::from(\"Peter\"),\n" -" age: 27,\n" -" };\n" -" println!(\"{} is {} years old\", peter.name, peter.age);\n" -" \n" -" peter.age = 28;\n" -" println!(\"{} is {} years old\", peter.name, peter.age);\n" -" \n" -" let jackie = Person {\n" -" name: String::from(\"Jackie\"),\n" -" ..peter\n" -" };\n" -" println!(\"{} is {} years old\", jackie.name, jackie.age);\n" +" let mut s1 = String::from(\"Hello\");\n" +" s1.push(' ');\n" +" s1.push_str(\"world\");\n" +" // DON'T DO THIS AT HOME! For educational purposes only.\n" +" // String provides no guarantees about its layout, so this could lead " +"to\n" +" // undefined behavior.\n" +" unsafe {\n" +" let (ptr, capacity, len): (usize, usize, usize) = std::mem::" +"transmute(s1);\n" +" println!(\"ptr = {ptr:#x}, len = {len}, capacity = {capacity}\");\n" +" }\n" "}\n" "```" msgstr "" -#: src/structs.md:31 src/enums.md:33 src/enums/sizes.md:29 src/methods.md:30 -#: src/methods/example.md:46 src/pattern-matching.md:25 -#: src/pattern-matching/match-guards.md:22 src/control-flow/blocks.md:42 -msgid "Key Points:" -msgstr "" - -#: src/structs.md:33 -msgid "Structs work like in C or C++." +#: src/memory-management/manual.md:3 +msgid "You allocate and deallocate heap memory yourself." msgstr "" -#: src/structs.md:34 -msgid "Like in C++, and unlike in C, no typedef is needed to define a type." +#: src/memory-management/manual.md:5 +msgid "" +"If not done with care, this can lead to crashes, bugs, security " +"vulnerabilities, and memory leaks." msgstr "" -#: src/structs.md:35 -msgid "Unlike in C++, there is no inheritance between structs." +#: src/memory-management/manual.md:7 +msgid "C Example" msgstr "" -#: src/structs.md:36 -msgid "" -"Methods are defined in an `impl` block, which we will see in following " -"slides." +#: src/memory-management/manual.md:9 +msgid "You must call `free` on every pointer you allocate with `malloc`:" msgstr "" -#: src/structs.md:37 +#: src/memory-management/manual.md:11 msgid "" -"This may be a good time to let people know there are different types of " -"structs. " +"```c\n" +"void foo(size_t n) {\n" +" int* int_array = malloc(n * sizeof(int));\n" +" //\n" +" // ... lots of code\n" +" //\n" +" free(int_array);\n" +"}\n" +"```" msgstr "" -#: src/structs.md:38 +#: src/memory-management/manual.md:21 msgid "" -"Zero-sized structs `e.g., struct Foo;` might be used when implementing a " -"trait on some type but don’t have any data that you want to store in the " -"value itself. " +"Memory is leaked if the function returns early between `malloc` and `free`: " +"the pointer is lost and we cannot deallocate the memory. Worse, freeing the " +"pointer twice, or accessing a freed pointer can lead to exploitable security " +"vulnerabilities." msgstr "" -#: src/structs.md:39 +#: src/memory-management/scope-based.md:3 msgid "" -"The next slide will introduce Tuple structs, used when the field names are " -"not important." +"Constructors and destructors let you hook into the lifetime of an object." msgstr "" -#: src/structs.md:40 +#: src/memory-management/scope-based.md:5 msgid "" -"The syntax `..peter` allows us to copy the majority of the fields from the " -"old struct without having to explicitly type it all out. It must always be " -"the last element." -msgstr "" - -#: src/structs/tuple-structs.md:3 -msgid "If the field names are unimportant, you can use a tuple struct:" +"By wrapping a pointer in an object, you can free memory when the object is " +"destroyed. The compiler guarantees that this happens, even if an exception " +"is raised." msgstr "" -#: src/structs/tuple-structs.md:5 +#: src/memory-management/scope-based.md:9 msgid "" -"```rust,editable\n" -"struct Point(i32, i32);\n" -"\n" -"fn main() {\n" -" let p = Point(17, 23);\n" -" println!(\"({}, {})\", p.0, p.1);\n" -"}\n" -"```" +"This is often called _resource acquisition is initialization_ (RAII) and " +"gives you smart pointers." msgstr "" -#: src/structs/tuple-structs.md:14 -msgid "This is often used for single-field wrappers (called newtypes):" +#: src/memory-management/scope-based.md:12 +msgid "C++ Example" msgstr "" -#: src/structs/tuple-structs.md:16 +#: src/memory-management/scope-based.md:14 msgid "" -"```rust,editable,compile_fail\n" -"struct PoundsOfForce(f64);\n" -"struct Newtons(f64);\n" -"\n" -"fn compute_thruster_force() -> PoundsOfForce {\n" -" todo!(\"Ask a rocket scientist at NASA\")\n" -"}\n" -"\n" -"fn set_thruster_force(force: Newtons) {\n" -" // ...\n" -"}\n" -"\n" -"fn main() {\n" -" let force = compute_thruster_force();\n" -" set_thruster_force(force);\n" +"```c++\n" +"void say_hello(std::unique_ptr person) {\n" +" std::cout << \"Hello \" << person->name << std::endl;\n" "}\n" -"\n" "```" msgstr "" -#: src/structs/tuple-structs.md:37 +#: src/memory-management/scope-based.md:20 msgid "" -"Newtypes are a great way to encode additional information about the value in " -"a primitive type, for example:" +"The `std::unique_ptr` object is allocated on the stack, and points to memory " +"allocated on the heap." msgstr "" -#: src/structs/tuple-structs.md:38 -msgid "The number is measured in some units: `Newtons` in the example above." +#: src/memory-management/scope-based.md:22 +msgid "At the end of `say_hello`, the `std::unique_ptr` destructor will run." msgstr "" -#: src/structs/tuple-structs.md:39 -msgid "" -"The value passed some validation when it was created, so you no longer have " -"to validate it again at every use: 'PhoneNumber(String)`or`OddNumber(u32)\\`." +#: src/memory-management/scope-based.md:23 +msgid "The destructor frees the `Person` object it points to." msgstr "" -#: src/structs/tuple-structs.md:40 +#: src/memory-management/scope-based.md:25 msgid "" -"Demonstrate how to add a `f64` value to a `Newtons` type by accessing the " -"single field in the newtype." +"Special move constructors are used when passing ownership to a function:" msgstr "" -#: src/structs/tuple-structs.md:41 +#: src/memory-management/scope-based.md:27 msgid "" -"Rust generally doesn’t like inexplicit things, like automatic unwrapping or " -"for instance using booleans as integers." +"```c++\n" +"std::unique_ptr person = find_person(\"Carla\");\n" +"say_hello(std::move(person));\n" +"```" msgstr "" -#: src/structs/tuple-structs.md:42 -msgid "Operator overloading is discussed on Day 3 (generics). " +#: src/memory-management/garbage-collection.md:1 +msgid "Automatic Memory Management" msgstr "" -#: src/structs/field-shorthand.md:3 +#: src/memory-management/garbage-collection.md:3 msgid "" -"If you already have variables with the right names, then you can create the " -"struct using a shorthand:" +"An alternative to manual and scope-based memory management is automatic " +"memory management:" msgstr "" -#: src/structs/field-shorthand.md:6 -msgid "" -"```rust,editable\n" -"#[derive(Debug)]\n" -"struct Person {\n" -" name: String,\n" -" age: u8,\n" -"}\n" -"\n" -"impl Person {\n" -" fn new(name: String, age: u8) -> Person {\n" -" Person { name, age }\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" let peter = Person::new(String::from(\"Peter\"), 27);\n" -" println!(\"{peter:?}\");\n" -"}\n" -"```" +#: src/memory-management/garbage-collection.md:6 +msgid "The programmer never allocates or deallocates memory explicitly." msgstr "" -#: src/structs/field-shorthand.md:27 +#: src/memory-management/garbage-collection.md:7 msgid "" -"The `new` function could be written using `Self` as a type, as it is " -"interchangeable with the struct type name" +"A garbage collector finds unused memory and deallocates it for the " +"programmer." msgstr "" -#: src/structs/field-shorthand.md:29 -msgid "" -"```rust,editable\n" -"#[derive(Debug)]\n" -"struct Person {\n" -" name: String,\n" -" age: u8,\n" -"}\n" -"impl Person {\n" -" fn new(name: String, age: u8) -> Self {\n" -" Self { name, age }\n" -" }\n" -"}\n" -"```" +#: src/memory-management/garbage-collection.md:9 +msgid "Java Example" msgstr "" -#: src/structs/field-shorthand.md:41 -msgid "" -"Implement the `Default` trait for the struct. Define some fields and use the " -"default values for the other fields." +#: src/memory-management/garbage-collection.md:11 +msgid "The `person` object is not deallocated after `sayHello` returns:" msgstr "" -#: src/structs/field-shorthand.md:43 +#: src/memory-management/garbage-collection.md:13 msgid "" -"```rust,editable\n" -"#[derive(Debug)]\n" -"struct Person {\n" -" name: String,\n" -" age: u8,\n" -"}\n" -"impl Default for Person {\n" -" fn default() -> Person {\n" -" Person {\n" -" name: \"Bot\".to_string(),\n" -" age: 0,\n" -" }\n" -" }\n" -"}\n" -"fn create_default() {\n" -" let tmp = Person {\n" -" ..Default::default()\n" -" };\n" -" let tmp = Person {\n" -" name: \"Sam\".to_string(),\n" -" ..Default::default()\n" -" };\n" +"```java\n" +"void sayHello(Person person) {\n" +" System.out.println(\"Hello \" + person.getName());\n" "}\n" "```" msgstr "" -#: src/structs/field-shorthand.md:68 -msgid "Methods are defined in the `impl` block." +#: src/memory-management/rust.md:1 +msgid "Memory Management in Rust" msgstr "" -#: src/structs/field-shorthand.md:69 -msgid "" -"Use struct update syntax to define a new structure using `peter`. Note that " -"the variable `peter` will no longer be accessible afterwards." +#: src/memory-management/rust.md:3 +msgid "Memory management in Rust is a mix:" msgstr "" -#: src/structs/field-shorthand.md:70 -msgid "" -"Use `{:#?}` when printing structs to request the `Debug` representation." +#: src/memory-management/rust.md:5 +msgid "Safe and correct like Java, but without a garbage collector." msgstr "" -#: src/enums.md:3 +#: src/memory-management/rust.md:6 msgid "" -"The `enum` keyword allows the creation of a type which has a few different " -"variants:" -msgstr "" - -#: src/enums.md:6 -msgid "" -"```rust,editable\n" -"fn generate_random_number() -> i32 {\n" -" 4 // Chosen by fair dice roll. Guaranteed to be random.\n" -"}\n" -"\n" -"#[derive(Debug)]\n" -"enum CoinFlip {\n" -" Heads,\n" -" Tails,\n" -"}\n" -"\n" -"fn flip_coin() -> CoinFlip {\n" -" let random_number = generate_random_number();\n" -" if random_number % 2 == 0 {\n" -" return CoinFlip::Heads;\n" -" } else {\n" -" return CoinFlip::Tails;\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" println!(\"You got: {:?}\", flip_coin());\n" -"}\n" -"```" +"Depending on which abstraction (or combination of abstractions) you choose, " +"can be a single unique pointer, reference counted, or atomically reference " +"counted." msgstr "" -#: src/enums.md:35 -msgid "Enumerations allow you to collect a set of values under one type" +#: src/memory-management/rust.md:7 +msgid "Scope-based like C++, but the compiler enforces full adherence." msgstr "" -#: src/enums.md:36 +#: src/memory-management/rust.md:8 msgid "" -"This page offers an enum type `CoinFlip` with two variants `Heads` and " -"`Tail`. You might note the namespace when using variants." +"A Rust user can choose the right abstraction for the situation, some even " +"have no cost at runtime like C." msgstr "" -#: src/enums.md:37 -msgid "This might be a good time to compare Structs and Enums:" +#: src/memory-management/rust.md:10 +msgid "Rust achieves this by modeling _ownership_ explicitly." msgstr "" -#: src/enums.md:38 +#: src/memory-management/rust.md:14 msgid "" -"In both, you can have a simple version without fields (unit struct) or one " -"with different types of fields (variant payloads). " +"If asked how at this point, you can mention that in Rust this is usually " +"handled by RAII wrapper types such as [Box](https://doc.rust-lang.org/std/" +"boxed/struct.Box.html), [Vec](https://doc.rust-lang.org/std/vec/struct.Vec." +"html), [Rc](https://doc.rust-lang.org/std/rc/struct.Rc.html), or [Arc]" +"(https://doc.rust-lang.org/std/sync/struct.Arc.html). These encapsulate " +"ownership and memory allocation via various means, and prevent the potential " +"errors in C." msgstr "" -#: src/enums.md:39 -msgid "In both, associated functions are defined within an `impl` block." +#: src/memory-management/rust.md:16 +msgid "" +"You may be asked about destructors here, the [Drop](https://doc.rust-lang." +"org/std/ops/trait.Drop.html) trait is the Rust equivalent." msgstr "" -#: src/enums.md:40 -msgid "" -"You could even implement the different variants of an enum with separate " -"structs but then they wouldn’t be the same type as they would if they were " -"all defined in an enum. " +#: src/memory-management/comparison.md:3 +msgid "Here is a rough comparison of the memory management techniques." msgstr "" -#: src/enums/variant-payloads.md:3 -msgid "" -"You can define richer enums where the variants carry data. You can then use " -"the `match` statement to extract the data from each variant:" +#: src/memory-management/comparison.md:5 +msgid "Pros of Different Memory Management Techniques" msgstr "" -#: src/enums/variant-payloads.md:6 -msgid "" -"```rust,editable\n" -"enum WebEvent {\n" -" PageLoad, // Variant without payload\n" -" KeyPress(char), // Tuple struct variant\n" -" Click { x: i64, y: i64 }, // Full struct variant\n" -"}\n" -"\n" -"#[rustfmt::skip]\n" -"fn inspect(event: WebEvent) {\n" -" match event {\n" -" WebEvent::PageLoad => println!(\"page loaded\"),\n" -" WebEvent::KeyPress(c) => println!(\"pressed '{c}'\"),\n" -" WebEvent::Click { x, y } => println!(\"clicked at x={x}, y={y}\"),\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" let load = WebEvent::PageLoad;\n" -" let press = WebEvent::KeyPress('x');\n" -" let click = WebEvent::Click { x: 20, y: 80 };\n" -"\n" -" inspect(load);\n" -" inspect(press);\n" -" inspect(click);\n" -"}\n" -"```" +#: src/memory-management/comparison.md:7 src/memory-management/comparison.md:22 +msgid "Manual like C:" msgstr "" -#: src/enums/variant-payloads.md:35 -msgid "" -"The values in the enum variants can only be accessed after being pattern " -"matched. The pattern binds references to the fields in the \"match arm\" " -"after the `=>`." +#: src/memory-management/comparison.md:8 src/memory-management/comparison.md:14 +#: src/memory-management/comparison.md:17 +msgid "No runtime overhead." msgstr "" -#: src/enums/variant-payloads.md:36 -msgid "" -"The expression is matched against the patterns from top to bottom. There is " -"no fall-through like in C or C++." +#: src/memory-management/comparison.md:9 src/memory-management/comparison.md:26 +msgid "Automatic like Java:" msgstr "" -#: src/enums/variant-payloads.md:37 -msgid "" -"The match expression has a value. The value is the last expression in the " -"match arm which was executed." +#: src/memory-management/comparison.md:10 +msgid "Fully automatic." msgstr "" -#: src/enums/variant-payloads.md:38 -msgid "" -"Starting from the top we look for what pattern matches the value then run " -"the code following the arrow. Once we find a match, we stop. " +#: src/memory-management/comparison.md:11 +#: src/memory-management/comparison.md:18 +msgid "Safe and correct." msgstr "" -#: src/enums/variant-payloads.md:39 -msgid "" -"Demonstrate what happens when the search is inexhaustive. Note the advantage " -"the Rust compiler provides by confirming when all cases are handled. " +#: src/memory-management/comparison.md:12 +#: src/memory-management/comparison.md:29 +msgid "Scope-based like C++:" msgstr "" -#: src/enums/variant-payloads.md:40 -msgid "`match` inspects a hidden discriminant field in the `enum`." +#: src/memory-management/comparison.md:13 +msgid "Partially automatic." msgstr "" -#: src/enums/variant-payloads.md:41 -msgid "" -"It is possible to retrieve the discriminant by calling `std::mem::" -"discriminant()`" +#: src/memory-management/comparison.md:15 +msgid "Compiler-enforced scope-based like Rust:" msgstr "" -#: src/enums/variant-payloads.md:42 -msgid "" -"This is useful, for example, if implementing `PartialEq` for structs where " -"comparing field values doesn't affect equality." +#: src/memory-management/comparison.md:16 +msgid "Enforced by compiler." msgstr "" -#: src/enums/variant-payloads.md:43 -msgid "" -"`WebEvent::Click { ... }` is not exactly the same as `WebEvent::" -"Click(Click)` with a top level `struct Click { ... }`. The inlined version " -"cannot implement traits, for example." +#: src/memory-management/comparison.md:20 +msgid "Cons of Different Memory Management Techniques" msgstr "" -#: src/enums/sizes.md:3 -msgid "" -"Rust enums are packed tightly, taking constraints due to alignment into " -"account:" +#: src/memory-management/comparison.md:23 +msgid "Use-after-free." msgstr "" -#: src/enums/sizes.md:5 -msgid "" -"```rust,editable\n" -"use std::mem::{align_of, size_of};\n" -"\n" -"macro_rules! dbg_size {\n" -" ($t:ty) => {\n" -" println!(\"{}: size {} bytes, align: {} bytes\",\n" -" stringify!($t), size_of::<$t>(), align_of::<$t>());\n" -" };\n" -"}\n" -"\n" -"enum Foo {\n" -" A,\n" -" B,\n" -"}\n" -"\n" -"fn main() {\n" -" dbg_size!(Foo);\n" -"}\n" -"```" +#: src/memory-management/comparison.md:24 +msgid "Double-frees." msgstr "" -#: src/enums/sizes.md:25 -msgid "" -"See the [Rust Reference](https://doc.rust-lang.org/reference/type-layout." -"html)." +#: src/memory-management/comparison.md:25 +msgid "Memory leaks." msgstr "" -#: src/enums/sizes.md:31 -msgid "" -"Internally Rust is using a field (discriminant) to keep track of the enum " -"variant." +#: src/memory-management/comparison.md:27 +msgid "Garbage collection pauses." msgstr "" -#: src/enums/sizes.md:33 -msgid "" -"You can control the discriminant if needed (e.g., for compatibility with C):" +#: src/memory-management/comparison.md:28 +msgid "Destructor delays." msgstr "" -#: src/enums/sizes.md:35 -msgid "" -"```rust,editable\n" -"#[repr(u32)]\n" -"enum Bar {\n" -" A, // 0\n" -" B = 10000,\n" -" C, // 10001\n" -"}\n" -"\n" -"fn main() {\n" -" println!(\"A: {}\", Bar::A as u32);\n" -" println!(\"B: {}\", Bar::B as u32);\n" -" println!(\"C: {}\", Bar::C as u32);\n" -"}\n" -"```" +#: src/memory-management/comparison.md:30 +msgid "Complex, opt-in by programmer (on C++)." msgstr "" -#: src/enums/sizes.md:50 -msgid "" -"Without `repr`, the discriminant type takes 2 bytes, because 10001 fits 2 " -"bytes." +#: src/memory-management/comparison.md:31 +msgid "Circular references can lead to memory leaks" msgstr "" -#: src/enums/sizes.md:54 -msgid "Try out other types such as" +#: src/memory-management/comparison.md:32 +msgid "Potential runtime overhead" msgstr "" -#: src/enums/sizes.md:56 -msgid "`dbg_size!(bool)`: size 1 bytes, align: 1 bytes," +#: src/memory-management/comparison.md:33 +msgid "Compiler-enforced and scope-based like Rust:" msgstr "" -#: src/enums/sizes.md:57 -msgid "" -"`dbg_size!(Option)`: size 1 bytes, align: 1 bytes (niche optimization, " -"see below)," +#: src/memory-management/comparison.md:34 +msgid "Some upfront complexity." msgstr "" -#: src/enums/sizes.md:58 -msgid "`dbg_size!(&i32)`: size 8 bytes, align: 8 bytes (on a 64-bit machine)," +#: src/memory-management/comparison.md:35 +msgid "Can reject valid programs." msgstr "" -#: src/enums/sizes.md:59 +#: src/ownership.md:3 msgid "" -"`dbg_size!(Option<&i32>)`: size 8 bytes, align: 8 bytes (null pointer " -"optimization, see below)." +"All variable bindings have a _scope_ where they are valid and it is an error " +"to use a variable outside its scope:" msgstr "" -#: src/enums/sizes.md:61 +#: src/ownership.md:6 msgid "" -"Niche optimization: Rust will merge use unused bit patterns for the enum " -"discriminant." +"```rust,editable,compile_fail\n" +"struct Point(i32, i32);\n" +"\n" +"fn main() {\n" +" {\n" +" let p = Point(3, 4);\n" +" println!(\"x: {}\", p.0);\n" +" }\n" +" println!(\"y: {}\", p.1);\n" +"}\n" +"```" msgstr "" -#: src/enums/sizes.md:64 +#: src/ownership.md:18 msgid "" -"Null pointer optimization: For [some types](https://doc.rust-lang.org/std/" -"option/#representation), Rust guarantees that `size_of::()` equals " -"`size_of::>()`." +"At the end of the scope, the variable is _dropped_ and the data is freed." msgstr "" -#: src/enums/sizes.md:68 -msgid "" -"Example code if you want to show how the bitwise representation _may_ look " -"like in practice. It's important to note that the compiler provides no " -"guarantees regarding this representation, therefore this is totally unsafe." +#: src/ownership.md:19 +msgid "A destructor can run here to free up resources." msgstr "" -#: src/enums/sizes.md:71 -msgid "" -"```rust,editable\n" -"use std::mem::transmute;\n" -"\n" -"macro_rules! dbg_bits {\n" -" ($e:expr, $bit_type:ty) => {\n" -" println!(\"- {}: {:#x}\", stringify!($e), transmute::<_, " -"$bit_type>($e));\n" -" };\n" -"}\n" -"\n" -"fn main() {\n" -" // TOTALLY UNSAFE. Rust provides no guarantees about the bitwise\n" -" // representation of types.\n" -" unsafe {\n" -" println!(\"Bitwise representation of bool\");\n" -" dbg_bits!(false, u8);\n" -" dbg_bits!(true, u8);\n" -"\n" -" println!(\"Bitwise representation of Option\");\n" -" dbg_bits!(None::, u8);\n" -" dbg_bits!(Some(false), u8);\n" -" dbg_bits!(Some(true), u8);\n" -"\n" -" println!(\"Bitwise representation of Option>\");\n" -" dbg_bits!(Some(Some(false)), u8);\n" -" dbg_bits!(Some(Some(true)), u8);\n" -" dbg_bits!(Some(None::), u8);\n" -" dbg_bits!(None::>, u8);\n" -"\n" -" println!(\"Bitwise representation of Option<&i32>\");\n" -" dbg_bits!(None::<&i32>, usize);\n" -" dbg_bits!(Some(&0i32), usize);\n" -" }\n" -"}\n" -"```" +#: src/ownership.md:20 +msgid "We say that the variable _owns_ the value." msgstr "" -#: src/enums/sizes.md:106 -msgid "" -"More complex example if you want to discuss what happens when we chain more " -"than 256 `Option`s together." +#: src/ownership/move-semantics.md:3 +msgid "An assignment will transfer _ownership_ between variables:" msgstr "" -#: src/enums/sizes.md:108 +#: src/ownership/move-semantics.md:5 msgid "" "```rust,editable\n" -"#![recursion_limit = \"1000\"]\n" -"\n" -"use std::mem::transmute;\n" -"\n" -"macro_rules! dbg_bits {\n" -" ($e:expr, $bit_type:ty) => {\n" -" println!(\"- {}: {:#x}\", stringify!($e), transmute::<_, " -"$bit_type>($e));\n" -" };\n" -"}\n" -"\n" -"// Macro to wrap a value in 2^n Some() where n is the number of \"@\" " -"signs.\n" -"// Increasing the recursion limit is required to evaluate this macro.\n" -"macro_rules! many_options {\n" -" ($value:expr) => { Some($value) };\n" -" ($value:expr, @) => {\n" -" Some(Some($value))\n" -" };\n" -" ($value:expr, @ $($more:tt)+) => {\n" -" many_options!(many_options!($value, $($more)+), $($more)+)\n" -" };\n" -"}\n" -"\n" "fn main() {\n" -" // TOTALLY UNSAFE. Rust provides no guarantees about the bitwise\n" -" // representation of types.\n" -" unsafe {\n" -" assert_eq!(many_options!(false), Some(false));\n" -" assert_eq!(many_options!(false, @), Some(Some(false)));\n" -" assert_eq!(many_options!(false, @@), " -"Some(Some(Some(Some(false)))));\n" -"\n" -" println!(\"Bitwise representation of a chain of 128 Option's.\");\n" -" dbg_bits!(many_options!(false, @@@@@@@), u8);\n" -" dbg_bits!(many_options!(true, @@@@@@@), u8);\n" -"\n" -" println!(\"Bitwise representation of a chain of 256 Option's.\");\n" -" dbg_bits!(many_options!(false, @@@@@@@@), u16);\n" -" dbg_bits!(many_options!(true, @@@@@@@@), u16);\n" -"\n" -" println!(\"Bitwise representation of a chain of 257 Option's.\");\n" -" dbg_bits!(many_options!(Some(false), @@@@@@@@), u16);\n" -" dbg_bits!(many_options!(Some(true), @@@@@@@@), u16);\n" -" dbg_bits!(many_options!(None::, @@@@@@@@), u16);\n" -" }\n" +" let s1: String = String::from(\"Hello!\");\n" +" let s2: String = s1;\n" +" println!(\"s2: {s2}\");\n" +" // println!(\"s1: {s1}\");\n" "}\n" "```" msgstr "" -#: src/methods.md:3 -msgid "" -"Rust allows you to associate functions with your new types. You do this with " -"an `impl` block:" +#: src/ownership/move-semantics.md:14 +msgid "The assignment of `s1` to `s2` transfers ownership." msgstr "" -#: src/methods.md:6 -msgid "" -"```rust,editable\n" -"#[derive(Debug)]\n" -"struct Person {\n" -" name: String,\n" -" age: u8,\n" -"}\n" -"\n" -"impl Person {\n" -" fn say_hello(&self) {\n" -" println!(\"Hello, my name is {}\", self.name);\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" let peter = Person {\n" -" name: String::from(\"Peter\"),\n" -" age: 27,\n" -" };\n" -" peter.say_hello();\n" -"}\n" -"```" +#: src/ownership/move-semantics.md:15 +msgid "When `s1` goes out of scope, nothing happens: it does not own anything." msgstr "" -#: src/methods.md:31 -msgid "It can be helpful to introduce methods by comparing them to functions." +#: src/ownership/move-semantics.md:16 +msgid "When `s2` goes out of scope, the string data is freed." msgstr "" -#: src/methods.md:32 -msgid "" -"Methods are called on an instance of a type (such as a struct or enum), the " -"first parameter represents the instance as `self`." +#: src/ownership/move-semantics.md:17 +msgid "There is always _exactly_ one variable binding which owns a value." msgstr "" -#: src/methods.md:33 +#: src/ownership/move-semantics.md:21 msgid "" -"Developers may choose to use methods to take advantage of method receiver " -"syntax and to help keep them more organized. By using methods we can keep " -"all the implementation code in one predictable place." +"Mention that this is the opposite of the defaults in C++, which copies by " +"value unless you use `std::move` (and the move constructor is defined!)." msgstr "" -#: src/methods.md:34 -msgid "Point out the use of the keyword `self`, a method receiver. " +#: src/ownership/move-semantics.md:23 +msgid "" +"It is only the ownership that moves. Whether any machine code is generated " +"to manipulate the data itself is a matter of optimization, and such copies " +"are aggressively optimized away." msgstr "" -#: src/methods.md:35 +#: src/ownership/move-semantics.md:25 msgid "" -"Show that it is an abbreviated term for `self:&Self` and perhaps show how " -"the struct name could also be used. " +"Simple values (such as integers) can be marked `Copy` (see later slides)." msgstr "" -#: src/methods.md:36 -msgid "" -"Explain that `Self` is a type alias for the type the `impl` block is in and " -"can be used elsewhere in the block." +#: src/ownership/move-semantics.md:27 +msgid "In Rust, clones are explicit (by using `clone`)." msgstr "" -#: src/methods.md:37 +#: src/ownership/moved-strings-rust.md:3 msgid "" -"Note how `self` is used like other structs and dot notation can be used to " -"refer to individual fields." +"```rust,editable\n" +"fn main() {\n" +" let s1: String = String::from(\"Rust\");\n" +" let s2: String = s1;\n" +"}\n" +"```" msgstr "" -#: src/methods.md:38 -msgid "" -"This might be a good time to demonstrate how the `&self` differs from `self` " -"by modifying the code and trying to run say_hello twice." +#: src/ownership/moved-strings-rust.md:10 +msgid "The heap data from `s1` is reused for `s2`." msgstr "" -#: src/methods.md:39 -msgid "We describe the distinction between method receivers next." +#: src/ownership/moved-strings-rust.md:11 +msgid "When `s1` goes out of scope, nothing happens (it has been moved from)." msgstr "" -#: src/methods/receiver.md:3 -msgid "" -"The `&self` above indicates that the method borrows the object immutably. " -"There are other possible receivers for a method:" +#: src/ownership/moved-strings-rust.md:13 +msgid "Before move to `s2`:" msgstr "" -#: src/methods/receiver.md:6 +#: src/ownership/moved-strings-rust.md:15 msgid "" -"`&self`: borrows the object from the caller using a shared and immutable " -"reference. The object can be used again afterwards." +"```bob\n" +" Stack Heap\n" +".- - - - - - - - - - - - - -. .- - - - - - - - - - - - - -.\n" +": : : :\n" +": s1 : : :\n" +": +-----------+-------+ : : +----+----+----+----+ :\n" +": | ptr | o---+---+-----+-->| R | u | s | t | :\n" +": | len | 4 | : : +----+----+----+----+ :\n" +": | capacity | 4 | : : :\n" +": +-----------+-------+ : : :\n" +": : `- - - - - - - - - - - - - -'\n" +": :\n" +"`- - - - - - - - - - - - - -'\n" +"```" msgstr "" -#: src/methods/receiver.md:8 -msgid "" -"`&mut self`: borrows the object from the caller using a unique and mutable " -"reference. The object can be used again afterwards." +#: src/ownership/moved-strings-rust.md:30 +msgid "After move to `s2`:" msgstr "" -#: src/methods/receiver.md:10 +#: src/ownership/moved-strings-rust.md:32 msgid "" -"`self`: takes ownership of the object and moves it away from the caller. The " -"method becomes the owner of the object. The object will be dropped " -"(deallocated) when the method returns, unless its ownership is explicitly " -"transmitted. Complete ownership does not automatically mean mutability." +"```bob\n" +" Stack Heap\n" +".- - - - - - - - - - - - - -. .- - - - - - - - - - - - - -.\n" +": : : :\n" +": s1 \"(inaccessible)\" : : :\n" +": +-----------+-------+ : : +----+----+----+----+ :\n" +": | ptr | o---+---+--+--+-->| R | u | s | t | :\n" +": | len | 4 | : | : +----+----+----+----+ :\n" +": | capacity | 4 | : | : :\n" +": +-----------+-------+ : | : :\n" +": : | `- - - - - - - - - - - - - -'\n" +": s2 : |\n" +": +-----------+-------+ : |\n" +": | ptr | o---+---+--'\n" +": | len | 4 | :\n" +": | capacity | 4 | :\n" +": +-----------+-------+ :\n" +": :\n" +"`- - - - - - - - - - - - - -'\n" +"```" msgstr "" -#: src/methods/receiver.md:14 -msgid "`mut self`: same as above, but the method can mutate the object. " +#: src/ownership/double-free-modern-cpp.md:1 +#, fuzzy +msgid "Extra Work in Modern C++" +msgstr "Modern C++'da Çifte Serbestlik" + +#: src/ownership/double-free-modern-cpp.md:3 +msgid "Modern C++ solves this differently:" msgstr "" -#: src/methods/receiver.md:15 +#: src/ownership/double-free-modern-cpp.md:5 msgid "" -"No receiver: this becomes a static method on the struct. Typically used to " -"create constructors which are called `new` by convention." +"```c++\n" +"std::string s1 = \"Cpp\";\n" +"std::string s2 = s1; // Duplicate the data in s1.\n" +"```" msgstr "" -#: src/methods/receiver.md:18 +#: src/ownership/double-free-modern-cpp.md:10 msgid "" -"Beyond variants on `self`, there are also [special wrapper types](https://" -"doc.rust-lang.org/reference/special-types-and-traits.html) allowed to be " -"receiver types, such as `Box`." +"The heap data from `s1` is duplicated and `s2` gets its own independent copy." msgstr "" -#: src/methods/receiver.md:24 -msgid "" -"Consider emphasizing \"shared and immutable\" and \"unique and mutable\". " -"These constraints always come together in Rust due to borrow checker rules, " -"and `self` is no exception. It isn't possible to reference a struct from " -"multiple locations and call a mutating (`&mut self`) method on it." +#: src/ownership/double-free-modern-cpp.md:11 +msgid "When `s1` and `s2` go out of scope, they each free their own memory." msgstr "" -#: src/methods/example.md:3 +#: src/ownership/double-free-modern-cpp.md:13 +msgid "Before copy-assignment:" +msgstr "" + +#: src/ownership/double-free-modern-cpp.md:16 +msgid "" +"```bob\n" +" Stack Heap\n" +".- - - - - - - - - - - - - -. .- - - - - - - - - - - -.\n" +": : : :\n" +": s1 : : :\n" +": +-----------+-------+ : : +----+----+----+ :\n" +": | ptr | o---+---+--+--+-->| C | p | p | :\n" +": | len | 3 | : : +----+----+----+ :\n" +": | capacity | 3 | : : :\n" +": +-----------+-------+ : : :\n" +": : `- - - - - - - - - - - -'\n" +"`- - - - - - - - - - - - - -'\n" +"```" +msgstr "" + +#: src/ownership/double-free-modern-cpp.md:30 +msgid "After copy-assignment:" +msgstr "" + +#: src/ownership/double-free-modern-cpp.md:32 +msgid "" +"```bob\n" +" Stack Heap\n" +".- - - - - - - - - - - - - -. .- - - - - - - - - - - -.\n" +": : : :\n" +": s1 : : :\n" +": +-----------+-------+ : : +----+----+----+ :\n" +": | ptr | o---+---+--+--+-->| C | p | p | :\n" +": | len | 3 | : : +----+----+----+ :\n" +": | capacity | 3 | : : :\n" +": +-----------+-------+ : : :\n" +": : : :\n" +": s2 : : :\n" +": +-----------+-------+ : : +----+----+----+ :\n" +": | ptr | o---+---+-----+-->| C | p | p | :\n" +": | len | 3 | : : +----+----+----+ :\n" +": | capacity | 3 | : : :\n" +": +-----------+-------+ : : :\n" +": : `- - - - - - - - - - - -'\n" +"`- - - - - - - - - - - - - -'\n" +"```" +msgstr "" + +#: src/ownership/moves-function-calls.md:3 +msgid "" +"When you pass a value to a function, the value is assigned to the function " +"parameter. This transfers ownership:" +msgstr "" + +#: src/ownership/moves-function-calls.md:6 msgid "" "```rust,editable\n" -"#[derive(Debug)]\n" -"struct Race {\n" -" name: String,\n" -" laps: Vec,\n" -"}\n" -"\n" -"impl Race {\n" -" fn new(name: &str) -> Race { // No receiver, a static method\n" -" Race { name: String::from(name), laps: Vec::new() }\n" -" }\n" -"\n" -" fn add_lap(&mut self, lap: i32) { // Exclusive borrowed read-write " -"access to self\n" -" self.laps.push(lap);\n" -" }\n" -"\n" -" fn print_laps(&self) { // Shared and read-only borrowed access to self\n" -" println!(\"Recorded {} laps for {}:\", self.laps.len(), self.name);\n" -" for (idx, lap) in self.laps.iter().enumerate() {\n" -" println!(\"Lap {idx}: {lap} sec\");\n" -" }\n" -" }\n" -"\n" -" fn finish(self) { // Exclusive ownership of self\n" -" let total = self.laps.iter().sum::();\n" -" println!(\"Race {} is finished, total lap time: {}\", self.name, " -"total);\n" -" }\n" +"fn say_hello(name: String) {\n" +" println!(\"Hello {name}\")\n" "}\n" "\n" "fn main() {\n" -" let mut race = Race::new(\"Monaco Grand Prix\");\n" -" race.add_lap(70);\n" -" race.add_lap(68);\n" -" race.print_laps();\n" -" race.add_lap(71);\n" -" race.print_laps();\n" -" race.finish();\n" -" // race.add_lap(42);\n" +" let name = String::from(\"Alice\");\n" +" say_hello(name);\n" +" // say_hello(name);\n" "}\n" "```" msgstr "" -#: src/methods/example.md:47 -msgid "All four methods here use a different method receiver." +#: src/ownership/moves-function-calls.md:20 +msgid "" +"With the first call to `say_hello`, `main` gives up ownership of `name`. " +"Afterwards, `name` cannot be used anymore within `main`." msgstr "" -#: src/methods/example.md:48 +#: src/ownership/moves-function-calls.md:21 msgid "" -"You can point out how that changes what the function can do with the " -"variable values and if/how it can be used again in `main`." +"The heap memory allocated for `name` will be freed at the end of the " +"`say_hello` function." msgstr "" -#: src/methods/example.md:49 +#: src/ownership/moves-function-calls.md:22 msgid "" -"You can showcase the error that appears when trying to call `finish` twice." +"`main` can retain ownership if it passes `name` as a reference (`&name`) and " +"if `say_hello` accepts a reference as a parameter." msgstr "" -#: src/methods/example.md:50 +#: src/ownership/moves-function-calls.md:23 msgid "" -"Note that although the method receivers are different, the non-static " -"functions are called the same way in the main body. Rust enables automatic " -"referencing and dereferencing when calling methods. Rust automatically adds " -"in the `&`, `*`, `muts` so that that object matches the method signature." +"Alternatively, `main` can pass a clone of `name` in the first call (`name." +"clone()`)." msgstr "" -#: src/methods/example.md:51 +#: src/ownership/moves-function-calls.md:24 msgid "" -"You might point out that `print_laps` is using a vector that is iterated " -"over. We describe vectors in more detail in the afternoon. " +"Rust makes it harder than C++ to inadvertently create copies by making move " +"semantics the default, and by forcing programmers to make clones explicit." msgstr "" -#: src/pattern-matching.md:3 +#: src/ownership/copy-clone.md:3 msgid "" -"The `match` keyword let you match a value against one or more _patterns_. " -"The comparisons are done from top to bottom and the first match wins." +"While move semantics are the default, certain types are copied by default:" msgstr "" -#: src/pattern-matching.md:6 -msgid "The patterns can be simple values, similarly to `switch` in C and C++:" +#: src/ownership/copy-clone.md:5 +msgid "" +"```rust,editable\n" +"fn main() {\n" +" let x = 42;\n" +" let y = x;\n" +" println!(\"x: {x}\");\n" +" println!(\"y: {y}\");\n" +"}\n" +"```" msgstr "" -#: src/pattern-matching.md:8 +#: src/ownership/copy-clone.md:14 +msgid "These types implement the `Copy` trait." +msgstr "" + +#: src/ownership/copy-clone.md:16 +msgid "You can opt-in your own types to use copy semantics:" +msgstr "" + +#: src/ownership/copy-clone.md:18 msgid "" "```rust,editable\n" -"fn main() {\n" -" let input = 'x';\n" +"#[derive(Copy, Clone, Debug)]\n" +"struct Point(i32, i32);\n" "\n" -" match input {\n" -" 'q' => println!(\"Quitting\"),\n" -" 'a' | 's' | 'w' | 'd' => println!(\"Moving around\"),\n" -" '0'..='9' => println!(\"Number input\"),\n" -" _ => println!(\"Something else\"),\n" -" }\n" +"fn main() {\n" +" let p1 = Point(3, 4);\n" +" let p2 = p1;\n" +" println!(\"p1: {p1:?}\");\n" +" println!(\"p2: {p2:?}\");\n" "}\n" "```" msgstr "" -#: src/pattern-matching.md:21 -msgid "The `_` pattern is a wildcard pattern which matches any value." +#: src/ownership/copy-clone.md:30 +msgid "After the assignment, both `p1` and `p2` own their own data." msgstr "" -#: src/pattern-matching.md:26 +#: src/ownership/copy-clone.md:31 +msgid "We can also use `p1.clone()` to explicitly copy the data." +msgstr "" + +#: src/ownership/copy-clone.md:35 +msgid "Copying and cloning are not the same thing:" +msgstr "" + +#: src/ownership/copy-clone.md:37 msgid "" -"You might point out how some specific characters are being used when in a " -"pattern" +"Copying refers to bitwise copies of memory regions and does not work on " +"arbitrary objects." msgstr "" -#: src/pattern-matching.md:27 -msgid "`|` as an `or`" +#: src/ownership/copy-clone.md:38 +msgid "" +"Copying does not allow for custom logic (unlike copy constructors in C++)." msgstr "" -#: src/pattern-matching.md:28 -msgid "`..` can expand as much as it needs to be" +#: src/ownership/copy-clone.md:39 +msgid "" +"Cloning is a more general operation and also allows for custom behavior by " +"implementing the `Clone` trait." msgstr "" -#: src/pattern-matching.md:29 -msgid "`1..=5` represents an inclusive range" +#: src/ownership/copy-clone.md:40 +msgid "Copying does not work on types that implement the `Drop` trait." msgstr "" -#: src/pattern-matching.md:30 -msgid "`_` is a wild card" +#: src/ownership/copy-clone.md:42 src/ownership/lifetimes-function-calls.md:29 +msgid "In the above example, try the following:" msgstr "" -#: src/pattern-matching.md:31 +#: src/ownership/copy-clone.md:44 msgid "" -"It can be useful to show how binding works, by for instance replacing a " -"wildcard character with a variable, or removing the quotes around `q`." +"Add a `String` field to `struct Point`. It will not compile because `String` " +"is not a `Copy` type." msgstr "" -#: src/pattern-matching.md:32 -msgid "You can demonstrate matching on a reference." +#: src/ownership/copy-clone.md:45 +msgid "" +"Remove `Copy` from the `derive` attribute. The compiler error is now in the " +"`println!` for `p1`." msgstr "" -#: src/pattern-matching.md:33 +#: src/ownership/copy-clone.md:46 +msgid "Show that it works if you clone `p1` instead." +msgstr "" + +#: src/ownership/copy-clone.md:48 msgid "" -"This might be a good time to bring up the concept of irrefutable patterns, " -"as the term can show up in error messages." +"If students ask about `derive`, it is sufficient to say that this is a way " +"to generate code in Rust at compile time. In this case the default " +"implementations of `Copy` and `Clone` traits are generated." msgstr "" -#: src/pattern-matching/destructuring-enums.md:3 +#: src/ownership/borrowing.md:3 msgid "" -"Patterns can also be used to bind variables to parts of your values. This is " -"how you inspect the structure of your types. Let us start with a simple " -"`enum` type:" +"Instead of transferring ownership when calling a function, you can let a " +"function _borrow_ the value:" msgstr "" -#: src/pattern-matching/destructuring-enums.md:6 +#: src/ownership/borrowing.md:6 msgid "" "```rust,editable\n" -"enum Result {\n" -" Ok(i32),\n" -" Err(String),\n" -"}\n" +"#[derive(Debug)]\n" +"struct Point(i32, i32);\n" "\n" -"fn divide_in_two(n: i32) -> Result {\n" -" if n % 2 == 0 {\n" -" Result::Ok(n / 2)\n" -" } else {\n" -" Result::Err(format!(\"cannot divide {n} into two equal parts\"))\n" -" }\n" +"fn add(p1: &Point, p2: &Point) -> Point {\n" +" Point(p1.0 + p2.0, p1.1 + p2.1)\n" "}\n" "\n" "fn main() {\n" -" let n = 100;\n" -" match divide_in_two(n) {\n" -" Result::Ok(half) => println!(\"{n} divided in two is {half}\"),\n" -" Result::Err(msg) => println!(\"sorry, an error happened: {msg}\"),\n" -" }\n" +" let p1 = Point(3, 4);\n" +" let p2 = Point(10, 20);\n" +" let p3 = add(&p1, &p2);\n" +" println!(\"{p1:?} + {p2:?} = {p3:?}\");\n" "}\n" "```" msgstr "" -#: src/pattern-matching/destructuring-enums.md:29 -msgid "" -"Here we have used the arms to _destructure_ the `Result` value. In the first " -"arm, `half` is bound to the value inside the `Ok` variant. In the second " -"arm, `msg` is bound to the error message." +#: src/ownership/borrowing.md:22 +msgid "The `add` function _borrows_ two points and returns a new point." msgstr "" -#: src/pattern-matching/destructuring-enums.md:36 -msgid "" -"The `if`/`else` expression is returning an enum that is later unpacked with " -"a `match`." +#: src/ownership/borrowing.md:23 +msgid "The caller retains ownership of the inputs." msgstr "" -#: src/pattern-matching/destructuring-enums.md:37 -msgid "" -"You can try adding a third variant to the enum definition and displaying the " -"errors when running the code. Point out the places where your code is now " -"inexhaustive and how the compiler tries to give you hints." +#: src/ownership/borrowing.md:27 +msgid "Notes on stack returns:" msgstr "" -#: src/pattern-matching/destructuring-structs.md:3 -msgid "You can also destructure `structs`:" +#: src/ownership/borrowing.md:28 +msgid "" +"Demonstrate that the return from `add` is cheap because the compiler can " +"eliminate the copy operation. Change the above code to print stack addresses " +"and run it on the [Playground](https://play.rust-lang.org/) or look at the " +"assembly in [Godbolt](https://rust.godbolt.org/). In the \"DEBUG\" " +"optimization level, the addresses should change, while they stay the same " +"when changing to the \"RELEASE\" setting:" msgstr "" -#: src/pattern-matching/destructuring-structs.md:5 +#: src/ownership/borrowing.md:30 msgid "" "```rust,editable\n" -"struct Foo {\n" -" x: (u32, u32),\n" -" y: u32,\n" +"#[derive(Debug)]\n" +"struct Point(i32, i32);\n" +"\n" +"fn add(p1: &Point, p2: &Point) -> Point {\n" +" let p = Point(p1.0 + p2.0, p1.1 + p2.1);\n" +" println!(\"&p.0: {:p}\", &p.0);\n" +" p\n" "}\n" "\n" -"#[rustfmt::skip]\n" -"fn main() {\n" -" let foo = Foo { x: (1, 2), y: 3 };\n" -" match foo {\n" -" Foo { x: (1, b), y } => println!(\"x.0 = 1, b = {b}, y = {y}\"),\n" -" Foo { y: 2, x: i } => println!(\"y = 2, x = {i:?}\"),\n" -" Foo { y, .. } => println!(\"y = {y}, other fields were " -"ignored\"),\n" -" }\n" +"pub fn main() {\n" +" let p1 = Point(3, 4);\n" +" let p2 = Point(10, 20);\n" +" let p3 = add(&p1, &p2);\n" +" println!(\"&p3.0: {:p}\", &p3.0);\n" +" println!(\"{p1:?} + {p2:?} = {p3:?}\");\n" "}\n" "```" msgstr "" -#: src/pattern-matching/destructuring-structs.md:23 -msgid "Change the literal values in `foo` to match with the other patterns." -msgstr "" - -#: src/pattern-matching/destructuring-structs.md:24 -msgid "Add a new field to `Foo` and make changes to the pattern as needed." +#: src/ownership/borrowing.md:48 +msgid "The Rust compiler can do return value optimization (RVO)." msgstr "" -#: src/pattern-matching/destructuring-structs.md:25 +#: src/ownership/borrowing.md:49 msgid "" -"The distinction between a capture and a constant expression can be hard to " -"spot. Try changing the `2` in the second arm to a variable, and see that it " -"subtly doesn't work. Change it to a `const` and see it working again." +"In C++, copy elision has to be defined in the language specification because " +"constructors can have side effects. In Rust, this is not an issue at all. If " +"RVO did not happen, Rust will always perform a simple and efficient `memcpy` " +"copy." msgstr "" -#: src/pattern-matching/destructuring-arrays.md:3 -msgid "" -"You can destructure arrays, tuples, and slices by matching on their elements:" +#: src/ownership/shared-unique-borrows.md:3 +msgid "Rust puts constraints on the ways you can borrow values:" msgstr "" -#: src/pattern-matching/destructuring-arrays.md:5 -msgid "" -"```rust,editable\n" -"#[rustfmt::skip]\n" -"fn main() {\n" -" let triple = [0, -2, 3];\n" -" println!(\"Tell me about {triple:?}\");\n" -" match triple {\n" -" [0, y, z] => println!(\"First is 0, y = {y}, and z = {z}\"),\n" -" [1, ..] => println!(\"First is 1 and the rest were ignored\"),\n" -" _ => println!(\"All elements were ignored\"),\n" -" }\n" -"}\n" -"```" +#: src/ownership/shared-unique-borrows.md:5 +msgid "You can have one or more `&T` values at any given time, _or_" msgstr "" -#: src/pattern-matching/destructuring-arrays.md:21 -msgid "" -"Destructuring of slices of unknown length also works with patterns of fixed " -"length." +#: src/ownership/shared-unique-borrows.md:6 +msgid "You can have exactly one `&mut T` value." msgstr "" -#: src/pattern-matching/destructuring-arrays.md:24 +#: src/ownership/shared-unique-borrows.md:8 msgid "" -"```rust,editable\n" +"```rust,editable,compile_fail\n" "fn main() {\n" -" inspect(&[0, -2, 3]);\n" -" inspect(&[0, -2, 3, 4]);\n" -"}\n" +" let mut a: i32 = 10;\n" +" let b: &i32 = &a;\n" "\n" -"#[rustfmt::skip]\n" -"fn inspect(slice: &[i32]) {\n" -" println!(\"Tell me about {slice:?}\");\n" -" match slice {\n" -" &[0, y, z] => println!(\"First is 0, y = {y}, and z = {z}\"),\n" -" &[1, ..] => println!(\"First is 1 and the rest were ignored\"),\n" -" _ => println!(\"All elements were ignored\"),\n" +" {\n" +" let c: &mut i32 = &mut a;\n" +" *c = 20;\n" " }\n" +"\n" +" println!(\"a: {a}\");\n" +" println!(\"b: {b}\");\n" "}\n" "```" msgstr "" -#: src/pattern-matching/destructuring-arrays.md:41 -msgid "Create a new pattern using `_` to represent an element. " +#: src/ownership/shared-unique-borrows.md:25 +msgid "" +"The above code does not compile because `a` is borrowed as mutable (through " +"`c`) and as immutable (through `b`) at the same time." msgstr "" -#: src/pattern-matching/destructuring-arrays.md:42 -msgid "Add more values to the array." +#: src/ownership/shared-unique-borrows.md:26 +msgid "" +"Move the `println!` statement for `b` before the scope that introduces `c` " +"to make the code compile." msgstr "" -#: src/pattern-matching/destructuring-arrays.md:43 +#: src/ownership/shared-unique-borrows.md:27 msgid "" -"Point out that how `..` will expand to account for different number of " -"elements." +"After that change, the compiler realizes that `b` is only ever used before " +"the new mutable borrow of `a` through `c`. This is a feature of the borrow " +"checker called \"non-lexical lifetimes\"." msgstr "" -#: src/pattern-matching/destructuring-arrays.md:44 -msgid "Show matching against the tail with patterns `[.., b]` and `[a@..,b]`" +#: src/ownership/lifetimes.md:3 +msgid "A borrowed value has a _lifetime_:" msgstr "" -#: src/pattern-matching/match-guards.md:3 -msgid "" -"When matching, you can add a _guard_ to a pattern. This is an arbitrary " -"Boolean expression which will be executed if the pattern matches:" +#: src/ownership/lifetimes.md:5 +msgid "The lifetime can be implicit: `add(p1: &Point, p2: &Point) -> Point`." msgstr "" -#: src/pattern-matching/match-guards.md:6 -msgid "" -"```rust,editable\n" -"#[rustfmt::skip]\n" -"fn main() {\n" -" let pair = (2, -2);\n" -" println!(\"Tell me about {pair:?}\");\n" -" match pair {\n" -" (x, y) if x == y => println!(\"These are twins\"),\n" -" (x, y) if x + y == 0 => println!(\"Antimatter, kaboom!\"),\n" -" (x, _) if x % 2 == 1 => println!(\"The first one is odd\"),\n" -" _ => println!(\"No correlation...\"),\n" -" }\n" -"}\n" -"```" +#: src/ownership/lifetimes.md:6 +msgid "Lifetimes can also be explicit: `&'a Point`, `&'document str`." msgstr "" -#: src/pattern-matching/match-guards.md:23 +#: src/ownership/lifetimes.md:7 src/ownership/lifetimes-function-calls.md:23 msgid "" -"Match guards as a separate syntax feature are important and necessary when " -"we wish to concisely express more complex ideas than patterns alone would " -"allow." +"Read `&'a Point` as \"a borrowed `Point` which is valid for at least the " +"lifetime `a`\"." msgstr "" -#: src/pattern-matching/match-guards.md:24 +#: src/ownership/lifetimes.md:9 msgid "" -"They are not the same as separate `if` expression inside of the match arm. " -"An `if` expression inside of the branch block (after `=>`) happens after the " -"match arm is selected. Failing the `if` condition inside of that block won't " -"result in other arms of the original `match` expression being considered." -msgstr "" - -#: src/pattern-matching/match-guards.md:26 -msgid "You can use the variables defined in the pattern in your if expression." +"Lifetimes are always inferred by the compiler: you cannot assign a lifetime " +"yourself." msgstr "" -#: src/pattern-matching/match-guards.md:27 +#: src/ownership/lifetimes.md:11 msgid "" -"The condition defined in the guard applies to every expression in a pattern " -"with an `|`." +"Lifetime annotations create constraints; the compiler verifies that there is " +"a valid solution." msgstr "" -#: src/exercises/day-2/morning.md:1 -msgid "Day 2: Morning Exercises" +#: src/ownership/lifetimes.md:13 +msgid "" +"Lifetimes for function arguments and return values must be fully specified, " +"but Rust allows lifetimes to be elided in most cases with [a few simple " +"rules](https://doc.rust-lang.org/nomicon/lifetime-elision.html)." msgstr "" -#: src/exercises/day-2/morning.md:3 -msgid "We will look at implementing methods in two contexts:" +#: src/ownership/lifetimes-function-calls.md:3 +msgid "" +"In addition to borrowing its arguments, a function can return a borrowed " +"value:" msgstr "" -#: src/exercises/day-2/morning.md:5 -msgid "Simple struct which tracks health statistics." +#: src/ownership/lifetimes-function-calls.md:5 +msgid "" +"```rust,editable\n" +"#[derive(Debug)]\n" +"struct Point(i32, i32);\n" +"\n" +"fn left_most<'a>(p1: &'a Point, p2: &'a Point) -> &'a Point {\n" +" if p1.0 < p2.0 { p1 } else { p2 }\n" +"}\n" +"\n" +"fn main() {\n" +" let p1: Point = Point(10, 10);\n" +" let p2: Point = Point(20, 20);\n" +" let p3: &Point = left_most(&p1, &p2);\n" +" println!(\"left-most point: {:?}\", p3);\n" +"}\n" +"```" msgstr "" -#: src/exercises/day-2/morning.md:7 -msgid "Multiple structs and enums for a drawing library." +#: src/ownership/lifetimes-function-calls.md:21 +msgid "`'a` is a generic parameter, it is inferred by the compiler." msgstr "" -#: src/exercises/day-2/health-statistics.md:3 -msgid "" -"You're working on implementing a health-monitoring system. As part of that, " -"you need to keep track of users' health statistics." +#: src/ownership/lifetimes-function-calls.md:22 +msgid "Lifetimes start with `'` and `'a` is a typical default name." msgstr "" -#: src/exercises/day-2/health-statistics.md:6 +#: src/ownership/lifetimes-function-calls.md:25 msgid "" -"You'll start with some stubbed functions in an `impl` block as well as a " -"`User` struct definition. Your goal is to implement the stubbed out methods " -"on the `User` `struct` defined in the `impl` block." +"The _at least_ part is important when parameters are in different scopes." msgstr "" -#: src/exercises/day-2/health-statistics.md:10 +#: src/ownership/lifetimes-function-calls.md:31 msgid "" -"Copy the code below to and fill in the missing " -"methods:" +"Move the declaration of `p2` and `p3` into a new scope (`{ ... }`), " +"resulting in the following code:" msgstr "" -#: src/exercises/day-2/health-statistics.md:13 +#: src/ownership/lifetimes-function-calls.md:32 msgid "" -"```rust,should_panic\n" -"// TODO: remove this when you're done with your implementation.\n" -"#![allow(unused_variables, dead_code)]\n" +"```rust,ignore\n" +"#[derive(Debug)]\n" +"struct Point(i32, i32);\n" "\n" -"struct User {\n" -" name: String,\n" -" age: u32,\n" -" weight: f32,\n" -"}\n" -"\n" -"impl User {\n" -" pub fn new(name: String, age: u32, weight: f32) -> Self {\n" -" unimplemented!()\n" -" }\n" -"\n" -" pub fn name(&self) -> &str {\n" -" unimplemented!()\n" -" }\n" -"\n" -" pub fn age(&self) -> u32 {\n" -" unimplemented!()\n" -" }\n" -"\n" -" pub fn weight(&self) -> f32 {\n" -" unimplemented!()\n" -" }\n" -"\n" -" pub fn set_age(&mut self, new_age: u32) {\n" -" unimplemented!()\n" -" }\n" -"\n" -" pub fn set_weight(&mut self, new_weight: f32) {\n" -" unimplemented!()\n" -" }\n" +"fn left_most<'a>(p1: &'a Point, p2: &'a Point) -> &'a Point {\n" +" if p1.0 < p2.0 { p1 } else { p2 }\n" "}\n" "\n" "fn main() {\n" -" let bob = User::new(String::from(\"Bob\"), 32, 155.2);\n" -" println!(\"I'm {} and my age is {}\", bob.name(), bob.age());\n" -"}\n" -"\n" -"#[test]\n" -"fn test_weight() {\n" -" let bob = User::new(String::from(\"Bob\"), 32, 155.2);\n" -" assert_eq!(bob.weight(), 155.2);\n" -"}\n" -"\n" -"#[test]\n" -"fn test_set_age() {\n" -" let mut bob = User::new(String::from(\"Bob\"), 32, 155.2);\n" -" assert_eq!(bob.age(), 32);\n" -" bob.set_age(33);\n" -" assert_eq!(bob.age(), 33);\n" -"}\n" -"```" -msgstr "" - -#: src/exercises/day-2/points-polygons.md:1 -msgid "Polygon Struct" -msgstr "" - -#: src/exercises/day-2/points-polygons.md:3 -msgid "" -"We will create a `Polygon` struct which contain some points. Copy the code " -"below to and fill in the missing methods to " -"make the tests pass:" -msgstr "" - -#: src/exercises/day-2/points-polygons.md:7 -msgid "" -"```rust\n" -"// TODO: remove this when you're done with your implementation.\n" -"#![allow(unused_variables, dead_code)]\n" -"\n" -"pub struct Point {\n" -" // add fields\n" -"}\n" -"\n" -"impl Point {\n" -" // add methods\n" -"}\n" -"\n" -"pub struct Polygon {\n" -" // add fields\n" -"}\n" -"\n" -"impl Polygon {\n" -" // add methods\n" -"}\n" -"\n" -"pub struct Circle {\n" -" // add fields\n" -"}\n" -"\n" -"impl Circle {\n" -" // add methods\n" -"}\n" -"\n" -"pub enum Shape {\n" -" Polygon(Polygon),\n" -" Circle(Circle),\n" -"}\n" -"\n" -"#[cfg(test)]\n" -"mod tests {\n" -" use super::*;\n" -"\n" -" fn round_two_digits(x: f64) -> f64 {\n" -" (x * 100.0).round() / 100.0\n" -" }\n" -"\n" -" #[test]\n" -" fn test_point_magnitude() {\n" -" let p1 = Point::new(12, 13);\n" -" assert_eq!(round_two_digits(p1.magnitude()), 17.69);\n" -" }\n" -"\n" -" #[test]\n" -" fn test_point_dist() {\n" -" let p1 = Point::new(10, 10);\n" -" let p2 = Point::new(14, 13);\n" -" assert_eq!(round_two_digits(p1.dist(p2)), 5.00);\n" -" }\n" -"\n" -" #[test]\n" -" fn test_point_add() {\n" -" let p1 = Point::new(16, 16);\n" -" let p2 = p1 + Point::new(-4, 3);\n" -" assert_eq!(p2, Point::new(12, 19));\n" -" }\n" -"\n" -" #[test]\n" -" fn test_polygon_left_most_point() {\n" -" let p1 = Point::new(12, 13);\n" -" let p2 = Point::new(16, 16);\n" -"\n" -" let mut poly = Polygon::new();\n" -" poly.add_point(p1);\n" -" poly.add_point(p2);\n" -" assert_eq!(poly.left_most_point(), Some(p1));\n" -" }\n" -"\n" -" #[test]\n" -" fn test_polygon_iter() {\n" -" let p1 = Point::new(12, 13);\n" -" let p2 = Point::new(16, 16);\n" -"\n" -" let mut poly = Polygon::new();\n" -" poly.add_point(p1);\n" -" poly.add_point(p2);\n" -"\n" -" let points = poly.iter().cloned().collect::>();\n" -" assert_eq!(points, vec![Point::new(12, 13), Point::new(16, 16)]);\n" -" }\n" -"\n" -" #[test]\n" -" fn test_shape_perimeters() {\n" -" let mut poly = Polygon::new();\n" -" poly.add_point(Point::new(12, 13));\n" -" poly.add_point(Point::new(17, 11));\n" -" poly.add_point(Point::new(16, 16));\n" -" let shapes = vec![\n" -" Shape::from(poly),\n" -" Shape::from(Circle::new(Point::new(10, 20), 5)),\n" -" ];\n" -" let perimeters = shapes\n" -" .iter()\n" -" .map(Shape::perimeter)\n" -" .map(round_two_digits)\n" -" .collect::>();\n" -" assert_eq!(perimeters, vec![15.48, 31.42]);\n" +" let p1: Point = Point(10, 10);\n" +" let p3: &Point;\n" +" {\n" +" let p2: Point = Point(20, 20);\n" +" p3 = left_most(&p1, &p2);\n" " }\n" +" println!(\"left-most point: {:?}\", p3);\n" "}\n" -"\n" -"#[allow(dead_code)]\n" -"fn main() {}\n" "```" msgstr "" -#: src/exercises/day-2/points-polygons.md:117 -msgid "" -"Since the method signatures are missing from the problem statements, the key " -"part of the exercise is to specify those correctly. You don't have to modify " -"the tests." -msgstr "" - -#: src/exercises/day-2/points-polygons.md:120 -msgid "Other interesting parts of the exercise:" +#: src/ownership/lifetimes-function-calls.md:50 +msgid "Note how this does not compile since `p3` outlives `p2`." msgstr "" -#: src/exercises/day-2/points-polygons.md:122 +#: src/ownership/lifetimes-function-calls.md:52 msgid "" -"Derive a `Copy` trait for some structs, as in tests the methods sometimes " -"don't borrow their arguments." +"Reset the workspace and change the function signature to `fn left_most<'a, " +"'b>(p1: &'a Point, p2: &'a Point) -> &'b Point`. This will not compile " +"because the relationship between the lifetimes `'a` and `'b` is unclear." msgstr "" -#: src/exercises/day-2/points-polygons.md:123 -msgid "" -"Discover that `Add` trait must be implemented for two objects to be addable " -"via \"+\". Note that we do not discuss generics until Day 3." +#: src/ownership/lifetimes-function-calls.md:53 +msgid "Another way to explain it:" msgstr "" -#: src/control-flow.md:3 +#: src/ownership/lifetimes-function-calls.md:54 msgid "" -"As we have seen, `if` is an expression in Rust. It is used to conditionally " -"evaluate one of two blocks, but the blocks can have a value which then " -"becomes the value of the `if` expression. Other control flow expressions " -"work similarly in Rust." +"Two references to two values are borrowed by a function and the function " +"returns another reference." msgstr "" -#: src/control-flow/blocks.md:3 +#: src/ownership/lifetimes-function-calls.md:56 msgid "" -"A block in Rust has a value and a type: the value is the last expression of " -"the block:" +"It must have come from one of those two inputs (or from a global variable)." msgstr "" -#: src/control-flow/blocks.md:6 +#: src/ownership/lifetimes-function-calls.md:57 msgid "" -"```rust,editable\n" -"fn main() {\n" -" let x = {\n" -" let y = 10;\n" -" println!(\"y: {y}\");\n" -" let z = {\n" -" let w = {\n" -" 3 + 4\n" -" };\n" -" println!(\"w: {w}\");\n" -" y * w\n" -" };\n" -" println!(\"z: {z}\");\n" -" z - y\n" -" };\n" -" println!(\"x: {x}\");\n" -"}\n" -"```" +"Which one is it? The compiler needs to know, so at the call site the " +"returned reference is not used for longer than a variable from where the " +"reference came from." msgstr "" -#: src/control-flow/blocks.md:25 +#: src/ownership/lifetimes-data-structures.md:3 msgid "" -"The same rule is used for functions: the value of the function body is the " -"return value:" +"If a data type stores borrowed data, it must be annotated with a lifetime:" msgstr "" -#: src/control-flow/blocks.md:28 +#: src/ownership/lifetimes-data-structures.md:5 msgid "" "```rust,editable\n" -"fn double(x: i32) -> i32 {\n" -" x + x\n" +"#[derive(Debug)]\n" +"struct Highlight<'doc>(&'doc str);\n" +"\n" +"fn erase(text: String) {\n" +" println!(\"Bye {text}!\");\n" "}\n" "\n" "fn main() {\n" -" println!(\"doubled: {}\", double(7));\n" +" let text = String::from(\"The quick brown fox jumps over the lazy dog." +"\");\n" +" let fox = Highlight(&text[4..19]);\n" +" let dog = Highlight(&text[35..43]);\n" +" // erase(text);\n" +" println!(\"{fox:?}\");\n" +" println!(\"{dog:?}\");\n" "}\n" "```" msgstr "" -#: src/control-flow/blocks.md:38 +#: src/ownership/lifetimes-data-structures.md:25 msgid "" -"However if the last expression ends with `;`, then the resulting value and " -"type is `()`." +"In the above example, the annotation on `Highlight` enforces that the data " +"underlying the contained `&str` lives at least as long as any instance of " +"`Highlight` that uses that data." msgstr "" -#: src/control-flow/blocks.md:43 +#: src/ownership/lifetimes-data-structures.md:26 msgid "" -"The point of this slide is to show that blocks have a type and value in " -"Rust. " +"If `text` is consumed before the end of the lifetime of `fox` (or `dog`), " +"the borrow checker throws an error." msgstr "" -#: src/control-flow/blocks.md:44 +#: src/ownership/lifetimes-data-structures.md:27 msgid "" -"You can show how the value of the block changes by changing the last line in " -"the block. For instance, adding/removing a semicolon or using a `return`." +"Types with borrowed data force users to hold on to the original data. This " +"can be useful for creating lightweight views, but it generally makes them " +"somewhat harder to use." msgstr "" -#: src/control-flow/if-expressions.md:1 -msgid "`if` expressions" +#: src/ownership/lifetimes-data-structures.md:28 +msgid "When possible, make data structures own their data directly." msgstr "" -#: src/control-flow/if-expressions.md:3 -msgid "" -"You use [`if` expressions](https://doc.rust-lang.org/reference/expressions/" -"if-expr.html#if-expressions) exactly like `if` statements in other languages:" -msgstr "" - -#: src/control-flow/if-expressions.md:7 +#: src/ownership/lifetimes-data-structures.md:29 msgid "" -"```rust,editable\n" -"fn main() {\n" -" let mut x = 10;\n" -" if x % 2 == 0 {\n" -" x = x / 2;\n" -" } else {\n" -" x = 3 * x + 1;\n" -" }\n" -"}\n" -"```" +"Some structs with multiple references inside can have more than one lifetime " +"annotation. This can be necessary if there is a need to describe lifetime " +"relationships between the references themselves, in addition to the lifetime " +"of the struct itself. Those are very advanced use cases." msgstr "" -#: src/control-flow/if-expressions.md:18 -msgid "" -"In addition, you can use `if` as an expression. The last expression of each " -"block becomes the value of the `if` expression:" +#: src/exercises/day-2/morning.md:1 +msgid "Day 2: Morning Exercises" msgstr "" -#: src/control-flow/if-expressions.md:22 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let mut x = 10;\n" -" x = if x % 2 == 0 {\n" -" x / 2\n" -" } else {\n" -" 3 * x + 1\n" -" };\n" -"}\n" -"```" +#: src/exercises/day-2/morning.md:3 +msgid "We will look at implementing methods in two contexts:" msgstr "" -#: src/control-flow/if-expressions.md:35 -msgid "" -"Because `if` is an expression and must have a particular type, both of its " -"branch blocks must have the same type. Consider showing what happens if you " -"add `;` after `x / 2` in the second example." +#: src/exercises/day-2/morning.md:5 +msgid "Simple struct which tracks health statistics." msgstr "" -#: src/control-flow/if-let-expressions.md:1 -msgid "`if let` expressions" +#: src/exercises/day-2/morning.md:7 +msgid "Multiple structs and enums for a drawing library." msgstr "" -#: src/control-flow/if-let-expressions.md:3 +#: src/exercises/day-2/book-library.md:3 msgid "" -"The [`if let` expression](https://doc.rust-lang.org/reference/expressions/if-" -"expr.html#if-let-expressions) lets you execute different code depending on " -"whether a value matches a pattern:" +"We will learn much more about structs and the `Vec` type tomorrow. For " +"now, you just need to know part of its API:" msgstr "" -#: src/control-flow/if-let-expressions.md:7 +#: src/exercises/day-2/book-library.md:6 msgid "" "```rust,editable\n" "fn main() {\n" -" let arg = std::env::args().next();\n" -" if let Some(value) = arg {\n" -" println!(\"Program name: {value}\");\n" -" } else {\n" -" println!(\"Missing name?\");\n" +" let mut vec = vec![10, 20];\n" +" vec.push(30);\n" +" let midpoint = vec.len() / 2;\n" +" println!(\"middle value: {}\", vec[midpoint]);\n" +" for item in &vec {\n" +" println!(\"item: {item}\");\n" " }\n" "}\n" "```" msgstr "" -#: src/control-flow/if-let-expressions.md:18 -#: src/control-flow/while-let-expressions.md:21 -#: src/control-flow/match-expressions.md:23 +#: src/exercises/day-2/book-library.md:18 msgid "" -"See [pattern matching](../pattern-matching.md) for more details on patterns " -"in Rust." +"Use this to model a library's book collection. Copy the code below to " +" and update the types to make it compile:" msgstr "" -#: src/control-flow/if-let-expressions.md:23 +#: src/exercises/day-2/book-library.md:21 msgid "" -"`if let` can be more concise than `match`, e.g., when only one case is " -"interesting. In contrast, `match` requires all branches to be covered." +"```rust,should_panic\n" +"struct Library {\n" +" books: Vec,\n" +"}\n" +"\n" +"struct Book {\n" +" title: String,\n" +" year: u16,\n" +"}\n" +"\n" +"impl Book {\n" +" // This is a constructor, used below.\n" +" fn new(title: &str, year: u16) -> Book {\n" +" Book {\n" +" title: String::from(title),\n" +" year,\n" +" }\n" +" }\n" +"}\n" +"\n" +"// Implement the methods below. Update the `self` parameter to\n" +"// indicate the method's required level of ownership over the object:\n" +"//\n" +"// - `&self` for shared read-only access,\n" +"// - `&mut self` for unique and mutable access,\n" +"// - `self` for unique access by value.\n" +"impl Library {\n" +" fn new() -> Library {\n" +" todo!(\"Initialize and return a `Library` value\")\n" +" }\n" +"\n" +" //fn len(self) -> usize {\n" +" // todo!(\"Return the length of `self.books`\")\n" +" //}\n" +"\n" +" //fn is_empty(self) -> bool {\n" +" // todo!(\"Return `true` if `self.books` is empty\")\n" +" //}\n" +"\n" +" //fn add_book(self, book: Book) {\n" +" // todo!(\"Add a new book to `self.books`\")\n" +" //}\n" +"\n" +" //fn print_books(self) {\n" +" // todo!(\"Iterate over `self.books` and each book's title and " +"year\")\n" +" //}\n" +"\n" +" //fn oldest_book(self) -> Option<&Book> {\n" +" // todo!(\"Return a reference to the oldest book (if any)\")\n" +" //}\n" +"}\n" +"\n" +"// This shows the desired behavior. Uncomment the code below and\n" +"// implement the missing methods. You will need to update the\n" +"// method signatures, including the \"self\" parameter! You may\n" +"// also need to update the variable bindings within main.\n" +"fn main() {\n" +" let library = Library::new();\n" +"\n" +" //println!(\"The library is empty: library.is_empty() -> {}\", library." +"is_empty());\n" +" //\n" +" //library.add_book(Book::new(\"Lord of the Rings\", 1954));\n" +" //library.add_book(Book::new(\"Alice's Adventures in Wonderland\", " +"1865));\n" +" //\n" +" //println!(\"The library is no longer empty: library.is_empty() -> {}\", " +"library.is_empty());\n" +" //\n" +" //\n" +" //library.print_books();\n" +" //\n" +" //match library.oldest_book() {\n" +" // Some(book) => println!(\"The oldest book is {}\", book.title),\n" +" // None => println!(\"The library is empty!\"),\n" +" //}\n" +" //\n" +" //println!(\"The library has {} books\", library.len());\n" +" //library.print_books();\n" +"}\n" +"```" msgstr "" -#: src/control-flow/if-let-expressions.md:24 -msgid "A common usage is handling `Some` values when working with `Option`." +#: src/exercises/day-2/book-library.md:102 +msgid "[Solution](solutions-afternoon.md#designing-a-library)" msgstr "" -#: src/control-flow/if-let-expressions.md:25 +#: src/exercises/day-2/iterators-and-ownership.md:3 msgid "" -"Unlike `match`, `if let` does not support guard clauses for pattern matching." +"The ownership model of Rust affects many APIs. An example of this is the " +"[`Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html) and " +"[`IntoIterator`](https://doc.rust-lang.org/std/iter/trait.IntoIterator.html) " +"traits." msgstr "" -#: src/control-flow/if-let-expressions.md:26 +#: src/exercises/day-2/iterators-and-ownership.md:8 src/bare-metal/no_std.md:28 +msgid "`Iterator`" +msgstr "" + +#: src/exercises/day-2/iterators-and-ownership.md:10 msgid "" -"Since 1.65, a similar [let-else](https://doc.rust-lang.org/rust-by-example/" -"flow_control/let_else.html) construct allows to do a destructuring " -"assignment, or if it fails, have a non-returning block branch (panic/return/" -"break/continue):" +"Traits are like interfaces: they describe behavior (methods) for a type. The " +"`Iterator` trait simply says that you can call `next` until you get `None` " +"back:" msgstr "" -#: src/control-flow/if-let-expressions.md:28 +#: src/exercises/day-2/iterators-and-ownership.md:13 msgid "" -"```rust,editable\n" -"fn main() {\n" -" println!(\"{:?}\", second_word_to_upper(\"foo bar\"));\n" -"}\n" -" \n" -"fn second_word_to_upper(s: &str) -> Option {\n" -" let mut it = s.split(' ');\n" -" let (Some(_), Some(item)) = (it.next(), it.next()) else {\n" -" return None;\n" -" };\n" -" Some(item.to_uppercase())\n" +"```rust\n" +"pub trait Iterator {\n" +" type Item;\n" +" fn next(&mut self) -> Option;\n" "}\n" "```" msgstr "" -#: src/control-flow/while-expressions.md:1 -msgid "`while` loops" -msgstr "" - -#: src/control-flow/while-expressions.md:3 -msgid "" -"The [`while` keyword](https://doc.rust-lang.org/reference/expressions/loop-" -"expr.html#predicate-loops) works very similar to other languages:" +#: src/exercises/day-2/iterators-and-ownership.md:20 +msgid "You use this trait like this:" msgstr "" -#: src/control-flow/while-expressions.md:6 +#: src/exercises/day-2/iterators-and-ownership.md:22 msgid "" "```rust,editable\n" "fn main() {\n" -" let mut x = 10;\n" -" while x != 1 {\n" -" x = if x % 2 == 0 {\n" -" x / 2\n" -" } else {\n" -" 3 * x + 1\n" -" };\n" -" }\n" -" println!(\"Final x: {x}\");\n" +" let v: Vec = vec![10, 20, 30];\n" +" let mut iter = v.iter();\n" +"\n" +" println!(\"v[0]: {:?}\", iter.next());\n" +" println!(\"v[1]: {:?}\", iter.next());\n" +" println!(\"v[2]: {:?}\", iter.next());\n" +" println!(\"No more items: {:?}\", iter.next());\n" "}\n" "```" msgstr "" -#: src/control-flow/while-let-expressions.md:1 -msgid "`while let` loops" -msgstr "" - -#: src/control-flow/while-let-expressions.md:3 -msgid "" -"Like with `if let`, there is a [`while let`](https://doc.rust-lang.org/" -"reference/expressions/loop-expr.html#predicate-pattern-loops) variant which " -"repeatedly tests a value against a pattern:" +#: src/exercises/day-2/iterators-and-ownership.md:34 +msgid "What is the type returned by the iterator? Test your answer here:" msgstr "" -#: src/control-flow/while-let-expressions.md:6 +#: src/exercises/day-2/iterators-and-ownership.md:36 msgid "" -"```rust,editable\n" +"```rust,editable,compile_fail\n" "fn main() {\n" -" let v = vec![10, 20, 30];\n" -" let mut iter = v.into_iter();\n" +" let v: Vec = vec![10, 20, 30];\n" +" let mut iter = v.iter();\n" "\n" -" while let Some(x) = iter.next() {\n" -" println!(\"x: {x}\");\n" -" }\n" +" let v0: Option<..> = iter.next();\n" +" println!(\"v0: {v0:?}\");\n" "}\n" "```" msgstr "" -#: src/control-flow/while-let-expressions.md:17 -msgid "" -"Here the iterator returned by `v.iter()` will return a `Option` on " -"every call to `next()`. It returns `Some(x)` until it is done, after which " -"it will return `None`. The `while let` lets us keep iterating through all " -"items." +#: src/exercises/day-2/iterators-and-ownership.md:46 +msgid "Why is this type used?" msgstr "" -#: src/control-flow/while-let-expressions.md:26 -msgid "" -"Point out that the `while let` loop will keep going as long as the value " -"matches the pattern." +#: src/exercises/day-2/iterators-and-ownership.md:48 +msgid "`IntoIterator`" msgstr "" -#: src/control-flow/while-let-expressions.md:27 +#: src/exercises/day-2/iterators-and-ownership.md:50 msgid "" -"You could rewrite the `while let` loop as an infinite loop with an if " -"statement that breaks when there is no value to unwrap for `iter.next()`. " -"The `while let` provides syntactic sugar for the above scenario." +"The `Iterator` trait tells you how to _iterate_ once you have created an " +"iterator. The related trait `IntoIterator` tells you how to create the " +"iterator:" msgstr "" -#: src/control-flow/for-expressions.md:1 -msgid "`for` loops" -msgstr "" - -#: src/control-flow/for-expressions.md:3 -msgid "" -"The [`for` loop](https://doc.rust-lang.org/std/keyword.for.html) is closely " -"related to the [`while let` loop](while-let-expression.md). It will " -"automatically call `into_iter()` on the expression and then iterate over it:" -msgstr "" - -#: src/control-flow/for-expressions.md:7 +#: src/exercises/day-2/iterators-and-ownership.md:53 msgid "" -"```rust,editable\n" -"fn main() {\n" -" let v = vec![10, 20, 30];\n" +"```rust\n" +"pub trait IntoIterator {\n" +" type Item;\n" +" type IntoIter: Iterator;\n" "\n" -" for x in v {\n" -" println!(\"x: {x}\");\n" -" }\n" -" \n" -" for i in (0..10).step_by(2) {\n" -" println!(\"i: {i}\");\n" -" }\n" +" fn into_iter(self) -> Self::IntoIter;\n" "}\n" "```" msgstr "" -#: src/control-flow/for-expressions.md:21 -msgid "You can use `break` and `continue` here as usual." +#: src/exercises/day-2/iterators-and-ownership.md:62 +msgid "" +"The syntax here means that every implementation of `IntoIterator` must " +"declare two types:" msgstr "" -#: src/control-flow/for-expressions.md:25 -msgid "Index iteration is not a special syntax in Rust for just that case." +#: src/exercises/day-2/iterators-and-ownership.md:65 +msgid "`Item`: the type we iterate over, such as `i8`," msgstr "" -#: src/control-flow/for-expressions.md:26 -msgid "`(0..10)` is a range that implements an `Iterator` trait. " +#: src/exercises/day-2/iterators-and-ownership.md:66 +msgid "`IntoIter`: the `Iterator` type returned by the `into_iter` method." msgstr "" -#: src/control-flow/for-expressions.md:27 +#: src/exercises/day-2/iterators-and-ownership.md:68 msgid "" -"`step_by` is a method that returns another `Iterator` that skips every other " -"element. " +"Note that `IntoIter` and `Item` are linked: the iterator must have the same " +"`Item` type, which means that it returns `Option`" msgstr "" -#: src/control-flow/for-expressions.md:28 -msgid "" -"Modify the elements in the vector and explain the compiler errors. Change " -"vector `v` to be mutable and the for loop to `for x in v.iter_mut()`." +#: src/exercises/day-2/iterators-and-ownership.md:71 +msgid "Like before, what is the type returned by the iterator?" msgstr "" -#: src/control-flow/loop-expressions.md:1 -msgid "`loop` expressions" +#: src/exercises/day-2/iterators-and-ownership.md:73 +msgid "" +"```rust,editable,compile_fail\n" +"fn main() {\n" +" let v: Vec = vec![String::from(\"foo\"), String::" +"from(\"bar\")];\n" +" let mut iter = v.into_iter();\n" +"\n" +" let v0: Option<..> = iter.next();\n" +" println!(\"v0: {v0:?}\");\n" +"}\n" +"```" msgstr "" -#: src/control-flow/loop-expressions.md:3 -msgid "" -"Finally, there is a [`loop` keyword](https://doc.rust-lang.org/reference/" -"expressions/loop-expr.html#infinite-loops) which creates an endless loop." +#: src/exercises/day-2/iterators-and-ownership.md:83 +msgid "`for` Loops" msgstr "" -#: src/control-flow/loop-expressions.md:6 -msgid "Here you must either `break` or `return` to stop the loop:" +#: src/exercises/day-2/iterators-and-ownership.md:85 +msgid "" +"Now that we know both `Iterator` and `IntoIterator`, we can build `for` " +"loops. They call `into_iter()` on an expression and iterates over the " +"resulting iterator:" msgstr "" -#: src/control-flow/loop-expressions.md:8 +#: src/exercises/day-2/iterators-and-ownership.md:89 msgid "" "```rust,editable\n" "fn main() {\n" -" let mut x = 10;\n" -" loop {\n" -" x = if x % 2 == 0 {\n" -" x / 2\n" -" } else {\n" -" 3 * x + 1\n" -" };\n" -" if x == 1 {\n" -" break;\n" -" }\n" +" let v: Vec = vec![String::from(\"foo\"), String::" +"from(\"bar\")];\n" +"\n" +" for word in &v {\n" +" println!(\"word: {word}\");\n" +" }\n" +"\n" +" for word in v {\n" +" println!(\"word: {word}\");\n" " }\n" -" println!(\"Final x: {x}\");\n" "}\n" "```" msgstr "" -#: src/control-flow/loop-expressions.md:27 -msgid "Break the `loop` with a value (e.g. `break 8`) and print it out." +#: src/exercises/day-2/iterators-and-ownership.md:103 +msgid "What is the type of `word` in each loop?" msgstr "" -#: src/control-flow/loop-expressions.md:28 +#: src/exercises/day-2/iterators-and-ownership.md:105 msgid "" -"Note that `loop` is the only looping construct which returns a non-trivial " -"value. This is because it's guaranteed to be entered at least once (unlike " -"`while` and `for` loops)." -msgstr "" - -#: src/control-flow/match-expressions.md:1 -msgid "`match` expressions" +"Experiment with the code above and then consult the documentation for [`impl " +"IntoIterator for &Vec`](https://doc.rust-lang.org/std/vec/struct.Vec." +"html#impl-IntoIterator-for-%26'a+Vec%3CT,+A%3E) and [`impl IntoIterator for " +"Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html#impl-IntoIterator-" +"for-Vec%3CT,+A%3E) to check your answers." msgstr "" -#: src/control-flow/match-expressions.md:3 -msgid "" -"The [`match` keyword](https://doc.rust-lang.org/reference/expressions/match-" -"expr.html) is used to match a value against one or more patterns. In that " -"sense, it works like a series of `if let` expressions:" +#: src/structs.md:3 +msgid "Like C and C++, Rust has support for custom structs:" msgstr "" -#: src/control-flow/match-expressions.md:7 +#: src/structs.md:5 msgid "" "```rust,editable\n" +"struct Person {\n" +" name: String,\n" +" age: u8,\n" +"}\n" +"\n" "fn main() {\n" -" match std::env::args().next().as_deref() {\n" -" Some(\"cat\") => println!(\"Will do cat things\"),\n" -" Some(\"ls\") => println!(\"Will ls some files\"),\n" -" Some(\"mv\") => println!(\"Let's move some files\"),\n" -" Some(\"rm\") => println!(\"Uh, dangerous!\"),\n" -" None => println!(\"Hmm, no program name?\"),\n" -" _ => println!(\"Unknown program name!\"),\n" -" }\n" +" let mut peter = Person {\n" +" name: String::from(\"Peter\"),\n" +" age: 27,\n" +" };\n" +" println!(\"{} is {} years old\", peter.name, peter.age);\n" +" \n" +" peter.age = 28;\n" +" println!(\"{} is {} years old\", peter.name, peter.age);\n" +" \n" +" let jackie = Person {\n" +" name: String::from(\"Jackie\"),\n" +" ..peter\n" +" };\n" +" println!(\"{} is {} years old\", jackie.name, jackie.age);\n" "}\n" "```" msgstr "" -#: src/control-flow/match-expressions.md:20 -msgid "" -"Like `if let`, each match arm must have the same type. The type is the last " -"expression of the block, if any. In the example above, the type is `()`." +#: src/structs.md:33 +msgid "Structs work like in C or C++." msgstr "" -#: src/control-flow/match-expressions.md:28 -msgid "Save the match expression to a variable and print it out." +#: src/structs.md:34 +msgid "Like in C++, and unlike in C, no typedef is needed to define a type." msgstr "" -#: src/control-flow/match-expressions.md:29 -msgid "Remove `.as_deref()` and explain the error." +#: src/structs.md:35 +msgid "Unlike in C++, there is no inheritance between structs." msgstr "" -#: src/control-flow/match-expressions.md:30 +#: src/structs.md:36 msgid "" -"`std::env::args().next()` returns an `Option`, but we cannot match " -"against `String`." +"Methods are defined in an `impl` block, which we will see in following " +"slides." msgstr "" -#: src/control-flow/match-expressions.md:31 +#: src/structs.md:37 msgid "" -"`as_deref()` transforms an `Option` to `Option<&T::Target>`. In our case, " -"this turns `Option` into `Option<&str>`." +"This may be a good time to let people know there are different types of " +"structs. " msgstr "" -#: src/control-flow/match-expressions.md:32 +#: src/structs.md:38 msgid "" -"We can now use pattern matching to match against the `&str` inside `Option`." -msgstr "" - -#: src/control-flow/break-continue.md:1 -msgid "`break` and `continue`" +"Zero-sized structs `e.g., struct Foo;` might be used when implementing a " +"trait on some type but don’t have any data that you want to store in the " +"value itself. " msgstr "" -#: src/control-flow/break-continue.md:3 +#: src/structs.md:39 msgid "" -"If you want to exit a loop early, use [`break`](https://doc.rust-lang.org/" -"reference/expressions/loop-expr.html#break-expressions)," +"The next slide will introduce Tuple structs, used when the field names are " +"not important." msgstr "" -#: src/control-flow/break-continue.md:4 +#: src/structs.md:40 msgid "" -"If you want to immediately start the next iteration use [`continue`](https://" -"doc.rust-lang.org/reference/expressions/loop-expr.html#continue-expressions)." +"The syntax `..peter` allows us to copy the majority of the fields from the " +"old struct without having to explicitly type it all out. It must always be " +"the last element." msgstr "" -#: src/control-flow/break-continue.md:7 -msgid "" -"Both `continue` and `break` can optionally take a label argument which is " -"used to break out of nested loops:" +#: src/structs/tuple-structs.md:3 +msgid "If the field names are unimportant, you can use a tuple struct:" msgstr "" -#: src/control-flow/break-continue.md:10 +#: src/structs/tuple-structs.md:5 msgid "" "```rust,editable\n" +"struct Point(i32, i32);\n" +"\n" "fn main() {\n" -" let v = vec![10, 20, 30];\n" -" let mut iter = v.into_iter();\n" -" 'outer: while let Some(x) = iter.next() {\n" -" println!(\"x: {x}\");\n" -" let mut i = 0;\n" -" while i < x {\n" -" println!(\"x: {x}, i: {i}\");\n" -" i += 1;\n" -" if i == 3 {\n" -" break 'outer;\n" -" }\n" -" }\n" -" }\n" +" let p = Point(17, 23);\n" +" println!(\"({}, {})\", p.0, p.1);\n" "}\n" "```" msgstr "" -#: src/control-flow/break-continue.md:28 +#: src/structs/tuple-structs.md:14 +msgid "This is often used for single-field wrappers (called newtypes):" +msgstr "" + +#: src/structs/tuple-structs.md:16 msgid "" -"In this case we break the outer loop after 3 iterations of the inner loop." +"```rust,editable,compile_fail\n" +"struct PoundsOfForce(f64);\n" +"struct Newtons(f64);\n" +"\n" +"fn compute_thruster_force() -> PoundsOfForce {\n" +" todo!(\"Ask a rocket scientist at NASA\")\n" +"}\n" +"\n" +"fn set_thruster_force(force: Newtons) {\n" +" // ...\n" +"}\n" +"\n" +"fn main() {\n" +" let force = compute_thruster_force();\n" +" set_thruster_force(force);\n" +"}\n" +"\n" +"```" msgstr "" -#: src/std.md:3 +#: src/structs/tuple-structs.md:37 msgid "" -"Rust comes with a standard library which helps establish a set of common " -"types used by Rust library and programs. This way, two libraries can work " -"together smoothly because they both use the same `String` type." +"Newtypes are a great way to encode additional information about the value in " +"a primitive type, for example:" msgstr "" -#: src/std.md:7 -msgid "The common vocabulary types include:" +#: src/structs/tuple-structs.md:38 +msgid "The number is measured in some units: `Newtons` in the example above." msgstr "" -#: src/std.md:9 +#: src/structs/tuple-structs.md:39 msgid "" -"[`Option` and `Result`](std/option-result.md) types: used for optional " -"values and [error handling](error-handling.md)." +"The value passed some validation when it was created, so you no longer have " +"to validate it again at every use: 'PhoneNumber(String)`or`OddNumber(u32)\\`." msgstr "" -#: src/std.md:12 -msgid "[`String`](std/string.md): the default string type used for owned data." -msgstr "" - -#: src/std.md:14 -msgid "[`Vec`](std/vec.md): a standard extensible vector." +#: src/structs/tuple-structs.md:40 +msgid "" +"Demonstrate how to add a `f64` value to a `Newtons` type by accessing the " +"single field in the newtype." msgstr "" -#: src/std.md:16 +#: src/structs/tuple-structs.md:41 msgid "" -"[`HashMap`](std/hashmap.md): a hash map type with a configurable hashing " -"algorithm." +"Rust generally doesn’t like inexplicit things, like automatic unwrapping or " +"for instance using booleans as integers." msgstr "" -#: src/std.md:19 -msgid "[`Box`](std/box.md): an owned pointer for heap-allocated data." +#: src/structs/tuple-structs.md:42 +msgid "Operator overloading is discussed on Day 3 (generics)." msgstr "" -#: src/std.md:21 +#: src/structs/tuple-structs.md:43 msgid "" -"[`Rc`](std/rc.md): a shared reference-counted pointer for heap-allocated " -"data." +"The example is a subtle reference to the [Mars Climate Orbiter](https://en." +"wikipedia.org/wiki/Mars_Climate_Orbiter) failure." msgstr "" -#: src/std.md:25 +#: src/structs/field-shorthand.md:3 msgid "" -"In fact, Rust contains several layers of the Standard Library: `core`, " -"`alloc` and `std`. " +"If you already have variables with the right names, then you can create the " +"struct using a shorthand:" msgstr "" -#: src/std.md:26 +#: src/structs/field-shorthand.md:6 msgid "" -"`core` includes the most basic types and functions that don't depend on " -"`libc`, allocator or even the presence of an operating system. " +"```rust,editable\n" +"#[derive(Debug)]\n" +"struct Person {\n" +" name: String,\n" +" age: u8,\n" +"}\n" +"\n" +"impl Person {\n" +" fn new(name: String, age: u8) -> Person {\n" +" Person { name, age }\n" +" }\n" +"}\n" +"\n" +"fn main() {\n" +" let peter = Person::new(String::from(\"Peter\"), 27);\n" +" println!(\"{peter:?}\");\n" +"}\n" +"```" msgstr "" -#: src/std.md:28 +#: src/structs/field-shorthand.md:27 msgid "" -"`alloc` includes types which require a global heap allocator, such as `Vec`, " -"`Box` and `Arc`." +"The `new` function could be written using `Self` as a type, as it is " +"interchangeable with the struct type name" msgstr "" -#: src/std.md:29 +#: src/structs/field-shorthand.md:29 msgid "" -"Embedded Rust applications often only use `core`, and sometimes `alloc`." -msgstr "" - -#: src/std/option-result.md:1 -msgid "`Option` and `Result`" +"```rust,editable\n" +"#[derive(Debug)]\n" +"struct Person {\n" +" name: String,\n" +" age: u8,\n" +"}\n" +"impl Person {\n" +" fn new(name: String, age: u8) -> Self {\n" +" Self { name, age }\n" +" }\n" +"}\n" +"```" msgstr "" -#: src/std/option-result.md:3 -msgid "The types represent optional data:" +#: src/structs/field-shorthand.md:41 +msgid "" +"Implement the `Default` trait for the struct. Define some fields and use the " +"default values for the other fields." msgstr "" -#: src/std/option-result.md:5 +#: src/structs/field-shorthand.md:43 msgid "" "```rust,editable\n" -"fn main() {\n" -" let numbers = vec![10, 20, 30];\n" -" let first: Option<&i8> = numbers.first();\n" -" println!(\"first: {first:?}\");\n" -"\n" -" let idx: Result = numbers.binary_search(&10);\n" -" println!(\"idx: {idx:?}\");\n" +"#[derive(Debug)]\n" +"struct Person {\n" +" name: String,\n" +" age: u8,\n" +"}\n" +"impl Default for Person {\n" +" fn default() -> Person {\n" +" Person {\n" +" name: \"Bot\".to_string(),\n" +" age: 0,\n" +" }\n" +" }\n" +"}\n" +"fn create_default() {\n" +" let tmp = Person {\n" +" ..Person::default()\n" +" };\n" +" let tmp = Person {\n" +" name: \"Sam\".to_string(),\n" +" ..Person::default()\n" +" };\n" "}\n" "```" msgstr "" -#: src/std/option-result.md:18 -msgid "`Option` and `Result` are widely used not just in the standard library." -msgstr "" - -#: src/std/option-result.md:19 -msgid "`Option<&T>` has zero space overhead compared to `&T`." +#: src/structs/field-shorthand.md:68 +msgid "Methods are defined in the `impl` block." msgstr "" -#: src/std/option-result.md:20 +#: src/structs/field-shorthand.md:69 msgid "" -"`Result` is the standard type to implement error handling as we will see on " -"Day 3." -msgstr "" - -#: src/std/option-result.md:21 -msgid "`binary_search` returns `Result`." -msgstr "" - -#: src/std/option-result.md:22 -msgid "If found, `Result::Ok` holds the index where the element is found." +"Use struct update syntax to define a new structure using `peter`. Note that " +"the variable `peter` will no longer be accessible afterwards." msgstr "" -#: src/std/option-result.md:23 +#: src/structs/field-shorthand.md:70 msgid "" -"Otherwise, `Result::Err` contains the index where such an element should be " -"inserted." +"Use `{:#?}` when printing structs to request the `Debug` representation." msgstr "" -#: src/std/string.md:3 +#: src/methods.md:3 msgid "" -"[`String`](https://doc.rust-lang.org/std/string/struct.String.html) is the " -"standard heap-allocated growable UTF-8 string buffer:" +"Rust allows you to associate functions with your new types. You do this with " +"an `impl` block:" msgstr "" -#: src/std/string.md:5 +#: src/methods.md:6 msgid "" "```rust,editable\n" -"fn main() {\n" -" let mut s1 = String::new();\n" -" s1.push_str(\"Hello\");\n" -" println!(\"s1: len = {}, capacity = {}\", s1.len(), s1.capacity());\n" +"#[derive(Debug)]\n" +"struct Person {\n" +" name: String,\n" +" age: u8,\n" +"}\n" "\n" -" let mut s2 = String::with_capacity(s1.len() + 1);\n" -" s2.push_str(&s1);\n" -" s2.push('!');\n" -" println!(\"s2: len = {}, capacity = {}\", s2.len(), s2.capacity());\n" +"impl Person {\n" +" fn say_hello(&self) {\n" +" println!(\"Hello, my name is {}\", self.name);\n" +" }\n" +"}\n" "\n" -" let s3 = String::from(\"🇨🇭\");\n" -" println!(\"s3: len = {}, number of chars = {}\", s3.len(),\n" -" s3.chars().count());\n" +"fn main() {\n" +" let peter = Person {\n" +" name: String::from(\"Peter\"),\n" +" age: 27,\n" +" };\n" +" peter.say_hello();\n" "}\n" "```" msgstr "" -#: src/std/string.md:22 -msgid "" -"`String` implements [`Deref`](https://doc.rust-lang.org/std/" -"string/struct.String.html#deref-methods-str), which means that you can call " -"all `str` methods on a `String`." +#: src/methods.md:31 +msgid "It can be helpful to introduce methods by comparing them to functions." msgstr "" -#: src/std/string.md:30 +#: src/methods.md:32 msgid "" -"`String::new` returns a new empty string, use `String::with_capacity` when " -"you know how much data you want to push to the string." +"Methods are called on an instance of a type (such as a struct or enum), the " +"first parameter represents the instance as `self`." msgstr "" -#: src/std/string.md:31 +#: src/methods.md:33 msgid "" -"`String::len` returns the size of the `String` in bytes (which can be " -"different from its length in characters)." +"Developers may choose to use methods to take advantage of method receiver " +"syntax and to help keep them more organized. By using methods we can keep " +"all the implementation code in one predictable place." msgstr "" -#: src/std/string.md:32 +#: src/methods.md:34 +msgid "Point out the use of the keyword `self`, a method receiver." +msgstr "" + +#: src/methods.md:35 msgid "" -"`String::chars` returns an iterator over the actual characters. Note that a " -"`char` can be different from what a human will consider a \"character\" due " -"to [grapheme clusters](https://docs.rs/unicode-segmentation/latest/" -"unicode_segmentation/struct.Graphemes.html)." +"Show that it is an abbreviated term for `self: Self` and perhaps show how " +"the struct name could also be used." msgstr "" -#: src/std/string.md:33 +#: src/methods.md:36 msgid "" -"When people refer to strings they could either be talking about `&str` or " -"`String`." +"Explain that `Self` is a type alias for the type the `impl` block is in and " +"can be used elsewhere in the block." msgstr "" -#: src/std/string.md:34 +#: src/methods.md:37 msgid "" -"When a type implements `Deref`, the compiler will let you " -"transparently call methods from `T`." +"Note how `self` is used like other structs and dot notation can be used to " +"refer to individual fields." msgstr "" -#: src/std/string.md:35 +#: src/methods.md:38 msgid "" -"`String` implements `Deref` which transparently gives it " -"access to `str`'s methods." +"This might be a good time to demonstrate how the `&self` differs from `self` " +"by modifying the code and trying to run say_hello twice." msgstr "" -#: src/std/string.md:36 -msgid "Write and compare `let s3 = s1.deref();` and `let s3 = &*s1`;." +#: src/methods.md:39 +msgid "We describe the distinction between method receivers next." msgstr "" -#: src/std/string.md:37 +#: src/methods/receiver.md:3 msgid "" -"`String` is implemented as a wrapper around a vector of bytes, many of the " -"operations you see supported on vectors are also supported on `String`, but " -"with some extra guarantees." +"The `&self` above indicates that the method borrows the object immutably. " +"There are other possible receivers for a method:" msgstr "" -#: src/std/string.md:38 -msgid "Compare the different ways to index a `String`:" +#: src/methods/receiver.md:6 +msgid "" +"`&self`: borrows the object from the caller using a shared and immutable " +"reference. The object can be used again afterwards." msgstr "" -#: src/std/string.md:39 +#: src/methods/receiver.md:8 msgid "" -"To a character by using `s3.chars().nth(i).unwrap()` where `i` is in-bound, " -"out-of-bounds." +"`&mut self`: borrows the object from the caller using a unique and mutable " +"reference. The object can be used again afterwards." msgstr "" -#: src/std/string.md:40 +#: src/methods/receiver.md:10 msgid "" -"To a substring by using `s3[0..4]`, where that slice is on character " -"boundaries or not." +"`self`: takes ownership of the object and moves it away from the caller. The " +"method becomes the owner of the object. The object will be dropped " +"(deallocated) when the method returns, unless its ownership is explicitly " +"transmitted. Complete ownership does not automatically mean mutability." msgstr "" -#: src/std/vec.md:1 -msgid "`Vec`" +#: src/methods/receiver.md:14 +msgid "`mut self`: same as above, but the method can mutate the object. " msgstr "" -#: src/std/vec.md:3 +#: src/methods/receiver.md:15 msgid "" -"[`Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html) is the standard " -"resizable heap-allocated buffer:" +"No receiver: this becomes a static method on the struct. Typically used to " +"create constructors which are called `new` by convention." msgstr "" -#: src/std/vec.md:5 +#: src/methods/receiver.md:18 +msgid "" +"Beyond variants on `self`, there are also [special wrapper types](https://" +"doc.rust-lang.org/reference/special-types-and-traits.html) allowed to be " +"receiver types, such as `Box`." +msgstr "" + +#: src/methods/receiver.md:24 +msgid "" +"Consider emphasizing \"shared and immutable\" and \"unique and mutable\". " +"These constraints always come together in Rust due to borrow checker rules, " +"and `self` is no exception. It isn't possible to reference a struct from " +"multiple locations and call a mutating (`&mut self`) method on it." +msgstr "" + +#: src/methods/example.md:3 msgid "" "```rust,editable\n" -"fn main() {\n" -" let mut v1 = Vec::new();\n" -" v1.push(42);\n" -" println!(\"v1: len = {}, capacity = {}\", v1.len(), v1.capacity());\n" +"#[derive(Debug)]\n" +"struct Race {\n" +" name: String,\n" +" laps: Vec,\n" +"}\n" "\n" -" let mut v2 = Vec::with_capacity(v1.len() + 1);\n" -" v2.extend(v1.iter());\n" -" v2.push(9999);\n" -" println!(\"v2: len = {}, capacity = {}\", v2.len(), v2.capacity());\n" +"impl Race {\n" +" fn new(name: &str) -> Race { // No receiver, a static method\n" +" Race { name: String::from(name), laps: Vec::new() }\n" +" }\n" "\n" -" // Canonical macro to initialize a vector with elements.\n" -" let mut v3 = vec![0, 0, 1, 2, 3, 4];\n" +" fn add_lap(&mut self, lap: i32) { // Exclusive borrowed read-write " +"access to self\n" +" self.laps.push(lap);\n" +" }\n" "\n" -" // Retain only the even elements.\n" -" v3.retain(|x| x % 2 == 0);\n" -" println!(\"{v3:?}\");\n" +" fn print_laps(&self) { // Shared and read-only borrowed access to self\n" +" println!(\"Recorded {} laps for {}:\", self.laps.len(), self.name);\n" +" for (idx, lap) in self.laps.iter().enumerate() {\n" +" println!(\"Lap {idx}: {lap} sec\");\n" +" }\n" +" }\n" "\n" -" // Remove consecutive duplicates.\n" -" v3.dedup();\n" -" println!(\"{v3:?}\");\n" +" fn finish(self) { // Exclusive ownership of self\n" +" let total = self.laps.iter().sum::();\n" +" println!(\"Race {} is finished, total lap time: {}\", self.name, " +"total);\n" +" }\n" +"}\n" +"\n" +"fn main() {\n" +" let mut race = Race::new(\"Monaco Grand Prix\");\n" +" race.add_lap(70);\n" +" race.add_lap(68);\n" +" race.print_laps();\n" +" race.add_lap(71);\n" +" race.print_laps();\n" +" race.finish();\n" +" // race.add_lap(42);\n" "}\n" "```" msgstr "" -#: src/std/vec.md:29 -msgid "" -"`Vec` implements [`Deref`](https://doc.rust-lang.org/std/vec/" -"struct.Vec.html#deref-methods-%5BT%5D), which means that you can call slice " -"methods on a `Vec`." +#: src/methods/example.md:47 +msgid "All four methods here use a different method receiver." msgstr "" -#: src/std/vec.md:37 +#: src/methods/example.md:48 msgid "" -"`Vec` is a type of collection, along with `String` and `HashMap`. The data " -"it contains is stored on the heap. This means the amount of data doesn't " -"need to be known at compile time. It can grow or shrink at runtime." +"You can point out how that changes what the function can do with the " +"variable values and if/how it can be used again in `main`." msgstr "" -#: src/std/vec.md:40 +#: src/methods/example.md:49 msgid "" -"Notice how `Vec` is a generic type too, but you don't have to specify `T` " -"explicitly. As always with Rust type inference, the `T` was established " -"during the first `push` call." +"You can showcase the error that appears when trying to call `finish` twice." msgstr "" -#: src/std/vec.md:42 +#: src/methods/example.md:50 msgid "" -"`vec![...]` is a canonical macro to use instead of `Vec::new()` and it " -"supports adding initial elements to the vector." +"Note that although the method receivers are different, the non-static " +"functions are called the same way in the main body. Rust enables automatic " +"referencing and dereferencing when calling methods. Rust automatically adds " +"in the `&`, `*`, `muts` so that that object matches the method signature." msgstr "" -#: src/std/vec.md:44 +#: src/methods/example.md:51 msgid "" -"To index the vector you use `[` `]`, but they will panic if out of bounds. " -"Alternatively, using `get` will return an `Option`. The `pop` function will " -"remove the last element." +"You might point out that `print_laps` is using a vector that is iterated " +"over. We describe vectors in more detail in the afternoon. " msgstr "" -#: src/std/vec.md:46 +#: src/exercises/day-2/afternoon.md:1 +msgid "Day 2: Afternoon Exercises" +msgstr "" + +#: src/exercises/day-2/afternoon.md:3 +msgid "The exercises for this afternoon will focus on strings and iterators." +msgstr "" + +#: src/exercises/day-2/health-statistics.md:3 msgid "" -"Show iterating over a vector and mutating the value: `for e in &mut v { *e " -"+= 50; }`" +"You're working on implementing a health-monitoring system. As part of that, " +"you need to keep track of users' health statistics." msgstr "" -#: src/std/hashmap.md:1 src/bare-metal/no_std.md:46 -msgid "`HashMap`" +#: src/exercises/day-2/health-statistics.md:6 +msgid "" +"You'll start with some stubbed functions in an `impl` block as well as a " +"`User` struct definition. Your goal is to implement the stubbed out methods " +"on the `User` `struct` defined in the `impl` block." msgstr "" -#: src/std/hashmap.md:3 -msgid "Standard hash map with protection against HashDoS attacks:" +#: src/exercises/day-2/health-statistics.md:10 +msgid "" +"Copy the code below to and fill in the missing " +"methods:" msgstr "" -#: src/std/hashmap.md:5 +#: src/exercises/day-2/health-statistics.md:13 msgid "" -"```rust,editable\n" -"use std::collections::HashMap;\n" +"```rust,should_panic\n" +"// TODO: remove this when you're done with your implementation.\n" +"#![allow(unused_variables, dead_code)]\n" "\n" -"fn main() {\n" -" let mut page_counts = HashMap::new();\n" -" page_counts.insert(\"Adventures of Huckleberry Finn\".to_string(), " -"207);\n" -" page_counts.insert(\"Grimms' Fairy Tales\".to_string(), 751);\n" -" page_counts.insert(\"Pride and Prejudice\".to_string(), 303);\n" +"pub struct User {\n" +" name: String,\n" +" age: u32,\n" +" height: f32,\n" +" visit_count: usize,\n" +" last_blood_pressure: Option<(u32, u32)>,\n" +"}\n" "\n" -" if !page_counts.contains_key(\"Les Misérables\") {\n" -" println!(\"We know about {} books, but not Les Misérables.\",\n" -" page_counts.len());\n" +"pub struct Measurements {\n" +" height: f32,\n" +" blood_pressure: (u32, u32),\n" +"}\n" +"\n" +"pub struct HealthReport<'a> {\n" +" patient_name: &'a str,\n" +" visit_count: u32,\n" +" height_change: f32,\n" +" blood_pressure_change: Option<(i32, i32)>,\n" +"}\n" +"\n" +"impl User {\n" +" pub fn new(name: String, age: u32, height: f32) -> Self {\n" +" unimplemented!()\n" " }\n" "\n" -" for book in [\"Pride and Prejudice\", \"Alice's Adventure in " -"Wonderland\"] {\n" -" match page_counts.get(book) {\n" -" Some(count) => println!(\"{book}: {count} pages\"),\n" -" None => println!(\"{book} is unknown.\")\n" -" }\n" +" pub fn name(&self) -> &str {\n" +" unimplemented!()\n" " }\n" "\n" -" // Use the .entry() method to insert a value if nothing is found.\n" -" for book in [\"Pride and Prejudice\", \"Alice's Adventure in " -"Wonderland\"] {\n" -" let page_count: &mut i32 = page_counts.entry(book.to_string())." -"or_insert(0);\n" -" *page_count += 1;\n" +" pub fn age(&self) -> u32 {\n" +" unimplemented!()\n" " }\n" "\n" -" println!(\"{page_counts:#?}\");\n" +" pub fn height(&self) -> f32 {\n" +" unimplemented!()\n" +" }\n" +"\n" +" pub fn doctor_visits(&self) -> u32 {\n" +" unimplemented!()\n" +" }\n" +"\n" +" pub fn set_age(&mut self, new_age: u32) {\n" +" unimplemented!()\n" +" }\n" +"\n" +" pub fn set_height(&mut self, new_height: f32) {\n" +" unimplemented!()\n" +" }\n" +"\n" +" pub fn visit_doctor(&mut self, measurements: Measurements) -> " +"HealthReport {\n" +" unimplemented!()\n" +" }\n" +"}\n" +"\n" +"fn main() {\n" +" let bob = User::new(String::from(\"Bob\"), 32, 155.2);\n" +" println!(\"I'm {} and my age is {}\", bob.name(), bob.age());\n" +"}\n" +"\n" +"#[test]\n" +"fn test_height() {\n" +" let bob = User::new(String::from(\"Bob\"), 32, 155.2);\n" +" assert_eq!(bob.height(), 155.2);\n" +"}\n" +"\n" +"#[test]\n" +"fn test_set_age() {\n" +" let mut bob = User::new(String::from(\"Bob\"), 32, 155.2);\n" +" assert_eq!(bob.age(), 32);\n" +" bob.set_age(33);\n" +" assert_eq!(bob.age(), 33);\n" +"}\n" +"\n" +"#[test]\n" +"fn test_visit() {\n" +" let mut bob = User::new(String::from(\"Bob\"), 32, 155.2);\n" +" assert_eq!(bob.doctor_visits(), 0);\n" +" let report = bob.visit_doctor(Measurements {\n" +" height: 156.1,\n" +" blood_pressure: (120, 80),\n" +" });\n" +" assert_eq!(report.patient_name, \"Bob\");\n" +" assert_eq!(report.visit_count, 1);\n" +" assert_eq!(report.blood_pressure_change, None);\n" +"\n" +" let report = bob.visit_doctor(Measurements {\n" +" height: 156.1,\n" +" blood_pressure: (115, 76),\n" +" });\n" +"\n" +" assert_eq!(report.visit_count, 2);\n" +" assert_eq!(report.blood_pressure_change, Some((-5, -4)));\n" "}\n" "```" msgstr "" -#: src/std/hashmap.md:38 +#: src/std.md:3 msgid "" -"`HashMap` is not defined in the prelude and needs to be brought into scope." +"Rust comes with a standard library which helps establish a set of common " +"types used by Rust library and programs. This way, two libraries can work " +"together smoothly because they both use the same `String` type." msgstr "" -#: src/std/hashmap.md:39 -msgid "" -"Try the following lines of code. The first line will see if a book is in the " -"hashmap and if not return an alternative value. The second line will insert " -"the alternative value in the hashmap if the book is not found." +#: src/std.md:7 +msgid "The common vocabulary types include:" msgstr "" -#: src/std/hashmap.md:41 +#: src/std.md:9 msgid "" -"```rust,ignore\n" -" let pc1 = page_counts\n" -" .get(\"Harry Potter and the Sorcerer's Stone \")\n" -" .unwrap_or(&336);\n" -" let pc2 = page_counts\n" -" .entry(\"The Hunger Games\".to_string())\n" -" .or_insert(374);\n" -"```" +"[`Option` and `Result`](std/option-result.md) types: used for optional " +"values and [error handling](error-handling.md)." msgstr "" -#: src/std/hashmap.md:49 -msgid "Unlike `vec!`, there is unfortunately no standard `hashmap!` macro." +#: src/std.md:12 +msgid "[`String`](std/string.md): the default string type used for owned data." msgstr "" -#: src/std/hashmap.md:50 -msgid "" -"Although, since Rust 1.56, HashMap implements [`From<[(K, V); N]>`](https://" -"doc.rust-lang.org/std/collections/hash_map/struct.HashMap.html#impl-" -"From%3C%5B(K,+V);+N%5D%3E-for-HashMap%3CK,+V,+RandomState%3E), which allows " -"us to easily initialize a hash map from a literal array:" +#: src/std.md:14 +msgid "[`Vec`](std/vec.md): a standard extensible vector." msgstr "" -#: src/std/hashmap.md:52 +#: src/std.md:16 msgid "" -"```rust,ignore\n" -" let page_counts = HashMap::from([\n" -" (\"Harry Potter and the Sorcerer's Stone\".to_string(), 336),\n" -" (\"The Hunger Games\".to_string(), 374),\n" -" ]);\n" -"```" +"[`HashMap`](std/hashmap.md): a hash map type with a configurable hashing " +"algorithm." msgstr "" -#: src/std/hashmap.md:59 +#: src/std.md:19 +msgid "[`Box`](std/box.md): an owned pointer for heap-allocated data." +msgstr "" + +#: src/std.md:21 msgid "" -"Alternatively HashMap can be built from any `Iterator` which yields key-" -"value tuples." +"[`Rc`](std/rc.md): a shared reference-counted pointer for heap-allocated " +"data." msgstr "" -#: src/std/hashmap.md:60 +#: src/std.md:25 msgid "" -"We are showing `HashMap`, and avoid using `&str` as key to make " -"examples easier. Using references in collections can, of course, be done, " -"but it can lead into complications with the borrow checker." +"In fact, Rust contains several layers of the Standard Library: `core`, " +"`alloc` and `std`. " msgstr "" -#: src/std/hashmap.md:62 +#: src/std.md:26 msgid "" -"Try removing `to_string()` from the example above and see if it still " -"compiles. Where do you think we might run into issues?" +"`core` includes the most basic types and functions that don't depend on " +"`libc`, allocator or even the presence of an operating system. " msgstr "" -#: src/std/box.md:1 -msgid "`Box`" +#: src/std.md:28 +msgid "" +"`alloc` includes types which require a global heap allocator, such as `Vec`, " +"`Box` and `Arc`." msgstr "" -#: src/std/box.md:3 +#: src/std.md:29 msgid "" -"[`Box`](https://doc.rust-lang.org/std/boxed/struct.Box.html) is an owned " -"pointer to data on the heap:" +"Embedded Rust applications often only use `core`, and sometimes `alloc`." msgstr "" -#: src/std/box.md:5 +#: src/std/option-result.md:1 +msgid "`Option` and `Result`" +msgstr "" + +#: src/std/option-result.md:3 +msgid "The types represent optional data:" +msgstr "" + +#: src/std/option-result.md:5 msgid "" "```rust,editable\n" "fn main() {\n" -" let five = Box::new(5);\n" -" println!(\"five: {}\", *five);\n" +" let numbers = vec![10, 20, 30];\n" +" let first: Option<&i8> = numbers.first();\n" +" println!(\"first: {first:?}\");\n" +"\n" +" let idx: Result = numbers.binary_search(&10);\n" +" println!(\"idx: {idx:?}\");\n" "}\n" "```" msgstr "" -#: src/std/box.md:13 -msgid "" -"```bob\n" -" Stack Heap\n" -".- - - - - - -. .- - - - - - -.\n" -": : : :\n" -": five : : :\n" -": +-----+ : : +-----+ :\n" -": | o---|---+-----+-->| 5 | :\n" -": +-----+ : : +-----+ :\n" -": : : :\n" -": : : :\n" -"`- - - - - - -' `- - - - - - -'\n" -"```" -msgstr "" - -#: src/std/box.md:26 -msgid "" -"`Box` implements `Deref`, which means that you can [call " -"methods from `T` directly on a `Box`](https://doc.rust-lang.org/std/ops/" -"trait.Deref.html#more-on-deref-coercion)." +#: src/std/option-result.md:18 +msgid "`Option` and `Result` are widely used not just in the standard library." msgstr "" -#: src/std/box.md:34 -msgid "" -"`Box` is like `std::unique_ptr` in C++, except that it's guaranteed to be " -"not null. " +#: src/std/option-result.md:19 +msgid "`Option<&T>` has zero space overhead compared to `&T`." msgstr "" -#: src/std/box.md:35 +#: src/std/option-result.md:20 msgid "" -"In the above example, you can even leave out the `*` in the `println!` " -"statement thanks to `Deref`. " +"`Result` is the standard type to implement error handling as we will see on " +"Day 3." msgstr "" -#: src/std/box.md:36 -msgid "A `Box` can be useful when you:" +#: src/std/option-result.md:21 +msgid "`binary_search` returns `Result`." msgstr "" -#: src/std/box.md:37 -msgid "" -"have a type whose size that can't be known at compile time, but the Rust " -"compiler wants to know an exact size." +#: src/std/option-result.md:22 +msgid "If found, `Result::Ok` holds the index where the element is found." msgstr "" -#: src/std/box.md:38 +#: src/std/option-result.md:23 msgid "" -"want to transfer ownership of a large amount of data. To avoid copying large " -"amounts of data on the stack, instead store the data on the heap in a `Box` " -"so only the pointer is moved." -msgstr "" - -#: src/std/box-recursive.md:1 -msgid "Box with Recursive Data Structures" +"Otherwise, `Result::Err` contains the index where such an element should be " +"inserted." msgstr "" -#: src/std/box-recursive.md:3 +#: src/std/string.md:3 msgid "" -"Recursive data types or data types with dynamic sizes need to use a `Box`:" +"[`String`](https://doc.rust-lang.org/std/string/struct.String.html) is the " +"standard heap-allocated growable UTF-8 string buffer:" msgstr "" -#: src/std/box-recursive.md:5 src/std/box-niche.md:3 +#: src/std/string.md:5 msgid "" "```rust,editable\n" -"#[derive(Debug)]\n" -"enum List {\n" -" Cons(T, Box>),\n" -" Nil,\n" -"}\n" -"\n" "fn main() {\n" -" let list: List = List::Cons(1, Box::new(List::Cons(2, Box::" -"new(List::Nil))));\n" -" println!(\"{list:?}\");\n" +" let mut s1 = String::new();\n" +" s1.push_str(\"Hello\");\n" +" println!(\"s1: len = {}, capacity = {}\", s1.len(), s1.capacity());\n" +"\n" +" let mut s2 = String::with_capacity(s1.len() + 1);\n" +" s2.push_str(&s1);\n" +" s2.push('!');\n" +" println!(\"s2: len = {}, capacity = {}\", s2.len(), s2.capacity());\n" +"\n" +" let s3 = String::from(\"🇨🇭\");\n" +" println!(\"s3: len = {}, number of chars = {}\", s3.len(),\n" +" s3.chars().count());\n" "}\n" "```" msgstr "" -#: src/std/box-recursive.md:18 +#: src/std/string.md:22 msgid "" -"```bob\n" -" Stack Heap\n" -".- - - - - - - - - - - - -. .- - - - - - - - - - - - - - - - - - - - - - " -"- -.\n" -": : : :\n" -": " -"list : : :\n" -": +------+----+----+ : : +------+----+----+ +------+----+----" -"+ :\n" -": | Cons | 1 | o--+----+-----+--->| Cons | 2 | o--+--->| Nil | // | // " -"| :\n" -": +------+----+----+ : : +------+----+----+ +------+----+----" -"+ :\n" -": : : :\n" -": : : :\n" -"'- - - - - - - - - - - - -' '- - - - - - - - - - - - - - - - - - - - - - " -"- -'\n" -"```" +"`String` implements [`Deref`](https://doc.rust-lang.org/std/" +"string/struct.String.html#deref-methods-str), which means that you can call " +"all `str` methods on a `String`." msgstr "" -#: src/std/box-recursive.md:33 +#: src/std/string.md:30 msgid "" -"If the `Box` was not used here and we attempted to embed a `List` directly " -"into the `List`, the compiler would not compute a fixed size of the struct " -"in memory, it would look infinite." +"`String::new` returns a new empty string, use `String::with_capacity` when " +"you know how much data you want to push to the string." msgstr "" -#: src/std/box-recursive.md:36 +#: src/std/string.md:31 msgid "" -"`Box` solves this problem as it has the same size as a regular pointer and " -"just points at the next element of the `List` in the heap." +"`String::len` returns the size of the `String` in bytes (which can be " +"different from its length in characters)." msgstr "" -#: src/std/box-recursive.md:39 +#: src/std/string.md:32 msgid "" -"Remove the `Box` in the List definition and show the compiler error. " -"\"Recursive with indirection\" is a hint you might want to use a Box or " -"reference of some kind, instead of storing a value directly." +"`String::chars` returns an iterator over the actual characters. Note that a " +"`char` can be different from what a human will consider a \"character\" due " +"to [grapheme clusters](https://docs.rs/unicode-segmentation/latest/" +"unicode_segmentation/struct.Graphemes.html)." msgstr "" -#: src/std/box-niche.md:16 +#: src/std/string.md:33 msgid "" -"A `Box` cannot be empty, so the pointer is always valid and non-`null`. This " -"allows the compiler to optimize the memory layout:" +"When people refer to strings they could either be talking about `&str` or " +"`String`." msgstr "" -#: src/std/box-niche.md:19 +#: src/std/string.md:34 msgid "" -"```bob\n" -" Stack Heap\n" -".- - - - - - - - - - - - -. .- - - - - - - - - - - - - - - - - - - - - - " -"-.\n" -": : : :\n" -": " -"list : : :\n" -": +----+----+ : : +----+----+ +----+------" -"+ :\n" -": | 1 | o--+-----------+-----+--->| 2 | o--+--->| // | null " -"| :\n" -": +----+----+ : : +----+----+ +----+------" -"+ :\n" -": : : :\n" -": : : :\n" -"`- - - - - - - - - - - - -' '- - - - - - - - - - - - - - - - - - - - - - " -"-'\n" -"```" +"When a type implements `Deref`, the compiler will let you " +"transparently call methods from `T`." msgstr "" -#: src/std/rc.md:1 -msgid "`Rc`" +#: src/std/string.md:35 +msgid "" +"`String` implements `Deref` which transparently gives it " +"access to `str`'s methods." msgstr "" -#: src/std/rc.md:3 -msgid "" -"[`Rc`](https://doc.rust-lang.org/std/rc/struct.Rc.html) is a reference-" -"counted shared pointer. Use this when you need to refer to the same data " -"from multiple places:" +#: src/std/string.md:36 +msgid "Write and compare `let s3 = s1.deref();` and `let s3 = &*s1`;." msgstr "" -#: src/std/rc.md:6 +#: src/std/string.md:37 msgid "" -"```rust,editable\n" -"use std::rc::Rc;\n" -"\n" -"fn main() {\n" -" let mut a = Rc::new(10);\n" -" let mut b = Rc::clone(&a);\n" -"\n" -" println!(\"a: {a}\");\n" -" println!(\"b: {b}\");\n" -"}\n" -"```" +"`String` is implemented as a wrapper around a vector of bytes, many of the " +"operations you see supported on vectors are also supported on `String`, but " +"with some extra guarantees." msgstr "" -#: src/std/rc.md:18 -msgid "" -"If you need to mutate the data inside an `Rc`, you will need to wrap the " -"data in a type such as [`Cell` or `RefCell`](../concurrency/shared_state/arc." -"md)." +#: src/std/string.md:38 +msgid "Compare the different ways to index a `String`:" msgstr "" -#: src/std/rc.md:20 +#: src/std/string.md:39 msgid "" -"See [`Arc`](https://doc.rust-lang.org/std/sync/struct.Mutex.html) if you are " -"in a multi-threaded context." +"To a character by using `s3.chars().nth(i).unwrap()` where `i` is in-bound, " +"out-of-bounds." msgstr "" -#: src/std/rc.md:21 +#: src/std/string.md:40 msgid "" -"You can _downgrade_ a shared pointer into a [`Weak`](https://doc.rust-lang." -"org/std/rc/struct.Weak.html) pointer to create cycles that will get dropped." +"To a substring by using `s3[0..4]`, where that slice is on character " +"boundaries or not." msgstr "" -#: src/std/rc.md:31 -msgid "" -"`Rc`'s count ensures that its contained value is valid for as long as there " -"are references." +#: src/std/vec.md:1 +msgid "`Vec`" msgstr "" -#: src/std/rc.md:32 -msgid "Like C++'s `std::shared_ptr`." -msgstr "" - -#: src/std/rc.md:33 -msgid "" -"`Rc::clone` is cheap: it creates a pointer to the same allocation and " -"increases the reference count. Does not make a deep clone and can generally " -"be ignored when looking for performance issues in code." -msgstr "" - -#: src/std/rc.md:34 -msgid "" -"`make_mut` actually clones the inner value if necessary (\"clone-on-write\") " -"and returns a mutable reference." -msgstr "" - -#: src/std/rc.md:35 -msgid "Use `Rc::strong_count` to check the reference count." -msgstr "" - -#: src/std/rc.md:36 -msgid "" -"Compare the different datatypes mentioned. `Box` enables (im)mutable borrows " -"that are enforced at compile time. `RefCell` enables (im)mutable borrows " -"that are enforced at run time and will panic if it fails at runtime." -msgstr "" - -#: src/std/rc.md:37 +#: src/std/vec.md:3 msgid "" -"`Rc::downgrade` gives you a _weakly reference-counted_ object to create " -"cycles that will be dropped properly (likely in combination with `RefCell`)." +"[`Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html) is the standard " +"resizable heap-allocated buffer:" msgstr "" -#: src/std/rc.md:41 +#: src/std/vec.md:5 msgid "" "```rust,editable\n" -"use std::rc::{Rc, Weak};\n" -"use std::cell::RefCell;\n" +"fn main() {\n" +" let mut v1 = Vec::new();\n" +" v1.push(42);\n" +" println!(\"v1: len = {}, capacity = {}\", v1.len(), v1.capacity());\n" "\n" -"#[derive(Debug)]\n" -"struct Node {\n" -" value: i64,\n" -" parent: Option>>,\n" -" children: Vec>>,\n" -"}\n" +" let mut v2 = Vec::with_capacity(v1.len() + 1);\n" +" v2.extend(v1.iter());\n" +" v2.push(9999);\n" +" println!(\"v2: len = {}, capacity = {}\", v2.len(), v2.capacity());\n" "\n" -"fn main() {\n" -" let mut root = Rc::new(RefCell::new(Node {\n" -" value: 42,\n" -" parent: None,\n" -" children: vec![],\n" -" }));\n" -" let child = Rc::new(RefCell::new(Node {\n" -" value: 43,\n" -" children: vec![],\n" -" parent: Some(Rc::downgrade(&root))\n" -" }));\n" -" root.borrow_mut().children.push(child);\n" +" // Canonical macro to initialize a vector with elements.\n" +" let mut v3 = vec![0, 0, 1, 2, 3, 4];\n" "\n" -" println!(\"graph: {root:#?}\");\n" +" // Retain only the even elements.\n" +" v3.retain(|x| x % 2 == 0);\n" +" println!(\"{v3:?}\");\n" +"\n" +" // Remove consecutive duplicates.\n" +" v3.dedup();\n" +" println!(\"{v3:?}\");\n" "}\n" "```" msgstr "" -#: src/modules.md:3 -msgid "We have seen how `impl` blocks let us namespace functions to a type." -msgstr "" - -#: src/modules.md:5 -msgid "Similarly, `mod` lets us namespace types and functions:" -msgstr "" - -#: src/modules.md:7 +#: src/std/vec.md:29 msgid "" -"```rust,editable\n" -"mod foo {\n" -" pub fn do_something() {\n" -" println!(\"In the foo module\");\n" -" }\n" -"}\n" -"\n" -"mod bar {\n" -" pub fn do_something() {\n" -" println!(\"In the bar module\");\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" foo::do_something();\n" -" bar::do_something();\n" -"}\n" -"```" +"`Vec` implements [`Deref`](https://doc.rust-lang.org/std/vec/" +"struct.Vec.html#deref-methods-%5BT%5D), which means that you can call slice " +"methods on a `Vec`." msgstr "" -#: src/modules.md:28 +#: src/std/vec.md:37 msgid "" -"Packages provide functionality and include a `Cargo.toml` file that " -"describes how to build a bundle of 1+ crates." +"`Vec` is a type of collection, along with `String` and `HashMap`. The data " +"it contains is stored on the heap. This means the amount of data doesn't " +"need to be known at compile time. It can grow or shrink at runtime." msgstr "" -#: src/modules.md:29 +#: src/std/vec.md:40 msgid "" -"Crates are a tree of modules, where a binary crate creates an executable and " -"a library crate compiles to a library." +"Notice how `Vec` is a generic type too, but you don't have to specify `T` " +"explicitly. As always with Rust type inference, the `T` was established " +"during the first `push` call." msgstr "" -#: src/modules.md:30 -msgid "Modules define organization, scope, and are the focus of this section." +#: src/std/vec.md:42 +msgid "" +"`vec![...]` is a canonical macro to use instead of `Vec::new()` and it " +"supports adding initial elements to the vector." msgstr "" -#: src/modules/visibility.md:3 -msgid "Modules are a privacy boundary:" +#: src/std/vec.md:44 +msgid "" +"To index the vector you use `[` `]`, but they will panic if out of bounds. " +"Alternatively, using `get` will return an `Option`. The `pop` function will " +"remove the last element." msgstr "" -#: src/modules/visibility.md:5 -msgid "Module items are private by default (hides implementation details)." +#: src/std/vec.md:46 +msgid "" +"Show iterating over a vector and mutating the value: `for e in &mut v { *e " +"+= 50; }`" msgstr "" -#: src/modules/visibility.md:6 -msgid "Parent and sibling items are always visible." +#: src/std/hashmap.md:1 src/bare-metal/no_std.md:46 +msgid "`HashMap`" msgstr "" -#: src/modules/visibility.md:7 -msgid "" -"In other words, if an item is visible in module `foo`, it's visible in all " -"the descendants of `foo`." +#: src/std/hashmap.md:3 +msgid "Standard hash map with protection against HashDoS attacks:" msgstr "" -#: src/modules/visibility.md:10 +#: src/std/hashmap.md:5 msgid "" "```rust,editable\n" -"mod outer {\n" -" fn private() {\n" -" println!(\"outer::private\");\n" -" }\n" +"use std::collections::HashMap;\n" "\n" -" pub fn public() {\n" -" println!(\"outer::public\");\n" +"fn main() {\n" +" let mut page_counts = HashMap::new();\n" +" page_counts.insert(\"Adventures of Huckleberry Finn\".to_string(), " +"207);\n" +" page_counts.insert(\"Grimms' Fairy Tales\".to_string(), 751);\n" +" page_counts.insert(\"Pride and Prejudice\".to_string(), 303);\n" +"\n" +" if !page_counts.contains_key(\"Les Misérables\") {\n" +" println!(\"We know about {} books, but not Les Misérables.\",\n" +" page_counts.len());\n" " }\n" "\n" -" mod inner {\n" -" fn private() {\n" -" println!(\"outer::inner::private\");\n" +" for book in [\"Pride and Prejudice\", \"Alice's Adventure in " +"Wonderland\"] {\n" +" match page_counts.get(book) {\n" +" Some(count) => println!(\"{book}: {count} pages\"),\n" +" None => println!(\"{book} is unknown.\")\n" " }\n" +" }\n" "\n" -" pub fn public() {\n" -" println!(\"outer::inner::public\");\n" -" super::private();\n" -" }\n" +" // Use the .entry() method to insert a value if nothing is found.\n" +" for book in [\"Pride and Prejudice\", \"Alice's Adventure in " +"Wonderland\"] {\n" +" let page_count: &mut i32 = page_counts.entry(book.to_string())." +"or_insert(0);\n" +" *page_count += 1;\n" " }\n" -"}\n" "\n" -"fn main() {\n" -" outer::public();\n" +" println!(\"{page_counts:#?}\");\n" "}\n" "```" msgstr "" -#: src/modules/visibility.md:39 -msgid "Use the `pub` keyword to make modules public." -msgstr "" - -#: src/modules/visibility.md:41 +#: src/std/hashmap.md:38 msgid "" -"Additionally, there are advanced `pub(...)` specifiers to restrict the scope " -"of public visibility." +"`HashMap` is not defined in the prelude and needs to be brought into scope." msgstr "" -#: src/modules/visibility.md:43 +#: src/std/hashmap.md:39 msgid "" -"See the [Rust Reference](https://doc.rust-lang.org/reference/visibility-and-" -"privacy.html#pubin-path-pubcrate-pubsuper-and-pubself)." +"Try the following lines of code. The first line will see if a book is in the " +"hashmap and if not return an alternative value. The second line will insert " +"the alternative value in the hashmap if the book is not found." msgstr "" -#: src/modules/visibility.md:44 -msgid "Configuring `pub(crate)` visibility is a common pattern." +#: src/std/hashmap.md:41 +msgid "" +"```rust,ignore\n" +" let pc1 = page_counts\n" +" .get(\"Harry Potter and the Sorcerer's Stone \")\n" +" .unwrap_or(&336);\n" +" let pc2 = page_counts\n" +" .entry(\"The Hunger Games\".to_string())\n" +" .or_insert(374);\n" +"```" msgstr "" -#: src/modules/visibility.md:45 -msgid "Less commonly, you can give visibility to a specific path." +#: src/std/hashmap.md:49 +msgid "Unlike `vec!`, there is unfortunately no standard `hashmap!` macro." msgstr "" -#: src/modules/visibility.md:46 +#: src/std/hashmap.md:50 msgid "" -"In any case, visibility must be granted to an ancestor module (and all of " -"its descendants)." -msgstr "" - -#: src/modules/paths.md:3 -msgid "Paths are resolved as follows:" +"Although, since Rust 1.56, HashMap implements [`From<[(K, V); N]>`](https://" +"doc.rust-lang.org/std/collections/hash_map/struct.HashMap.html#impl-" +"From%3C%5B(K,+V);+N%5D%3E-for-HashMap%3CK,+V,+RandomState%3E), which allows " +"us to easily initialize a hash map from a literal array:" msgstr "" -#: src/modules/paths.md:5 -msgid "As a relative path:" +#: src/std/hashmap.md:52 +msgid "" +"```rust,ignore\n" +" let page_counts = HashMap::from([\n" +" (\"Harry Potter and the Sorcerer's Stone\".to_string(), 336),\n" +" (\"The Hunger Games\".to_string(), 374),\n" +" ]);\n" +"```" msgstr "" -#: src/modules/paths.md:6 -msgid "`foo` or `self::foo` refers to `foo` in the current module," +#: src/std/hashmap.md:59 +msgid "" +"Alternatively HashMap can be built from any `Iterator` which yields key-" +"value tuples." msgstr "" -#: src/modules/paths.md:7 -msgid "`super::foo` refers to `foo` in the parent module." +#: src/std/hashmap.md:60 +msgid "" +"We are showing `HashMap`, and avoid using `&str` as key to make " +"examples easier. Using references in collections can, of course, be done, " +"but it can lead into complications with the borrow checker." msgstr "" -#: src/modules/paths.md:9 -msgid "As an absolute path:" +#: src/std/hashmap.md:62 +msgid "" +"Try removing `to_string()` from the example above and see if it still " +"compiles. Where do you think we might run into issues?" msgstr "" -#: src/modules/paths.md:10 -msgid "`crate::foo` refers to `foo` in the root of the current crate," +#: src/std/hashmap.md:64 +msgid "" +"This type has several \"method-specific\" return types, such as `std::" +"collections::hash_map::Keys`. These types often appear in searches of the " +"Rust docs. Show students the docs for this type, and the helpful link back " +"to the `keys` method." msgstr "" -#: src/modules/paths.md:11 -msgid "`bar::foo` refers to `foo` in the `bar` crate." +#: src/std/box.md:1 +msgid "`Box`" msgstr "" -#: src/modules/paths.md:13 +#: src/std/box.md:3 msgid "" -"A module can bring symbols from another module into scope with `use`. You " -"will typically see something like this at the top of each module:" +"[`Box`](https://doc.rust-lang.org/std/boxed/struct.Box.html) is an owned " +"pointer to data on the heap:" msgstr "" -#: src/modules/paths.md:16 +#: src/std/box.md:5 msgid "" "```rust,editable\n" -"use std::collections::HashSet;\n" -"use std::mem::transmute;\n" +"fn main() {\n" +" let five = Box::new(5);\n" +" println!(\"five: {}\", *five);\n" +"}\n" "```" msgstr "" -#: src/modules/filesystem.md:3 -msgid "The module content can be omitted:" +#: src/std/box.md:13 +msgid "" +"```bob\n" +" Stack Heap\n" +".- - - - - - -. .- - - - - - -.\n" +": : : :\n" +": five : : :\n" +": +-----+ : : +-----+ :\n" +": | o---|---+-----+-->| 5 | :\n" +": +-----+ : : +-----+ :\n" +": : : :\n" +": : : :\n" +"`- - - - - - -' `- - - - - - -'\n" +"```" msgstr "" -#: src/modules/filesystem.md:5 +#: src/std/box.md:26 msgid "" -"```rust,editable,compile_fail\n" -"mod garden;\n" -"```" +"`Box` implements `Deref`, which means that you can [call " +"methods from `T` directly on a `Box`](https://doc.rust-lang.org/std/ops/" +"trait.Deref.html#more-on-deref-coercion)." msgstr "" -#: src/modules/filesystem.md:9 -msgid "The `garden` module content is found at:" +#: src/std/box.md:34 +msgid "" +"`Box` is like `std::unique_ptr` in C++, except that it's guaranteed to be " +"not null. " msgstr "" -#: src/modules/filesystem.md:11 -msgid "`src/garden.rs` (modern Rust 2018 style)" +#: src/std/box.md:35 +msgid "" +"In the above example, you can even leave out the `*` in the `println!` " +"statement thanks to `Deref`. " msgstr "" -#: src/modules/filesystem.md:12 -msgid "`src/garden/mod.rs` (older Rust 2015 style)" +#: src/std/box.md:36 +msgid "A `Box` can be useful when you:" msgstr "" -#: src/modules/filesystem.md:14 -msgid "Similarly, a `garden::vegetables` module can be found at:" +#: src/std/box.md:37 +msgid "" +"have a type whose size that can't be known at compile time, but the Rust " +"compiler wants to know an exact size." msgstr "" -#: src/modules/filesystem.md:16 -msgid "`src/garden/vegetables.rs` (modern Rust 2018 style)" +#: src/std/box.md:38 +msgid "" +"want to transfer ownership of a large amount of data. To avoid copying large " +"amounts of data on the stack, instead store the data on the heap in a `Box` " +"so only the pointer is moved." msgstr "" -#: src/modules/filesystem.md:17 -msgid "`src/garden/vegetables/mod.rs` (older Rust 2015 style)" +#: src/std/box-recursive.md:1 +msgid "Box with Recursive Data Structures" msgstr "" -#: src/modules/filesystem.md:19 -msgid "The `crate` root is in:" +#: src/std/box-recursive.md:3 +msgid "" +"Recursive data types or data types with dynamic sizes need to use a `Box`:" msgstr "" -#: src/modules/filesystem.md:21 -msgid "`src/lib.rs` (for a library crate)" +#: src/std/box-recursive.md:5 src/std/box-niche.md:3 +msgid "" +"```rust,editable\n" +"#[derive(Debug)]\n" +"enum List {\n" +" Cons(T, Box>),\n" +" Nil,\n" +"}\n" +"\n" +"fn main() {\n" +" let list: List = List::Cons(1, Box::new(List::Cons(2, Box::" +"new(List::Nil))));\n" +" println!(\"{list:?}\");\n" +"}\n" +"```" msgstr "" -#: src/modules/filesystem.md:22 -msgid "`src/main.rs` (for a binary crate)" +#: src/std/box-recursive.md:18 +msgid "" +"```bob\n" +" Stack Heap\n" +".- - - - - - - - - - - - -. .- - - - - - - - - - - - - - - - - - - - - - " +"- -.\n" +": : : :\n" +": " +"list : : :\n" +": +------+----+----+ : : +------+----+----+ +------+----+----" +"+ :\n" +": | Cons | 1 | o--+----+-----+--->| Cons | 2 | o--+--->| Nil | // | // " +"| :\n" +": +------+----+----+ : : +------+----+----+ +------+----+----" +"+ :\n" +": : : :\n" +": : : :\n" +"'- - - - - - - - - - - - -' '- - - - - - - - - - - - - - - - - - - - - - " +"- -'\n" +"```" msgstr "" -#: src/modules/filesystem.md:24 +#: src/std/box-recursive.md:33 msgid "" -"Modules defined in files can be documented, too, using \"inner doc " -"comments\". These document the item that contains them -- in this case, a " -"module." +"If `Box` was not used and we attempted to embed a `List` directly into the " +"`List`, the compiler would not compute a fixed size of the struct in memory " +"(`List` would be of infinite size)." msgstr "" -#: src/modules/filesystem.md:27 +#: src/std/box-recursive.md:36 msgid "" -"```rust,editable,compile_fail\n" -"//! This module implements the garden, including a highly performant " -"germination\n" -"//! implementation.\n" -"\n" -"// Re-export types from this module.\n" -"pub use seeds::SeedPacket;\n" -"pub use garden::Garden;\n" -"\n" -"/// Sow the given seed packets.\n" -"pub fn sow(seeds: Vec) { todo!() }\n" -"\n" -"/// Harvest the produce in the garden that is ready.\n" -"pub fn harvest(garden: &mut Garden) { todo!() }\n" -"```" +"`Box` solves this problem as it has the same size as a regular pointer and " +"just points at the next element of the `List` in the heap." msgstr "" -#: src/modules/filesystem.md:44 +#: src/std/box-recursive.md:39 msgid "" -"The change from `module/mod.rs` to `module.rs` doesn't preclude the use of " -"submodules in Rust 2018. (It was mandatory in Rust 2015.)" +"Remove the `Box` in the List definition and show the compiler error. " +"\"Recursive with indirection\" is a hint you might want to use a Box or " +"reference of some kind, instead of storing a value directly." msgstr "" -#: src/modules/filesystem.md:47 -msgid "The following is valid:" +#: src/std/box-niche.md:16 +msgid "" +"A `Box` cannot be empty, so the pointer is always valid and non-`null`. This " +"allows the compiler to optimize the memory layout:" msgstr "" -#: src/modules/filesystem.md:49 +#: src/std/box-niche.md:19 msgid "" -"```ignore\n" -"src/\n" -"├── main.rs\n" -"├── top_module.rs\n" -"└── top_module/\n" -" └── sub_module.rs\n" +"```bob\n" +" Stack Heap\n" +".- - - - - - - - - - - - -. .- - - - - - - - - - - - - - - - - - - - - - " +"-.\n" +": : : :\n" +": " +"list : : :\n" +": +----+----+ : : +----+----+ +----+------" +"+ :\n" +": | 1 | o--+-----------+-----+--->| 2 | o--+--->| // | null " +"| :\n" +": +----+----+ : : +----+----+ +----+------" +"+ :\n" +": : : :\n" +": : : :\n" +"`- - - - - - - - - - - - -' '- - - - - - - - - - - - - - - - - - - - - - " +"-'\n" "```" msgstr "" -#: src/modules/filesystem.md:57 -msgid "" -"The main reason for the change is to prevent many files named `mod.rs`, " -"which can be hard to distinguish in IDEs." +#: src/std/rc.md:1 +msgid "`Rc`" msgstr "" -#: src/modules/filesystem.md:60 +#: src/std/rc.md:3 msgid "" -"Rust will look for modules in `modulename/mod.rs` and `modulename.rs`, but " -"this can be changed with a compiler directive:" +"[`Rc`](https://doc.rust-lang.org/std/rc/struct.Rc.html) is a reference-" +"counted shared pointer. Use this when you need to refer to the same data " +"from multiple places:" msgstr "" -#: src/modules/filesystem.md:63 +#: src/std/rc.md:6 msgid "" -"```rust,ignore\n" -"#[path = \"some/path.rs\"]\n" -"mod some_module { }\n" +"```rust,editable\n" +"use std::rc::Rc;\n" +"\n" +"fn main() {\n" +" let mut a = Rc::new(10);\n" +" let mut b = Rc::clone(&a);\n" +"\n" +" println!(\"a: {a}\");\n" +" println!(\"b: {b}\");\n" +"}\n" "```" msgstr "" -#: src/modules/filesystem.md:68 +#: src/std/rc.md:18 msgid "" -"This is useful, for example, if you would like to place tests for a module " -"in a file named `some_module_test.rs`, similar to the convention in Go." +"See [`Arc`](../concurrency/shared_state/arc.md) and [`Mutex`](https://doc." +"rust-lang.org/std/sync/struct.Mutex.html) if you are in a multi-threaded " +"context." msgstr "" -#: src/exercises/day-2/afternoon.md:1 -msgid "Day 2: Afternoon Exercises" +#: src/std/rc.md:19 +msgid "" +"You can _downgrade_ a shared pointer into a [`Weak`](https://doc.rust-lang." +"org/std/rc/struct.Weak.html) pointer to create cycles that will get dropped." msgstr "" -#: src/exercises/day-2/afternoon.md:3 -msgid "The exercises for this afternoon will focus on strings and iterators." +#: src/std/rc.md:29 +msgid "" +"`Rc`'s count ensures that its contained value is valid for as long as there " +"are references." msgstr "" -#: src/exercises/day-2/luhn.md:3 -msgid "" -"The [Luhn algorithm](https://en.wikipedia.org/wiki/Luhn_algorithm) is used " -"to validate credit card numbers. The algorithm takes a string as input and " -"does the following to validate the credit card number:" +#: src/std/rc.md:30 +msgid "`Rc` in Rust is like `std::shared_ptr` in C++." msgstr "" -#: src/exercises/day-2/luhn.md:7 -msgid "Ignore all spaces. Reject number with less than two digits." +#: src/std/rc.md:31 +msgid "" +"`Rc::clone` is cheap: it creates a pointer to the same allocation and " +"increases the reference count. Does not make a deep clone and can generally " +"be ignored when looking for performance issues in code." msgstr "" -#: src/exercises/day-2/luhn.md:9 +#: src/std/rc.md:32 msgid "" -"Moving from right to left, double every second digit: for the number `1234`, " -"we double `3` and `1`." +"`make_mut` actually clones the inner value if necessary (\"clone-on-write\") " +"and returns a mutable reference." +msgstr "" + +#: src/std/rc.md:33 +msgid "Use `Rc::strong_count` to check the reference count." msgstr "" -#: src/exercises/day-2/luhn.md:12 +#: src/std/rc.md:34 msgid "" -"After doubling a digit, sum the digits. So doubling `7` becomes `14` which " -"becomes `5`." +"`Rc::downgrade` gives you a _weakly reference-counted_ object to create " +"cycles that will be dropped properly (likely in combination with `RefCell`, " +"on the next slide)." msgstr "" -#: src/exercises/day-2/luhn.md:15 -msgid "Sum all the undoubled and doubled digits." +#: src/std/cell.md:1 +msgid "`Cell` and `RefCell`" msgstr "" -#: src/exercises/day-2/luhn.md:17 -msgid "The credit card number is valid if the sum ends with `0`." +#: src/std/cell.md:3 +msgid "" +"[`Cell`](https://doc.rust-lang.org/std/cell/struct.Cell.html) and [`RefCell`]" +"(https://doc.rust-lang.org/std/cell/struct.RefCell.html) implement what Rust " +"calls _interior mutability:_ mutation of values in an immutable context." msgstr "" -#: src/exercises/day-2/luhn.md:19 +#: src/std/cell.md:8 msgid "" -"Copy the following code to and implement the " -"function:" +"`Cell` is typically used for simple types, as it requires copying or moving " +"values. More complex interior types typically use `RefCell`, which tracks " +"shared and exclusive references at runtime and panics if they are misused." msgstr "" -#: src/exercises/day-2/luhn.md:23 +#: src/std/cell.md:12 msgid "" -"```rust\n" -"// TODO: remove this when you're done with your implementation.\n" -"#![allow(unused_variables, dead_code)]\n" -"\n" -"pub fn luhn(cc_number: &str) -> bool {\n" -" unimplemented!()\n" -"}\n" -"\n" -"#[test]\n" -"fn test_non_digit_cc_number() {\n" -" assert!(!luhn(\"foo\"));\n" -"}\n" +"```rust,editable\n" +"use std::cell::RefCell;\n" +"use std::rc::Rc;\n" "\n" -"#[test]\n" -"fn test_empty_cc_number() {\n" -" assert!(!luhn(\"\"));\n" -" assert!(!luhn(\" \"));\n" -" assert!(!luhn(\" \"));\n" -" assert!(!luhn(\" \"));\n" +"#[derive(Debug, Default)]\n" +"struct Node {\n" +" value: i64,\n" +" children: Vec>>,\n" "}\n" "\n" -"#[test]\n" -"fn test_single_digit_cc_number() {\n" -" assert!(!luhn(\"0\"));\n" -"}\n" +"impl Node {\n" +" fn new(value: i64) -> Rc> {\n" +" Rc::new(RefCell::new(Node { value, ..Node::default() }))\n" +" }\n" "\n" -"#[test]\n" -"fn test_two_digit_cc_number() {\n" -" assert!(luhn(\" 0 0 \"));\n" +" fn sum(&self) -> i64 {\n" +" self.value + self.children.iter().map(|c| c.borrow().sum()).sum::" +"()\n" +" }\n" "}\n" "\n" -"#[test]\n" -"fn test_valid_cc_number() {\n" -" assert!(luhn(\"4263 9826 4026 9299\"));\n" -" assert!(luhn(\"4539 3195 0343 6467\"));\n" -" assert!(luhn(\"7992 7398 713\"));\n" -"}\n" +"fn main() {\n" +" let root = Node::new(1);\n" +" root.borrow_mut().children.push(Node::new(5));\n" +" let subtree = Node::new(10);\n" +" subtree.borrow_mut().children.push(Node::new(11));\n" +" subtree.borrow_mut().children.push(Node::new(12));\n" +" root.borrow_mut().children.push(subtree);\n" "\n" -"#[test]\n" -"fn test_invalid_cc_number() {\n" -" assert!(!luhn(\"4223 9826 4026 9299\"));\n" -" assert!(!luhn(\"4539 3195 0343 6476\"));\n" -" assert!(!luhn(\"8273 1232 7352 0569\"));\n" +" println!(\"graph: {root:#?}\");\n" +" println!(\"graph sum: {}\", root.borrow().sum());\n" "}\n" -"\n" -"#[allow(dead_code)]\n" -"fn main() {}\n" "```" msgstr "" -#: src/exercises/day-2/strings-iterators.md:3 +#: src/std/cell.md:47 msgid "" -"In this exercise, you are implementing a routing component of a web server. " -"The server is configured with a number of _path prefixes_ which are matched " -"against _request paths_. The path prefixes can contain a wildcard character " -"which matches a full segment. See the unit tests below." +"If we were using `Cell` instead of `RefCell` in this example, we would have " +"to move the `Node` out of the `Rc` to push children, then move it back in. " +"This is safe because there's always one, un-referenced value in the cell, " +"but it's not ergonomic." msgstr "" -#: src/exercises/day-2/strings-iterators.md:8 +#: src/std/cell.md:48 msgid "" -"Copy the following code to and make the tests " -"pass. Try avoiding allocating a `Vec` for your intermediate results:" +"To do anything with a Node, you must call a `RefCell` method, usually " +"`borrow` or `borrow_mut`." msgstr "" -#: src/exercises/day-2/strings-iterators.md:12 +#: src/std/cell.md:49 msgid "" -"```rust\n" -"// TODO: remove this when you're done with your implementation.\n" -"#![allow(unused_variables, dead_code)]\n" -"\n" -"pub fn prefix_matches(prefix: &str, request_path: &str) -> bool {\n" -" unimplemented!()\n" -"}\n" -"\n" -"#[test]\n" -"fn test_matches_without_wildcard() {\n" -" assert!(prefix_matches(\"/v1/publishers\", \"/v1/publishers\"));\n" -" assert!(prefix_matches(\"/v1/publishers\", \"/v1/publishers/" -"abc-123\"));\n" -" assert!(prefix_matches(\"/v1/publishers\", \"/v1/publishers/abc/" -"books\"));\n" -"\n" -" assert!(!prefix_matches(\"/v1/publishers\", \"/v1\"));\n" -" assert!(!prefix_matches(\"/v1/publishers\", \"/v1/publishersBooks\"));\n" -" assert!(!prefix_matches(\"/v1/publishers\", \"/v1/parent/" -"publishers\"));\n" -"}\n" -"\n" -"#[test]\n" -"fn test_matches_with_wildcard() {\n" -" assert!(prefix_matches(\n" -" \"/v1/publishers/*/books\",\n" -" \"/v1/publishers/foo/books\"\n" -" ));\n" -" assert!(prefix_matches(\n" -" \"/v1/publishers/*/books\",\n" -" \"/v1/publishers/bar/books\"\n" -" ));\n" -" assert!(prefix_matches(\n" -" \"/v1/publishers/*/books\",\n" -" \"/v1/publishers/foo/books/book1\"\n" -" ));\n" -"\n" -" assert!(!prefix_matches(\"/v1/publishers/*/books\", \"/v1/" -"publishers\"));\n" -" assert!(!prefix_matches(\n" -" \"/v1/publishers/*/books\",\n" -" \"/v1/publishers/foo/booksByAuthor\"\n" -" ));\n" -"}\n" -"```" -msgstr "" - -#: src/welcome-day-3.md:1 -msgid "Welcome to Day 3" -msgstr "" - -#: src/welcome-day-3.md:3 -msgid "Today, we will cover some more advanced topics of Rust:" +"Demonstrate that reference loops can be created by adding `root` to `subtree." +"children` (don't try to print it!)." msgstr "" -#: src/welcome-day-3.md:5 +#: src/std/cell.md:50 msgid "" -"Traits: deriving traits, default methods, and important standard library " -"traits." +"To demonstrate a runtime panic, add a `fn inc(&mut self)` that increments " +"`self.value` and calls the same method on its children. This will panic in " +"the presence of the reference loop, with `thread 'main' panicked at 'already " +"borrowed: BorrowMutError'`." msgstr "" -#: src/welcome-day-3.md:8 -msgid "" -"Generics: generic data types, generic methods, monomorphization, and trait " -"objects." +#: src/modules.md:3 +msgid "We have seen how `impl` blocks let us namespace functions to a type." msgstr "" -#: src/welcome-day-3.md:11 -msgid "Error handling: panics, `Result`, and the try operator `?`." +#: src/modules.md:5 +msgid "Similarly, `mod` lets us namespace types and functions:" msgstr "" -#: src/welcome-day-3.md:13 -msgid "Testing: unit tests, documentation tests, and integration tests." +#: src/modules.md:7 +msgid "" +"```rust,editable\n" +"mod foo {\n" +" pub fn do_something() {\n" +" println!(\"In the foo module\");\n" +" }\n" +"}\n" +"\n" +"mod bar {\n" +" pub fn do_something() {\n" +" println!(\"In the bar module\");\n" +" }\n" +"}\n" +"\n" +"fn main() {\n" +" foo::do_something();\n" +" bar::do_something();\n" +"}\n" +"```" msgstr "" -#: src/welcome-day-3.md:15 +#: src/modules.md:28 msgid "" -"Unsafe Rust: raw pointers, static variables, unsafe functions, and extern " -"functions." +"Packages provide functionality and include a `Cargo.toml` file that " +"describes how to build a bundle of 1+ crates." msgstr "" -#: src/generics.md:3 +#: src/modules.md:29 msgid "" -"Rust support generics, which lets you abstract an algorithm (such as " -"sorting) over the types used in the algorithm." +"Crates are a tree of modules, where a binary crate creates an executable and " +"a library crate compiles to a library." msgstr "" -#: src/generics/data-types.md:3 -msgid "You can use generics to abstract over the concrete field type:" +#: src/modules.md:30 +msgid "Modules define organization, scope, and are the focus of this section." msgstr "" -#: src/generics/data-types.md:5 -msgid "" -"```rust,editable\n" -"#[derive(Debug)]\n" -"struct Point {\n" -" x: T,\n" -" y: T,\n" -"}\n" -"\n" -"fn main() {\n" -" let integer = Point { x: 5, y: 10 };\n" -" let float = Point { x: 1.0, y: 4.0 };\n" -" println!(\"{integer:?} and {float:?}\");\n" -"}\n" -"```" +#: src/modules/visibility.md:3 +msgid "Modules are a privacy boundary:" msgstr "" -#: src/generics/data-types.md:21 -msgid "Try declaring a new variable `let p = Point { x: 5, y: 10.0 };`." +#: src/modules/visibility.md:5 +msgid "Module items are private by default (hides implementation details)." msgstr "" -#: src/generics/data-types.md:23 -msgid "Fix the code to allow points that have elements of different types." +#: src/modules/visibility.md:6 +msgid "Parent and sibling items are always visible." msgstr "" -#: src/generics/methods.md:3 -msgid "You can declare a generic type on your `impl` block:" +#: src/modules/visibility.md:7 +msgid "" +"In other words, if an item is visible in module `foo`, it's visible in all " +"the descendants of `foo`." msgstr "" -#: src/generics/methods.md:5 +#: src/modules/visibility.md:10 msgid "" "```rust,editable\n" -"#[derive(Debug)]\n" -"struct Point(T, T);\n" +"mod outer {\n" +" fn private() {\n" +" println!(\"outer::private\");\n" +" }\n" "\n" -"impl Point {\n" -" fn x(&self) -> &T {\n" -" &self.0 // + 10\n" +" pub fn public() {\n" +" println!(\"outer::public\");\n" " }\n" "\n" -" // fn set_x(&mut self, x: T)\n" +" mod inner {\n" +" fn private() {\n" +" println!(\"outer::inner::private\");\n" +" }\n" +"\n" +" pub fn public() {\n" +" println!(\"outer::inner::public\");\n" +" super::private();\n" +" }\n" +" }\n" "}\n" "\n" "fn main() {\n" -" let p = Point(5, 10);\n" -" println!(\"p.x = {}\", p.x());\n" +" outer::public();\n" "}\n" "```" msgstr "" -#: src/generics/methods.md:25 +#: src/modules/visibility.md:39 +msgid "Use the `pub` keyword to make modules public." +msgstr "" + +#: src/modules/visibility.md:41 msgid "" -"_Q:_ Why `T` is specified twice in `impl Point {}`? Isn't that " -"redundant?" +"Additionally, there are advanced `pub(...)` specifiers to restrict the scope " +"of public visibility." msgstr "" -#: src/generics/methods.md:26 +#: src/modules/visibility.md:43 msgid "" -"This is because it is a generic implementation section for generic type. " -"They are independently generic." +"See the [Rust Reference](https://doc.rust-lang.org/reference/visibility-and-" +"privacy.html#pubin-path-pubcrate-pubsuper-and-pubself)." msgstr "" -#: src/generics/methods.md:27 -msgid "It means these methods are defined for any `T`." +#: src/modules/visibility.md:44 +msgid "Configuring `pub(crate)` visibility is a common pattern." msgstr "" -#: src/generics/methods.md:28 -msgid "It is possible to write `impl Point { .. }`. " +#: src/modules/visibility.md:45 +msgid "Less commonly, you can give visibility to a specific path." msgstr "" -#: src/generics/methods.md:29 +#: src/modules/visibility.md:46 msgid "" -"`Point` is still generic and you can use `Point`, but methods in this " -"block will only be available for `Point`." +"In any case, visibility must be granted to an ancestor module (and all of " +"its descendants)." msgstr "" -#: src/generics/monomorphization.md:3 -msgid "Generic code is turned into non-generic code based on the call sites:" +#: src/modules/paths.md:3 +msgid "Paths are resolved as follows:" msgstr "" -#: src/generics/monomorphization.md:5 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let integer = Some(5);\n" -" let float = Some(5.0);\n" -"}\n" -"```" +#: src/modules/paths.md:5 +msgid "As a relative path:" msgstr "" -#: src/generics/monomorphization.md:12 -msgid "behaves as if you wrote" +#: src/modules/paths.md:6 +msgid "`foo` or `self::foo` refers to `foo` in the current module," msgstr "" -#: src/generics/monomorphization.md:14 -msgid "" -"```rust,editable\n" -"enum Option_i32 {\n" -" Some(i32),\n" -" None,\n" -"}\n" -"\n" -"enum Option_f64 {\n" -" Some(f64),\n" -" None,\n" -"}\n" -"\n" -"fn main() {\n" -" let integer = Option_i32::Some(5);\n" -" let float = Option_f64::Some(5.0);\n" -"}\n" -"```" +#: src/modules/paths.md:7 +msgid "`super::foo` refers to `foo` in the parent module." msgstr "" -#: src/generics/monomorphization.md:31 -msgid "" -"This is a zero-cost abstraction: you get exactly the same result as if you " -"had hand-coded the data structures without the abstraction." +#: src/modules/paths.md:9 +msgid "As an absolute path:" msgstr "" -#: src/traits.md:3 -msgid "" -"Rust lets you abstract over types with traits. They're similar to interfaces:" +#: src/modules/paths.md:10 +msgid "`crate::foo` refers to `foo` in the root of the current crate," msgstr "" -#: src/traits.md:5 +#: src/modules/paths.md:11 +msgid "`bar::foo` refers to `foo` in the `bar` crate." +msgstr "" + +#: src/modules/paths.md:13 msgid "" -"```rust,editable\n" -"trait Pet {\n" -" fn name(&self) -> String;\n" -"}\n" -"\n" -"struct Dog {\n" -" name: String,\n" -"}\n" -"\n" -"struct Cat;\n" -"\n" -"impl Pet for Dog {\n" -" fn name(&self) -> String {\n" -" self.name.clone()\n" -" }\n" -"}\n" -"\n" -"impl Pet for Cat {\n" -" fn name(&self) -> String {\n" -" String::from(\"The cat\") // No name, cats won't respond to it " -"anyway.\n" -" }\n" -"}\n" -"\n" -"fn greet(pet: &P) {\n" -" println!(\"Who's a cutie? {} is!\", pet.name());\n" -"}\n" -"\n" -"fn main() {\n" -" let fido = Dog { name: \"Fido\".into() };\n" -" greet(&fido);\n" -"\n" -" let captain_floof = Cat;\n" -" greet(&captain_floof);\n" -"}\n" -"```" -msgstr "" - -#: src/traits/trait-objects.md:3 -msgid "" -"Trait objects allow for values of different types, for instance in a " -"collection:" +"A module can bring symbols from another module into scope with `use`. You " +"will typically see something like this at the top of each module:" msgstr "" -#: src/traits/trait-objects.md:5 +#: src/modules/paths.md:16 msgid "" "```rust,editable\n" -"trait Pet {\n" -" fn name(&self) -> String;\n" -"}\n" -"\n" -"struct Dog {\n" -" name: String,\n" -"}\n" -"\n" -"struct Cat;\n" -"\n" -"impl Pet for Dog {\n" -" fn name(&self) -> String {\n" -" self.name.clone()\n" -" }\n" -"}\n" -"\n" -"impl Pet for Cat {\n" -" fn name(&self) -> String {\n" -" String::from(\"The cat\") // No name, cats won't respond to it " -"anyway.\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" let pets: Vec> = vec![\n" -" Box::new(Cat),\n" -" Box::new(Dog { name: String::from(\"Fido\") }),\n" -" ];\n" -" for pet in pets {\n" -" println!(\"Hello {}!\", pet.name());\n" -" }\n" -"}\n" -"```" -msgstr "" - -#: src/traits/trait-objects.md:40 -msgid "Memory layout after allocating `pets`:" -msgstr "" - -#: src/traits/trait-objects.md:42 -msgid "" -"```bob\n" -" Stack Heap\n" -".- - - - - - - - - - - - - -. .- - - - - - - - - - - - - - - - - - - - - " -"- -.\n" -": : : :\n" -": " -"pets : : :\n" -": +-----------+-------+ : : +-----+-----" -"+ :\n" -": | ptr | o---+---+-----+-->| o o | o o " -"| :\n" -": | len | 2 | : : +-|-|-+-|-|-" -"+ :\n" -": | capacity | 2 | : : | | | | +---------------" -"+ :\n" -": +-----------+-------+ : : | | | '-->| name: \"Fido\" " -"| :\n" -": : : | | | +---------------" -"+ :\n" -"`- - - - - - - - - - - - - -' : | | " -"| :\n" -" : | | | +----------------------" -"+ : \n" -" : | | '---->| \"::name\" " -"| :\n" -" : | | +----------------------" -"+ : \n" -" : | " -"| : \n" -" : | | +-" -"+ : \n" -" : | '-->|" -"\\| : \n" -" : | +-" -"+ : \n" -" : " -"| : \n" -" : | +----------------------" -"+ : \n" -" : '---->| \"::name\" " -"| : \n" -" : +----------------------" -"+ :\n" -" : :\n" -" '- - - - - - - - - - - - - - - - - - - - - " -"- -'\n" -"\n" +"use std::collections::HashSet;\n" +"use std::mem::transmute;\n" "```" msgstr "" -#: src/traits/trait-objects.md:72 +#: src/modules/filesystem.md:3 msgid "" -"Types that implement a given trait may be of different sizes. This makes it " -"impossible to have things like `Vec` in the example above." +"Omitting the module content will tell Rust to look for it in another file:" msgstr "" -#: src/traits/trait-objects.md:73 +#: src/modules/filesystem.md:5 msgid "" -"`dyn Pet` is a way to tell the compiler about a dynamically sized type that " -"implements `Pet`." +"```rust,editable,compile_fail\n" +"mod garden;\n" +"```" msgstr "" -#: src/traits/trait-objects.md:74 +#: src/modules/filesystem.md:9 msgid "" -"In the example, `pets` holds _fat pointers_ to objects that implement `Pet`. " -"The fat pointer consists of two components, a pointer to the actual object " -"and a pointer to the virtual method table for the `Pet` implementation of " -"that particular object." +"This tells rust that the `garden` module content is found at `src/garden." +"rs`. Similarly, a `garden::vegetables` module can be found at `src/garden/" +"vegetables.rs`." msgstr "" -#: src/traits/trait-objects.md:75 -msgid "Compare these outputs in the above example:" +#: src/modules/filesystem.md:12 +msgid "The `crate` root is in:" msgstr "" -#: src/traits/trait-objects.md:76 -msgid "" -"```rust,ignore\n" -" println!(\"{} {}\", std::mem::size_of::(), std::mem::size_of::" -"());\n" -" println!(\"{} {}\", std::mem::size_of::<&Dog>(), std::mem::size_of::" -"<&Cat>());\n" -" println!(\"{}\", std::mem::size_of::<&dyn Pet>());\n" -" println!(\"{}\", std::mem::size_of::>());\n" -"```" +#: src/modules/filesystem.md:14 +msgid "`src/lib.rs` (for a library crate)" msgstr "" -#: src/traits/deriving-traits.md:3 -msgid "You can let the compiler derive a number of traits:" +#: src/modules/filesystem.md:15 +msgid "`src/main.rs` (for a binary crate)" msgstr "" -#: src/traits/deriving-traits.md:5 +#: src/modules/filesystem.md:17 msgid "" -"```rust,editable\n" -"#[derive(Debug, Clone, PartialEq, Eq, Default)]\n" -"struct Player {\n" -" name: String,\n" -" strength: u8,\n" -" hit_points: u8,\n" -"}\n" -"\n" -"fn main() {\n" -" let p1 = Player::default();\n" -" let p2 = p1.clone();\n" -" println!(\"Is {:?}\\nequal to {:?}?\\nThe answer is {}!\", &p1, &p2,\n" -" if p1 == p2 { \"yes\" } else { \"no\" });\n" -"}\n" -"```" -msgstr "" - -#: src/traits/default-methods.md:3 -msgid "Traits can implement behavior in terms of other trait methods:" +"Modules defined in files can be documented, too, using \"inner doc " +"comments\". These document the item that contains them -- in this case, a " +"module." msgstr "" -#: src/traits/default-methods.md:5 +#: src/modules/filesystem.md:20 msgid "" -"```rust,editable\n" -"trait Equals {\n" -" fn equal(&self, other: &Self) -> bool;\n" -" fn not_equal(&self, other: &Self) -> bool {\n" -" !self.equal(other)\n" -" }\n" -"}\n" +"```rust,editable,compile_fail\n" +"//! This module implements the garden, including a highly performant " +"germination\n" +"//! implementation.\n" "\n" -"#[derive(Debug)]\n" -"struct Centimeter(i16);\n" +"// Re-export types from this module.\n" +"pub use seeds::SeedPacket;\n" +"pub use garden::Garden;\n" "\n" -"impl Equals for Centimeter {\n" -" fn equal(&self, other: &Centimeter) -> bool {\n" -" self.0 == other.0\n" -" }\n" -"}\n" +"/// Sow the given seed packets.\n" +"pub fn sow(seeds: Vec) { todo!() }\n" "\n" -"fn main() {\n" -" let a = Centimeter(10);\n" -" let b = Centimeter(20);\n" -" println!(\"{a:?} equals {b:?}: {}\", a.equal(&b));\n" -" println!(\"{a:?} not_equals {b:?}: {}\", a.not_equal(&b));\n" -"}\n" +"/// Harvest the produce in the garden that is ready.\n" +"pub fn harvest(garden: &mut Garden) { todo!() }\n" "```" msgstr "" -#: src/traits/default-methods.md:32 +#: src/modules/filesystem.md:37 msgid "" -"Traits may specify pre-implemented (default) methods and methods that users " -"are required to implement themselves. Methods with default implementations " -"can rely on required methods." +"Before Rust 2018, modules needed to be located at `module/mod.rs` instead of " +"`module.rs`, and this is still a working alternative for editions after 2018." msgstr "" -#: src/traits/default-methods.md:35 -msgid "Move method `not_equal` to a new trait `NotEqual`." +#: src/modules/filesystem.md:39 +msgid "" +"The main reason to introduce `filename.rs` as alternative to `filename/mod." +"rs` was because many files named `mod.rs` can be hard to distinguish in IDEs." msgstr "" -#: src/traits/default-methods.md:37 -msgid "Make `NotEqual` a super trait for `Equal`." +#: src/modules/filesystem.md:42 +msgid "Deeper nesting can use folders, even if the main module is a file:" msgstr "" -#: src/traits/default-methods.md:38 +#: src/modules/filesystem.md:44 msgid "" -"```rust,editable,compile_fail\n" -"trait NotEqual: Equals {\n" -" fn not_equal(&self, other: &Self) -> bool {\n" -" !self.equal(other)\n" -" }\n" -"}\n" +"```ignore\n" +"src/\n" +"├── main.rs\n" +"├── top_module.rs\n" +"└── top_module/\n" +" └── sub_module.rs\n" "```" msgstr "" -#: src/traits/default-methods.md:46 -msgid "Provide a blanket implementation of `NotEqual` for `Equal`." +#: src/modules/filesystem.md:52 +msgid "" +"The place rust will look for modules can be changed with a compiler " +"directive:" msgstr "" -#: src/traits/default-methods.md:47 +#: src/modules/filesystem.md:54 msgid "" -"```rust,editable,compile_fail\n" -"trait NotEqual {\n" -" fn not_equal(&self, other: &Self) -> bool;\n" -"}\n" -"\n" -"impl NotEqual for T where T: Equals {\n" -" fn not_equal(&self, other: &Self) -> bool {\n" -" !self.equal(other)\n" -" }\n" -"}\n" +"```rust,ignore\n" +"#[path = \"some/path.rs\"]\n" +"mod some_module;\n" "```" msgstr "" -#: src/traits/default-methods.md:58 +#: src/modules/filesystem.md:59 msgid "" -"With the blanket implementation, you no longer need `NotEqual` as a super " -"trait for `Equal`." +"This is useful, for example, if you would like to place tests for a module " +"in a file named `some_module_test.rs`, similar to the convention in Go." msgstr "" -#: src/traits/trait-bounds.md:3 +#: src/exercises/day-2/strings-iterators.md:3 msgid "" -"When working with generics, you often want to require the types to implement " -"some trait, so that you can call this trait's methods." -msgstr "" +"In this exercise, you are implementing a routing component of a web server. " +"The server is configured with a number of _path prefixes_ which are matched " +"against _request paths_. The path prefixes can contain a wildcard character " +"which matches a full segment. See the unit tests below." +msgstr "" -#: src/traits/trait-bounds.md:6 -msgid "You can do this with `T: Trait` or `impl Trait`:" +#: src/exercises/day-2/strings-iterators.md:8 +msgid "" +"Copy the following code to and make the tests " +"pass. Try avoiding allocating a `Vec` for your intermediate results:" msgstr "" -#: src/traits/trait-bounds.md:8 +#: src/exercises/day-2/strings-iterators.md:12 msgid "" -"```rust,editable\n" -"fn duplicate(a: T) -> (T, T) {\n" -" (a.clone(), a.clone())\n" -"}\n" +"```rust\n" +"// TODO: remove this when you're done with your implementation.\n" +"#![allow(unused_variables, dead_code)]\n" "\n" -"// Syntactic sugar for:\n" -"// fn add_42_millions>(x: T) -> i32 {\n" -"fn add_42_millions(x: impl Into) -> i32 {\n" -" x.into() + 42_000_000\n" +"pub fn prefix_matches(prefix: &str, request_path: &str) -> bool {\n" +" unimplemented!()\n" "}\n" "\n" -"// struct NotClonable;\n" +"#[test]\n" +"fn test_matches_without_wildcard() {\n" +" assert!(prefix_matches(\"/v1/publishers\", \"/v1/publishers\"));\n" +" assert!(prefix_matches(\"/v1/publishers\", \"/v1/publishers/" +"abc-123\"));\n" +" assert!(prefix_matches(\"/v1/publishers\", \"/v1/publishers/abc/" +"books\"));\n" "\n" -"fn main() {\n" -" let foo = String::from(\"foo\");\n" -" let pair = duplicate(foo);\n" -" println!(\"{pair:?}\");\n" +" assert!(!prefix_matches(\"/v1/publishers\", \"/v1\"));\n" +" assert!(!prefix_matches(\"/v1/publishers\", \"/v1/publishersBooks\"));\n" +" assert!(!prefix_matches(\"/v1/publishers\", \"/v1/parent/" +"publishers\"));\n" +"}\n" "\n" -" let many = add_42_millions(42_i8);\n" -" println!(\"{many}\");\n" -" let many_more = add_42_millions(10_000_000);\n" -" println!(\"{many_more}\");\n" +"#[test]\n" +"fn test_matches_with_wildcard() {\n" +" assert!(prefix_matches(\n" +" \"/v1/publishers/*/books\",\n" +" \"/v1/publishers/foo/books\"\n" +" ));\n" +" assert!(prefix_matches(\n" +" \"/v1/publishers/*/books\",\n" +" \"/v1/publishers/bar/books\"\n" +" ));\n" +" assert!(prefix_matches(\n" +" \"/v1/publishers/*/books\",\n" +" \"/v1/publishers/foo/books/book1\"\n" +" ));\n" +"\n" +" assert!(!prefix_matches(\"/v1/publishers/*/books\", \"/v1/" +"publishers\"));\n" +" assert!(!prefix_matches(\n" +" \"/v1/publishers/*/books\",\n" +" \"/v1/publishers/foo/booksByAuthor\"\n" +" ));\n" "}\n" "```" msgstr "" -#: src/traits/trait-bounds.md:35 -msgid "Show a `where` clause, students will encounter it when reading code." +#: src/welcome-day-3.md:1 +msgid "Welcome to Day 3" msgstr "" -#: src/traits/trait-bounds.md:37 +#: src/welcome-day-3.md:3 +msgid "Today, we will cover some more advanced topics of Rust:" +msgstr "" + +#: src/welcome-day-3.md:5 msgid "" -"```rust,ignore\n" -"fn duplicate(a: T) -> (T, T)\n" -"where\n" -" T: Clone,\n" -"{\n" -" (a.clone(), a.clone())\n" -"}\n" -"```" +"Traits: deriving traits, default methods, and important standard library " +"traits." msgstr "" -#: src/traits/trait-bounds.md:46 -msgid "It declutters the function signature if you have many parameters." +#: src/welcome-day-3.md:8 +msgid "" +"Generics: generic data types, generic methods, monomorphization, and trait " +"objects." msgstr "" -#: src/traits/trait-bounds.md:47 -msgid "It has additional features making it more powerful." +#: src/welcome-day-3.md:11 +msgid "Error handling: panics, `Result`, and the try operator `?`." msgstr "" -#: src/traits/trait-bounds.md:48 -msgid "" -"If someone asks, the extra feature is that the type on the left of \":\" can " -"be arbitrary, like `Option`." +#: src/welcome-day-3.md:13 +msgid "Testing: unit tests, documentation tests, and integration tests." msgstr "" -#: src/traits/impl-trait.md:1 -msgid "`impl Trait`" +#: src/welcome-day-3.md:15 +msgid "" +"Unsafe Rust: raw pointers, static variables, unsafe functions, and extern " +"functions." msgstr "" -#: src/traits/impl-trait.md:3 +#: src/generics.md:3 msgid "" -"Similar to trait bounds, an `impl Trait` syntax can be used in function " -"arguments and return values:" +"Rust support generics, which lets you abstract algorithms or data structures " +"(such as sorting or a binary tree) over the types used or stored." msgstr "" -#: src/traits/impl-trait.md:6 +#: src/generics/data-types.md:3 +msgid "You can use generics to abstract over the concrete field type:" +msgstr "" + +#: src/generics/data-types.md:5 msgid "" "```rust,editable\n" -"use std::fmt::Display;\n" -"\n" -"fn get_x(name: impl Display) -> impl Display {\n" -" format!(\"Hello {name}\")\n" +"#[derive(Debug)]\n" +"struct Point {\n" +" x: T,\n" +" y: T,\n" "}\n" "\n" "fn main() {\n" -" let x = get_x(\"foo\");\n" -" println!(\"{x}\");\n" +" let integer = Point { x: 5, y: 10 };\n" +" let float = Point { x: 1.0, y: 4.0 };\n" +" println!(\"{integer:?} and {float:?}\");\n" "}\n" "```" msgstr "" -#: src/traits/impl-trait.md:19 -msgid "`impl Trait` allows you to work with types which you cannot name." +#: src/generics/data-types.md:21 +msgid "Try declaring a new variable `let p = Point { x: 5, y: 10.0 };`." msgstr "" -#: src/traits/impl-trait.md:23 -msgid "" -"The meaning of `impl Trait` is a bit different in the different positions." +#: src/generics/data-types.md:23 +msgid "Fix the code to allow points that have elements of different types." msgstr "" -#: src/traits/impl-trait.md:25 -msgid "" -"For a parameter, `impl Trait` is like an anonymous generic parameter with a " -"trait bound." +#: src/generics/methods.md:3 +msgid "You can declare a generic type on your `impl` block:" msgstr "" -#: src/traits/impl-trait.md:27 +#: src/generics/methods.md:5 msgid "" -"For a return type, it means that the return type is some concrete type that " -"implements the trait, without naming the type. This can be useful when you " -"don't want to expose the concrete type in a public API." +"```rust,editable\n" +"#[derive(Debug)]\n" +"struct Point(T, T);\n" +"\n" +"impl Point {\n" +" fn x(&self) -> &T {\n" +" &self.0 // + 10\n" +" }\n" +"\n" +" // fn set_x(&mut self, x: T)\n" +"}\n" +"\n" +"fn main() {\n" +" let p = Point(5, 10);\n" +" println!(\"p.x = {}\", p.x());\n" +"}\n" +"```" msgstr "" -#: src/traits/impl-trait.md:31 +#: src/generics/methods.md:25 msgid "" -"Inference is hard in return position. A function returning `impl Foo` picks " -"the concrete type it returns, without writing it out in the source. A " -"function returning a generic type like `collect() -> B` can return any " -"type satisfying `B`, and the caller may need to choose one, such as with " -"`let x: Vec<_> = foo.collect()` or with the turbofish, `foo.collect::" -">()`." +"_Q:_ Why `T` is specified twice in `impl Point {}`? Isn't that " +"redundant?" msgstr "" -#: src/traits/impl-trait.md:37 +#: src/generics/methods.md:26 msgid "" -"This example is great, because it uses `impl Display` twice. It helps to " -"explain that nothing here enforces that it is _the same_ `impl Display` " -"type. If we used a single `T: Display`, it would enforce the constraint " -"that input `T` and return `T` type are the same type. It would not work for " -"this particular function, as the type we expect as input is likely not what " -"`format!` returns. If we wanted to do the same via `: Display` syntax, we'd " -"need two independent generic parameters." +"This is because it is a generic implementation section for generic type. " +"They are independently generic." msgstr "" -#: src/traits/important-traits.md:3 -msgid "" -"We will now look at some of the most common traits of the Rust standard " -"library:" +#: src/generics/methods.md:27 +msgid "It means these methods are defined for any `T`." msgstr "" -#: src/traits/important-traits.md:5 -msgid "" -"[`Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html) and " -"[`IntoIterator`](https://doc.rust-lang.org/std/iter/trait.IntoIterator.html) " -"used in `for` loops," +#: src/generics/methods.md:28 +msgid "It is possible to write `impl Point { .. }`. " msgstr "" -#: src/traits/important-traits.md:6 +#: src/generics/methods.md:29 msgid "" -"[`From`](https://doc.rust-lang.org/std/convert/trait.From.html) and [`Into`]" -"(https://doc.rust-lang.org/std/convert/trait.Into.html) used to convert " -"values," +"`Point` is still generic and you can use `Point`, but methods in this " +"block will only be available for `Point`." msgstr "" -#: src/traits/important-traits.md:7 -msgid "" -"[`Read`](https://doc.rust-lang.org/std/io/trait.Read.html) and [`Write`]" -"(https://doc.rust-lang.org/std/io/trait.Write.html) used for IO," +#: src/generics/monomorphization.md:3 +msgid "Generic code is turned into non-generic code based on the call sites:" msgstr "" -#: src/traits/important-traits.md:8 +#: src/generics/monomorphization.md:5 msgid "" -"[`Add`](https://doc.rust-lang.org/std/ops/trait.Add.html), [`Mul`](https://" -"doc.rust-lang.org/std/ops/trait.Mul.html), ... used for operator " -"overloading, and" +"```rust,editable\n" +"fn main() {\n" +" let integer = Some(5);\n" +" let float = Some(5.0);\n" +"}\n" +"```" msgstr "" -#: src/traits/important-traits.md:9 -msgid "" -"[`Drop`](https://doc.rust-lang.org/std/ops/trait.Drop.html) used for " -"defining destructors." +#: src/generics/monomorphization.md:12 +msgid "behaves as if you wrote" msgstr "" -#: src/traits/important-traits.md:10 +#: src/generics/monomorphization.md:14 msgid "" -"[`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) used " -"to construct a default instance of a type." +"```rust,editable\n" +"enum Option_i32 {\n" +" Some(i32),\n" +" None,\n" +"}\n" +"\n" +"enum Option_f64 {\n" +" Some(f64),\n" +" None,\n" +"}\n" +"\n" +"fn main() {\n" +" let integer = Option_i32::Some(5);\n" +" let float = Option_f64::Some(5.0);\n" +"}\n" +"```" msgstr "" -#: src/traits/iterator.md:1 -msgid "Iterators" +#: src/generics/monomorphization.md:31 +msgid "" +"This is a zero-cost abstraction: you get exactly the same result as if you " +"had hand-coded the data structures without the abstraction." msgstr "" -#: src/traits/iterator.md:3 +#: src/traits.md:3 msgid "" -"You can implement the [`Iterator`](https://doc.rust-lang.org/std/iter/trait." -"Iterator.html) trait on your own types:" +"Rust lets you abstract over types with traits. They're similar to interfaces:" msgstr "" -#: src/traits/iterator.md:5 +#: src/traits.md:5 msgid "" "```rust,editable\n" -"struct Fibonacci {\n" -" curr: u32,\n" -" next: u32,\n" +"trait Pet {\n" +" fn name(&self) -> String;\n" "}\n" "\n" -"impl Iterator for Fibonacci {\n" -" type Item = u32;\n" +"struct Dog {\n" +" name: String,\n" +"}\n" "\n" -" fn next(&mut self) -> Option {\n" -" let new_next = self.curr + self.next;\n" -" self.curr = self.next;\n" -" self.next = new_next;\n" -" Some(self.curr)\n" +"struct Cat;\n" +"\n" +"impl Pet for Dog {\n" +" fn name(&self) -> String {\n" +" self.name.clone()\n" " }\n" "}\n" "\n" -"fn main() {\n" -" let fib = Fibonacci { curr: 0, next: 1 };\n" -" for (i, n) in fib.enumerate().take(5) {\n" -" println!(\"fib({i}): {n}\");\n" +"impl Pet for Cat {\n" +" fn name(&self) -> String {\n" +" String::from(\"The cat\") // No name, cats won't respond to it " +"anyway.\n" " }\n" "}\n" +"\n" +"fn greet(pet: &P) {\n" +" println!(\"Who's a cutie? {} is!\", pet.name());\n" +"}\n" +"\n" +"fn main() {\n" +" let fido = Dog { name: \"Fido\".into() };\n" +" greet(&fido);\n" +"\n" +" let captain_floof = Cat;\n" +" greet(&captain_floof);\n" +"}\n" "```" msgstr "" -#: src/traits/iterator.md:32 +#: src/traits/trait-objects.md:3 msgid "" -"The `Iterator` trait implements many common functional programming " -"operations over collections (e.g. `map`, `filter`, `reduce`, etc). This is " -"the trait where you can find all the documentation about them. In Rust these " -"functions should produce the code as efficient as equivalent imperative " -"implementations." +"Trait objects allow for values of different types, for instance in a " +"collection:" msgstr "" -#: src/traits/iterator.md:37 +#: src/traits/trait-objects.md:5 msgid "" -"`IntoIterator` is the trait that makes for loops work. It is implemented by " -"collection types such as `Vec` and references to them such as `&Vec` " -"and `&[T]`. Ranges also implement it. This is why you can iterate over a " -"vector with `for i in some_vec { .. }` but `some_vec.next()` doesn't exist." +"```rust,editable\n" +"trait Pet {\n" +" fn name(&self) -> String;\n" +"}\n" +"\n" +"struct Dog {\n" +" name: String,\n" +"}\n" +"\n" +"struct Cat;\n" +"\n" +"impl Pet for Dog {\n" +" fn name(&self) -> String {\n" +" self.name.clone()\n" +" }\n" +"}\n" +"\n" +"impl Pet for Cat {\n" +" fn name(&self) -> String {\n" +" String::from(\"The cat\") // No name, cats won't respond to it " +"anyway.\n" +" }\n" +"}\n" +"\n" +"fn main() {\n" +" let pets: Vec> = vec![\n" +" Box::new(Cat),\n" +" Box::new(Dog { name: String::from(\"Fido\") }),\n" +" ];\n" +" for pet in pets {\n" +" println!(\"Hello {}!\", pet.name());\n" +" }\n" +"}\n" +"```" msgstr "" -#: src/traits/from-iterator.md:3 -msgid "" -"[`FromIterator`](https://doc.rust-lang.org/std/iter/trait.FromIterator.html) " -"lets you build a collection from an [`Iterator`](https://doc.rust-lang.org/" -"std/iter/trait.Iterator.html)." +#: src/traits/trait-objects.md:40 +msgid "Memory layout after allocating `pets`:" msgstr "" -#: src/traits/from-iterator.md:5 +#: src/traits/trait-objects.md:42 msgid "" -"```rust,editable\n" -"fn main() {\n" -" let primes = vec![2, 3, 5, 7];\n" -" let prime_squares = primes\n" -" .into_iter()\n" -" .map(|prime| prime * prime)\n" -" .collect::>();\n" -"}\n" +"```bob\n" +" Stack Heap\n" +".- - - - - - - - - - - - - -. .- - - - - - - - - - - - - - - - - - - - - " +"- -.\n" +": : : :\n" +": " +"pets : : :\n" +": +-----------+-------+ : : +-----+-----" +"+ :\n" +": | ptr | o---+---+-----+-->| o o | o o " +"| :\n" +": | len | 2 | : : +-|-|-+-|-|-" +"+ :\n" +": | capacity | 2 | : : | | | | +---------------" +"+ :\n" +": +-----------+-------+ : : | | | '-->| name: \"Fido\" " +"| :\n" +": : : | | | +---------------" +"+ :\n" +"`- - - - - - - - - - - - - -' : | | " +"| :\n" +" : | | | +----------------------" +"+ : \n" +" : | | '---->| \"::name\" " +"| :\n" +" : | | +----------------------" +"+ : \n" +" : | " +"| : \n" +" : | | +-" +"+ : \n" +" : | '-->|" +"\\| : \n" +" : | +-" +"+ : \n" +" : " +"| : \n" +" : | +----------------------" +"+ : \n" +" : '---->| \"::name\" " +"| : \n" +" : +----------------------" +"+ :\n" +" : :\n" +" '- - - - - - - - - - - - - - - - - - - - - " +"- -'\n" +"\n" "```" msgstr "" -#: src/traits/from-iterator.md:17 +#: src/traits/trait-objects.md:72 msgid "" -"`Iterator` implements `fn collect(self) -> B where B: FromIterator, Self: Sized`" +"Types that implement a given trait may be of different sizes. This makes it " +"impossible to have things like `Vec` in the example above." msgstr "" -#: src/traits/from-iterator.md:23 +#: src/traits/trait-objects.md:73 msgid "" -"There are also implementations which let you do cool things like convert an " -"`Iterator>` into a `Result, E>`." +"`dyn Pet` is a way to tell the compiler about a dynamically sized type that " +"implements `Pet`." msgstr "" -#: src/traits/from-into.md:1 -msgid "`From` and `Into`" +#: src/traits/trait-objects.md:74 +msgid "" +"In the example, `pets` holds _fat pointers_ to objects that implement `Pet`. " +"The fat pointer consists of two components, a pointer to the actual object " +"and a pointer to the virtual method table for the `Pet` implementation of " +"that particular object." msgstr "" -#: src/traits/from-into.md:3 +#: src/traits/trait-objects.md:75 +msgid "Compare these outputs in the above example:" +msgstr "" + +#: src/traits/trait-objects.md:76 msgid "" -"Types implement [`From`](https://doc.rust-lang.org/std/convert/trait.From." -"html) and [`Into`](https://doc.rust-lang.org/std/convert/trait.Into.html) to " -"facilitate type conversions:" +"```rust,ignore\n" +" println!(\"{} {}\", std::mem::size_of::(), std::mem::size_of::" +"());\n" +" println!(\"{} {}\", std::mem::size_of::<&Dog>(), std::mem::size_of::" +"<&Cat>());\n" +" println!(\"{}\", std::mem::size_of::<&dyn Pet>());\n" +" println!(\"{}\", std::mem::size_of::>());\n" +"```" msgstr "" -#: src/traits/from-into.md:5 +#: src/traits/deriving-traits.md:3 +msgid "" +"Rust derive macros work by automatically generating code that implements the " +"specified traits for a data structure." +msgstr "" + +#: src/traits/deriving-traits.md:5 +msgid "You can let the compiler derive a number of traits as follows:" +msgstr "" + +#: src/traits/deriving-traits.md:7 msgid "" "```rust,editable\n" +"#[derive(Debug, Clone, PartialEq, Eq, Default)]\n" +"struct Player {\n" +" name: String,\n" +" strength: u8,\n" +" hit_points: u8,\n" +"}\n" +"\n" "fn main() {\n" -" let s = String::from(\"hello\");\n" -" let addr = std::net::Ipv4Addr::from([127, 0, 0, 1]);\n" -" let one = i16::from(true);\n" -" let bigger = i32::from(123i16);\n" -" println!(\"{s}, {addr}, {one}, {bigger}\");\n" +" let p1 = Player::default();\n" +" let p2 = p1.clone();\n" +" println!(\"Is {:?}\\nequal to {:?}?\\nThe answer is {}!\", &p1, &p2,\n" +" if p1 == p2 { \"yes\" } else { \"no\" });\n" "}\n" "```" msgstr "" -#: src/traits/from-into.md:15 -msgid "" -"[`Into`](https://doc.rust-lang.org/std/convert/trait.Into.html) is " -"automatically implemented when [`From`](https://doc.rust-lang.org/std/" -"convert/trait.From.html) is implemented:" +#: src/traits/default-methods.md:3 +msgid "Traits can implement behavior in terms of other trait methods:" msgstr "" -#: src/traits/from-into.md:17 +#: src/traits/default-methods.md:5 msgid "" "```rust,editable\n" +"trait Equals {\n" +" fn equals(&self, other: &Self) -> bool;\n" +" fn not_equals(&self, other: &Self) -> bool {\n" +" !self.equals(other)\n" +" }\n" +"}\n" +"\n" +"#[derive(Debug)]\n" +"struct Centimeter(i16);\n" +"\n" +"impl Equals for Centimeter {\n" +" fn equals(&self, other: &Centimeter) -> bool {\n" +" self.0 == other.0\n" +" }\n" +"}\n" +"\n" "fn main() {\n" -" let s: String = \"hello\".into();\n" -" let addr: std::net::Ipv4Addr = [127, 0, 0, 1].into();\n" -" let one: i16 = true.into();\n" -" let bigger: i32 = 123i16.into();\n" -" println!(\"{s}, {addr}, {one}, {bigger}\");\n" +" let a = Centimeter(10);\n" +" let b = Centimeter(20);\n" +" println!(\"{a:?} equals {b:?}: {}\", a.equals(&b));\n" +" println!(\"{a:?} not_equals {b:?}: {}\", a.not_equals(&b));\n" "}\n" "```" msgstr "" -#: src/traits/from-into.md:29 +#: src/traits/default-methods.md:32 msgid "" -"That's why it is common to only implement `From`, as your type will get " -"`Into` implementation too." -msgstr "" - -#: src/traits/from-into.md:30 -msgid "" -"When declaring a function argument input type like \"anything that can be " -"converted into a `String`\", the rule is opposite, you should use `Into`. " -"Your function will accept types that implement `From` and those that _only_ " -"implement `Into`." +"Traits may specify pre-implemented (default) methods and methods that users " +"are required to implement themselves. Methods with default implementations " +"can rely on required methods." msgstr "" -#: src/traits/read-write.md:1 -msgid "`Read` and `Write`" +#: src/traits/default-methods.md:35 +msgid "Move method `not_equals` to a new trait `NotEquals`." msgstr "" -#: src/traits/read-write.md:3 -msgid "" -"Using [`Read`](https://doc.rust-lang.org/std/io/trait.Read.html) and " -"[`BufRead`](https://doc.rust-lang.org/std/io/trait.BufRead.html), you can " -"abstract over `u8` sources:" +#: src/traits/default-methods.md:37 +msgid "Make `Equals` a super trait for `NotEquals`." msgstr "" -#: src/traits/read-write.md:5 +#: src/traits/default-methods.md:38 msgid "" -"```rust,editable\n" -"use std::io::{BufRead, BufReader, Read, Result};\n" -"\n" -"fn count_lines(reader: R) -> usize {\n" -" let buf_reader = BufReader::new(reader);\n" -" buf_reader.lines().count()\n" -"}\n" -"\n" -"fn main() -> Result<()> {\n" -" let slice: &[u8] = b\"foo\\nbar\\nbaz\\n\";\n" -" println!(\"lines in slice: {}\", count_lines(slice));\n" -"\n" -" let file = std::fs::File::open(std::env::current_exe()?)?;\n" -" println!(\"lines in file: {}\", count_lines(file));\n" -" Ok(())\n" +"```rust,editable,compile_fail\n" +"trait NotEquals: Equals {\n" +" fn not_equals(&self, other: &Self) -> bool {\n" +" !self.equals(other)\n" +" }\n" "}\n" "```" msgstr "" -#: src/traits/read-write.md:23 -msgid "" -"Similarly, [`Write`](https://doc.rust-lang.org/std/io/trait.Write.html) lets " -"you abstract over `u8` sinks:" +#: src/traits/default-methods.md:46 +msgid "Provide a blanket implementation of `NotEquals` for `Equals`." msgstr "" -#: src/traits/read-write.md:25 +#: src/traits/default-methods.md:47 msgid "" -"```rust,editable\n" -"use std::io::{Result, Write};\n" -"\n" -"fn log(writer: &mut W, msg: &str) -> Result<()> {\n" -" writer.write_all(msg.as_bytes())?;\n" -" writer.write_all(\"\\n\".as_bytes())\n" +"```rust,editable,compile_fail\n" +"trait NotEquals {\n" +" fn not_equals(&self, other: &Self) -> bool;\n" "}\n" "\n" -"fn main() -> Result<()> {\n" -" let mut buffer = Vec::new();\n" -" log(&mut buffer, \"Hello\")?;\n" -" log(&mut buffer, \"World\")?;\n" -" println!(\"Logged: {:?}\", buffer);\n" -" Ok(())\n" +"impl NotEquals for T where T: Equals {\n" +" fn not_equals(&self, other: &Self) -> bool {\n" +" !self.equals(other)\n" +" }\n" "}\n" "```" msgstr "" -#: src/traits/drop.md:1 -msgid "The `Drop` Trait" +#: src/traits/default-methods.md:58 +msgid "" +"With the blanket implementation, you no longer need `Equals` as a super " +"trait for `NotEqual`." msgstr "" -#: src/traits/drop.md:3 +#: src/traits/trait-bounds.md:3 msgid "" -"Values which implement [`Drop`](https://doc.rust-lang.org/std/ops/trait.Drop." -"html) can specify code to run when they go out of scope:" +"When working with generics, you often want to require the types to implement " +"some trait, so that you can call this trait's methods." msgstr "" -#: src/traits/drop.md:5 +#: src/traits/trait-bounds.md:6 +msgid "You can do this with `T: Trait` or `impl Trait`:" +msgstr "" + +#: src/traits/trait-bounds.md:8 msgid "" "```rust,editable\n" -"struct Droppable {\n" -" name: &'static str,\n" +"fn duplicate(a: T) -> (T, T) {\n" +" (a.clone(), a.clone())\n" "}\n" "\n" -"impl Drop for Droppable {\n" -" fn drop(&mut self) {\n" -" println!(\"Dropping {}\", self.name);\n" -" }\n" +"// Syntactic sugar for:\n" +"// fn add_42_millions>(x: T) -> i32 {\n" +"fn add_42_millions(x: impl Into) -> i32 {\n" +" x.into() + 42_000_000\n" "}\n" "\n" +"// struct NotClonable;\n" +"\n" "fn main() {\n" -" let a = Droppable { name: \"a\" };\n" -" {\n" -" let b = Droppable { name: \"b\" };\n" -" {\n" -" let c = Droppable { name: \"c\" };\n" -" let d = Droppable { name: \"d\" };\n" -" println!(\"Exiting block B\");\n" -" }\n" -" println!(\"Exiting block A\");\n" -" }\n" -" drop(a);\n" -" println!(\"Exiting main\");\n" +" let foo = String::from(\"foo\");\n" +" let pair = duplicate(foo);\n" +" println!(\"{pair:?}\");\n" +"\n" +" let many = add_42_millions(42_i8);\n" +" println!(\"{many}\");\n" +" let many_more = add_42_millions(10_000_000);\n" +" println!(\"{many_more}\");\n" "}\n" "```" msgstr "" -#: src/traits/drop.md:34 src/traits/operators.md:26 -msgid "Discussion points:" +#: src/traits/trait-bounds.md:35 +msgid "Show a `where` clause, students will encounter it when reading code." msgstr "" -#: src/traits/drop.md:36 -msgid "Why doesn't `Drop::drop` take `self`?" +#: src/traits/trait-bounds.md:37 +msgid "" +"```rust,ignore\n" +"fn duplicate(a: T) -> (T, T)\n" +"where\n" +" T: Clone,\n" +"{\n" +" (a.clone(), a.clone())\n" +"}\n" +"```" msgstr "" -#: src/traits/drop.md:37 -msgid "" -"Short-answer: If it did, `std::mem::drop` would be called at the end of the " -"block, resulting in another call to `Drop::drop`, and a stack overflow!" +#: src/traits/trait-bounds.md:46 +msgid "It declutters the function signature if you have many parameters." msgstr "" -#: src/traits/drop.md:40 -msgid "Try replacing `drop(a)` with `a.drop()`." +#: src/traits/trait-bounds.md:47 +msgid "It has additional features making it more powerful." msgstr "" -#: src/traits/default.md:1 -msgid "The `Default` Trait" +#: src/traits/trait-bounds.md:48 +msgid "" +"If someone asks, the extra feature is that the type on the left of \":\" can " +"be arbitrary, like `Option`." msgstr "" -#: src/traits/default.md:3 +#: src/traits/impl-trait.md:1 +msgid "`impl Trait`" +msgstr "" + +#: src/traits/impl-trait.md:3 msgid "" -"[`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) trait " -"provides a default implementation of a trait." +"Similar to trait bounds, an `impl Trait` syntax can be used in function " +"arguments and return values:" msgstr "" -#: src/traits/default.md:5 +#: src/traits/impl-trait.md:6 msgid "" "```rust,editable\n" -"#[derive(Debug, Default)]\n" -"struct Derived {\n" -" x: u32,\n" -" y: String,\n" -" z: Implemented,\n" -"}\n" -"\n" -"#[derive(Debug)]\n" -"struct Implemented(String);\n" +"use std::fmt::Display;\n" "\n" -"impl Default for Implemented {\n" -" fn default() -> Self {\n" -" Self(\"John Smith\".into())\n" -" }\n" +"fn get_x(name: impl Display) -> impl Display {\n" +" format!(\"Hello {name}\")\n" "}\n" "\n" "fn main() {\n" -" let default_struct: Derived = Default::default();\n" -" println!(\"{default_struct:#?}\");\n" -"\n" -" let almost_default_struct = Derived {\n" -" y: \"Y is set!\".into(),\n" -" ..Default::default()\n" -" };\n" -" println!(\"{almost_default_struct:#?}\");\n" -"\n" -" let nothing: Option = None;\n" -" println!(\"{:#?}\", nothing.unwrap_or_default());\n" +" let x = get_x(\"foo\");\n" +" println!(\"{x}\");\n" "}\n" -"\n" "```" msgstr "" -#: src/traits/default.md:40 +#: src/traits/impl-trait.md:19 +msgid "`impl Trait` allows you to work with types which you cannot name." +msgstr "" + +#: src/traits/impl-trait.md:23 msgid "" -"It can be implemented directly or it can be derived via `#[derive(Default)]`." +"The meaning of `impl Trait` is a bit different in the different positions." msgstr "" -#: src/traits/default.md:41 +#: src/traits/impl-trait.md:25 msgid "" -"Derived implementation will produce an instance where all fields are set to " -"their default values." +"For a parameter, `impl Trait` is like an anonymous generic parameter with a " +"trait bound." msgstr "" -#: src/traits/default.md:42 -msgid "This means all types in the struct must implement `Default` too." +#: src/traits/impl-trait.md:27 +msgid "" +"For a return type, it means that the return type is some concrete type that " +"implements the trait, without naming the type. This can be useful when you " +"don't want to expose the concrete type in a public API." msgstr "" -#: src/traits/default.md:43 +#: src/traits/impl-trait.md:31 msgid "" -"Standard Rust types often implement `Default` with reasonable values (e.g. " -"`0`, `\"\"`, etc)." +"Inference is hard in return position. A function returning `impl Foo` picks " +"the concrete type it returns, without writing it out in the source. A " +"function returning a generic type like `collect() -> B` can return any " +"type satisfying `B`, and the caller may need to choose one, such as with " +"`let x: Vec<_> = foo.collect()` or with the turbofish, `foo.collect::" +">()`." msgstr "" -#: src/traits/default.md:44 -msgid "The partial struct copy works nicely with default." +#: src/traits/impl-trait.md:37 +msgid "" +"This example is great, because it uses `impl Display` twice. It helps to " +"explain that nothing here enforces that it is _the same_ `impl Display` " +"type. If we used a single `T: Display`, it would enforce the constraint " +"that input `T` and return `T` type are the same type. It would not work for " +"this particular function, as the type we expect as input is likely not what " +"`format!` returns. If we wanted to do the same via `: Display` syntax, we'd " +"need two independent generic parameters." msgstr "" -#: src/traits/default.md:45 +#: src/traits/important-traits.md:3 msgid "" -"Rust standard library is aware that types can implement `Default` and " -"provides convenience methods that use it." +"We will now look at some of the most common traits of the Rust standard " +"library:" msgstr "" -#: src/traits/operators.md:1 -msgid "`Add`, `Mul`, ..." +#: src/traits/important-traits.md:5 +msgid "" +"[`Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html) and " +"[`IntoIterator`](https://doc.rust-lang.org/std/iter/trait.IntoIterator.html) " +"used in `for` loops," msgstr "" -#: src/traits/operators.md:3 +#: src/traits/important-traits.md:6 msgid "" -"Operator overloading is implemented via traits in [`std::ops`](https://doc." -"rust-lang.org/std/ops/index.html):" +"[`From`](https://doc.rust-lang.org/std/convert/trait.From.html) and [`Into`]" +"(https://doc.rust-lang.org/std/convert/trait.Into.html) used to convert " +"values," msgstr "" -#: src/traits/operators.md:5 +#: src/traits/important-traits.md:7 msgid "" -"```rust,editable\n" -"#[derive(Debug, Copy, Clone)]\n" -"struct Point { x: i32, y: i32 }\n" -"\n" -"impl std::ops::Add for Point {\n" -" type Output = Self;\n" -"\n" -" fn add(self, other: Self) -> Self {\n" -" Self {x: self.x + other.x, y: self.y + other.y}\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" let p1 = Point { x: 10, y: 20 };\n" -" let p2 = Point { x: 100, y: 200 };\n" -" println!(\"{:?} + {:?} = {:?}\", p1, p2, p1 + p2);\n" -"}\n" -"```" +"[`Read`](https://doc.rust-lang.org/std/io/trait.Read.html) and [`Write`]" +"(https://doc.rust-lang.org/std/io/trait.Write.html) used for IO," msgstr "" -#: src/traits/operators.md:28 +#: src/traits/important-traits.md:8 msgid "" -"You could implement `Add` for `&Point`. In which situations is that useful? " +"[`Add`](https://doc.rust-lang.org/std/ops/trait.Add.html), [`Mul`](https://" +"doc.rust-lang.org/std/ops/trait.Mul.html), ... used for operator " +"overloading, and" msgstr "" -#: src/traits/operators.md:29 +#: src/traits/important-traits.md:9 msgid "" -"Answer: `Add:add` consumes `self`. If type `T` for which you are overloading " -"the operator is not `Copy`, you should consider overloading the operator for " -"`&T` as well. This avoids unnecessary cloning on the call site." -msgstr "" - -#: src/traits/operators.md:33 -msgid "Why is `Output` an associated type? Could it be made a type parameter?" +"[`Drop`](https://doc.rust-lang.org/std/ops/trait.Drop.html) used for " +"defining destructors." msgstr "" -#: src/traits/operators.md:34 +#: src/traits/important-traits.md:10 msgid "" -"Short answer: Type parameters are controlled by the caller, but associated " -"types (like `Output`) are controlled by the implementor of a trait." +"[`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) used " +"to construct a default instance of a type." msgstr "" -#: src/traits/closures.md:1 -msgid "Closures" +#: src/traits/iterator.md:1 +msgid "Iterators" msgstr "" -#: src/traits/closures.md:3 +#: src/traits/iterator.md:3 msgid "" -"Closures or lambda expressions have types which cannot be named. However, " -"they implement special [`Fn`](https://doc.rust-lang.org/std/ops/trait.Fn." -"html), [`FnMut`](https://doc.rust-lang.org/std/ops/trait.FnMut.html), and " -"[`FnOnce`](https://doc.rust-lang.org/std/ops/trait.FnOnce.html) traits:" +"You can implement the [`Iterator`](https://doc.rust-lang.org/std/iter/trait." +"Iterator.html) trait on your own types:" msgstr "" -#: src/traits/closures.md:8 +#: src/traits/iterator.md:5 msgid "" "```rust,editable\n" -"fn apply_with_log(func: impl FnOnce(i32) -> i32, input: i32) -> i32 {\n" -" println!(\"Calling function on {input}\");\n" -" func(input)\n" +"struct Fibonacci {\n" +" curr: u32,\n" +" next: u32,\n" "}\n" "\n" -"fn main() {\n" -" let add_3 = |x| x + 3;\n" -" let mul_5 = |x| x * 5;\n" +"impl Iterator for Fibonacci {\n" +" type Item = u32;\n" "\n" -" println!(\"add_3: {}\", apply_with_log(add_3, 10));\n" -" println!(\"mul_5: {}\", apply_with_log(mul_5, 20));\n" +" fn next(&mut self) -> Option {\n" +" let new_next = self.curr + self.next;\n" +" self.curr = self.next;\n" +" self.next = new_next;\n" +" Some(self.curr)\n" +" }\n" +"}\n" +"\n" +"fn main() {\n" +" let fib = Fibonacci { curr: 0, next: 1 };\n" +" for (i, n) in fib.enumerate().take(5) {\n" +" println!(\"fib({i}): {n}\");\n" +" }\n" "}\n" "```" msgstr "" -#: src/traits/closures.md:25 +#: src/traits/iterator.md:32 msgid "" -"If you have an `FnOnce`, you may only call it once. It might consume " -"captured values." +"The `Iterator` trait implements many common functional programming " +"operations over collections (e.g. `map`, `filter`, `reduce`, etc). This is " +"the trait where you can find all the documentation about them. In Rust these " +"functions should produce the code as efficient as equivalent imperative " +"implementations." msgstr "" -#: src/traits/closures.md:27 +#: src/traits/iterator.md:37 msgid "" -"An `FnMut` might mutate captured values, so you can call it multiple times " -"but not concurrently." +"`IntoIterator` is the trait that makes for loops work. It is implemented by " +"collection types such as `Vec` and references to them such as `&Vec` " +"and `&[T]`. Ranges also implement it. This is why you can iterate over a " +"vector with `for i in some_vec { .. }` but `some_vec.next()` doesn't exist." msgstr "" -#: src/traits/closures.md:29 +#: src/traits/from-iterator.md:3 msgid "" -"An `Fn` neither consumes nor mutates captured values, or perhaps captures " -"nothing at all, so it can be called multiple times concurrently." +"[`FromIterator`](https://doc.rust-lang.org/std/iter/trait.FromIterator.html) " +"lets you build a collection from an [`Iterator`](https://doc.rust-lang.org/" +"std/iter/trait.Iterator.html)." msgstr "" -#: src/traits/closures.md:32 +#: src/traits/from-iterator.md:5 msgid "" -"`FnMut` is a subtype of `FnOnce`. `Fn` is a subtype of `FnMut` and `FnOnce`. " -"I.e. you can use an `FnMut` wherever an `FnOnce` is called for, and you can " -"use an `Fn` wherever an `FnMut` or `FnOnce` is called for." +"```rust,editable\n" +"fn main() {\n" +" let primes = vec![2, 3, 5, 7];\n" +" let prime_squares = primes\n" +" .into_iter()\n" +" .map(|prime| prime * prime)\n" +" .collect::>();\n" +"}\n" +"```" msgstr "" -#: src/traits/closures.md:36 -msgid "`move` closures only implement `FnOnce`." +#: src/traits/from-iterator.md:17 +msgid "" +"`Iterator` implements `fn collect(self) -> B where B: FromIterator, Self: Sized`" msgstr "" -#: src/exercises/day-3/morning.md:1 -msgid "Day 3: Morning Exercises" +#: src/traits/from-iterator.md:23 +msgid "" +"There are also implementations which let you do cool things like convert an " +"`Iterator>` into a `Result, E>`." msgstr "" -#: src/exercises/day-3/morning.md:3 -msgid "We will design a classical GUI library traits and trait objects." +#: src/traits/from-into.md:1 +msgid "`From` and `Into`" msgstr "" -#: src/exercises/day-3/simple-gui.md:3 +#: src/traits/from-into.md:3 msgid "" -"Let us design a classical GUI library using our new knowledge of traits and " -"trait objects." +"Types implement [`From`](https://doc.rust-lang.org/std/convert/trait.From." +"html) and [`Into`](https://doc.rust-lang.org/std/convert/trait.Into.html) to " +"facilitate type conversions:" msgstr "" -#: src/exercises/day-3/simple-gui.md:6 -msgid "We will have a number of widgets in our library:" +#: src/traits/from-into.md:5 +msgid "" +"```rust,editable\n" +"fn main() {\n" +" let s = String::from(\"hello\");\n" +" let addr = std::net::Ipv4Addr::from([127, 0, 0, 1]);\n" +" let one = i16::from(true);\n" +" let bigger = i32::from(123i16);\n" +" println!(\"{s}, {addr}, {one}, {bigger}\");\n" +"}\n" +"```" msgstr "" -#: src/exercises/day-3/simple-gui.md:8 -msgid "`Window`: has a `title` and contains other widgets." +#: src/traits/from-into.md:15 +msgid "" +"[`Into`](https://doc.rust-lang.org/std/convert/trait.Into.html) is " +"automatically implemented when [`From`](https://doc.rust-lang.org/std/" +"convert/trait.From.html) is implemented:" msgstr "" -#: src/exercises/day-3/simple-gui.md:9 +#: src/traits/from-into.md:17 msgid "" -"`Button`: has a `label` and a callback function which is invoked when the " -"button is pressed." +"```rust,editable\n" +"fn main() {\n" +" let s: String = \"hello\".into();\n" +" let addr: std::net::Ipv4Addr = [127, 0, 0, 1].into();\n" +" let one: i16 = true.into();\n" +" let bigger: i32 = 123i16.into();\n" +" println!(\"{s}, {addr}, {one}, {bigger}\");\n" +"}\n" +"```" msgstr "" -#: src/exercises/day-3/simple-gui.md:11 -msgid "`Label`: has a `label`." +#: src/traits/from-into.md:29 +msgid "" +"That's why it is common to only implement `From`, as your type will get " +"`Into` implementation too." msgstr "" -#: src/exercises/day-3/simple-gui.md:13 -msgid "The widgets will implement a `Widget` trait, see below." +#: src/traits/from-into.md:30 +msgid "" +"When declaring a function argument input type like \"anything that can be " +"converted into a `String`\", the rule is opposite, you should use `Into`. " +"Your function will accept types that implement `From` and those that _only_ " +"implement `Into`." msgstr "" -#: src/exercises/day-3/simple-gui.md:15 +#: src/traits/read-write.md:1 +msgid "`Read` and `Write`" +msgstr "" + +#: src/traits/read-write.md:3 msgid "" -"Copy the code below to , fill in the missing " -"`draw_into` methods so that you implement the `Widget` trait:" +"Using [`Read`](https://doc.rust-lang.org/std/io/trait.Read.html) and " +"[`BufRead`](https://doc.rust-lang.org/std/io/trait.BufRead.html), you can " +"abstract over `u8` sources:" msgstr "" -#: src/exercises/day-3/simple-gui.md:18 +#: src/traits/read-write.md:5 msgid "" -"```rust,should_panic\n" -"// TODO: remove this when you're done with your implementation.\n" -"#![allow(unused_imports, unused_variables, dead_code)]\n" +"```rust,editable\n" +"use std::io::{BufRead, BufReader, Read, Result};\n" "\n" -"pub trait Widget {\n" -" /// Natural width of `self`.\n" -" fn width(&self) -> usize;\n" +"fn count_lines(reader: R) -> usize {\n" +" let buf_reader = BufReader::new(reader);\n" +" buf_reader.lines().count()\n" +"}\n" "\n" -" /// Draw the widget into a buffer.\n" -" fn draw_into(&self, buffer: &mut dyn std::fmt::Write);\n" +"fn main() -> Result<()> {\n" +" let slice: &[u8] = b\"foo\\nbar\\nbaz\\n\";\n" +" println!(\"lines in slice: {}\", count_lines(slice));\n" "\n" -" /// Draw the widget on standard output.\n" -" fn draw(&self) {\n" -" let mut buffer = String::new();\n" -" self.draw_into(&mut buffer);\n" -" println!(\"{buffer}\");\n" -" }\n" +" let file = std::fs::File::open(std::env::current_exe()?)?;\n" +" println!(\"lines in file: {}\", count_lines(file));\n" +" Ok(())\n" "}\n" +"```" +msgstr "" + +#: src/traits/read-write.md:23 +msgid "" +"Similarly, [`Write`](https://doc.rust-lang.org/std/io/trait.Write.html) lets " +"you abstract over `u8` sinks:" +msgstr "" + +#: src/traits/read-write.md:25 +msgid "" +"```rust,editable\n" +"use std::io::{Result, Write};\n" "\n" -"pub struct Label {\n" -" label: String,\n" +"fn log(writer: &mut W, msg: &str) -> Result<()> {\n" +" writer.write_all(msg.as_bytes())?;\n" +" writer.write_all(\"\\n\".as_bytes())\n" "}\n" "\n" -"impl Label {\n" -" fn new(label: &str) -> Label {\n" -" Label {\n" -" label: label.to_owned(),\n" -" }\n" -" }\n" +"fn main() -> Result<()> {\n" +" let mut buffer = Vec::new();\n" +" log(&mut buffer, \"Hello\")?;\n" +" log(&mut buffer, \"World\")?;\n" +" println!(\"Logged: {:?}\", buffer);\n" +" Ok(())\n" "}\n" -"\n" -"pub struct Button {\n" -" label: Label,\n" -" callback: Box,\n" +"```" +msgstr "" + +#: src/traits/drop.md:1 +msgid "The `Drop` Trait" +msgstr "" + +#: src/traits/drop.md:3 +msgid "" +"Values which implement [`Drop`](https://doc.rust-lang.org/std/ops/trait.Drop." +"html) can specify code to run when they go out of scope:" +msgstr "" + +#: src/traits/drop.md:5 +msgid "" +"```rust,editable\n" +"struct Droppable {\n" +" name: &'static str,\n" "}\n" "\n" -"impl Button {\n" -" fn new(label: &str, callback: Box) -> Button {\n" -" Button {\n" -" label: Label::new(label),\n" -" callback,\n" -" }\n" +"impl Drop for Droppable {\n" +" fn drop(&mut self) {\n" +" println!(\"Dropping {}\", self.name);\n" " }\n" "}\n" "\n" -"pub struct Window {\n" -" title: String,\n" -" widgets: Vec>,\n" -"}\n" -"\n" -"impl Window {\n" -" fn new(title: &str) -> Window {\n" -" Window {\n" -" title: title.to_owned(),\n" -" widgets: Vec::new(),\n" +"fn main() {\n" +" let a = Droppable { name: \"a\" };\n" +" {\n" +" let b = Droppable { name: \"b\" };\n" +" {\n" +" let c = Droppable { name: \"c\" };\n" +" let d = Droppable { name: \"d\" };\n" +" println!(\"Exiting block B\");\n" " }\n" +" println!(\"Exiting block A\");\n" " }\n" -"\n" -" fn add_widget(&mut self, widget: Box) {\n" -" self.widgets.push(widget);\n" -" }\n" -"\n" -" fn inner_width(&self) -> usize {\n" -" std::cmp::max(\n" -" self.title.chars().count(),\n" -" self.widgets.iter().map(|w| w.width()).max().unwrap_or(0),\n" -" )\n" -" }\n" -"}\n" -"\n" -"\n" -"impl Widget for Label {\n" -" fn width(&self) -> usize {\n" -" unimplemented!()\n" -" }\n" -"\n" -" fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {\n" -" unimplemented!()\n" -" }\n" -"}\n" -"\n" -"impl Widget for Button {\n" -" fn width(&self) -> usize {\n" -" unimplemented!()\n" -" }\n" -"\n" -" fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {\n" -" unimplemented!()\n" -" }\n" -"}\n" -"\n" -"impl Widget for Window {\n" -" fn width(&self) -> usize {\n" -" unimplemented!()\n" -" }\n" -"\n" -" fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {\n" -" unimplemented!()\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" let mut window = Window::new(\"Rust GUI Demo 1.23\");\n" -" window.add_widget(Box::new(Label::new(\"This is a small text GUI demo." -"\")));\n" -" window.add_widget(Box::new(Button::new(\n" -" \"Click me!\",\n" -" Box::new(|| println!(\"You clicked the button!\")),\n" -" )));\n" -" window.draw();\n" +" drop(a);\n" +" println!(\"Exiting main\");\n" "}\n" "```" msgstr "" -#: src/exercises/day-3/simple-gui.md:130 -msgid "The output of the above program can be something simple like this:" +#: src/traits/drop.md:34 src/traits/operators.md:26 +msgid "Discussion points:" msgstr "" -#: src/exercises/day-3/simple-gui.md:132 +#: src/traits/drop.md:36 +msgid "Why doesn't `Drop::drop` take `self`?" +msgstr "" + +#: src/traits/drop.md:37 msgid "" -"```text\n" -"========\n" -"Rust GUI Demo 1.23\n" -"========\n" -"\n" -"This is a small text GUI demo.\n" -"\n" -"| Click me! |\n" -"```" +"Short-answer: If it did, `std::mem::drop` would be called at the end of the " +"block, resulting in another call to `Drop::drop`, and a stack overflow!" msgstr "" -#: src/exercises/day-3/simple-gui.md:142 +#: src/traits/drop.md:40 +msgid "Try replacing `drop(a)` with `a.drop()`." +msgstr "" + +#: src/traits/default.md:1 +msgid "The `Default` Trait" +msgstr "" + +#: src/traits/default.md:3 msgid "" -"If you want to draw aligned text, you can use the [fill/alignment](https://" -"doc.rust-lang.org/std/fmt/index.html#fillalignment) formatting operators. In " -"particular, notice how you can pad with different characters (here a `'/'`) " -"and how you can control alignment:" +"[`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) trait " +"produces a default value for a type." msgstr "" -#: src/exercises/day-3/simple-gui.md:147 +#: src/traits/default.md:5 msgid "" "```rust,editable\n" +"#[derive(Debug, Default)]\n" +"struct Derived {\n" +" x: u32,\n" +" y: String,\n" +" z: Implemented,\n" +"}\n" +"\n" +"#[derive(Debug)]\n" +"struct Implemented(String);\n" +"\n" +"impl Default for Implemented {\n" +" fn default() -> Self {\n" +" Self(\"John Smith\".into())\n" +" }\n" +"}\n" +"\n" "fn main() {\n" -" let width = 10;\n" -" println!(\"left aligned: |{:/width$}|\", \"foo\");\n" +" let default_struct = Derived::default();\n" +" println!(\"{default_struct:#?}\");\n" +"\n" +" let almost_default_struct = Derived {\n" +" y: \"Y is set!\".into(),\n" +" ..Derived::default()\n" +" };\n" +" println!(\"{almost_default_struct:#?}\");\n" +"\n" +" let nothing: Option = None;\n" +" println!(\"{:#?}\", nothing.unwrap_or_default());\n" "}\n" +"\n" "```" msgstr "" -#: src/exercises/day-3/simple-gui.md:156 +#: src/traits/default.md:40 msgid "" -"Using such alignment tricks, you can for example produce output like this:" +"It can be implemented directly or it can be derived via `#[derive(Default)]`." msgstr "" -#: src/exercises/day-3/simple-gui.md:158 +#: src/traits/default.md:41 msgid "" -"```text\n" -"+--------------------------------+\n" -"| Rust GUI Demo 1.23 |\n" -"+================================+\n" -"| This is a small text GUI demo. |\n" -"| +-----------+ |\n" -"| | Click me! | |\n" -"| +-----------+ |\n" -"+--------------------------------+\n" -"```" -msgstr "" - -#: src/error-handling.md:3 -msgid "Error handling in Rust is done using explicit control flow:" -msgstr "" - -#: src/error-handling.md:5 -msgid "Functions that can have errors list this in their return type," -msgstr "" - -#: src/error-handling.md:6 -msgid "There are no exceptions." +"A derived implementation will produce a value where all fields are set to " +"their default values." msgstr "" -#: src/error-handling/panics.md:3 -msgid "Rust will trigger a panic if a fatal error happens at runtime:" +#: src/traits/default.md:42 +msgid "This means all types in the struct must implement `Default` too." msgstr "" -#: src/error-handling/panics.md:5 +#: src/traits/default.md:43 msgid "" -"```rust,editable,should_panic\n" -"fn main() {\n" -" let v = vec![10, 20, 30];\n" -" println!(\"v[100]: {}\", v[100]);\n" -"}\n" -"```" +"Standard Rust types often implement `Default` with reasonable values (e.g. " +"`0`, `\"\"`, etc)." msgstr "" -#: src/error-handling/panics.md:12 -msgid "Panics are for unrecoverable and unexpected errors." +#: src/traits/default.md:44 +msgid "The partial struct copy works nicely with default." msgstr "" -#: src/error-handling/panics.md:13 -msgid "Panics are symptoms of bugs in the program." +#: src/traits/default.md:45 +msgid "" +"Rust standard library is aware that types can implement `Default` and " +"provides convenience methods that use it." msgstr "" -#: src/error-handling/panics.md:14 +#: src/traits/default.md:46 msgid "" -"Use non-panicking APIs (such as `Vec::get`) if crashing is not acceptable." +"the `..` syntax is called [struct update syntax](https://doc.rust-lang.org/" +"book/ch05-01-defining-structs.html#creating-instances-from-other-instances-" +"with-struct-update-syntax)" msgstr "" -#: src/error-handling/panic-unwind.md:1 -msgid "Catching the Stack Unwinding" +#: src/traits/operators.md:1 +msgid "`Add`, `Mul`, ..." msgstr "" -#: src/error-handling/panic-unwind.md:3 +#: src/traits/operators.md:3 msgid "" -"By default, a panic will cause the stack to unwind. The unwinding can be " -"caught:" +"Operator overloading is implemented via traits in [`std::ops`](https://doc." +"rust-lang.org/std/ops/index.html):" msgstr "" -#: src/error-handling/panic-unwind.md:5 +#: src/traits/operators.md:5 msgid "" "```rust,editable\n" -"use std::panic;\n" +"#[derive(Debug, Copy, Clone)]\n" +"struct Point { x: i32, y: i32 }\n" +"\n" +"impl std::ops::Add for Point {\n" +" type Output = Self;\n" "\n" -"let result = panic::catch_unwind(|| {\n" -" println!(\"hello!\");\n" -"});\n" -"assert!(result.is_ok());\n" +" fn add(self, other: Self) -> Self {\n" +" Self {x: self.x + other.x, y: self.y + other.y}\n" +" }\n" +"}\n" "\n" -"let result = panic::catch_unwind(|| {\n" -" panic!(\"oh no!\");\n" -"});\n" -"assert!(result.is_err());\n" +"fn main() {\n" +" let p1 = Point { x: 10, y: 20 };\n" +" let p2 = Point { x: 100, y: 200 };\n" +" println!(\"{:?} + {:?} = {:?}\", p1, p2, p1 + p2);\n" +"}\n" "```" msgstr "" -#: src/error-handling/panic-unwind.md:19 +#: src/traits/operators.md:28 msgid "" -"This can be useful in servers which should keep running even if a single " -"request crashes." +"You could implement `Add` for `&Point`. In which situations is that useful? " msgstr "" -#: src/error-handling/panic-unwind.md:21 -msgid "This does not work if `panic = 'abort'` is set in your `Cargo.toml`." +#: src/traits/operators.md:29 +msgid "" +"Answer: `Add:add` consumes `self`. If type `T` for which you are overloading " +"the operator is not `Copy`, you should consider overloading the operator for " +"`&T` as well. This avoids unnecessary cloning on the call site." msgstr "" -#: src/error-handling/result.md:1 -msgid "Structured Error Handling with `Result`" +#: src/traits/operators.md:33 +msgid "" +"Why is `Output` an associated type? Could it be made a type parameter of the " +"method?" msgstr "" -#: src/error-handling/result.md:3 +#: src/traits/operators.md:34 msgid "" -"We have already seen the `Result` enum. This is used pervasively when errors " -"are expected as part of normal operation:" +"Short answer: Function type parameters are controlled by the caller, but " +"associated types (like `Output`) are controlled by the implementor of a " +"trait." msgstr "" -#: src/error-handling/result.md:6 +#: src/traits/operators.md:37 msgid "" -"```rust,editable\n" -"use std::fs::File;\n" -"use std::io::Read;\n" -"\n" -"fn main() {\n" -" let file = File::open(\"diary.txt\");\n" -" match file {\n" -" Ok(mut file) => {\n" -" let mut contents = String::new();\n" -" file.read_to_string(&mut contents);\n" -" println!(\"Dear diary: {contents}\");\n" -" },\n" -" Err(err) => {\n" -" println!(\"The diary could not be opened: {err}\");\n" -" }\n" -" }\n" -"}\n" -"```" +"You could implement `Add` for two different types, e.g. `impl Add<(i32, " +"i32)> for Point` would add a tuple to a `Point`." msgstr "" -#: src/error-handling/result.md:27 +#: src/traits/closures.md:1 +msgid "Closures" +msgstr "" + +#: src/traits/closures.md:3 msgid "" -"As with `Option`, the successful value sits inside of `Result`, forcing the " -"developer to explicitly extract it. This encourages error checking. In the " -"case where an error should never happen, `unwrap()` or `expect()` can be " -"called, and this is a signal of the developer intent too." +"Closures or lambda expressions have types which cannot be named. However, " +"they implement special [`Fn`](https://doc.rust-lang.org/std/ops/trait.Fn." +"html), [`FnMut`](https://doc.rust-lang.org/std/ops/trait.FnMut.html), and " +"[`FnOnce`](https://doc.rust-lang.org/std/ops/trait.FnOnce.html) traits:" msgstr "" -#: src/error-handling/result.md:30 +#: src/traits/closures.md:8 msgid "" -"`Result` documentation is a recommended read. Not during the course, but it " -"is worth mentioning. It contains a lot of convenience methods and functions " -"that help functional-style programming. " +"```rust,editable\n" +"fn apply_with_log(func: impl FnOnce(i32) -> i32, input: i32) -> i32 {\n" +" println!(\"Calling function on {input}\");\n" +" func(input)\n" +"}\n" +"\n" +"fn main() {\n" +" let add_3 = |x| x + 3;\n" +" println!(\"add_3: {}\", apply_with_log(add_3, 10));\n" +" println!(\"add_3: {}\", apply_with_log(add_3, 20));\n" +"\n" +" let mut v = Vec::new();\n" +" let mut accumulate = |x: i32| {\n" +" v.push(x);\n" +" v.iter().sum::()\n" +" };\n" +" println!(\"accumulate: {}\", apply_with_log(&mut accumulate, 4));\n" +" println!(\"accumulate: {}\", apply_with_log(&mut accumulate, 5));\n" +"\n" +" let multiply_sum = |x| x * v.into_iter().sum::();\n" +" println!(\"multiply_sum: {}\", apply_with_log(multiply_sum, 3));\n" +"}\n" +"```" msgstr "" -#: src/error-handling/try-operator.md:1 -msgid "Propagating Errors with `?`" +#: src/traits/closures.md:34 +msgid "" +"An `Fn` (e.g. `add_3`) neither consumes nor mutates captured values, or " +"perhaps captures nothing at all. It can be called multiple times " +"concurrently." msgstr "" -#: src/error-handling/try-operator.md:3 +#: src/traits/closures.md:37 msgid "" -"The try-operator `?` is used to return errors to the caller. It lets you " -"turn the common" +"An `FnMut` (e.g. `accumulate`) might mutate captured values. You can call it " +"multiple times, but not concurrently." msgstr "" -#: src/error-handling/try-operator.md:6 +#: src/traits/closures.md:40 msgid "" -"```rust,ignore\n" -"match some_expression {\n" -" Ok(value) => value,\n" -" Err(err) => return Err(err),\n" -"}\n" -"```" +"If you have an `FnOnce` (e.g. `multiply_sum`), you may only call it once. It " +"might consume captured values." msgstr "" -#: src/error-handling/try-operator.md:13 -msgid "into the much simpler" +#: src/traits/closures.md:43 +msgid "" +"`FnMut` is a subtype of `FnOnce`. `Fn` is a subtype of `FnMut` and `FnOnce`. " +"I.e. you can use an `FnMut` wherever an `FnOnce` is called for, and you can " +"use an `Fn` wherever an `FnMut` or `FnOnce` is called for." msgstr "" -#: src/error-handling/try-operator.md:15 +#: src/traits/closures.md:47 msgid "" -"```rust,ignore\n" -"some_expression?\n" -"```" +"The compiler also infers `Copy` (e.g. for `add_3`) and `Clone` (e.g. " +"`multiply_sum`), depending on what the closure captures." msgstr "" -#: src/error-handling/try-operator.md:19 -msgid "We can use this to simplify our error handing code:" +#: src/traits/closures.md:50 +msgid "" +"By default, closures will capture by reference if they can. The `move` " +"keyword makes them capture by value." msgstr "" -#: src/error-handling/try-operator.md:21 +#: src/traits/closures.md:52 msgid "" "```rust,editable\n" -"use std::fs;\n" -"use std::io::{self, Read};\n" -"\n" -"fn read_username(path: &str) -> Result {\n" -" let username_file_result = fs::File::open(path);\n" -" let mut username_file = match username_file_result {\n" -" Ok(file) => file,\n" -" Err(err) => return Err(err),\n" -" };\n" -"\n" -" let mut username = String::new();\n" -" match username_file.read_to_string(&mut username) {\n" -" Ok(_) => Ok(username),\n" -" Err(err) => Err(err),\n" -" }\n" +"fn make_greeter(prefix: String) -> impl Fn(&str) {\n" +" return move |name| println!(\"{} {}\", prefix, name)\n" "}\n" "\n" "fn main() {\n" -" //fs::write(\"config.dat\", \"alice\").unwrap();\n" -" let username = read_username(\"config.dat\");\n" -" println!(\"username or error: {username:?}\");\n" +" let hi = make_greeter(\"Hi\".to_string());\n" +" hi(\"there\");\n" "}\n" "```" msgstr "" -#: src/error-handling/try-operator.md:50 -#: src/error-handling/converting-error-types-example.md:52 -msgid "The `username` variable can be either `Ok(string)` or `Err(error)`." +#: src/exercises/day-3/morning.md:1 +msgid "Day 3: Morning Exercises" msgstr "" -#: src/error-handling/try-operator.md:51 -#: src/error-handling/converting-error-types-example.md:53 -msgid "" -"Use the `fs::write` call to test out the different scenarios: no file, empty " -"file, file with username." +#: src/exercises/day-3/morning.md:3 +msgid "We will design a classical GUI library using traits and trait objects." msgstr "" -#: src/error-handling/converting-error-types.md:3 +#: src/exercises/day-3/morning.md:5 msgid "" -"The effective expansion of `?` is a little more complicated than previously " -"indicated:" +"We will also look at enum dispatch with an exercise involving points and " +"polygons." msgstr "" -#: src/error-handling/converting-error-types.md:5 +#: src/exercises/day-3/simple-gui.md:3 msgid "" -"```rust,ignore\n" -"expression?\n" -"```" +"Let us design a classical GUI library using our new knowledge of traits and " +"trait objects." msgstr "" -#: src/error-handling/converting-error-types.md:9 -msgid "works the same as" +#: src/exercises/day-3/simple-gui.md:6 +msgid "We will have a number of widgets in our library:" msgstr "" -#: src/error-handling/converting-error-types.md:11 +#: src/exercises/day-3/simple-gui.md:8 +msgid "`Window`: has a `title` and contains other widgets." +msgstr "" + +#: src/exercises/day-3/simple-gui.md:9 msgid "" -"```rust,ignore\n" -"match expression {\n" -" Ok(value) => value,\n" -" Err(err) => return Err(From::from(err)),\n" -"}\n" -"```" +"`Button`: has a `label` and a callback function which is invoked when the " +"button is pressed." msgstr "" -#: src/error-handling/converting-error-types.md:18 +#: src/exercises/day-3/simple-gui.md:11 +msgid "`Label`: has a `label`." +msgstr "" + +#: src/exercises/day-3/simple-gui.md:13 +msgid "The widgets will implement a `Widget` trait, see below." +msgstr "" + +#: src/exercises/day-3/simple-gui.md:15 msgid "" -"The `From::from` call here means we attempt to convert the error type to the " -"type returned by the function:" +"Copy the code below to , fill in the missing " +"`draw_into` methods so that you implement the `Widget` trait:" msgstr "" -#: src/error-handling/converting-error-types-example.md:3 +#: src/exercises/day-3/simple-gui.md:18 msgid "" -"```rust,editable\n" -"use std::error::Error;\n" -"use std::fmt::{self, Display, Formatter};\n" -"use std::fs::{self, File};\n" -"use std::io::{self, Read};\n" +"```rust,should_panic\n" +"// TODO: remove this when you're done with your implementation.\n" +"#![allow(unused_imports, unused_variables, dead_code)]\n" "\n" -"#[derive(Debug)]\n" -"enum ReadUsernameError {\n" -" IoError(io::Error),\n" -" EmptyUsername(String),\n" -"}\n" +"pub trait Widget {\n" +" /// Natural width of `self`.\n" +" fn width(&self) -> usize;\n" "\n" -"impl Error for ReadUsernameError {}\n" +" /// Draw the widget into a buffer.\n" +" fn draw_into(&self, buffer: &mut dyn std::fmt::Write);\n" "\n" -"impl Display for ReadUsernameError {\n" -" fn fmt(&self, f: &mut Formatter) -> fmt::Result {\n" -" match self {\n" -" Self::IoError(e) => write!(f, \"IO error: {e}\"),\n" -" Self::EmptyUsername(filename) => write!(f, \"Found no username " -"in {filename}\"),\n" -" }\n" +" /// Draw the widget on standard output.\n" +" fn draw(&self) {\n" +" let mut buffer = String::new();\n" +" self.draw_into(&mut buffer);\n" +" println!(\"{buffer}\");\n" " }\n" "}\n" "\n" -"impl From for ReadUsernameError {\n" -" fn from(err: io::Error) -> ReadUsernameError {\n" -" ReadUsernameError::IoError(err)\n" -" }\n" +"pub struct Label {\n" +" label: String,\n" "}\n" "\n" -"fn read_username(path: &str) -> Result {\n" -" let mut username = String::with_capacity(100);\n" -" File::open(path)?.read_to_string(&mut username)?;\n" -" if username.is_empty() {\n" -" return Err(ReadUsernameError::EmptyUsername(String::from(path)));\n" +"impl Label {\n" +" fn new(label: &str) -> Label {\n" +" Label {\n" +" label: label.to_owned(),\n" +" }\n" " }\n" -" Ok(username)\n" "}\n" "\n" -"fn main() {\n" -" //fs::write(\"config.dat\", \"\").unwrap();\n" -" let username = read_username(\"config.dat\");\n" -" println!(\"username or error: {username:?}\");\n" +"pub struct Button {\n" +" label: Label,\n" +" callback: Box,\n" "}\n" -"```" -msgstr "" - -#: src/error-handling/converting-error-types-example.md:55 -msgid "" -"It is good practice for all error types to implement `std::error::Error`, " -"which requires `Debug` and `Display`. It's generally helpful for them to " -"implement `Clone` and `Eq` too where possible, to make life easier for tests " -"and consumers of your library. In this case we can't easily do so, because " -"`io::Error` doesn't implement them." -msgstr "" - -#: src/error-handling/deriving-error-enums.md:3 -msgid "" -"The [thiserror](https://docs.rs/thiserror/) crate is a popular way to create " -"an error enum like we did on the previous page:" -msgstr "" - -#: src/error-handling/deriving-error-enums.md:6 -msgid "" -"```rust,editable,compile_fail\n" -"use std::{fs, io};\n" -"use std::io::Read;\n" -"use thiserror::Error;\n" "\n" -"#[derive(Debug, Error)]\n" -"enum ReadUsernameError {\n" -" #[error(\"Could not read: {0}\")]\n" -" IoError(#[from] io::Error),\n" -" #[error(\"Found no username in {0}\")]\n" -" EmptyUsername(String),\n" +"impl Button {\n" +" fn new(label: &str, callback: Box) -> Button {\n" +" Button {\n" +" label: Label::new(label),\n" +" callback,\n" +" }\n" +" }\n" "}\n" "\n" -"fn read_username(path: &str) -> Result {\n" -" let mut username = String::with_capacity(100);\n" -" fs::File::open(path)?.read_to_string(&mut username)?;\n" -" if username.is_empty() {\n" -" return Err(ReadUsernameError::EmptyUsername(String::from(path)));\n" -" }\n" -" Ok(username)\n" +"pub struct Window {\n" +" title: String,\n" +" widgets: Vec>,\n" "}\n" "\n" -"fn main() {\n" -" //fs::write(\"config.dat\", \"\").unwrap();\n" -" match read_username(\"config.dat\") {\n" -" Ok(username) => println!(\"Username: {username}\"),\n" -" Err(err) => println!(\"Error: {err}\"),\n" +"impl Window {\n" +" fn new(title: &str) -> Window {\n" +" Window {\n" +" title: title.to_owned(),\n" +" widgets: Vec::new(),\n" +" }\n" " }\n" -"}\n" -"```" -msgstr "" - -#: src/error-handling/deriving-error-enums.md:39 -msgid "" -"`thiserror`'s derive macro automatically implements `std::error::Error`, and " -"optionally `Display` (if the `#[error(...)]` attributes are provided) and " -"`From` (if the `#[from]` attribute is added). It also works for structs." -msgstr "" - -#: src/error-handling/deriving-error-enums.md:43 -msgid "It doesn't affect your public API, which makes it good for libraries." -msgstr "" - -#: src/error-handling/dynamic-errors.md:3 -msgid "" -"Sometimes we want to allow any type of error to be returned without writing " -"our own enum covering all the different possibilities. `std::error::Error` " -"makes this easy." -msgstr "" - -#: src/error-handling/dynamic-errors.md:6 -msgid "" -"```rust,editable,compile_fail\n" -"use std::fs::{self, File};\n" -"use std::io::Read;\n" -"use thiserror::Error;\n" -"use std::error::Error;\n" "\n" -"#[derive(Clone, Debug, Eq, Error, PartialEq)]\n" -"#[error(\"Found no username in {0}\")]\n" -"struct EmptyUsernameError(String);\n" +" fn add_widget(&mut self, widget: Box) {\n" +" self.widgets.push(widget);\n" +" }\n" "\n" -"fn read_username(path: &str) -> Result> {\n" -" let mut username = String::with_capacity(100);\n" -" File::open(path)?.read_to_string(&mut username)?;\n" -" if username.is_empty() {\n" -" return Err(EmptyUsernameError(String::from(path)).into());\n" +" fn inner_width(&self) -> usize {\n" +" std::cmp::max(\n" +" self.title.chars().count(),\n" +" self.widgets.iter().map(|w| w.width()).max().unwrap_or(0),\n" +" )\n" " }\n" -" Ok(username)\n" "}\n" "\n" -"fn main() {\n" -" //fs::write(\"config.dat\", \"\").unwrap();\n" -" match read_username(\"config.dat\") {\n" -" Ok(username) => println!(\"Username: {username}\"),\n" -" Err(err) => println!(\"Error: {err}\"),\n" +"\n" +"impl Widget for Label {\n" +" fn width(&self) -> usize {\n" +" unimplemented!()\n" +" }\n" +"\n" +" fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {\n" +" unimplemented!()\n" " }\n" "}\n" -"```" -msgstr "" - -#: src/error-handling/dynamic-errors.md:36 -msgid "" -"This saves on code, but gives up the ability to cleanly handle different " -"error cases differently in the program. As such it's generally not a good " -"idea to use `Box` in the public API of a library, but it can be a " -"good option in a program where you just want to display the error message " -"somewhere." -msgstr "" - -#: src/error-handling/error-contexts.md:3 -msgid "" -"The widely used [anyhow](https://docs.rs/anyhow/) crate can help you add " -"contextual information to your errors and allows you to have fewer custom " -"error types:" -msgstr "" - -#: src/error-handling/error-contexts.md:7 -msgid "" -"```rust,editable,compile_fail\n" -"use std::{fs, io};\n" -"use std::io::Read;\n" -"use anyhow::{Context, Result, bail};\n" "\n" -"fn read_username(path: &str) -> Result {\n" -" let mut username = String::with_capacity(100);\n" -" fs::File::open(path)\n" -" .with_context(|| format!(\"Failed to open {path}\"))?\n" -" .read_to_string(&mut username)\n" -" .context(\"Failed to read\")?;\n" -" if username.is_empty() {\n" -" bail!(\"Found no username in {path}\");\n" +"impl Widget for Button {\n" +" fn width(&self) -> usize {\n" +" unimplemented!()\n" +" }\n" +"\n" +" fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {\n" +" unimplemented!()\n" " }\n" -" Ok(username)\n" "}\n" "\n" -"fn main() {\n" -" //fs::write(\"config.dat\", \"\").unwrap();\n" -" match read_username(\"config.dat\") {\n" -" Ok(username) => println!(\"Username: {username}\"),\n" -" Err(err) => println!(\"Error: {err:?}\"),\n" +"impl Widget for Window {\n" +" fn width(&self) -> usize {\n" +" unimplemented!()\n" +" }\n" +"\n" +" fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {\n" +" unimplemented!()\n" " }\n" "}\n" +"\n" +"fn main() {\n" +" let mut window = Window::new(\"Rust GUI Demo 1.23\");\n" +" window.add_widget(Box::new(Label::new(\"This is a small text GUI demo." +"\")));\n" +" window.add_widget(Box::new(Button::new(\n" +" \"Click me!\",\n" +" Box::new(|| println!(\"You clicked the button!\")),\n" +" )));\n" +" window.draw();\n" +"}\n" "```" msgstr "" -#: src/error-handling/error-contexts.md:35 -msgid "`anyhow::Result` is a type alias for `Result`." +#: src/exercises/day-3/simple-gui.md:130 +msgid "The output of the above program can be something simple like this:" msgstr "" -#: src/error-handling/error-contexts.md:36 +#: src/exercises/day-3/simple-gui.md:132 msgid "" -"`anyhow::Error` is essentially a wrapper around `Box`. As such " -"it's again generally not a good choice for the public API of a library, but " -"is widely used in applications." +"```text\n" +"========\n" +"Rust GUI Demo 1.23\n" +"========\n" +"\n" +"This is a small text GUI demo.\n" +"\n" +"| Click me! |\n" +"```" msgstr "" -#: src/error-handling/error-contexts.md:38 +#: src/exercises/day-3/simple-gui.md:142 msgid "" -"Actual error type inside of it can be extracted for examination if necessary." +"If you want to draw aligned text, you can use the [fill/alignment](https://" +"doc.rust-lang.org/std/fmt/index.html#fillalignment) formatting operators. In " +"particular, notice how you can pad with different characters (here a `'/'`) " +"and how you can control alignment:" msgstr "" -#: src/error-handling/error-contexts.md:39 +#: src/exercises/day-3/simple-gui.md:147 msgid "" -"Functionality provided by `anyhow::Result` may be familiar to Go " -"developers, as it provides similar usage patterns and ergonomics to `(T, " -"error)` from Go." +"```rust,editable\n" +"fn main() {\n" +" let width = 10;\n" +" println!(\"left aligned: |{:/width$}|\", \"foo\");\n" +"}\n" +"```" msgstr "" -#: src/testing.md:3 -msgid "Rust and Cargo come with a simple unit test framework:" +#: src/exercises/day-3/simple-gui.md:156 +msgid "" +"Using such alignment tricks, you can for example produce output like this:" msgstr "" -#: src/testing.md:5 -msgid "Unit tests are supported throughout your code." +#: src/exercises/day-3/simple-gui.md:158 +msgid "" +"```text\n" +"+--------------------------------+\n" +"| Rust GUI Demo 1.23 |\n" +"+================================+\n" +"| This is a small text GUI demo. |\n" +"| +-----------+ |\n" +"| | Click me! | |\n" +"| +-----------+ |\n" +"+--------------------------------+\n" +"```" msgstr "" -#: src/testing.md:7 -msgid "Integration tests are supported via the `tests/` directory." +#: src/exercises/day-3/points-polygons.md:1 +msgid "Polygon Struct" msgstr "" -#: src/testing/unit-tests.md:3 -msgid "Mark unit tests with `#[test]`:" +#: src/exercises/day-3/points-polygons.md:3 +msgid "" +"We will create a `Polygon` struct which contain some points. Copy the code " +"below to and fill in the missing methods to " +"make the tests pass:" msgstr "" -#: src/testing/unit-tests.md:5 +#: src/exercises/day-3/points-polygons.md:7 msgid "" -"```rust,editable,ignore\n" -"fn first_word(text: &str) -> &str {\n" -" match text.find(' ') {\n" -" Some(idx) => &text[..idx],\n" -" None => &text,\n" -" }\n" +"```rust\n" +"// TODO: remove this when you're done with your implementation.\n" +"#![allow(unused_variables, dead_code)]\n" +"\n" +"pub struct Point {\n" +" // add fields\n" "}\n" "\n" -"#[test]\n" -"fn test_empty() {\n" -" assert_eq!(first_word(\"\"), \"\");\n" +"impl Point {\n" +" // add methods\n" "}\n" "\n" -"#[test]\n" -"fn test_single_word() {\n" -" assert_eq!(first_word(\"Hello\"), \"Hello\");\n" +"pub struct Polygon {\n" +" // add fields\n" "}\n" "\n" -"#[test]\n" -"fn test_multiple_words() {\n" -" assert_eq!(first_word(\"Hello World\"), \"Hello\");\n" +"impl Polygon {\n" +" // add methods\n" "}\n" -"```" -msgstr "" - -#: src/testing/unit-tests.md:29 -msgid "Use `cargo test` to find and run the unit tests." -msgstr "" - -#: src/testing/test-modules.md:3 -msgid "" -"Unit tests are often put in a nested module (run tests on the [Playground]" -"(https://play.rust-lang.org/)):" -msgstr "" - -#: src/testing/test-modules.md:6 -msgid "" -"```rust,editable\n" -"fn helper(a: &str, b: &str) -> String {\n" -" format!(\"{a} {b}\")\n" +"\n" +"pub struct Circle {\n" +" // add fields\n" "}\n" "\n" -"pub fn main() {\n" -" println!(\"{}\", helper(\"Hello\", \"World\"));\n" +"impl Circle {\n" +" // add methods\n" +"}\n" +"\n" +"pub enum Shape {\n" +" Polygon(Polygon),\n" +" Circle(Circle),\n" "}\n" "\n" "#[cfg(test)]\n" "mod tests {\n" " use super::*;\n" "\n" +" fn round_two_digits(x: f64) -> f64 {\n" +" (x * 100.0).round() / 100.0\n" +" }\n" +"\n" " #[test]\n" -" fn test_helper() {\n" -" assert_eq!(helper(\"foo\", \"bar\"), \"foo bar\");\n" +" fn test_point_magnitude() {\n" +" let p1 = Point::new(12, 13);\n" +" assert_eq!(round_two_digits(p1.magnitude()), 17.69);\n" " }\n" -"}\n" -"```" -msgstr "" - -#: src/testing/test-modules.md:26 -msgid "This lets you unit test private helpers." +"\n" +" #[test]\n" +" fn test_point_dist() {\n" +" let p1 = Point::new(10, 10);\n" +" let p2 = Point::new(14, 13);\n" +" assert_eq!(round_two_digits(p1.dist(p2)), 5.00);\n" +" }\n" +"\n" +" #[test]\n" +" fn test_point_add() {\n" +" let p1 = Point::new(16, 16);\n" +" let p2 = p1 + Point::new(-4, 3);\n" +" assert_eq!(p2, Point::new(12, 19));\n" +" }\n" +"\n" +" #[test]\n" +" fn test_polygon_left_most_point() {\n" +" let p1 = Point::new(12, 13);\n" +" let p2 = Point::new(16, 16);\n" +"\n" +" let mut poly = Polygon::new();\n" +" poly.add_point(p1);\n" +" poly.add_point(p2);\n" +" assert_eq!(poly.left_most_point(), Some(p1));\n" +" }\n" +"\n" +" #[test]\n" +" fn test_polygon_iter() {\n" +" let p1 = Point::new(12, 13);\n" +" let p2 = Point::new(16, 16);\n" +"\n" +" let mut poly = Polygon::new();\n" +" poly.add_point(p1);\n" +" poly.add_point(p2);\n" +"\n" +" let points = poly.iter().cloned().collect::>();\n" +" assert_eq!(points, vec![Point::new(12, 13), Point::new(16, 16)]);\n" +" }\n" +"\n" +" #[test]\n" +" fn test_shape_perimeters() {\n" +" let mut poly = Polygon::new();\n" +" poly.add_point(Point::new(12, 13));\n" +" poly.add_point(Point::new(17, 11));\n" +" poly.add_point(Point::new(16, 16));\n" +" let shapes = vec![\n" +" Shape::from(poly),\n" +" Shape::from(Circle::new(Point::new(10, 20), 5)),\n" +" ];\n" +" let perimeters = shapes\n" +" .iter()\n" +" .map(Shape::perimeter)\n" +" .map(round_two_digits)\n" +" .collect::>();\n" +" assert_eq!(perimeters, vec![15.48, 31.42]);\n" +" }\n" +"}\n" +"\n" +"#[allow(dead_code)]\n" +"fn main() {}\n" +"```" msgstr "" -#: src/testing/test-modules.md:27 -msgid "The `#[cfg(test)]` attribute is only active when you run `cargo test`." +#: src/exercises/day-3/points-polygons.md:117 +msgid "" +"Since the method signatures are missing from the problem statements, the key " +"part of the exercise is to specify those correctly. You don't have to modify " +"the tests." msgstr "" -#: src/testing/doc-tests.md:3 -msgid "Rust has built-in support for documentation tests:" +#: src/exercises/day-3/points-polygons.md:120 +msgid "Other interesting parts of the exercise:" msgstr "" -#: src/testing/doc-tests.md:5 +#: src/exercises/day-3/points-polygons.md:122 msgid "" -"```rust\n" -"/// Shortens a string to the given length.\n" -"///\n" -"/// ```\n" -"/// use playground::shorten_string;\n" -"/// assert_eq!(shorten_string(\"Hello World\", 5), \"Hello\");\n" -"/// assert_eq!(shorten_string(\"Hello World\", 20), \"Hello World\");\n" -"/// ```\n" -"pub fn shorten_string(s: &str, length: usize) -> &str {\n" -" &s[..std::cmp::min(length, s.len())]\n" -"}\n" -"```" +"Derive a `Copy` trait for some structs, as in tests the methods sometimes " +"don't borrow their arguments." msgstr "" -#: src/testing/doc-tests.md:18 -msgid "Code blocks in `///` comments are automatically seen as Rust code." +#: src/exercises/day-3/points-polygons.md:123 +msgid "" +"Discover that `Add` trait must be implemented for two objects to be addable " +"via \"+\". Note that we do not discuss generics until Day 3." msgstr "" -#: src/testing/doc-tests.md:19 -msgid "The code will be compiled and executed as part of `cargo test`." +#: src/error-handling.md:3 +msgid "Error handling in Rust is done using explicit control flow:" msgstr "" -#: src/testing/doc-tests.md:20 -msgid "" -"Test the above code on the [Rust Playground](https://play.rust-lang.org/?" -"version=stable&mode=debug&edition=2021&gist=3ce2ad13ea1302f6572cb15cd96becf0)." +#: src/error-handling.md:5 +msgid "Functions that can have errors list this in their return type," msgstr "" -#: src/testing/integration-tests.md:3 -msgid "If you want to test your library as a client, use an integration test." +#: src/error-handling.md:6 +msgid "There are no exceptions." msgstr "" -#: src/testing/integration-tests.md:5 -msgid "Create a `.rs` file under `tests/`:" +#: src/error-handling/panics.md:3 +msgid "Rust will trigger a panic if a fatal error happens at runtime:" msgstr "" -#: src/testing/integration-tests.md:7 +#: src/error-handling/panics.md:5 msgid "" -"```rust,ignore\n" -"use my_library::init;\n" -"\n" -"#[test]\n" -"fn test_init() {\n" -" assert!(init().is_ok());\n" +"```rust,editable,should_panic\n" +"fn main() {\n" +" let v = vec![10, 20, 30];\n" +" println!(\"v[100]: {}\", v[100]);\n" "}\n" "```" msgstr "" -#: src/testing/integration-tests.md:16 -msgid "These tests only have access to the public API of your crate." +#: src/error-handling/panics.md:12 +msgid "Panics are for unrecoverable and unexpected errors." msgstr "" -#: src/testing/useful-crates.md:1 -msgid "Useful crates for writing tests" +#: src/error-handling/panics.md:13 +msgid "Panics are symptoms of bugs in the program." msgstr "" -#: src/testing/useful-crates.md:3 -msgid "Rust comes with only basic support for writing tests." +#: src/error-handling/panics.md:14 +msgid "" +"Use non-panicking APIs (such as `Vec::get`) if crashing is not acceptable." msgstr "" -#: src/testing/useful-crates.md:5 -msgid "Here are some additional crates which we recommend for writing tests:" +#: src/error-handling/panic-unwind.md:1 +msgid "Catching the Stack Unwinding" msgstr "" -#: src/testing/useful-crates.md:7 +#: src/error-handling/panic-unwind.md:3 msgid "" -"[googletest](https://docs.rs/googletest): Comprehensive test assertion " -"library in the tradition of GoogleTest for C++." +"By default, a panic will cause the stack to unwind. The unwinding can be " +"caught:" msgstr "" -#: src/testing/useful-crates.md:8 -msgid "[proptest](https://docs.rs/proptest): Property-based testing for Rust." +#: src/error-handling/panic-unwind.md:5 +msgid "" +"```rust,editable\n" +"use std::panic;\n" +"\n" +"fn main() {\n" +" let result = panic::catch_unwind(|| {\n" +" println!(\"hello!\");\n" +" });\n" +" assert!(result.is_ok());\n" +" \n" +" let result = panic::catch_unwind(|| {\n" +" panic!(\"oh no!\");\n" +" });\n" +" assert!(result.is_err());\n" +"}\n" +"```" msgstr "" -#: src/testing/useful-crates.md:9 +#: src/error-handling/panic-unwind.md:21 msgid "" -"[rstest](https://docs.rs/rstest): Support for fixtures and parameterised " -"tests." +"This can be useful in servers which should keep running even if a single " +"request crashes." msgstr "" -#: src/unsafe.md:3 -msgid "The Rust language has two parts:" +#: src/error-handling/panic-unwind.md:23 +msgid "This does not work if `panic = 'abort'` is set in your `Cargo.toml`." msgstr "" -#: src/unsafe.md:5 -msgid "**Safe Rust:** memory safe, no undefined behavior possible." +#: src/error-handling/result.md:1 +msgid "Structured Error Handling with `Result`" msgstr "" -#: src/unsafe.md:6 +#: src/error-handling/result.md:3 msgid "" -"**Unsafe Rust:** can trigger undefined behavior if preconditions are " -"violated." +"We have already seen the `Result` enum. This is used pervasively when errors " +"are expected as part of normal operation:" msgstr "" -#: src/unsafe.md:8 +#: src/error-handling/result.md:6 msgid "" -"We will be seeing mostly safe Rust in this course, but it's important to " -"know what Unsafe Rust is." +"```rust,editable\n" +"use std::fs;\n" +"use std::io::Read;\n" +"\n" +"fn main() {\n" +" let file = fs::File::open(\"diary.txt\");\n" +" match file {\n" +" Ok(mut file) => {\n" +" let mut contents = String::new();\n" +" file.read_to_string(&mut contents);\n" +" println!(\"Dear diary: {contents}\");\n" +" },\n" +" Err(err) => {\n" +" println!(\"The diary could not be opened: {err}\");\n" +" }\n" +" }\n" +"}\n" +"```" msgstr "" -#: src/unsafe.md:11 +#: src/error-handling/result.md:27 msgid "" -"Unsafe code is usually small and isolated, and its correctness should be " -"carefully documented. It is usually wrapped in a safe abstraction layer." +"As with `Option`, the successful value sits inside of `Result`, forcing the " +"developer to explicitly extract it. This encourages error checking. In the " +"case where an error should never happen, `unwrap()` or `expect()` can be " +"called, and this is a signal of the developer intent too." msgstr "" -#: src/unsafe.md:14 -msgid "Unsafe Rust gives you access to five new capabilities:" +#: src/error-handling/result.md:30 +msgid "" +"`Result` documentation is a recommended read. Not during the course, but it " +"is worth mentioning. It contains a lot of convenience methods and functions " +"that help functional-style programming. " msgstr "" -#: src/unsafe.md:16 -msgid "Dereference raw pointers." +#: src/error-handling/try-operator.md:1 +msgid "Propagating Errors with `?`" msgstr "" -#: src/unsafe.md:17 -msgid "Access or modify mutable static variables." +#: src/error-handling/try-operator.md:3 +msgid "" +"The try-operator `?` is used to return errors to the caller. It lets you " +"turn the common" msgstr "" -#: src/unsafe.md:18 -msgid "Access `union` fields." +#: src/error-handling/try-operator.md:6 +msgid "" +"```rust,ignore\n" +"match some_expression {\n" +" Ok(value) => value,\n" +" Err(err) => return Err(err),\n" +"}\n" +"```" msgstr "" -#: src/unsafe.md:19 -msgid "Call `unsafe` functions, including `extern` functions." +#: src/error-handling/try-operator.md:13 +msgid "into the much simpler" msgstr "" -#: src/unsafe.md:20 -msgid "Implement `unsafe` traits." +#: src/error-handling/try-operator.md:15 +msgid "" +"```rust,ignore\n" +"some_expression?\n" +"```" msgstr "" -#: src/unsafe.md:22 -msgid "" -"We will briefly cover unsafe capabilities next. For full details, please see " -"[Chapter 19.1 in the Rust Book](https://doc.rust-lang.org/book/ch19-01-" -"unsafe-rust.html) and the [Rustonomicon](https://doc.rust-lang.org/nomicon/)." +#: src/error-handling/try-operator.md:19 +msgid "We can use this to simplify our error handling code:" msgstr "" -#: src/unsafe.md:28 -msgid "" -"Unsafe Rust does not mean the code is incorrect. It means that developers " -"have turned off the compiler safety features and have to write correct code " -"by themselves. It means the compiler no longer enforces Rust's memory-safety " -"rules." -msgstr "" - -#: src/unsafe/raw-pointers.md:3 -msgid "Creating pointers is safe, but dereferencing them requires `unsafe`:" -msgstr "" - -#: src/unsafe/raw-pointers.md:5 +#: src/error-handling/try-operator.md:21 msgid "" "```rust,editable\n" -"fn main() {\n" -" let mut num = 5;\n" +"use std::{fs, io};\n" +"use std::io::Read;\n" "\n" -" let r1 = &mut num as *mut i32;\n" -" let r2 = r1 as *const i32;\n" +"fn read_username(path: &str) -> Result {\n" +" let username_file_result = fs::File::open(path);\n" +" let mut username_file = match username_file_result {\n" +" Ok(file) => file,\n" +" Err(err) => return Err(err),\n" +" };\n" "\n" -" // Safe because r1 and r2 were obtained from references and so are\n" -" // guaranteed to be non-null and properly aligned, the objects " -"underlying\n" -" // the references from which they were obtained are live throughout the\n" -" // whole unsafe block, and they are not accessed either through the\n" -" // references or concurrently through any other pointers.\n" -" unsafe {\n" -" println!(\"r1 is: {}\", *r1);\n" -" *r1 = 10;\n" -" println!(\"r2 is: {}\", *r2);\n" +" let mut username = String::new();\n" +" match username_file.read_to_string(&mut username) {\n" +" Ok(_) => Ok(username),\n" +" Err(err) => Err(err),\n" " }\n" "}\n" +"\n" +"fn main() {\n" +" //fs::write(\"config.dat\", \"alice\").unwrap();\n" +" let username = read_username(\"config.dat\");\n" +" println!(\"username or error: {username:?}\");\n" +"}\n" "```" msgstr "" -#: src/unsafe/raw-pointers.md:27 -msgid "" -"It is good practice (and required by the Android Rust style guide) to write " -"a comment for each `unsafe` block explaining how the code inside it " -"satisfies the safety requirements of the unsafe operations it is doing." +#: src/error-handling/try-operator.md:50 +#: src/error-handling/converting-error-types-example.md:52 +msgid "The `username` variable can be either `Ok(string)` or `Err(error)`." msgstr "" -#: src/unsafe/raw-pointers.md:31 +#: src/error-handling/try-operator.md:51 +#: src/error-handling/converting-error-types-example.md:53 msgid "" -"In the case of pointer dereferences, this means that the pointers must be " -"[_valid_](https://doc.rust-lang.org/std/ptr/index.html#safety), i.e.:" -msgstr "" - -#: src/unsafe/raw-pointers.md:34 -msgid "The pointer must be non-null." +"Use the `fs::write` call to test out the different scenarios: no file, empty " +"file, file with username." msgstr "" -#: src/unsafe/raw-pointers.md:35 +#: src/error-handling/try-operator.md:52 msgid "" -"The pointer must be _dereferenceable_ (within the bounds of a single " -"allocated object)." -msgstr "" - -#: src/unsafe/raw-pointers.md:36 -msgid "The object must not have been deallocated." +"The return type of the function has to be compatible with the nested " +"functions it calls. For instance, a function returning a `Result` " +"can only apply the `?` operator on a function returning a `Result`. It cannot apply the `?` operator on a function returning an " +"`Option` or `Result` unless `OtherErr` implements " +"`From`. Reciprocally, a function returning an `Option` can only " +"apply the `?` operator on a function returning an `Option`." msgstr "" -#: src/unsafe/raw-pointers.md:37 -msgid "There must not be concurrent accesses to the same location." +#: src/error-handling/try-operator.md:57 +msgid "" +"You can convert incompatible types into one another with the different " +"`Option` and `Result` methods such as `Option::ok_or`, `Result::ok`, " +"`Result::err`." msgstr "" -#: src/unsafe/raw-pointers.md:38 +#: src/error-handling/converting-error-types.md:3 msgid "" -"If the pointer was obtained by casting a reference, the underlying object " -"must be live and no reference may be used to access the memory." +"The effective expansion of `?` is a little more complicated than previously " +"indicated:" msgstr "" -#: src/unsafe/raw-pointers.md:41 -msgid "In most cases the pointer must also be properly aligned." +#: src/error-handling/converting-error-types.md:5 +msgid "" +"```rust,ignore\n" +"expression?\n" +"```" msgstr "" -#: src/unsafe/mutable-static-variables.md:3 -msgid "It is safe to read an immutable static variable:" +#: src/error-handling/converting-error-types.md:9 +msgid "works the same as" msgstr "" -#: src/unsafe/mutable-static-variables.md:5 +#: src/error-handling/converting-error-types.md:11 msgid "" -"```rust,editable\n" -"static HELLO_WORLD: &str = \"Hello, world!\";\n" -"\n" -"fn main() {\n" -" println!(\"HELLO_WORLD: {HELLO_WORLD}\");\n" +"```rust,ignore\n" +"match expression {\n" +" Ok(value) => value,\n" +" Err(err) => return Err(From::from(err)),\n" "}\n" "```" msgstr "" -#: src/unsafe/mutable-static-variables.md:13 +#: src/error-handling/converting-error-types.md:18 msgid "" -"However, since data races can occur, it is unsafe to read and write mutable " -"static variables:" +"The `From::from` call here means we attempt to convert the error type to the " +"type returned by the function:" msgstr "" -#: src/unsafe/mutable-static-variables.md:16 +#: src/error-handling/converting-error-types-example.md:3 msgid "" "```rust,editable\n" -"static mut COUNTER: u32 = 0;\n" +"use std::error::Error;\n" +"use std::fmt::{self, Display, Formatter};\n" +"use std::fs::{self, File};\n" +"use std::io::{self, Read};\n" "\n" -"fn add_to_counter(inc: u32) {\n" -" unsafe { COUNTER += inc; } // Potential data race!\n" +"#[derive(Debug)]\n" +"enum ReadUsernameError {\n" +" IoError(io::Error),\n" +" EmptyUsername(String),\n" "}\n" "\n" -"fn main() {\n" -" add_to_counter(42);\n" +"impl Error for ReadUsernameError {}\n" "\n" -" unsafe { println!(\"COUNTER: {COUNTER}\"); } // Potential data race!\n" +"impl Display for ReadUsernameError {\n" +" fn fmt(&self, f: &mut Formatter) -> fmt::Result {\n" +" match self {\n" +" Self::IoError(e) => write!(f, \"IO error: {e}\"),\n" +" Self::EmptyUsername(filename) => write!(f, \"Found no username " +"in {filename}\"),\n" +" }\n" +" }\n" "}\n" -"```" -msgstr "" - -#: src/unsafe/mutable-static-variables.md:32 -msgid "" -"Using a mutable static is generally a bad idea, but there are some cases " -"where it might make sense in low-level `no_std` code, such as implementing a " -"heap allocator or working with some C APIs." -msgstr "" - -#: src/unsafe/unions.md:3 -msgid "Unions are like enums, but you need to track the active field yourself:" -msgstr "" - -#: src/unsafe/unions.md:5 -msgid "" -"```rust,editable\n" -"#[repr(C)]\n" -"union MyUnion {\n" -" i: u8,\n" -" b: bool,\n" +"\n" +"impl From for ReadUsernameError {\n" +" fn from(err: io::Error) -> ReadUsernameError {\n" +" ReadUsernameError::IoError(err)\n" +" }\n" +"}\n" +"\n" +"fn read_username(path: &str) -> Result {\n" +" let mut username = String::with_capacity(100);\n" +" File::open(path)?.read_to_string(&mut username)?;\n" +" if username.is_empty() {\n" +" return Err(ReadUsernameError::EmptyUsername(String::from(path)));\n" +" }\n" +" Ok(username)\n" "}\n" "\n" "fn main() {\n" -" let u = MyUnion { i: 42 };\n" -" println!(\"int: {}\", unsafe { u.i });\n" -" println!(\"bool: {}\", unsafe { u.b }); // Undefined behavior!\n" +" //fs::write(\"config.dat\", \"\").unwrap();\n" +" let username = read_username(\"config.dat\");\n" +" println!(\"username or error: {username:?}\");\n" "}\n" "```" msgstr "" -#: src/unsafe/unions.md:21 +#: src/error-handling/converting-error-types-example.md:55 msgid "" -"Unions are very rarely needed in Rust as you can usually use an enum. They " -"are occasionally needed for interacting with C library APIs." +"It is good practice for all error types that don't need to be `no_std` to " +"implement `std::error::Error`, which requires `Debug` and `Display`. The " +"`Error` crate for `core` is only available in [nightly](https://github.com/" +"rust-lang/rust/issues/103765), so not fully `no_std` compatible yet." msgstr "" -#: src/unsafe/unions.md:24 +#: src/error-handling/converting-error-types-example.md:57 msgid "" -"If you just want to reinterpret bytes as a different type, you probably want " -"[`std::mem::transmute`](https://doc.rust-lang.org/stable/std/mem/fn." -"transmute.html) or a safe wrapper such as the [`zerocopy`](https://crates.io/" -"crates/zerocopy) crate." +"It's generally helpful for them to implement `Clone` and `Eq` too where " +"possible, to make life easier for tests and consumers of your library. In " +"this case we can't easily do so, because `io::Error` doesn't implement them." msgstr "" -#: src/unsafe/calling-unsafe-functions.md:3 +#: src/error-handling/deriving-error-enums.md:3 msgid "" -"A function or method can be marked `unsafe` if it has extra preconditions " -"you must uphold to avoid undefined behaviour:" +"The [thiserror](https://docs.rs/thiserror/) crate is a popular way to create " +"an error enum like we did on the previous page:" msgstr "" -#: src/unsafe/calling-unsafe-functions.md:6 +#: src/error-handling/deriving-error-enums.md:6 msgid "" -"```rust,editable\n" -"fn main() {\n" -" let emojis = \"🗻∈🌏\";\n" -"\n" -" // Safe because the indices are in the correct order, within the bounds " -"of\n" -" // the string slice, and lie on UTF-8 sequence boundaries.\n" -" unsafe {\n" -" println!(\"emoji: {}\", emojis.get_unchecked(0..4));\n" -" println!(\"emoji: {}\", emojis.get_unchecked(4..7));\n" -" println!(\"emoji: {}\", emojis.get_unchecked(7..11));\n" -" }\n" +"```rust,editable,compile_fail\n" +"use std::{fs, io};\n" +"use std::io::Read;\n" +"use thiserror::Error;\n" "\n" -" println!(\"char count: {}\", count_chars(unsafe { emojis." -"get_unchecked(0..7) }));\n" +"#[derive(Debug, Error)]\n" +"enum ReadUsernameError {\n" +" #[error(\"Could not read: {0}\")]\n" +" IoError(#[from] io::Error),\n" +" #[error(\"Found no username in {0}\")]\n" +" EmptyUsername(String),\n" +"}\n" "\n" -" // Not upholding the UTF-8 encoding requirement breaks memory safety!\n" -" // println!(\"emoji: {}\", unsafe { emojis.get_unchecked(0..3) });\n" -" // println!(\"char count: {}\", count_chars(unsafe { emojis." -"get_unchecked(0..3) }));\n" +"fn read_username(path: &str) -> Result {\n" +" let mut username = String::new();\n" +" fs::File::open(path)?.read_to_string(&mut username)?;\n" +" if username.is_empty() {\n" +" return Err(ReadUsernameError::EmptyUsername(String::from(path)));\n" +" }\n" +" Ok(username)\n" "}\n" "\n" -"fn count_chars(s: &str) -> usize {\n" -" s.chars().map(|_| 1).sum()\n" +"fn main() {\n" +" //fs::write(\"config.dat\", \"\").unwrap();\n" +" match read_username(\"config.dat\") {\n" +" Ok(username) => println!(\"Username: {username}\"),\n" +" Err(err) => println!(\"Error: {err}\"),\n" +" }\n" "}\n" "```" msgstr "" -#: src/unsafe/writing-unsafe-functions.md:3 +#: src/error-handling/deriving-error-enums.md:39 msgid "" -"You can mark your own functions as `unsafe` if they require particular " -"conditions to avoid undefined behaviour." +"`thiserror`'s derive macro automatically implements `std::error::Error`, and " +"optionally `Display` (if the `#[error(...)]` attributes are provided) and " +"`From` (if the `#[from]` attribute is added). It also works for structs." msgstr "" -#: src/unsafe/writing-unsafe-functions.md:6 +#: src/error-handling/deriving-error-enums.md:43 +msgid "It doesn't affect your public API, which makes it good for libraries." +msgstr "" + +#: src/error-handling/dynamic-errors.md:3 msgid "" -"```rust,editable\n" -"/// Swaps the values pointed to by the given pointers.\n" -"///\n" -"/// # Safety\n" -"///\n" -"/// The pointers must be valid and properly aligned.\n" -"unsafe fn swap(a: *mut u8, b: *mut u8) {\n" -" let temp = *a;\n" -" *a = *b;\n" -" *b = temp;\n" -"}\n" -"\n" -"fn main() {\n" -" let mut a = 42;\n" -" let mut b = 66;\n" +"Sometimes we want to allow any type of error to be returned without writing " +"our own enum covering all the different possibilities. `std::error::Error` " +"makes this easy." +msgstr "" + +#: src/error-handling/dynamic-errors.md:6 +msgid "" +"```rust,editable,compile_fail\n" +"use std::fs;\n" +"use std::io::Read;\n" +"use thiserror::Error;\n" +"use std::error::Error;\n" "\n" -" // Safe because ...\n" -" unsafe {\n" -" swap(&mut a, &mut b);\n" +"#[derive(Clone, Debug, Eq, Error, PartialEq)]\n" +"#[error(\"Found no username in {0}\")]\n" +"struct EmptyUsernameError(String);\n" +"\n" +"fn read_username(path: &str) -> Result> {\n" +" let mut username = String::new();\n" +" fs::File::open(path)?.read_to_string(&mut username)?;\n" +" if username.is_empty() {\n" +" return Err(EmptyUsernameError(String::from(path)).into());\n" " }\n" +" Ok(username)\n" +"}\n" "\n" -" println!(\"a = {}, b = {}\", a, b);\n" +"fn main() {\n" +" //fs::write(\"config.dat\", \"\").unwrap();\n" +" match read_username(\"config.dat\") {\n" +" Ok(username) => println!(\"Username: {username}\"),\n" +" Err(err) => println!(\"Error: {err}\"),\n" +" }\n" "}\n" "```" msgstr "" -#: src/unsafe/writing-unsafe-functions.md:33 -msgid "" -"We wouldn't actually use pointers for this because it can be done safely " -"with references." -msgstr "" - -#: src/unsafe/writing-unsafe-functions.md:35 +#: src/error-handling/dynamic-errors.md:36 msgid "" -"Note that unsafe code is allowed within an unsafe function without an " -"`unsafe` block. We can prohibit this with `#[deny(unsafe_op_in_unsafe_fn)]`. " -"Try adding it and see what happens." -msgstr "" - -#: src/unsafe/extern-functions.md:1 -msgid "Calling External Code" +"This saves on code, but gives up the ability to cleanly handle different " +"error cases differently in the program. As such it's generally not a good " +"idea to use `Box` in the public API of a library, but it can be a " +"good option in a program where you just want to display the error message " +"somewhere." msgstr "" -#: src/unsafe/extern-functions.md:3 +#: src/error-handling/error-contexts.md:3 msgid "" -"Functions from other languages might violate the guarantees of Rust. Calling " -"them is thus unsafe:" +"The widely used [anyhow](https://docs.rs/anyhow/) crate can help you add " +"contextual information to your errors and allows you to have fewer custom " +"error types:" msgstr "" -#: src/unsafe/extern-functions.md:6 +#: src/error-handling/error-contexts.md:7 msgid "" -"```rust,editable\n" -"extern \"C\" {\n" -" fn abs(input: i32) -> i32;\n" +"```rust,editable,compile_fail\n" +"use std::{fs, io};\n" +"use std::io::Read;\n" +"use anyhow::{Context, Result, bail};\n" +"\n" +"fn read_username(path: &str) -> Result {\n" +" let mut username = String::with_capacity(100);\n" +" fs::File::open(path)\n" +" .with_context(|| format!(\"Failed to open {path}\"))?\n" +" .read_to_string(&mut username)\n" +" .context(\"Failed to read\")?;\n" +" if username.is_empty() {\n" +" bail!(\"Found no username in {path}\");\n" +" }\n" +" Ok(username)\n" "}\n" "\n" "fn main() {\n" -" unsafe {\n" -" // Undefined behavior if abs misbehaves.\n" -" println!(\"Absolute value of -3 according to C: {}\", abs(-3));\n" +" //fs::write(\"config.dat\", \"\").unwrap();\n" +" match read_username(\"config.dat\") {\n" +" Ok(username) => println!(\"Username: {username}\"),\n" +" Err(err) => println!(\"Error: {err:?}\"),\n" " }\n" "}\n" "```" msgstr "" -#: src/unsafe/extern-functions.md:21 -msgid "" -"This is usually only a problem for extern functions which do things with " -"pointers which might violate Rust's memory model, but in general any C " -"function might have undefined behaviour under any arbitrary circumstances." +#: src/error-handling/error-contexts.md:35 +msgid "`anyhow::Result` is a type alias for `Result`." msgstr "" -#: src/unsafe/extern-functions.md:25 +#: src/error-handling/error-contexts.md:36 msgid "" -"The `\"C\"` in this example is the ABI; [other ABIs are available too]" -"(https://doc.rust-lang.org/reference/items/external-blocks.html)." +"`anyhow::Error` is essentially a wrapper around `Box`. As such " +"it's again generally not a good choice for the public API of a library, but " +"is widely used in applications." msgstr "" -#: src/unsafe/unsafe-traits.md:3 +#: src/error-handling/error-contexts.md:38 msgid "" -"Like with functions, you can mark a trait as `unsafe` if the implementation " -"must guarantee particular conditions to avoid undefined behaviour." +"Actual error type inside of it can be extracted for examination if necessary." msgstr "" -#: src/unsafe/unsafe-traits.md:6 +#: src/error-handling/error-contexts.md:39 msgid "" -"For example, the `zerocopy` crate has an unsafe trait that looks [something " -"like this](https://docs.rs/zerocopy/latest/zerocopy/trait.AsBytes.html):" +"Functionality provided by `anyhow::Result` may be familiar to Go " +"developers, as it provides similar usage patterns and ergonomics to `(T, " +"error)` from Go." msgstr "" -#: src/unsafe/unsafe-traits.md:9 +#: src/testing.md:3 +msgid "Rust and Cargo come with a simple unit test framework:" +msgstr "" + +#: src/testing.md:5 +msgid "Unit tests are supported throughout your code." +msgstr "" + +#: src/testing.md:7 +msgid "Integration tests are supported via the `tests/` directory." +msgstr "" + +#: src/testing/unit-tests.md:3 +msgid "Mark unit tests with `#[test]`:" +msgstr "" + +#: src/testing/unit-tests.md:5 msgid "" -"```rust,editable\n" -"use std::mem::size_of_val;\n" -"use std::slice;\n" -"\n" -"/// ...\n" -"/// # Safety\n" -"/// The type must have a defined representation and no padding.\n" -"pub unsafe trait AsBytes {\n" -" fn as_bytes(&self) -> &[u8] {\n" -" unsafe {\n" -" slice::from_raw_parts(self as *const Self as *const u8, " -"size_of_val(self))\n" -" }\n" +"```rust,editable,ignore\n" +"fn first_word(text: &str) -> &str {\n" +" match text.find(' ') {\n" +" Some(idx) => &text[..idx],\n" +" None => &text,\n" " }\n" "}\n" "\n" -"// Safe because u32 has a defined representation and no padding.\n" -"unsafe impl AsBytes for u32 {}\n" +"#[test]\n" +"fn test_empty() {\n" +" assert_eq!(first_word(\"\"), \"\");\n" +"}\n" +"\n" +"#[test]\n" +"fn test_single_word() {\n" +" assert_eq!(first_word(\"Hello\"), \"Hello\");\n" +"}\n" +"\n" +"#[test]\n" +"fn test_multiple_words() {\n" +" assert_eq!(first_word(\"Hello World\"), \"Hello\");\n" +"}\n" "```" msgstr "" -#: src/unsafe/unsafe-traits.md:30 +#: src/testing/unit-tests.md:29 +msgid "Use `cargo test` to find and run the unit tests." +msgstr "" + +#: src/testing/test-modules.md:3 msgid "" -"There should be a `# Safety` section on the Rustdoc for the trait explaining " -"the requirements for the trait to be safely implemented." +"Unit tests are often put in a nested module (run tests on the [Playground]" +"(https://play.rust-lang.org/)):" msgstr "" -#: src/unsafe/unsafe-traits.md:33 +#: src/testing/test-modules.md:6 msgid "" -"The actual safety section for `AsBytes` is rather longer and more " -"complicated." +"```rust,editable\n" +"fn helper(a: &str, b: &str) -> String {\n" +" format!(\"{a} {b}\")\n" +"}\n" +"\n" +"pub fn main() {\n" +" println!(\"{}\", helper(\"Hello\", \"World\"));\n" +"}\n" +"\n" +"#[cfg(test)]\n" +"mod tests {\n" +" use super::*;\n" +"\n" +" #[test]\n" +" fn test_helper() {\n" +" assert_eq!(helper(\"foo\", \"bar\"), \"foo bar\");\n" +" }\n" +"}\n" +"```" msgstr "" -#: src/unsafe/unsafe-traits.md:35 -msgid "The built-in `Send` and `Sync` traits are unsafe." +#: src/testing/test-modules.md:26 +msgid "This lets you unit test private helpers." msgstr "" -#: src/exercises/day-3/afternoon.md:1 -msgid "Day 3: Afternoon Exercises" +#: src/testing/test-modules.md:27 +msgid "The `#[cfg(test)]` attribute is only active when you run `cargo test`." msgstr "" -#: src/exercises/day-3/afternoon.md:3 -msgid "Let us build a safe wrapper for reading directory content!" +#: src/testing/doc-tests.md:3 +msgid "Rust has built-in support for documentation tests:" msgstr "" -#: src/exercises/day-3/afternoon.md:7 +#: src/testing/doc-tests.md:5 msgid "" -"After looking at the exercise, you can look at the [solution](solutions-" -"afternoon.md) provided." +"```rust\n" +"/// Shortens a string to the given length.\n" +"///\n" +"/// ```\n" +"/// use playground::shorten_string;\n" +"/// assert_eq!(shorten_string(\"Hello World\", 5), \"Hello\");\n" +"/// assert_eq!(shorten_string(\"Hello World\", 20), \"Hello World\");\n" +"/// ```\n" +"pub fn shorten_string(s: &str, length: usize) -> &str {\n" +" &s[..std::cmp::min(length, s.len())]\n" +"}\n" +"```" msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:3 -msgid "" -"Rust has great support for calling functions through a _foreign function " -"interface_ (FFI). We will use this to build a safe wrapper for the `libc` " -"functions you would use from C to read the filenames of a directory." +#: src/testing/doc-tests.md:18 +msgid "Code blocks in `///` comments are automatically seen as Rust code." msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:7 -msgid "You will want to consult the manual pages:" +#: src/testing/doc-tests.md:19 +msgid "The code will be compiled and executed as part of `cargo test`." msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:9 -msgid "[`opendir(3)`](https://man7.org/linux/man-pages/man3/opendir.3.html)" +#: src/testing/doc-tests.md:20 +msgid "" +"Test the above code on the [Rust Playground](https://play.rust-lang.org/?" +"version=stable&mode=debug&edition=2021&gist=3ce2ad13ea1302f6572cb15cd96becf0)." msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:10 -msgid "[`readdir(3)`](https://man7.org/linux/man-pages/man3/readdir.3.html)" +#: src/testing/integration-tests.md:3 +msgid "If you want to test your library as a client, use an integration test." msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:11 -msgid "[`closedir(3)`](https://man7.org/linux/man-pages/man3/closedir.3.html)" +#: src/testing/integration-tests.md:5 +msgid "Create a `.rs` file under `tests/`:" msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:13 +#: src/testing/integration-tests.md:7 msgid "" -"You will also want to browse the [`std::ffi`](https://doc.rust-lang.org/std/" -"ffi/) module. There you find a number of string types which you need for the " -"exercise:" +"```rust,ignore\n" +"use my_library::init;\n" +"\n" +"#[test]\n" +"fn test_init() {\n" +" assert!(init().is_ok());\n" +"}\n" +"```" msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:16 -msgid "Encoding" +#: src/testing/integration-tests.md:16 +msgid "These tests only have access to the public API of your crate." msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:16 -msgid "Use" +#: src/testing/useful-crates.md:1 +msgid "Useful crates for writing tests" msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:18 -msgid "" -"[`str`](https://doc.rust-lang.org/std/primitive.str.html) and [`String`]" -"(https://doc.rust-lang.org/std/string/struct.String.html)" +#: src/testing/useful-crates.md:3 +msgid "Rust comes with only basic support for writing tests." msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:18 -msgid "UTF-8" +#: src/testing/useful-crates.md:5 +msgid "Here are some additional crates which we recommend for writing tests:" msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:18 -msgid "Text processing in Rust" +#: src/testing/useful-crates.md:7 +msgid "" +"[googletest](https://docs.rs/googletest): Comprehensive test assertion " +"library in the tradition of GoogleTest for C++." msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:19 +#: src/testing/useful-crates.md:8 +msgid "[proptest](https://docs.rs/proptest): Property-based testing for Rust." +msgstr "" + +#: src/testing/useful-crates.md:9 msgid "" -"[`CStr`](https://doc.rust-lang.org/std/ffi/struct.CStr.html) and [`CString`]" -"(https://doc.rust-lang.org/std/ffi/struct.CString.html)" +"[rstest](https://docs.rs/rstest): Support for fixtures and parameterised " +"tests." msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:19 -msgid "NUL-terminated" +#: src/unsafe.md:3 +msgid "The Rust language has two parts:" msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:19 -msgid "Communicating with C functions" +#: src/unsafe.md:5 +msgid "**Safe Rust:** memory safe, no undefined behavior possible." msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:20 +#: src/unsafe.md:6 msgid "" -"[`OsStr`](https://doc.rust-lang.org/std/ffi/struct.OsStr.html) and " -"[`OsString`](https://doc.rust-lang.org/std/ffi/struct.OsString.html)" +"**Unsafe Rust:** can trigger undefined behavior if preconditions are " +"violated." msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:20 -msgid "OS-specific" +#: src/unsafe.md:8 +msgid "" +"We will be seeing mostly safe Rust in this course, but it's important to " +"know what Unsafe Rust is." msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:20 -msgid "Communicating with the OS" +#: src/unsafe.md:11 +msgid "" +"Unsafe code is usually small and isolated, and its correctness should be " +"carefully documented. It is usually wrapped in a safe abstraction layer." msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:22 -msgid "You will convert between all these types:" +#: src/unsafe.md:14 +msgid "Unsafe Rust gives you access to five new capabilities:" msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:24 -msgid "" -"`&str` to `CString`: you need to allocate space for a trailing `\\0` " -"character," +#: src/unsafe.md:16 +msgid "Dereference raw pointers." msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:25 -msgid "`CString` to `*const i8`: you need a pointer to call C functions," +#: src/unsafe.md:17 +msgid "Access or modify mutable static variables." msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:26 -msgid "" -"`*const i8` to `&CStr`: you need something which can find the trailing `\\0` " -"character," +#: src/unsafe.md:18 +msgid "Access `union` fields." msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:27 -msgid "" -"`&CStr` to `&[u8]`: a slice of bytes is the universal interface for \"some " -"unknow data\"," +#: src/unsafe.md:19 +msgid "Call `unsafe` functions, including `extern` functions." msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:28 -msgid "" -"`&[u8]` to `&OsStr`: `&OsStr` is a step towards `OsString`, use [`OsStrExt`]" -"(https://doc.rust-lang.org/std/os/unix/ffi/trait.OsStrExt.html) to create it," +#: src/unsafe.md:20 +msgid "Implement `unsafe` traits." msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:31 +#: src/unsafe.md:22 msgid "" -"`&OsStr` to `OsString`: you need to clone the data in `&OsStr` to be able to " -"return it and call `readdir` again." +"We will briefly cover unsafe capabilities next. For full details, please see " +"[Chapter 19.1 in the Rust Book](https://doc.rust-lang.org/book/ch19-01-" +"unsafe-rust.html) and the [Rustonomicon](https://doc.rust-lang.org/nomicon/)." msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:34 +#: src/unsafe.md:28 msgid "" -"The [Nomicon](https://doc.rust-lang.org/nomicon/ffi.html) also has a very " -"useful chapter about FFI." +"Unsafe Rust does not mean the code is incorrect. It means that developers " +"have turned off the compiler safety features and have to write correct code " +"by themselves. It means the compiler no longer enforces Rust's memory-safety " +"rules." msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:45 -msgid "" -"Copy the code below to and fill in the missing " -"functions and methods:" +#: src/unsafe/raw-pointers.md:3 +msgid "Creating pointers is safe, but dereferencing them requires `unsafe`:" msgstr "" -#: src/exercises/day-3/safe-ffi-wrapper.md:48 +#: src/unsafe/raw-pointers.md:5 msgid "" -"```rust,should_panic\n" -"// TODO: remove this when you're done with your implementation.\n" -"#![allow(unused_imports, unused_variables, dead_code)]\n" -"\n" -"mod ffi {\n" -" use std::os::raw::{c_char, c_int};\n" -" #[cfg(not(target_os = \"macos\"))]\n" -" use std::os::raw::{c_long, c_ulong, c_ushort};\n" -"\n" -" // Opaque type. See https://doc.rust-lang.org/nomicon/ffi.html.\n" -" #[repr(C)]\n" -" pub struct DIR {\n" -" _data: [u8; 0],\n" -" _marker: core::marker::PhantomData<(*mut u8, core::marker::" -"PhantomPinned)>,\n" -" }\n" -"\n" -" // Layout as per readdir(3) and definitions in /usr/include/x86_64-linux-" -"gnu.\n" -" #[cfg(not(target_os = \"macos\"))]\n" -" #[repr(C)]\n" -" pub struct dirent {\n" -" pub d_ino: c_long,\n" -" pub d_off: c_ulong,\n" -" pub d_reclen: c_ushort,\n" -" pub d_type: c_char,\n" -" pub d_name: [c_char; 256],\n" -" }\n" -"\n" -" // Layout as per man entry for dirent\n" -" #[cfg(target_os = \"macos\")]\n" -" #[repr(C)]\n" -" pub struct dirent {\n" -" pub d_ino: u64,\n" -" pub d_seekoff: u64,\n" -" pub d_reclen: u16,\n" -" pub d_namlen: u16,\n" -" pub d_type: u8,\n" -" pub d_name: [c_char; 1024],\n" -" }\n" -"\n" -" extern \"C\" {\n" -" pub fn opendir(s: *const c_char) -> *mut DIR;\n" -" pub fn readdir(s: *mut DIR) -> *const dirent;\n" -" pub fn closedir(s: *mut DIR) -> c_int;\n" -" }\n" -"}\n" -"\n" -"use std::ffi::{CStr, CString, OsStr, OsString};\n" -"use std::os::unix::ffi::OsStrExt;\n" -"\n" -"#[derive(Debug)]\n" -"struct DirectoryIterator {\n" -" path: CString,\n" -" dir: *mut ffi::DIR,\n" -"}\n" -"\n" -"impl DirectoryIterator {\n" -" fn new(path: &str) -> Result {\n" -" // Call opendir and return a Ok value if that worked,\n" -" // otherwise return Err with a message.\n" -" unimplemented!()\n" -" }\n" -"}\n" +"```rust,editable\n" +"fn main() {\n" +" let mut num = 5;\n" "\n" -"impl Iterator for DirectoryIterator {\n" -" type Item = OsString;\n" -" fn next(&mut self) -> Option {\n" -" // Keep calling readdir until we get a NULL pointer back.\n" -" unimplemented!()\n" -" }\n" -"}\n" +" let r1 = &mut num as *mut i32;\n" +" let r2 = r1 as *const i32;\n" "\n" -"impl Drop for DirectoryIterator {\n" -" fn drop(&mut self) {\n" -" // Call closedir as needed.\n" -" unimplemented!()\n" +" // Safe because r1 and r2 were obtained from references and so are\n" +" // guaranteed to be non-null and properly aligned, the objects " +"underlying\n" +" // the references from which they were obtained are live throughout the\n" +" // whole unsafe block, and they are not accessed either through the\n" +" // references or concurrently through any other pointers.\n" +" unsafe {\n" +" println!(\"r1 is: {}\", *r1);\n" +" *r1 = 10;\n" +" println!(\"r2 is: {}\", *r2);\n" " }\n" "}\n" -"\n" -"fn main() -> Result<(), String> {\n" -" let iter = DirectoryIterator::new(\".\")?;\n" -" println!(\"files: {:#?}\", iter.collect::>());\n" -" Ok(())\n" -"}\n" "```" msgstr "" -#: src/android.md:1 -msgid "Welcome to Rust in Android" -msgstr "" - -#: src/android.md:3 +#: src/unsafe/raw-pointers.md:27 msgid "" -"Rust is supported for native platform development on Android. This means " -"that you can write new operating system services in Rust, as well as " -"extending existing services." +"It is good practice (and required by the Android Rust style guide) to write " +"a comment for each `unsafe` block explaining how the code inside it " +"satisfies the safety requirements of the unsafe operations it is doing." msgstr "" -#: src/android.md:7 +#: src/unsafe/raw-pointers.md:31 msgid "" -"We will attempt to call Rust from one of your own projects today. So try to " -"find a little corner of your code base where we can move some lines of code " -"to Rust. The fewer dependencies and \"exotic\" types the better. Something " -"that parses some raw bytes would be ideal." +"In the case of pointer dereferences, this means that the pointers must be " +"[_valid_](https://doc.rust-lang.org/std/ptr/index.html#safety), i.e.:" msgstr "" -#: src/android/setup.md:3 -msgid "" -"We will be using an Android Virtual Device to test our code. Make sure you " -"have access to one or create a new one with:" +#: src/unsafe/raw-pointers.md:34 +msgid "The pointer must be non-null." msgstr "" -#: src/android/setup.md:6 +#: src/unsafe/raw-pointers.md:35 msgid "" -"```shell\n" -"$ source build/envsetup.sh\n" -"$ lunch aosp_cf_x86_64_phone-userdebug\n" -"$ acloud create\n" -"```" +"The pointer must be _dereferenceable_ (within the bounds of a single " +"allocated object)." msgstr "" -#: src/android/setup.md:12 -msgid "" -"Please see the [Android Developer Codelab](https://source.android.com/docs/" -"setup/start) for details." +#: src/unsafe/raw-pointers.md:36 +msgid "The object must not have been deallocated." msgstr "" -#: src/android/build-rules.md:3 -msgid "The Android build system (Soong) supports Rust via a number of modules:" +#: src/unsafe/raw-pointers.md:37 +msgid "There must not be concurrent accesses to the same location." msgstr "" -#: src/android/build-rules.md:5 -msgid "Module Type" -msgstr "" - -#: src/android/build-rules.md:5 -msgid "Description" -msgstr "" - -#: src/android/build-rules.md:7 -msgid "`rust_binary`" -msgstr "" - -#: src/android/build-rules.md:7 -msgid "Produces a Rust binary." -msgstr "" - -#: src/android/build-rules.md:8 -msgid "`rust_library`" +#: src/unsafe/raw-pointers.md:38 +msgid "" +"If the pointer was obtained by casting a reference, the underlying object " +"must be live and no reference may be used to access the memory." msgstr "" -#: src/android/build-rules.md:8 -msgid "Produces a Rust library, and provides both `rlib` and `dylib` variants." +#: src/unsafe/raw-pointers.md:41 +msgid "In most cases the pointer must also be properly aligned." msgstr "" -#: src/android/build-rules.md:9 -msgid "`rust_ffi`" +#: src/unsafe/mutable-static-variables.md:3 +msgid "It is safe to read an immutable static variable:" msgstr "" -#: src/android/build-rules.md:9 +#: src/unsafe/mutable-static-variables.md:5 msgid "" -"Produces a Rust C library usable by `cc` modules, and provides both static " -"and shared variants." +"```rust,editable\n" +"static HELLO_WORLD: &str = \"Hello, world!\";\n" +"\n" +"fn main() {\n" +" println!(\"HELLO_WORLD: {HELLO_WORLD}\");\n" +"}\n" +"```" msgstr "" -#: src/android/build-rules.md:10 -msgid "`rust_proc_macro`" +#: src/unsafe/mutable-static-variables.md:13 +msgid "" +"However, since data races can occur, it is unsafe to read and write mutable " +"static variables:" msgstr "" -#: src/android/build-rules.md:10 +#: src/unsafe/mutable-static-variables.md:16 msgid "" -"Produces a `proc-macro` Rust library. These are analogous to compiler " -"plugins." +"```rust,editable\n" +"static mut COUNTER: u32 = 0;\n" +"\n" +"fn add_to_counter(inc: u32) {\n" +" unsafe { COUNTER += inc; } // Potential data race!\n" +"}\n" +"\n" +"fn main() {\n" +" add_to_counter(42);\n" +"\n" +" unsafe { println!(\"COUNTER: {COUNTER}\"); } // Potential data race!\n" +"}\n" +"```" msgstr "" -#: src/android/build-rules.md:11 -msgid "`rust_test`" +#: src/unsafe/mutable-static-variables.md:32 +msgid "" +"Using a mutable static is generally a bad idea, but there are some cases " +"where it might make sense in low-level `no_std` code, such as implementing a " +"heap allocator or working with some C APIs." msgstr "" -#: src/android/build-rules.md:11 -msgid "Produces a Rust test binary that uses the standard Rust test harness." +#: src/unsafe/unions.md:3 +msgid "Unions are like enums, but you need to track the active field yourself:" msgstr "" -#: src/android/build-rules.md:12 -msgid "`rust_fuzz`" +#: src/unsafe/unions.md:5 +msgid "" +"```rust,editable\n" +"#[repr(C)]\n" +"union MyUnion {\n" +" i: u8,\n" +" b: bool,\n" +"}\n" +"\n" +"fn main() {\n" +" let u = MyUnion { i: 42 };\n" +" println!(\"int: {}\", unsafe { u.i });\n" +" println!(\"bool: {}\", unsafe { u.b }); // Undefined behavior!\n" +"}\n" +"```" msgstr "" -#: src/android/build-rules.md:12 -msgid "Produces a Rust fuzz binary leveraging `libfuzzer`." +#: src/unsafe/unions.md:21 +msgid "" +"Unions are very rarely needed in Rust as you can usually use an enum. They " +"are occasionally needed for interacting with C library APIs." msgstr "" -#: src/android/build-rules.md:13 -msgid "`rust_protobuf`" +#: src/unsafe/unions.md:24 +msgid "" +"If you just want to reinterpret bytes as a different type, you probably want " +"[`std::mem::transmute`](https://doc.rust-lang.org/stable/std/mem/fn." +"transmute.html) or a safe wrapper such as the [`zerocopy`](https://crates.io/" +"crates/zerocopy) crate." msgstr "" -#: src/android/build-rules.md:13 +#: src/unsafe/calling-unsafe-functions.md:3 msgid "" -"Generates source and produces a Rust library that provides an interface for " -"a particular protobuf." +"A function or method can be marked `unsafe` if it has extra preconditions " +"you must uphold to avoid undefined behaviour:" msgstr "" -#: src/android/build-rules.md:14 -msgid "`rust_bindgen`" +#: src/unsafe/calling-unsafe-functions.md:6 +msgid "" +"```rust,editable\n" +"fn main() {\n" +" let emojis = \"🗻∈🌏\";\n" +"\n" +" // Safe because the indices are in the correct order, within the bounds " +"of\n" +" // the string slice, and lie on UTF-8 sequence boundaries.\n" +" unsafe {\n" +" println!(\"emoji: {}\", emojis.get_unchecked(0..4));\n" +" println!(\"emoji: {}\", emojis.get_unchecked(4..7));\n" +" println!(\"emoji: {}\", emojis.get_unchecked(7..11));\n" +" }\n" +"\n" +" println!(\"char count: {}\", count_chars(unsafe { emojis." +"get_unchecked(0..7) }));\n" +"\n" +" // Not upholding the UTF-8 encoding requirement breaks memory safety!\n" +" // println!(\"emoji: {}\", unsafe { emojis.get_unchecked(0..3) });\n" +" // println!(\"char count: {}\", count_chars(unsafe { emojis." +"get_unchecked(0..3) }));\n" +"}\n" +"\n" +"fn count_chars(s: &str) -> usize {\n" +" s.chars().map(|_| 1).sum()\n" +"}\n" +"```" msgstr "" -#: src/android/build-rules.md:14 +#: src/unsafe/writing-unsafe-functions.md:3 msgid "" -"Generates source and produces a Rust library containing Rust bindings to C " -"libraries." +"You can mark your own functions as `unsafe` if they require particular " +"conditions to avoid undefined behaviour." msgstr "" -#: src/android/build-rules.md:16 -msgid "We will look at `rust_binary` and `rust_library` next." +#: src/unsafe/writing-unsafe-functions.md:6 +msgid "" +"```rust,editable\n" +"/// Swaps the values pointed to by the given pointers.\n" +"///\n" +"/// # Safety\n" +"///\n" +"/// The pointers must be valid and properly aligned.\n" +"unsafe fn swap(a: *mut u8, b: *mut u8) {\n" +" let temp = *a;\n" +" *a = *b;\n" +" *b = temp;\n" +"}\n" +"\n" +"fn main() {\n" +" let mut a = 42;\n" +" let mut b = 66;\n" +"\n" +" // Safe because ...\n" +" unsafe {\n" +" swap(&mut a, &mut b);\n" +" }\n" +"\n" +" println!(\"a = {}, b = {}\", a, b);\n" +"}\n" +"```" msgstr "" -#: src/android/build-rules/binary.md:1 -msgid "Rust Binaries" +#: src/unsafe/writing-unsafe-functions.md:33 +msgid "" +"We wouldn't actually use pointers for this because it can be done safely " +"with references." msgstr "" -#: src/android/build-rules/binary.md:3 +#: src/unsafe/writing-unsafe-functions.md:35 msgid "" -"Let us start with a simple application. At the root of an AOSP checkout, " -"create the following files:" +"Note that unsafe code is allowed within an unsafe function without an " +"`unsafe` block. We can prohibit this with `#[deny(unsafe_op_in_unsafe_fn)]`. " +"Try adding it and see what happens." msgstr "" -#: src/android/build-rules/binary.md:6 src/android/build-rules/library.md:13 -msgid "_hello_rust/Android.bp_:" +#: src/unsafe/extern-functions.md:1 +msgid "Calling External Code" msgstr "" -#: src/android/build-rules/binary.md:8 +#: src/unsafe/extern-functions.md:3 msgid "" -"```javascript\n" -"rust_binary {\n" -" name: \"hello_rust\",\n" -" crate_name: \"hello_rust\",\n" -" srcs: [\"src/main.rs\"],\n" -"}\n" -"```" -msgstr "" - -#: src/android/build-rules/binary.md:16 src/android/build-rules/library.md:34 -msgid "_hello_rust/src/main.rs_:" +"Functions from other languages might violate the guarantees of Rust. Calling " +"them is thus unsafe:" msgstr "" -#: src/android/build-rules/binary.md:18 +#: src/unsafe/extern-functions.md:6 msgid "" -"```rust\n" -"//! Rust demo.\n" +"```rust,editable\n" +"extern \"C\" {\n" +" fn abs(input: i32) -> i32;\n" +"}\n" "\n" -"/// Prints a greeting to standard output.\n" "fn main() {\n" -" println!(\"Hello from Rust!\");\n" +" unsafe {\n" +" // Undefined behavior if abs misbehaves.\n" +" println!(\"Absolute value of -3 according to C: {}\", abs(-3));\n" +" }\n" "}\n" "```" msgstr "" -#: src/android/build-rules/binary.md:27 -msgid "You can now build, push, and run the binary:" -msgstr "" - -#: src/android/build-rules/binary.md:29 +#: src/unsafe/extern-functions.md:21 msgid "" -"```shell\n" -"$ m hello_rust\n" -"$ adb push \"$ANDROID_PRODUCT_OUT/system/bin/hello_rust /data/local/tmp\"\n" -"$ adb shell /data/local/tmp/hello_rust\n" -"Hello from Rust!\n" -"```" -msgstr "" - -#: src/android/build-rules/library.md:1 -msgid "Rust Libraries" +"This is usually only a problem for extern functions which do things with " +"pointers which might violate Rust's memory model, but in general any C " +"function might have undefined behaviour under any arbitrary circumstances." msgstr "" -#: src/android/build-rules/library.md:3 -msgid "You use `rust_library` to create a new Rust library for Android." +#: src/unsafe/extern-functions.md:25 +msgid "" +"The `\"C\"` in this example is the ABI; [other ABIs are available too]" +"(https://doc.rust-lang.org/reference/items/external-blocks.html)." msgstr "" -#: src/android/build-rules/library.md:5 -msgid "Here we declare a dependency on two libraries:" +#: src/unsafe/unsafe-traits.md:3 +msgid "" +"Like with functions, you can mark a trait as `unsafe` if the implementation " +"must guarantee particular conditions to avoid undefined behaviour." msgstr "" -#: src/android/build-rules/library.md:7 -msgid "`libgreeting`, which we define below," +#: src/unsafe/unsafe-traits.md:6 +msgid "" +"For example, the `zerocopy` crate has an unsafe trait that looks [something " +"like this](https://docs.rs/zerocopy/latest/zerocopy/trait.AsBytes.html):" msgstr "" -#: src/android/build-rules/library.md:8 +#: src/unsafe/unsafe-traits.md:9 msgid "" -"`libtextwrap`, which is a crate already vendored in [`external/rust/crates/`]" -"(https://cs.android.com/android/platform/superproject/+/master:external/rust/" -"crates/)." -msgstr "" - -#: src/android/build-rules/library.md:15 -msgid "" -"```javascript\n" -"rust_binary {\n" -" name: \"hello_rust_with_dep\",\n" -" crate_name: \"hello_rust_with_dep\",\n" -" srcs: [\"src/main.rs\"],\n" -" rustlibs: [\n" -" \"libgreetings\",\n" -" \"libtextwrap\",\n" -" ],\n" -" prefer_rlib: true,\n" -"}\n" +"```rust,editable\n" +"use std::mem::size_of_val;\n" +"use std::slice;\n" "\n" -"rust_library {\n" -" name: \"libgreetings\",\n" -" crate_name: \"greetings\",\n" -" srcs: [\"src/lib.rs\"],\n" +"/// ...\n" +"/// # Safety\n" +"/// The type must have a defined representation and no padding.\n" +"pub unsafe trait AsBytes {\n" +" fn as_bytes(&self) -> &[u8] {\n" +" unsafe {\n" +" slice::from_raw_parts(self as *const Self as *const u8, " +"size_of_val(self))\n" +" }\n" +" }\n" "}\n" +"\n" +"// Safe because u32 has a defined representation and no padding.\n" +"unsafe impl AsBytes for u32 {}\n" "```" msgstr "" -#: src/android/build-rules/library.md:36 +#: src/unsafe/unsafe-traits.md:30 msgid "" -"```rust,ignore\n" -"//! Rust demo.\n" -"\n" -"use greetings::greeting;\n" -"use textwrap::fill;\n" -"\n" -"/// Prints a greeting to standard output.\n" -"fn main() {\n" -" println!(\"{}\", fill(&greeting(\"Bob\"), 24));\n" -"}\n" -"```" +"There should be a `# Safety` section on the Rustdoc for the trait explaining " +"the requirements for the trait to be safely implemented." msgstr "" -#: src/android/build-rules/library.md:48 -msgid "_hello_rust/src/lib.rs_:" +#: src/unsafe/unsafe-traits.md:33 +msgid "" +"The actual safety section for `AsBytes` is rather longer and more " +"complicated." msgstr "" -#: src/android/build-rules/library.md:50 +#: src/unsafe/unsafe-traits.md:35 +msgid "The built-in `Send` and `Sync` traits are unsafe." +msgstr "" + +#: src/exercises/day-3/afternoon.md:1 +msgid "Day 3: Afternoon Exercises" +msgstr "" + +#: src/exercises/day-3/afternoon.md:3 +msgid "Let us build a safe wrapper for reading directory content!" +msgstr "" + +#: src/exercises/day-3/afternoon.md:5 msgid "" -"```rust,ignore\n" -"//! Greeting library.\n" -"\n" -"/// Greet `name`.\n" -"pub fn greeting(name: &str) -> String {\n" -" format!(\"Hello {name}, it is very nice to meet you!\")\n" -"}\n" -"```" +"For this exercise, we suggest using a local dev environment instead of the " +"Playground. This will allow you to run your binary on your own machine." msgstr "" -#: src/android/build-rules/library.md:59 -msgid "You build, push, and run the binary like before:" +#: src/exercises/day-3/afternoon.md:8 +msgid "" +"To get started, follow the [running locally](../../cargo/running-locally.md) " +"instructions." msgstr "" -#: src/android/build-rules/library.md:61 +#: src/exercises/day-3/afternoon.md:14 msgid "" -"```shell\n" -"$ m hello_rust_with_dep\n" -"$ adb push \"$ANDROID_PRODUCT_OUT/system/bin/hello_rust_with_dep /data/local/" -"tmp\"\n" -"$ adb shell /data/local/tmp/hello_rust_with_dep\n" -"Hello Bob, it is very\n" -"nice to meet you!\n" -"```" +"After looking at the exercise, you can look at the [solution](solutions-" +"afternoon.md) provided." msgstr "" -#: src/android/aidl.md:3 +#: src/exercises/day-3/safe-ffi-wrapper.md:3 msgid "" -"The [Android Interface Definition Language (AIDL)](https://developer.android." -"com/guide/components/aidl) is supported in Rust:" +"Rust has great support for calling functions through a _foreign function " +"interface_ (FFI). We will use this to build a safe wrapper for the `libc` " +"functions you would use from C to read the filenames of a directory." msgstr "" -#: src/android/aidl.md:6 -msgid "Rust code can call existing AIDL servers," +#: src/exercises/day-3/safe-ffi-wrapper.md:7 +msgid "You will want to consult the manual pages:" msgstr "" -#: src/android/aidl.md:7 -msgid "You can create new AIDL servers in Rust." +#: src/exercises/day-3/safe-ffi-wrapper.md:9 +msgid "[`opendir(3)`](https://man7.org/linux/man-pages/man3/opendir.3.html)" msgstr "" -#: src/android/aidl/interface.md:1 -msgid "AIDL Interfaces" +#: src/exercises/day-3/safe-ffi-wrapper.md:10 +msgid "[`readdir(3)`](https://man7.org/linux/man-pages/man3/readdir.3.html)" msgstr "" -#: src/android/aidl/interface.md:3 -msgid "You declare the API of your service using an AIDL interface:" +#: src/exercises/day-3/safe-ffi-wrapper.md:11 +msgid "[`closedir(3)`](https://man7.org/linux/man-pages/man3/closedir.3.html)" msgstr "" -#: src/android/aidl/interface.md:5 +#: src/exercises/day-3/safe-ffi-wrapper.md:13 msgid "" -"_birthday_service/aidl/com/example/birthdayservice/IBirthdayService.aidl_:" +"You will also want to browse the [`std::ffi`](https://doc.rust-lang.org/std/" +"ffi/) module. There you find a number of string types which you need for the " +"exercise:" msgstr "" -#: src/android/aidl/interface.md:7 +#: src/exercises/day-3/safe-ffi-wrapper.md:16 +msgid "Encoding" +msgstr "" + +#: src/exercises/day-3/safe-ffi-wrapper.md:16 +msgid "Use" +msgstr "" + +#: src/exercises/day-3/safe-ffi-wrapper.md:18 msgid "" -"```java\n" -"package com.example.birthdayservice;\n" -"\n" -"/** Birthday service interface. */\n" -"interface IBirthdayService {\n" -" /** Generate a Happy Birthday message. */\n" -" String wishHappyBirthday(String name, int years);\n" -"}\n" -"```" +"[`str`](https://doc.rust-lang.org/std/primitive.str.html) and [`String`]" +"(https://doc.rust-lang.org/std/string/struct.String.html)" msgstr "" -#: src/android/aidl/interface.md:17 -msgid "_birthday_service/aidl/Android.bp_:" +#: src/exercises/day-3/safe-ffi-wrapper.md:18 +msgid "UTF-8" msgstr "" -#: src/android/aidl/interface.md:19 +#: src/exercises/day-3/safe-ffi-wrapper.md:18 +msgid "Text processing in Rust" +msgstr "" + +#: src/exercises/day-3/safe-ffi-wrapper.md:19 msgid "" -"```javascript\n" -"aidl_interface {\n" -" name: \"com.example.birthdayservice\",\n" -" srcs: [\"com/example/birthdayservice/*.aidl\"],\n" -" unstable: true,\n" -" backend: {\n" -" rust: { // Rust is not enabled by default\n" -" enabled: true,\n" -" },\n" -" },\n" -"}\n" -"```" +"[`CStr`](https://doc.rust-lang.org/std/ffi/struct.CStr.html) and [`CString`]" +"(https://doc.rust-lang.org/std/ffi/struct.CString.html)" msgstr "" -#: src/android/aidl/interface.md:32 +#: src/exercises/day-3/safe-ffi-wrapper.md:19 +msgid "NUL-terminated" +msgstr "" + +#: src/exercises/day-3/safe-ffi-wrapper.md:19 +msgid "Communicating with C functions" +msgstr "" + +#: src/exercises/day-3/safe-ffi-wrapper.md:20 msgid "" -"Add `vendor_available: true` if your AIDL file is used by a binary in the " -"vendor partition." +"[`OsStr`](https://doc.rust-lang.org/std/ffi/struct.OsStr.html) and " +"[`OsString`](https://doc.rust-lang.org/std/ffi/struct.OsString.html)" msgstr "" -#: src/android/aidl/implementation.md:1 -msgid "Service Implementation" +#: src/exercises/day-3/safe-ffi-wrapper.md:20 +msgid "OS-specific" msgstr "" -#: src/android/aidl/implementation.md:3 -msgid "We can now implement the AIDL service:" +#: src/exercises/day-3/safe-ffi-wrapper.md:20 +msgid "Communicating with the OS" msgstr "" -#: src/android/aidl/implementation.md:5 -msgid "_birthday_service/src/lib.rs_:" +#: src/exercises/day-3/safe-ffi-wrapper.md:22 +msgid "You will convert between all these types:" msgstr "" -#: src/android/aidl/implementation.md:7 +#: src/exercises/day-3/safe-ffi-wrapper.md:24 msgid "" -"```rust,ignore\n" -"//! Implementation of the `IBirthdayService` AIDL interface.\n" -"use com_example_birthdayservice::aidl::com::example::birthdayservice::" -"IBirthdayService::IBirthdayService;\n" -"use com_example_birthdayservice::binder;\n" -"\n" -"/// The `IBirthdayService` implementation.\n" -"pub struct BirthdayService;\n" -"\n" -"impl binder::Interface for BirthdayService {}\n" -"\n" -"impl IBirthdayService for BirthdayService {\n" -" fn wishHappyBirthday(&self, name: &str, years: i32) -> binder::" -"Result {\n" -" Ok(format!(\n" -" \"Happy Birthday {name}, congratulations with the {years} years!" -"\"\n" -" ))\n" -" }\n" -"}\n" -"```" +"`&str` to `CString`: you need to allocate space for a trailing `\\0` " +"character," msgstr "" -#: src/android/aidl/implementation.md:26 src/android/aidl/server.md:28 -#: src/android/aidl/client.md:37 -msgid "_birthday_service/Android.bp_:" +#: src/exercises/day-3/safe-ffi-wrapper.md:25 +msgid "`CString` to `*const i8`: you need a pointer to call C functions," msgstr "" -#: src/android/aidl/implementation.md:28 +#: src/exercises/day-3/safe-ffi-wrapper.md:26 msgid "" -"```javascript\n" -"rust_library {\n" -" name: \"libbirthdayservice\",\n" -" srcs: [\"src/lib.rs\"],\n" -" crate_name: \"birthdayservice\",\n" -" rustlibs: [\n" -" \"com.example.birthdayservice-rust\",\n" -" \"libbinder_rs\",\n" -" ],\n" -"}\n" -"```" +"`*const i8` to `&CStr`: you need something which can find the trailing `\\0` " +"character," msgstr "" -#: src/android/aidl/server.md:1 -msgid "AIDL Server" +#: src/exercises/day-3/safe-ffi-wrapper.md:27 +msgid "" +"`&CStr` to `&[u8]`: a slice of bytes is the universal interface for \"some " +"unknow data\"," msgstr "" -#: src/android/aidl/server.md:3 -msgid "Finally, we can create a server which exposes the service:" +#: src/exercises/day-3/safe-ffi-wrapper.md:28 +msgid "" +"`&[u8]` to `&OsStr`: `&OsStr` is a step towards `OsString`, use [`OsStrExt`]" +"(https://doc.rust-lang.org/std/os/unix/ffi/trait.OsStrExt.html) to create it," msgstr "" -#: src/android/aidl/server.md:5 -msgid "_birthday_service/src/server.rs_:" +#: src/exercises/day-3/safe-ffi-wrapper.md:31 +msgid "" +"`&OsStr` to `OsString`: you need to clone the data in `&OsStr` to be able to " +"return it and call `readdir` again." msgstr "" -#: src/android/aidl/server.md:7 +#: src/exercises/day-3/safe-ffi-wrapper.md:34 msgid "" -"```rust,ignore\n" -"//! Birthday service.\n" -"use birthdayservice::BirthdayService;\n" -"use com_example_birthdayservice::aidl::com::example::birthdayservice::" -"IBirthdayService::BnBirthdayService;\n" -"use com_example_birthdayservice::binder;\n" +"The [Nomicon](https://doc.rust-lang.org/nomicon/ffi.html) also has a very " +"useful chapter about FFI." +msgstr "" + +#: src/exercises/day-3/safe-ffi-wrapper.md:45 +msgid "" +"Copy the code below to and fill in the missing " +"functions and methods:" +msgstr "" + +#: src/exercises/day-3/safe-ffi-wrapper.md:48 +msgid "" +"```rust,should_panic\n" +"// TODO: remove this when you're done with your implementation.\n" +"#![allow(unused_imports, unused_variables, dead_code)]\n" "\n" -"const SERVICE_IDENTIFIER: &str = \"birthdayservice\";\n" +"mod ffi {\n" +" use std::os::raw::{c_char, c_int};\n" +" #[cfg(not(target_os = \"macos\"))]\n" +" use std::os::raw::{c_long, c_ulong, c_ushort, c_uchar};\n" "\n" -"/// Entry point for birthday service.\n" -"fn main() {\n" -" let birthday_service = BirthdayService;\n" -" let birthday_service_binder = BnBirthdayService::new_binder(\n" -" birthday_service,\n" -" binder::BinderFeatures::default(),\n" -" );\n" -" binder::add_service(SERVICE_IDENTIFIER, birthday_service_binder." -"as_binder())\n" -" .expect(\"Failed to register service\");\n" -" binder::ProcessState::join_thread_pool()\n" +" // Opaque type. See https://doc.rust-lang.org/nomicon/ffi.html.\n" +" #[repr(C)]\n" +" pub struct DIR {\n" +" _data: [u8; 0],\n" +" _marker: core::marker::PhantomData<(*mut u8, core::marker::" +"PhantomPinned)>,\n" +" }\n" +"\n" +" // Layout according to the Linux man page for readdir(3), where ino_t " +"and\n" +" // off_t are resolved according to the definitions in\n" +" // /usr/include/x86_64-linux-gnu/{sys/types.h, bits/typesizes.h}.\n" +" #[cfg(not(target_os = \"macos\"))]\n" +" #[repr(C)]\n" +" pub struct dirent {\n" +" pub d_ino: c_ulong,\n" +" pub d_off: c_long,\n" +" pub d_reclen: c_ushort,\n" +" pub d_type: c_uchar,\n" +" pub d_name: [c_char; 256],\n" +" }\n" +"\n" +" // Layout according to the macOS man page for dir(5).\n" +" #[cfg(all(target_os = \"macos\"))]\n" +" #[repr(C)]\n" +" pub struct dirent {\n" +" pub d_fileno: u64,\n" +" pub d_seekoff: u64,\n" +" pub d_reclen: u16,\n" +" pub d_namlen: u16,\n" +" pub d_type: u8,\n" +" pub d_name: [c_char; 1024],\n" +" }\n" +"\n" +" extern \"C\" {\n" +" pub fn opendir(s: *const c_char) -> *mut DIR;\n" +"\n" +" #[cfg(not(all(target_os = \"macos\", target_arch = \"x86_64\")))]\n" +" pub fn readdir(s: *mut DIR) -> *const dirent;\n" +"\n" +" // See https://github.com/rust-lang/libc/issues/414 and the section " +"on\n" +" // _DARWIN_FEATURE_64_BIT_INODE in the macOS man page for stat(2).\n" +" //\n" +" // \"Platforms that existed before these updates were available\" " +"refers\n" +" // to macOS (as opposed to iOS / wearOS / etc.) on Intel and " +"PowerPC.\n" +" #[cfg(all(target_os = \"macos\", target_arch = \"x86_64\"))]\n" +" #[link_name = \"readdir$INODE64\"]\n" +" pub fn readdir(s: *mut DIR) -> *const dirent;\n" +"\n" +" pub fn closedir(s: *mut DIR) -> c_int;\n" +" }\n" +"}\n" +"\n" +"use std::ffi::{CStr, CString, OsStr, OsString};\n" +"use std::os::unix::ffi::OsStrExt;\n" +"\n" +"#[derive(Debug)]\n" +"struct DirectoryIterator {\n" +" path: CString,\n" +" dir: *mut ffi::DIR,\n" +"}\n" +"\n" +"impl DirectoryIterator {\n" +" fn new(path: &str) -> Result {\n" +" // Call opendir and return a Ok value if that worked,\n" +" // otherwise return Err with a message.\n" +" unimplemented!()\n" +" }\n" +"}\n" +"\n" +"impl Iterator for DirectoryIterator {\n" +" type Item = OsString;\n" +" fn next(&mut self) -> Option {\n" +" // Keep calling readdir until we get a NULL pointer back.\n" +" unimplemented!()\n" +" }\n" +"}\n" +"\n" +"impl Drop for DirectoryIterator {\n" +" fn drop(&mut self) {\n" +" // Call closedir as needed.\n" +" unimplemented!()\n" +" }\n" +"}\n" +"\n" +"fn main() -> Result<(), String> {\n" +" let iter = DirectoryIterator::new(\".\")?;\n" +" println!(\"files: {:#?}\", iter.collect::>());\n" +" Ok(())\n" "}\n" "```" msgstr "" -#: src/android/aidl/server.md:30 -msgid "" -"```javascript\n" -"rust_binary {\n" -" name: \"birthday_server\",\n" -" crate_name: \"birthday_server\",\n" -" srcs: [\"src/server.rs\"],\n" -" rustlibs: [\n" -" \"com.example.birthdayservice-rust\",\n" -" \"libbinder_rs\",\n" -" \"libbirthdayservice\",\n" -" ],\n" -" prefer_rlib: true,\n" -"}\n" -"```" +#: src/android.md:1 +msgid "Welcome to Rust in Android" msgstr "" -#: src/android/aidl/deploy.md:3 -msgid "We can now build, push, and start the service:" +#: src/android.md:3 +msgid "" +"Rust is supported for native platform development on Android. This means " +"that you can write new operating system services in Rust, as well as " +"extending existing services." msgstr "" -#: src/android/aidl/deploy.md:5 +#: src/android.md:7 msgid "" -"```shell\n" -"$ m birthday_server\n" -"$ adb push \"$ANDROID_PRODUCT_OUT/system/bin/birthday_server /data/local/" -"tmp\"\n" -"$ adb shell /data/local/tmp/birthday_server\n" -"```" +"We will attempt to call Rust from one of your own projects today. So try to " +"find a little corner of your code base where we can move some lines of code " +"to Rust. The fewer dependencies and \"exotic\" types the better. Something " +"that parses some raw bytes would be ideal." msgstr "" -#: src/android/aidl/deploy.md:11 -msgid "In another terminal, check that the service runs:" +#: src/android/setup.md:3 +msgid "" +"We will be using an Android Virtual Device to test our code. Make sure you " +"have access to one or create a new one with:" msgstr "" -#: src/android/aidl/deploy.md:13 +#: src/android/setup.md:6 msgid "" "```shell\n" -"$ adb shell service check birthdayservice\n" -"Service birthdayservice: found\n" +"source build/envsetup.sh\n" +"lunch aosp_cf_x86_64_phone-userdebug\n" +"acloud create\n" "```" msgstr "" -#: src/android/aidl/deploy.md:18 -msgid "You can also call the service with `service call`:" +#: src/android/setup.md:12 +msgid "" +"Please see the [Android Developer Codelab](https://source.android.com/docs/" +"setup/start) for details." msgstr "" -#: src/android/aidl/deploy.md:20 -msgid "" -"```shell\n" -"$ $ adb shell service call birthdayservice 1 s16 Bob i32 24\n" -"Result: Parcel(\n" -" 0x00000000: 00000000 00000036 00610048 00700070 '....6...H.a.p.p.'\n" -" 0x00000010: 00200079 00690042 00740072 00640068 'y. .B.i.r.t.h.d.'\n" -" 0x00000020: 00790061 00420020 0062006f 0020002c 'a.y. .B.o.b.,. .'\n" -" 0x00000030: 006f0063 0067006e 00610072 00750074 'c.o.n.g.r.a.t.u.'\n" -" 0x00000040: 0061006c 00690074 006e006f 00200073 'l.a.t.i.o.n.s. .'\n" -" 0x00000050: 00690077 00680074 00740020 00650068 'w.i.t.h. .t.h.e.'\n" -" 0x00000060: 00320020 00200034 00650079 00720061 ' .2.4. .y.e.a.r.'\n" -" 0x00000070: 00210073 00000000 's.!..... ')\n" -"```" +#: src/android/build-rules.md:3 +msgid "The Android build system (Soong) supports Rust via a number of modules:" msgstr "" -#: src/android/aidl/client.md:1 -msgid "AIDL Client" +#: src/android/build-rules.md:5 +msgid "Module Type" msgstr "" -#: src/android/aidl/client.md:3 -msgid "Finally, we can create a Rust client for our new service." +#: src/android/build-rules.md:5 +msgid "Description" msgstr "" -#: src/android/aidl/client.md:5 -msgid "_birthday_service/src/client.rs_:" +#: src/android/build-rules.md:7 +msgid "`rust_binary`" msgstr "" -#: src/android/aidl/client.md:7 -msgid "" -"```rust,ignore\n" -"//! Birthday service.\n" -"use com_example_birthdayservice::aidl::com::example::birthdayservice::" -"IBirthdayService::IBirthdayService;\n" -"use com_example_birthdayservice::binder;\n" -"\n" -"const SERVICE_IDENTIFIER: &str = \"birthdayservice\";\n" -"\n" -"/// Connect to the BirthdayService.\n" -"pub fn connect() -> Result, binder::" -"StatusCode> {\n" -" binder::get_interface(SERVICE_IDENTIFIER)\n" -"}\n" -"\n" -"/// Call the birthday service.\n" -"fn main() -> Result<(), binder::Status> {\n" -" let name = std::env::args()\n" -" .nth(1)\n" -" .unwrap_or_else(|| String::from(\"Bob\"));\n" -" let years = std::env::args()\n" -" .nth(2)\n" -" .and_then(|arg| arg.parse::().ok())\n" -" .unwrap_or(42);\n" -"\n" -" binder::ProcessState::start_thread_pool();\n" -" let service = connect().expect(\"Failed to connect to " -"BirthdayService\");\n" -" let msg = service.wishHappyBirthday(&name, years)?;\n" -" println!(\"{msg}\");\n" -" Ok(())\n" -"}\n" -"```" +#: src/android/build-rules.md:7 +msgid "Produces a Rust binary." msgstr "" -#: src/android/aidl/client.md:39 -msgid "" -"```javascript\n" -"rust_binary {\n" -" name: \"birthday_client\",\n" -" crate_name: \"birthday_client\",\n" -" srcs: [\"src/client.rs\"],\n" -" rustlibs: [\n" -" \"com.example.birthdayservice-rust\",\n" -" \"libbinder_rs\",\n" -" ],\n" -" prefer_rlib: true,\n" -"}\n" -"```" +#: src/android/build-rules.md:8 +msgid "`rust_library`" msgstr "" -#: src/android/aidl/client.md:52 -msgid "Notice that the client does not depend on `libbirthdayservice`." +#: src/android/build-rules.md:8 +msgid "Produces a Rust library, and provides both `rlib` and `dylib` variants." msgstr "" -#: src/android/aidl/client.md:54 -msgid "Build, push, and run the client on your device:" +#: src/android/build-rules.md:9 +msgid "`rust_ffi`" msgstr "" -#: src/android/aidl/client.md:56 +#: src/android/build-rules.md:9 msgid "" -"```shell\n" -"$ m birthday_client\n" -"$ adb push \"$ANDROID_PRODUCT_OUT/system/bin/birthday_client /data/local/" -"tmp\"\n" -"$ adb shell /data/local/tmp/birthday_client Charlie 60\n" -"Happy Birthday Charlie, congratulations with the 60 years!\n" -"```" +"Produces a Rust C library usable by `cc` modules, and provides both static " +"and shared variants." msgstr "" -#: src/android/aidl/changing.md:3 -msgid "" -"Let us extend the API with more functionality: we want to let clients " -"specify a list of lines for the birthday card:" +#: src/android/build-rules.md:10 +msgid "`rust_proc_macro`" msgstr "" -#: src/android/aidl/changing.md:6 -msgid "" -"```java\n" -"package com.example.birthdayservice;\n" -"\n" -"/** Birthday service interface. */\n" -"interface IBirthdayService {\n" -" /** Generate a Happy Birthday message. */\n" -" String wishHappyBirthday(String name, int years, in String[] text);\n" -"}\n" -"```" -msgstr "" - -#: src/android/logging.md:3 +#: src/android/build-rules.md:10 msgid "" -"You should use the `log` crate to automatically log to `logcat` (on-device) " -"or `stdout` (on-host):" +"Produces a `proc-macro` Rust library. These are analogous to compiler " +"plugins." msgstr "" -#: src/android/logging.md:6 -msgid "_hello_rust_logs/Android.bp_:" +#: src/android/build-rules.md:11 +msgid "`rust_test`" msgstr "" -#: src/android/logging.md:8 -msgid "" -"```javascript\n" -"rust_binary {\n" -" name: \"hello_rust_logs\",\n" -" crate_name: \"hello_rust_logs\",\n" -" srcs: [\"src/main.rs\"],\n" -" rustlibs: [\n" -" \"liblog_rust\",\n" -" \"liblogger\",\n" -" ],\n" -" prefer_rlib: true,\n" -" host_supported: true,\n" -"}\n" -"```" +#: src/android/build-rules.md:11 +msgid "Produces a Rust test binary that uses the standard Rust test harness." msgstr "" -#: src/android/logging.md:22 -msgid "_hello_rust_logs/src/main.rs_:" +#: src/android/build-rules.md:12 +msgid "`rust_fuzz`" msgstr "" -#: src/android/logging.md:24 -msgid "" -"```rust,ignore\n" -"//! Rust logging demo.\n" -"\n" -"use log::{debug, error, info};\n" -"\n" -"/// Logs a greeting.\n" -"fn main() {\n" -" logger::init(\n" -" logger::Config::default()\n" -" .with_tag_on_device(\"rust\")\n" -" .with_min_level(log::Level::Trace),\n" -" );\n" -" debug!(\"Starting program.\");\n" -" info!(\"Things are going fine.\");\n" -" error!(\"Something went wrong!\");\n" -"}\n" -"```" +#: src/android/build-rules.md:12 +msgid "Produces a Rust fuzz binary leveraging `libfuzzer`." msgstr "" -#: src/android/logging.md:42 src/android/interoperability/with-c/bindgen.md:98 -#: src/android/interoperability/with-c/rust.md:73 -msgid "Build, push, and run the binary on your device:" +#: src/android/build-rules.md:13 +msgid "`rust_protobuf`" msgstr "" -#: src/android/logging.md:44 +#: src/android/build-rules.md:13 msgid "" -"```shell\n" -"$ m hello_rust_logs\n" -"$ adb push \"$ANDROID_PRODUCT_OUT/system/bin/hello_rust_logs /data/local/" -"tmp\"\n" -"$ adb shell /data/local/tmp/hello_rust_logs\n" -"```" -msgstr "" - -#: src/android/logging.md:50 -msgid "The logs show up in `adb logcat`:" +"Generates source and produces a Rust library that provides an interface for " +"a particular protobuf." msgstr "" -#: src/android/logging.md:52 -msgid "" -"```shell\n" -"$ adb logcat -s rust\n" -"09-08 08:38:32.454 2420 2420 D rust: hello_rust_logs: Starting program.\n" -"09-08 08:38:32.454 2420 2420 I rust: hello_rust_logs: Things are going " -"fine.\n" -"09-08 08:38:32.454 2420 2420 E rust: hello_rust_logs: Something went " -"wrong!\n" -"```" +#: src/android/build-rules.md:14 +msgid "`rust_bindgen`" msgstr "" -#: src/android/interoperability.md:3 +#: src/android/build-rules.md:14 msgid "" -"Rust has excellent support for interoperability with other languages. This " -"means that you can:" +"Generates source and produces a Rust library containing Rust bindings to C " +"libraries." msgstr "" -#: src/android/interoperability.md:6 -msgid "Call Rust functions from other languages." +#: src/android/build-rules.md:16 +msgid "We will look at `rust_binary` and `rust_library` next." msgstr "" -#: src/android/interoperability.md:7 -msgid "Call functions written in other languages from Rust." +#: src/android/build-rules/binary.md:1 +msgid "Rust Binaries" msgstr "" -#: src/android/interoperability.md:9 +#: src/android/build-rules/binary.md:3 msgid "" -"When you call functions in a foreign language we say that you're using a " -"_foreign function interface_, also known as FFI." +"Let us start with a simple application. At the root of an AOSP checkout, " +"create the following files:" msgstr "" -#: src/android/interoperability/with-c.md:1 -msgid "Interoperability with C" +#: src/android/build-rules/binary.md:6 src/android/build-rules/library.md:13 +msgid "_hello_rust/Android.bp_:" msgstr "" -#: src/android/interoperability/with-c.md:3 +#: src/android/build-rules/binary.md:8 msgid "" -"Rust has full support for linking object files with a C calling convention. " -"Similarly, you can export Rust functions and call them from C." +"```javascript\n" +"rust_binary {\n" +" name: \"hello_rust\",\n" +" crate_name: \"hello_rust\",\n" +" srcs: [\"src/main.rs\"],\n" +"}\n" +"```" msgstr "" -#: src/android/interoperability/with-c.md:6 -msgid "You can do it by hand if you want:" +#: src/android/build-rules/binary.md:16 src/android/build-rules/library.md:34 +msgid "_hello_rust/src/main.rs_:" msgstr "" -#: src/android/interoperability/with-c.md:8 +#: src/android/build-rules/binary.md:18 msgid "" "```rust\n" -"extern \"C\" {\n" -" fn abs(x: i32) -> i32;\n" -"}\n" +"//! Rust demo.\n" "\n" +"/// Prints a greeting to standard output.\n" "fn main() {\n" -" let x = -42;\n" -" let abs_x = unsafe { abs(x) };\n" -" println!(\"{x}, {abs_x}\");\n" +" println!(\"Hello from Rust!\");\n" "}\n" "```" msgstr "" -#: src/android/interoperability/with-c.md:20 +#: src/android/build-rules/binary.md:27 +msgid "You can now build, push, and run the binary:" +msgstr "" + +#: src/android/build-rules/binary.md:29 msgid "" -"We already saw this in the [Safe FFI Wrapper exercise](../../exercises/day-3/" -"safe-ffi-wrapper.md)." +"```shell\n" +"m hello_rust\n" +"adb push \"$ANDROID_PRODUCT_OUT/system/bin/hello_rust /data/local/tmp\"\n" +"adb shell /data/local/tmp/hello_rust\n" +"```" msgstr "" -#: src/android/interoperability/with-c.md:23 +#: src/android/build-rules/binary.md:35 msgid "" -"This assumes full knowledge of the target platform. Not recommended for " -"production." +"```text\n" +"Hello from Rust!\n" +"```" msgstr "" -#: src/android/interoperability/with-c.md:26 -msgid "We will look at better options next." +#: src/android/build-rules/library.md:1 +msgid "Rust Libraries" msgstr "" -#: src/android/interoperability/with-c/bindgen.md:1 -msgid "Using Bindgen" +#: src/android/build-rules/library.md:3 +msgid "You use `rust_library` to create a new Rust library for Android." msgstr "" -#: src/android/interoperability/with-c/bindgen.md:3 -msgid "" -"The [bindgen](https://rust-lang.github.io/rust-bindgen/introduction.html) " -"tool can auto-generate bindings from a C header file." +#: src/android/build-rules/library.md:5 +msgid "Here we declare a dependency on two libraries:" msgstr "" -#: src/android/interoperability/with-c/bindgen.md:6 -msgid "First create a small C library:" +#: src/android/build-rules/library.md:7 +msgid "`libgreeting`, which we define below," msgstr "" -#: src/android/interoperability/with-c/bindgen.md:8 -msgid "_interoperability/bindgen/libbirthday.h_:" +#: src/android/build-rules/library.md:8 +msgid "" +"`libtextwrap`, which is a crate already vendored in [`external/rust/crates/`]" +"(https://cs.android.com/android/platform/superproject/+/master:external/rust/" +"crates/)." msgstr "" -#: src/android/interoperability/with-c/bindgen.md:10 +#: src/android/build-rules/library.md:15 msgid "" -"```c\n" -"typedef struct card {\n" -" const char* name;\n" -" int years;\n" -"} card;\n" +"```javascript\n" +"rust_binary {\n" +" name: \"hello_rust_with_dep\",\n" +" crate_name: \"hello_rust_with_dep\",\n" +" srcs: [\"src/main.rs\"],\n" +" rustlibs: [\n" +" \"libgreetings\",\n" +" \"libtextwrap\",\n" +" ],\n" +" prefer_rlib: true,\n" +"}\n" "\n" -"void print_card(const card* card);\n" +"rust_library {\n" +" name: \"libgreetings\",\n" +" crate_name: \"greetings\",\n" +" srcs: [\"src/lib.rs\"],\n" +"}\n" "```" msgstr "" -#: src/android/interoperability/with-c/bindgen.md:19 -msgid "_interoperability/bindgen/libbirthday.c_:" -msgstr "" - -#: src/android/interoperability/with-c/bindgen.md:21 +#: src/android/build-rules/library.md:36 msgid "" -"```c\n" -"#include \n" -"#include \"libbirthday.h\"\n" +"```rust,ignore\n" +"//! Rust demo.\n" "\n" -"void print_card(const card* card) {\n" -" printf(\"+--------------\\n\");\n" -" printf(\"| Happy Birthday %s!\\n\", card->name);\n" -" printf(\"| Congratulations with the %i years!\\n\", card->years);\n" -" printf(\"+--------------\\n\");\n" +"use greetings::greeting;\n" +"use textwrap::fill;\n" +"\n" +"/// Prints a greeting to standard output.\n" +"fn main() {\n" +" println!(\"{}\", fill(&greeting(\"Bob\"), 24));\n" "}\n" "```" msgstr "" -#: src/android/interoperability/with-c/bindgen.md:33 -msgid "Add this to your `Android.bp` file:" -msgstr "" - -#: src/android/interoperability/with-c/bindgen.md:35 -#: src/android/interoperability/with-c/bindgen.md:55 -#: src/android/interoperability/with-c/bindgen.md:69 -#: src/android/interoperability/with-c/bindgen.md:108 -msgid "_interoperability/bindgen/Android.bp_:" +#: src/android/build-rules/library.md:48 +msgid "_hello_rust/src/lib.rs_:" msgstr "" -#: src/android/interoperability/with-c/bindgen.md:37 +#: src/android/build-rules/library.md:50 msgid "" -"```javascript\n" -"cc_library {\n" -" name: \"libbirthday\",\n" -" srcs: [\"libbirthday.c\"],\n" +"```rust,ignore\n" +"//! Greeting library.\n" +"\n" +"/// Greet `name`.\n" +"pub fn greeting(name: &str) -> String {\n" +" format!(\"Hello {name}, it is very nice to meet you!\")\n" "}\n" "```" msgstr "" -#: src/android/interoperability/with-c/bindgen.md:44 -msgid "" -"Create a wrapper header file for the library (not strictly needed in this " -"example):" -msgstr "" - -#: src/android/interoperability/with-c/bindgen.md:47 -msgid "_interoperability/bindgen/libbirthday_wrapper.h_:" +#: src/android/build-rules/library.md:59 +msgid "You build, push, and run the binary like before:" msgstr "" -#: src/android/interoperability/with-c/bindgen.md:49 +#: src/android/build-rules/library.md:61 msgid "" -"```c\n" -"#include \"libbirthday.h\"\n" +"```shell\n" +"m hello_rust_with_dep\n" +"adb push \"$ANDROID_PRODUCT_OUT/system/bin/hello_rust_with_dep /data/local/" +"tmp\"\n" +"adb shell /data/local/tmp/hello_rust_with_dep\n" "```" msgstr "" -#: src/android/interoperability/with-c/bindgen.md:53 -msgid "You can now auto-generate the bindings:" +#: src/android/build-rules/library.md:67 +msgid "" +"```text\n" +"Hello Bob, it is very\n" +"nice to meet you!\n" +"```" msgstr "" -#: src/android/interoperability/with-c/bindgen.md:57 +#: src/android/aidl.md:3 msgid "" -"```javascript\n" -"rust_bindgen {\n" -" name: \"libbirthday_bindgen\",\n" -" crate_name: \"birthday_bindgen\",\n" -" wrapper_src: \"libbirthday_wrapper.h\",\n" -" source_stem: \"bindings\",\n" -" static_libs: [\"libbirthday\"],\n" -"}\n" -"```" +"The [Android Interface Definition Language (AIDL)](https://developer.android." +"com/guide/components/aidl) is supported in Rust:" msgstr "" -#: src/android/interoperability/with-c/bindgen.md:67 -msgid "Finally, we can use the bindings in our Rust program:" +#: src/android/aidl.md:6 +msgid "Rust code can call existing AIDL servers," msgstr "" -#: src/android/interoperability/with-c/bindgen.md:71 -msgid "" -"```javascript\n" -"rust_binary {\n" -" name: \"print_birthday_card\",\n" -" srcs: [\"main.rs\"],\n" -" rustlibs: [\"libbirthday_bindgen\"],\n" -"}\n" -"```" +#: src/android/aidl.md:7 +msgid "You can create new AIDL servers in Rust." msgstr "" -#: src/android/interoperability/with-c/bindgen.md:79 -msgid "_interoperability/bindgen/main.rs_:" +#: src/android/aidl/interface.md:1 +msgid "AIDL Interfaces" msgstr "" -#: src/android/interoperability/with-c/bindgen.md:81 +#: src/android/aidl/interface.md:3 +msgid "You declare the API of your service using an AIDL interface:" +msgstr "" + +#: src/android/aidl/interface.md:5 msgid "" -"```rust,compile_fail\n" -"//! Bindgen demo.\n" -"\n" -"use birthday_bindgen::{card, print_card};\n" -"\n" -"fn main() {\n" -" let name = std::ffi::CString::new(\"Peter\").unwrap();\n" -" let card = card {\n" -" name: name.as_ptr(),\n" -" years: 42,\n" -" };\n" -" unsafe {\n" -" print_card(&card as *const card);\n" -" }\n" -"}\n" -"```" +"_birthday_service/aidl/com/example/birthdayservice/IBirthdayService.aidl_:" msgstr "" -#: src/android/interoperability/with-c/bindgen.md:100 +#: src/android/aidl/interface.md:7 msgid "" -"```shell\n" -"$ m print_birthday_card\n" -"$ adb push \"$ANDROID_PRODUCT_OUT/system/bin/print_birthday_card /data/local/" -"tmp\"\n" -"$ adb shell /data/local/tmp/print_birthday_card\n" +"```java\n" +"package com.example.birthdayservice;\n" +"\n" +"/** Birthday service interface. */\n" +"interface IBirthdayService {\n" +" /** Generate a Happy Birthday message. */\n" +" String wishHappyBirthday(String name, int years);\n" +"}\n" "```" msgstr "" -#: src/android/interoperability/with-c/bindgen.md:106 -msgid "Finally, we can run auto-generated tests to ensure the bindings work:" +#: src/android/aidl/interface.md:17 +msgid "_birthday_service/aidl/Android.bp_:" msgstr "" -#: src/android/interoperability/with-c/bindgen.md:110 +#: src/android/aidl/interface.md:19 msgid "" "```javascript\n" -"rust_test {\n" -" name: \"libbirthday_bindgen_test\",\n" -" srcs: [\":libbirthday_bindgen\"],\n" -" crate_name: \"libbirthday_bindgen_test\",\n" -" test_suites: [\"general-tests\"],\n" -" auto_gen_config: true,\n" -" clippy_lints: \"none\", // Generated file, skip linting\n" -" lints: \"none\",\n" +"aidl_interface {\n" +" name: \"com.example.birthdayservice\",\n" +" srcs: [\"com/example/birthdayservice/*.aidl\"],\n" +" unstable: true,\n" +" backend: {\n" +" rust: { // Rust is not enabled by default\n" +" enabled: true,\n" +" },\n" +" },\n" "}\n" "```" msgstr "" -#: src/android/interoperability/with-c/bindgen.md:122 +#: src/android/aidl/interface.md:32 msgid "" -"```shell\n" -"$ atest libbirthday_bindgen_test\n" -"```" +"Add `vendor_available: true` if your AIDL file is used by a binary in the " +"vendor partition." msgstr "" -#: src/android/interoperability/with-c/rust.md:1 -msgid "Calling Rust" +#: src/android/aidl/implementation.md:1 +msgid "Service Implementation" msgstr "" -#: src/android/interoperability/with-c/rust.md:3 -msgid "Exporting Rust functions and types to C is easy:" +#: src/android/aidl/implementation.md:3 +msgid "We can now implement the AIDL service:" msgstr "" -#: src/android/interoperability/with-c/rust.md:5 -msgid "_interoperability/rust/libanalyze/analyze.rs_" +#: src/android/aidl/implementation.md:5 +msgid "_birthday_service/src/lib.rs_:" msgstr "" -#: src/android/interoperability/with-c/rust.md:7 +#: src/android/aidl/implementation.md:7 msgid "" -"```rust,editable\n" -"//! Rust FFI demo.\n" -"#![deny(improper_ctypes_definitions)]\n" +"```rust,ignore\n" +"//! Implementation of the `IBirthdayService` AIDL interface.\n" +"use com_example_birthdayservice::aidl::com::example::birthdayservice::" +"IBirthdayService::IBirthdayService;\n" +"use com_example_birthdayservice::binder;\n" "\n" -"use std::os::raw::c_int;\n" +"/// The `IBirthdayService` implementation.\n" +"pub struct BirthdayService;\n" "\n" -"/// Analyze the numbers.\n" -"#[no_mangle]\n" -"pub extern \"C\" fn analyze_numbers(x: c_int, y: c_int) {\n" -" if x < y {\n" -" println!(\"x ({x}) is smallest!\");\n" -" } else {\n" -" println!(\"y ({y}) is probably larger than x ({x})\");\n" +"impl binder::Interface for BirthdayService {}\n" +"\n" +"impl IBirthdayService for BirthdayService {\n" +" fn wishHappyBirthday(&self, name: &str, years: i32) -> binder::" +"Result {\n" +" Ok(format!(\n" +" \"Happy Birthday {name}, congratulations with the {years} years!" +"\"\n" +" ))\n" " }\n" "}\n" "```" msgstr "" -#: src/android/interoperability/with-c/rust.md:24 -msgid "_interoperability/rust/libanalyze/analyze.h_" +#: src/android/aidl/implementation.md:26 src/android/aidl/server.md:28 +#: src/android/aidl/client.md:37 +msgid "_birthday_service/Android.bp_:" msgstr "" -#: src/android/interoperability/with-c/rust.md:26 +#: src/android/aidl/implementation.md:28 msgid "" -"```c\n" -"#ifndef ANALYSE_H\n" -"#define ANALYSE_H\n" -"\n" -"extern \"C\" {\n" -"void analyze_numbers(int x, int y);\n" +"```javascript\n" +"rust_library {\n" +" name: \"libbirthdayservice\",\n" +" srcs: [\"src/lib.rs\"],\n" +" crate_name: \"birthdayservice\",\n" +" rustlibs: [\n" +" \"com.example.birthdayservice-rust\",\n" +" \"libbinder_rs\",\n" +" ],\n" "}\n" -"\n" -"#endif\n" "```" msgstr "" -#: src/android/interoperability/with-c/rust.md:37 -msgid "_interoperability/rust/libanalyze/Android.bp_" -msgstr "" - -#: src/android/interoperability/with-c/rust.md:39 -msgid "" -"```javascript\n" -"rust_ffi {\n" -" name: \"libanalyze_ffi\",\n" -" crate_name: \"analyze_ffi\",\n" -" srcs: [\"analyze.rs\"],\n" -" include_dirs: [\".\"],\n" -"}\n" -"```" +#: src/android/aidl/server.md:1 +msgid "AIDL Server" msgstr "" -#: src/android/interoperability/with-c/rust.md:48 -msgid "We can now call this from a C binary:" +#: src/android/aidl/server.md:3 +msgid "Finally, we can create a server which exposes the service:" msgstr "" -#: src/android/interoperability/with-c/rust.md:50 -msgid "_interoperability/rust/analyze/main.c_" +#: src/android/aidl/server.md:5 +msgid "_birthday_service/src/server.rs_:" msgstr "" -#: src/android/interoperability/with-c/rust.md:52 +#: src/android/aidl/server.md:7 msgid "" -"```c\n" -"#include \"analyze.h\"\n" +"```rust,ignore\n" +"//! Birthday service.\n" +"use birthdayservice::BirthdayService;\n" +"use com_example_birthdayservice::aidl::com::example::birthdayservice::" +"IBirthdayService::BnBirthdayService;\n" +"use com_example_birthdayservice::binder;\n" "\n" -"int main() {\n" -" analyze_numbers(10, 20);\n" -" analyze_numbers(123, 123);\n" -" return 0;\n" +"const SERVICE_IDENTIFIER: &str = \"birthdayservice\";\n" +"\n" +"/// Entry point for birthday service.\n" +"fn main() {\n" +" let birthday_service = BirthdayService;\n" +" let birthday_service_binder = BnBirthdayService::new_binder(\n" +" birthday_service,\n" +" binder::BinderFeatures::default(),\n" +" );\n" +" binder::add_service(SERVICE_IDENTIFIER, birthday_service_binder." +"as_binder())\n" +" .expect(\"Failed to register service\");\n" +" binder::ProcessState::join_thread_pool()\n" "}\n" "```" msgstr "" -#: src/android/interoperability/with-c/rust.md:62 -msgid "_interoperability/rust/analyze/Android.bp_" -msgstr "" - -#: src/android/interoperability/with-c/rust.md:64 +#: src/android/aidl/server.md:30 msgid "" "```javascript\n" -"cc_binary {\n" -" name: \"analyze_numbers\",\n" -" srcs: [\"main.c\"],\n" -" static_libs: [\"libanalyze_ffi\"],\n" +"rust_binary {\n" +" name: \"birthday_server\",\n" +" crate_name: \"birthday_server\",\n" +" srcs: [\"src/server.rs\"],\n" +" rustlibs: [\n" +" \"com.example.birthdayservice-rust\",\n" +" \"libbinder_rs\",\n" +" \"libbirthdayservice\",\n" +" ],\n" +" prefer_rlib: true,\n" "}\n" "```" msgstr "" -#: src/android/interoperability/with-c/rust.md:75 +#: src/android/aidl/deploy.md:3 +msgid "We can now build, push, and start the service:" +msgstr "" + +#: src/android/aidl/deploy.md:5 msgid "" "```shell\n" -"$ m analyze_numbers\n" -"$ adb push \"$ANDROID_PRODUCT_OUT/system/bin/analyze_numbers /data/local/" +"m birthday_server\n" +"adb push \"$ANDROID_PRODUCT_OUT/system/bin/birthday_server /data/local/" "tmp\"\n" -"$ adb shell /data/local/tmp/analyze_numbers\n" +"adb shell /data/local/tmp/birthday_server\n" "```" msgstr "" -#: src/android/interoperability/with-c/rust.md:83 +#: src/android/aidl/deploy.md:11 +msgid "In another terminal, check that the service runs:" +msgstr "" + +#: src/android/aidl/deploy.md:13 msgid "" -"`#[no_mangle]` disables Rust's usual name mangling, so the exported symbol " -"will just be the name of the function. You can also use `#[export_name = " -"\"some_name\"]` to specify whatever name you want." +"```shell\n" +"adb shell service check birthdayservice\n" +"```" msgstr "" -#: src/android/interoperability/cpp.md:3 +#: src/android/aidl/deploy.md:17 msgid "" -"The [CXX crate](https://cxx.rs/) makes it possible to do safe " -"interoperability between Rust and C++." +"```text\n" +"Service birthdayservice: found\n" +"```" msgstr "" -#: src/android/interoperability/cpp.md:6 -msgid "The overall approach looks like this:" +#: src/android/aidl/deploy.md:21 +msgid "You can also call the service with `service call`:" msgstr "" -#: src/android/interoperability/cpp.md:10 +#: src/android/aidl/deploy.md:23 msgid "" -"See the [CXX tutorial](https://cxx.rs/tutorial.html) for an full example of " -"using this." +"```shell\n" +"adb shell service call birthdayservice 1 s16 Bob i32 24\n" +"```" msgstr "" -#: src/android/interoperability/java.md:1 -msgid "Interoperability with Java" +#: src/android/aidl/deploy.md:27 +msgid "" +"```text\n" +"Result: Parcel(\n" +" 0x00000000: 00000000 00000036 00610048 00700070 '....6...H.a.p.p.'\n" +" 0x00000010: 00200079 00690042 00740072 00640068 'y. .B.i.r.t.h.d.'\n" +" 0x00000020: 00790061 00420020 0062006f 0020002c 'a.y. .B.o.b.,. .'\n" +" 0x00000030: 006f0063 0067006e 00610072 00750074 'c.o.n.g.r.a.t.u.'\n" +" 0x00000040: 0061006c 00690074 006e006f 00200073 'l.a.t.i.o.n.s. .'\n" +" 0x00000050: 00690077 00680074 00740020 00650068 'w.i.t.h. .t.h.e.'\n" +" 0x00000060: 00320020 00200034 00650079 00720061 ' .2.4. .y.e.a.r.'\n" +" 0x00000070: 00210073 00000000 's.!..... ')\n" +"```" msgstr "" -#: src/android/interoperability/java.md:3 -msgid "" -"Java can load shared objects via [Java Native Interface (JNI)](https://en." -"wikipedia.org/wiki/Java_Native_Interface). The [`jni` crate](https://docs.rs/" -"jni/) allows you to create a compatible library." +#: src/android/aidl/client.md:1 +msgid "AIDL Client" msgstr "" -#: src/android/interoperability/java.md:7 -msgid "First, we create a Rust function to export to Java:" +#: src/android/aidl/client.md:3 +msgid "Finally, we can create a Rust client for our new service." msgstr "" -#: src/android/interoperability/java.md:9 -msgid "_interoperability/java/src/lib.rs_:" +#: src/android/aidl/client.md:5 +msgid "_birthday_service/src/client.rs_:" msgstr "" -#: src/android/interoperability/java.md:11 +#: src/android/aidl/client.md:7 msgid "" -"```rust,compile_fail\n" -"//! Rust <-> Java FFI demo.\n" +"```rust,ignore\n" +"//! Birthday service.\n" +"use com_example_birthdayservice::aidl::com::example::birthdayservice::" +"IBirthdayService::IBirthdayService;\n" +"use com_example_birthdayservice::binder;\n" "\n" -"use jni::objects::{JClass, JString};\n" -"use jni::sys::jstring;\n" -"use jni::JNIEnv;\n" +"const SERVICE_IDENTIFIER: &str = \"birthdayservice\";\n" "\n" -"/// HelloWorld::hello method implementation.\n" -"#[no_mangle]\n" -"pub extern \"system\" fn Java_HelloWorld_hello(\n" -" env: JNIEnv,\n" -" _class: JClass,\n" -" name: JString,\n" -") -> jstring {\n" -" let input: String = env.get_string(name).unwrap().into();\n" -" let greeting = format!(\"Hello, {input}!\");\n" -" let output = env.new_string(greeting).unwrap();\n" -" output.into_inner()\n" +"/// Connect to the BirthdayService.\n" +"pub fn connect() -> Result, binder::" +"StatusCode> {\n" +" binder::get_interface(SERVICE_IDENTIFIER)\n" +"}\n" +"\n" +"/// Call the birthday service.\n" +"fn main() -> Result<(), binder::Status> {\n" +" let name = std::env::args()\n" +" .nth(1)\n" +" .unwrap_or_else(|| String::from(\"Bob\"));\n" +" let years = std::env::args()\n" +" .nth(2)\n" +" .and_then(|arg| arg.parse::().ok())\n" +" .unwrap_or(42);\n" +"\n" +" binder::ProcessState::start_thread_pool();\n" +" let service = connect().expect(\"Failed to connect to " +"BirthdayService\");\n" +" let msg = service.wishHappyBirthday(&name, years)?;\n" +" println!(\"{msg}\");\n" +" Ok(())\n" "}\n" "```" msgstr "" -#: src/android/interoperability/java.md:32 -#: src/android/interoperability/java.md:62 -msgid "_interoperability/java/Android.bp_:" -msgstr "" - -#: src/android/interoperability/java.md:34 +#: src/android/aidl/client.md:39 msgid "" "```javascript\n" -"rust_ffi_shared {\n" -" name: \"libhello_jni\",\n" -" crate_name: \"hello_jni\",\n" -" srcs: [\"src/lib.rs\"],\n" -" rustlibs: [\"libjni\"],\n" +"rust_binary {\n" +" name: \"birthday_client\",\n" +" crate_name: \"birthday_client\",\n" +" srcs: [\"src/client.rs\"],\n" +" rustlibs: [\n" +" \"com.example.birthdayservice-rust\",\n" +" \"libbinder_rs\",\n" +" ],\n" +" prefer_rlib: true,\n" "}\n" "```" msgstr "" -#: src/android/interoperability/java.md:43 -msgid "Finally, we can call this function from Java:" +#: src/android/aidl/client.md:52 +msgid "Notice that the client does not depend on `libbirthdayservice`." msgstr "" -#: src/android/interoperability/java.md:45 -msgid "_interoperability/java/HelloWorld.java_:" +#: src/android/aidl/client.md:54 +msgid "Build, push, and run the client on your device:" msgstr "" -#: src/android/interoperability/java.md:47 +#: src/android/aidl/client.md:56 msgid "" -"```java\n" -"class HelloWorld {\n" -" private static native String hello(String name);\n" -"\n" -" static {\n" -" System.loadLibrary(\"hello_jni\");\n" -" }\n" -"\n" -" public static void main(String[] args) {\n" -" String output = HelloWorld.hello(\"Alice\");\n" -" System.out.println(output);\n" -" }\n" -"}\n" +"```shell\n" +"m birthday_client\n" +"adb push \"$ANDROID_PRODUCT_OUT/system/bin/birthday_client /data/local/" +"tmp\"\n" +"adb shell /data/local/tmp/birthday_client Charlie 60\n" "```" msgstr "" -#: src/android/interoperability/java.md:64 +#: src/android/aidl/client.md:62 msgid "" -"```javascript\n" -"java_binary {\n" -" name: \"helloworld_jni\",\n" -" srcs: [\"HelloWorld.java\"],\n" -" main_class: \"HelloWorld\",\n" -" required: [\"libhello_jni\"],\n" -"}\n" +"```text\n" +"Happy Birthday Charlie, congratulations with the 60 years!\n" "```" msgstr "" -#: src/android/interoperability/java.md:73 -msgid "Finally, you can build, sync, and run the binary:" +#: src/android/aidl/changing.md:3 +msgid "" +"Let us extend the API with more functionality: we want to let clients " +"specify a list of lines for the birthday card:" msgstr "" -#: src/android/interoperability/java.md:75 +#: src/android/aidl/changing.md:6 msgid "" -"```shell\n" -"$ m helloworld_jni\n" -"$ adb sync # requires adb root && adb remount\n" -"$ adb shell /system/bin/helloworld_jni\n" +"```java\n" +"package com.example.birthdayservice;\n" +"\n" +"/** Birthday service interface. */\n" +"interface IBirthdayService {\n" +" /** Generate a Happy Birthday message. */\n" +" String wishHappyBirthday(String name, int years, in String[] text);\n" +"}\n" "```" msgstr "" -#: src/exercises/android/morning.md:3 +#: src/android/logging.md:3 msgid "" -"This is a group exercise: We will look at one of the projects you work with " -"and try to integrate some Rust into it. Some suggestions:" -msgstr "" - -#: src/exercises/android/morning.md:6 -msgid "Call your AIDL service with a client written in Rust." +"You should use the `log` crate to automatically log to `logcat` (on-device) " +"or `stdout` (on-host):" msgstr "" -#: src/exercises/android/morning.md:8 -msgid "Move a function from your project to Rust and call it." +#: src/android/logging.md:6 +msgid "_hello_rust_logs/Android.bp_:" msgstr "" -#: src/exercises/android/morning.md:12 +#: src/android/logging.md:8 msgid "" -"No solution is provided here since this is open-ended: it relies on someone " -"in the class having a piece of code which you can turn in to Rust on the fly." +"```javascript\n" +"rust_binary {\n" +" name: \"hello_rust_logs\",\n" +" crate_name: \"hello_rust_logs\",\n" +" srcs: [\"src/main.rs\"],\n" +" rustlibs: [\n" +" \"liblog_rust\",\n" +" \"liblogger\",\n" +" ],\n" +" prefer_rlib: true,\n" +" host_supported: true,\n" +"}\n" +"```" msgstr "" -#: src/bare-metal.md:1 -msgid "Welcome to Bare Metal Rust" +#: src/android/logging.md:22 +msgid "_hello_rust_logs/src/main.rs_:" msgstr "" -#: src/bare-metal.md:3 +#: src/android/logging.md:24 msgid "" -"This is a standalone one-day course about bare-metal Rust, aimed at people " -"who are familiar with the basics of Rust (perhaps from completing the " -"Comprehensive Rust course), and ideally also have some experience with bare-" -"metal programming in some other language such as C." +"```rust,ignore\n" +"//! Rust logging demo.\n" +"\n" +"use log::{debug, error, info};\n" +"\n" +"/// Logs a greeting.\n" +"fn main() {\n" +" logger::init(\n" +" logger::Config::default()\n" +" .with_tag_on_device(\"rust\")\n" +" .with_min_level(log::Level::Trace),\n" +" );\n" +" debug!(\"Starting program.\");\n" +" info!(\"Things are going fine.\");\n" +" error!(\"Something went wrong!\");\n" +"}\n" +"```" msgstr "" -#: src/bare-metal.md:7 -msgid "" -"Today we will talk about 'bare-metal' Rust: running Rust code without an OS " -"underneath us. This will be divided into several parts:" +#: src/android/logging.md:42 src/android/interoperability/with-c/bindgen.md:98 +#: src/android/interoperability/with-c/rust.md:73 +msgid "Build, push, and run the binary on your device:" msgstr "" -#: src/bare-metal.md:10 -msgid "What is `no_std` Rust?" +#: src/android/logging.md:44 +msgid "" +"```shell\n" +"m hello_rust_logs\n" +"adb push \"$ANDROID_PRODUCT_OUT/system/bin/hello_rust_logs /data/local/" +"tmp\"\n" +"adb shell /data/local/tmp/hello_rust_logs\n" +"```" msgstr "" -#: src/bare-metal.md:11 -msgid "Writing firmware for microcontrollers." +#: src/android/logging.md:50 +msgid "The logs show up in `adb logcat`:" msgstr "" -#: src/bare-metal.md:12 -msgid "Writing bootloader / kernel code for application processors." +#: src/android/logging.md:52 +msgid "" +"```shell\n" +"adb logcat -s rust\n" +"```" msgstr "" -#: src/bare-metal.md:13 -msgid "Some useful crates for bare-metal Rust development." -msgstr "" - -#: src/bare-metal.md:15 +#: src/android/logging.md:56 msgid "" -"For the microcontroller part of the course we will use the [BBC micro:bit]" -"(https://microbit.org/) v2 as an example. It's a [development board](https://" -"tech.microbit.org/hardware/) based on the Nordic nRF51822 microcontroller " -"with some LEDs and buttons, an I2C-connected accelerometer and compass, and " -"an on-board SWD debugger." +"```text\n" +"09-08 08:38:32.454 2420 2420 D rust: hello_rust_logs: Starting program.\n" +"09-08 08:38:32.454 2420 2420 I rust: hello_rust_logs: Things are going " +"fine.\n" +"09-08 08:38:32.454 2420 2420 E rust: hello_rust_logs: Something went " +"wrong!\n" +"```" msgstr "" -#: src/bare-metal.md:20 +#: src/android/interoperability.md:3 msgid "" -"To get started, install some tools we'll need later. On gLinux or Debian:" +"Rust has excellent support for interoperability with other languages. This " +"means that you can:" msgstr "" -#: src/bare-metal.md:22 -msgid "" -"```bash\n" -"sudo apt install gcc-aarch64-linux-gnu gdb-multiarch libudev-dev picocom pkg-" -"config qemu-system-arm\n" -"rustup update\n" -"rustup target add aarch64-unknown-none thumbv7em-none-eabihf\n" -"rustup component add llvm-tools-preview\n" -"cargo install cargo-binutils cargo-embed\n" -"```" +#: src/android/interoperability.md:6 +msgid "Call Rust functions from other languages." msgstr "" -#: src/bare-metal.md:30 -msgid "" -"And give users in the `plugdev` group access to the micro:bit programmer:" +#: src/android/interoperability.md:7 +msgid "Call functions written in other languages from Rust." msgstr "" -#: src/bare-metal.md:32 +#: src/android/interoperability.md:9 msgid "" -"```bash\n" -"echo 'SUBSYSTEM==\"usb\", ATTR{idVendor}==\"0d28\", MODE=\"0664\", " -"GROUP=\"plugdev\"' |\\\n" -" sudo tee /etc/udev/rules.d/50-microbit.rules\n" -"sudo udevadm control --reload-rules\n" -"```" +"When you call functions in a foreign language we say that you're using a " +"_foreign function interface_, also known as FFI." msgstr "" -#: src/bare-metal.md:38 -msgid "On MacOS:" +#: src/android/interoperability/with-c.md:1 +msgid "Interoperability with C" msgstr "" -#: src/bare-metal.md:40 +#: src/android/interoperability/with-c.md:3 msgid "" -"```bash\n" -"xcode-select --install\n" -"brew install gdb picocom qemu\n" -"brew install --cask gcc-aarch64-embedded\n" -"rustup update\n" -"rustup target add aarch64-unknown-none thumbv7em-none-eabihf\n" -"rustup component add llvm-tools-preview\n" -"cargo install cargo-binutils cargo-embed\n" -"```" +"Rust has full support for linking object files with a C calling convention. " +"Similarly, you can export Rust functions and call them from C." msgstr "" -#: src/bare-metal/no_std.md:1 -msgid "`no_std`" +#: src/android/interoperability/with-c.md:6 +msgid "You can do it by hand if you want:" msgstr "" -#: src/bare-metal/no_std.md:7 -msgid "`core`" +#: src/android/interoperability/with-c.md:8 +msgid "" +"```rust\n" +"extern \"C\" {\n" +" fn abs(x: i32) -> i32;\n" +"}\n" +"\n" +"fn main() {\n" +" let x = -42;\n" +" let abs_x = unsafe { abs(x) };\n" +" println!(\"{x}, {abs_x}\");\n" +"}\n" +"```" msgstr "" -#: src/bare-metal/no_std.md:12 src/bare-metal/alloc.md:1 -msgid "`alloc`" +#: src/android/interoperability/with-c.md:20 +msgid "" +"We already saw this in the [Safe FFI Wrapper exercise](../../exercises/day-3/" +"safe-ffi-wrapper.md)." msgstr "" -#: src/bare-metal/no_std.md:17 -msgid "`std`" +#: src/android/interoperability/with-c.md:23 +msgid "" +"This assumes full knowledge of the target platform. Not recommended for " +"production." msgstr "" -#: src/bare-metal/no_std.md:24 -msgid "Slices, `&str`, `CStr`" +#: src/android/interoperability/with-c.md:26 +msgid "We will look at better options next." msgstr "" -#: src/bare-metal/no_std.md:25 -msgid "`NonZeroU8`..." +#: src/android/interoperability/with-c/bindgen.md:1 +msgid "Using Bindgen" msgstr "" -#: src/bare-metal/no_std.md:26 -msgid "`Option`, `Result`" +#: src/android/interoperability/with-c/bindgen.md:3 +msgid "" +"The [bindgen](https://rust-lang.github.io/rust-bindgen/introduction.html) " +"tool can auto-generate bindings from a C header file." msgstr "" -#: src/bare-metal/no_std.md:27 -msgid "`Display`, `Debug`, `write!`..." +#: src/android/interoperability/with-c/bindgen.md:6 +msgid "First create a small C library:" msgstr "" -#: src/bare-metal/no_std.md:29 -msgid "`panic!`, `assert_eq!`..." +#: src/android/interoperability/with-c/bindgen.md:8 +msgid "_interoperability/bindgen/libbirthday.h_:" msgstr "" -#: src/bare-metal/no_std.md:30 -msgid "`NonNull` and all the usual pointer-related functions" +#: src/android/interoperability/with-c/bindgen.md:10 +msgid "" +"```c\n" +"typedef struct card {\n" +" const char* name;\n" +" int years;\n" +"} card;\n" +"\n" +"void print_card(const card* card);\n" +"```" msgstr "" -#: src/bare-metal/no_std.md:31 -msgid "`Future` and `async`/`await`" +#: src/android/interoperability/with-c/bindgen.md:19 +msgid "_interoperability/bindgen/libbirthday.c_:" msgstr "" -#: src/bare-metal/no_std.md:32 -msgid "`fence`, `AtomicBool`, `AtomicPtr`, `AtomicU32`..." +#: src/android/interoperability/with-c/bindgen.md:21 +msgid "" +"```c\n" +"#include \n" +"#include \"libbirthday.h\"\n" +"\n" +"void print_card(const card* card) {\n" +" printf(\"+--------------\\n\");\n" +" printf(\"| Happy Birthday %s!\\n\", card->name);\n" +" printf(\"| Congratulations with the %i years!\\n\", card->years);\n" +" printf(\"+--------------\\n\");\n" +"}\n" +"```" msgstr "" -#: src/bare-metal/no_std.md:33 -msgid "`Duration`" +#: src/android/interoperability/with-c/bindgen.md:33 +msgid "Add this to your `Android.bp` file:" msgstr "" -#: src/bare-metal/no_std.md:38 -msgid "`Box`, `Cow`, `Arc`, `Rc`" +#: src/android/interoperability/with-c/bindgen.md:35 +#: src/android/interoperability/with-c/bindgen.md:55 +#: src/android/interoperability/with-c/bindgen.md:69 +#: src/android/interoperability/with-c/bindgen.md:108 +msgid "_interoperability/bindgen/Android.bp_:" msgstr "" -#: src/bare-metal/no_std.md:39 -msgid "`Vec`, `BinaryHeap`, `BtreeMap`, `LinkedList`, `VecDeque`" +#: src/android/interoperability/with-c/bindgen.md:37 +msgid "" +"```javascript\n" +"cc_library {\n" +" name: \"libbirthday\",\n" +" srcs: [\"libbirthday.c\"],\n" +"}\n" +"```" msgstr "" -#: src/bare-metal/no_std.md:40 -msgid "`String`, `CString`, `format!`" +#: src/android/interoperability/with-c/bindgen.md:44 +msgid "" +"Create a wrapper header file for the library (not strictly needed in this " +"example):" msgstr "" -#: src/bare-metal/no_std.md:45 -msgid "`Error`" +#: src/android/interoperability/with-c/bindgen.md:47 +msgid "_interoperability/bindgen/libbirthday_wrapper.h_:" msgstr "" -#: src/bare-metal/no_std.md:47 -msgid "`Mutex`, `Condvar`, `Barrier`, `Once`, `RwLock`, `mpsc`" +#: src/android/interoperability/with-c/bindgen.md:49 +msgid "" +"```c\n" +"#include \"libbirthday.h\"\n" +"```" msgstr "" -#: src/bare-metal/no_std.md:48 -msgid "`File` and the rest of `fs`" +#: src/android/interoperability/with-c/bindgen.md:53 +msgid "You can now auto-generate the bindings:" msgstr "" -#: src/bare-metal/no_std.md:49 -msgid "`println!`, `Read`, `Write`, `Stdin`, `Stdout` and the rest of `io`" +#: src/android/interoperability/with-c/bindgen.md:57 +msgid "" +"```javascript\n" +"rust_bindgen {\n" +" name: \"libbirthday_bindgen\",\n" +" crate_name: \"birthday_bindgen\",\n" +" wrapper_src: \"libbirthday_wrapper.h\",\n" +" source_stem: \"bindings\",\n" +" static_libs: [\"libbirthday\"],\n" +"}\n" +"```" msgstr "" -#: src/bare-metal/no_std.md:50 -msgid "`Path`, `OsString`" +#: src/android/interoperability/with-c/bindgen.md:67 +msgid "Finally, we can use the bindings in our Rust program:" msgstr "" -#: src/bare-metal/no_std.md:51 -msgid "`net`" +#: src/android/interoperability/with-c/bindgen.md:71 +msgid "" +"```javascript\n" +"rust_binary {\n" +" name: \"print_birthday_card\",\n" +" srcs: [\"main.rs\"],\n" +" rustlibs: [\"libbirthday_bindgen\"],\n" +"}\n" +"```" msgstr "" -#: src/bare-metal/no_std.md:52 -msgid "`Command`, `Child`, `ExitCode`" +#: src/android/interoperability/with-c/bindgen.md:79 +msgid "_interoperability/bindgen/main.rs_:" msgstr "" -#: src/bare-metal/no_std.md:53 -msgid "`spawn`, `sleep` and the rest of `thread`" +#: src/android/interoperability/with-c/bindgen.md:81 +msgid "" +"```rust,compile_fail\n" +"//! Bindgen demo.\n" +"\n" +"use birthday_bindgen::{card, print_card};\n" +"\n" +"fn main() {\n" +" let name = std::ffi::CString::new(\"Peter\").unwrap();\n" +" let card = card {\n" +" name: name.as_ptr(),\n" +" years: 42,\n" +" };\n" +" unsafe {\n" +" print_card(&card as *const card);\n" +" }\n" +"}\n" +"```" msgstr "" -#: src/bare-metal/no_std.md:54 -msgid "`SystemTime`, `Instant`" +#: src/android/interoperability/with-c/bindgen.md:100 +msgid "" +"```shell\n" +"m print_birthday_card\n" +"adb push \"$ANDROID_PRODUCT_OUT/system/bin/print_birthday_card /data/local/" +"tmp\"\n" +"adb shell /data/local/tmp/print_birthday_card\n" +"```" msgstr "" -#: src/bare-metal/no_std.md:62 -msgid "`HashMap` depends on RNG." +#: src/android/interoperability/with-c/bindgen.md:106 +msgid "Finally, we can run auto-generated tests to ensure the bindings work:" msgstr "" -#: src/bare-metal/no_std.md:63 -msgid "`std` re-exports the contents of both `core` and `alloc`." +#: src/android/interoperability/with-c/bindgen.md:110 +msgid "" +"```javascript\n" +"rust_test {\n" +" name: \"libbirthday_bindgen_test\",\n" +" srcs: [\":libbirthday_bindgen\"],\n" +" crate_name: \"libbirthday_bindgen_test\",\n" +" test_suites: [\"general-tests\"],\n" +" auto_gen_config: true,\n" +" clippy_lints: \"none\", // Generated file, skip linting\n" +" lints: \"none\",\n" +"}\n" +"```" msgstr "" -#: src/bare-metal/minimal.md:1 -msgid "A minimal `no_std` program" +#: src/android/interoperability/with-c/bindgen.md:122 +msgid "" +"```shell\n" +"atest libbirthday_bindgen_test\n" +"```" msgstr "" -#: src/bare-metal/minimal.md:3 +#: src/android/interoperability/with-c/rust.md:1 +msgid "Calling Rust" +msgstr "" + +#: src/android/interoperability/with-c/rust.md:3 +msgid "Exporting Rust functions and types to C is easy:" +msgstr "" + +#: src/android/interoperability/with-c/rust.md:5 +msgid "_interoperability/rust/libanalyze/analyze.rs_" +msgstr "" + +#: src/android/interoperability/with-c/rust.md:7 msgid "" -"```rust,editable,compile_fail\n" -"#![no_main]\n" -"#![no_std]\n" +"```rust,editable\n" +"//! Rust FFI demo.\n" +"#![deny(improper_ctypes_definitions)]\n" "\n" -"use core::panic::PanicInfo;\n" +"use std::os::raw::c_int;\n" "\n" -"#[panic_handler]\n" -"fn panic(_panic: &PanicInfo) -> ! {\n" -" loop {}\n" +"/// Analyze the numbers.\n" +"#[no_mangle]\n" +"pub extern \"C\" fn analyze_numbers(x: c_int, y: c_int) {\n" +" if x < y {\n" +" println!(\"x ({x}) is smallest!\");\n" +" } else {\n" +" println!(\"y ({y}) is probably larger than x ({x})\");\n" +" }\n" "}\n" "```" msgstr "" -#: src/bare-metal/minimal.md:17 -msgid "This will compile to an empty binary." +#: src/android/interoperability/with-c/rust.md:24 +msgid "_interoperability/rust/libanalyze/analyze.h_" msgstr "" -#: src/bare-metal/minimal.md:18 -msgid "`std` provides a panic handler; without it we must provide our own." +#: src/android/interoperability/with-c/rust.md:26 +msgid "" +"```c\n" +"#ifndef ANALYSE_H\n" +"#define ANALYSE_H\n" +"\n" +"extern \"C\" {\n" +"void analyze_numbers(int x, int y);\n" +"}\n" +"\n" +"#endif\n" +"```" msgstr "" -#: src/bare-metal/minimal.md:19 -msgid "It can also be provided by another crate, such as `panic-halt`." +#: src/android/interoperability/with-c/rust.md:37 +msgid "_interoperability/rust/libanalyze/Android.bp_" msgstr "" -#: src/bare-metal/minimal.md:20 +#: src/android/interoperability/with-c/rust.md:39 msgid "" -"Depending on the target, you may need to compile with `panic = \"abort\"` to " -"avoid an error about `eh_personality`." +"```javascript\n" +"rust_ffi {\n" +" name: \"libanalyze_ffi\",\n" +" crate_name: \"analyze_ffi\",\n" +" srcs: [\"analyze.rs\"],\n" +" include_dirs: [\".\"],\n" +"}\n" +"```" msgstr "" -#: src/bare-metal/minimal.md:22 -msgid "" -"Note that there is no `main` or any other entry point; it's up to you to " -"define your own entry point. This will typically involve a linker script and " -"some assembly code to set things up ready for Rust code to run." +#: src/android/interoperability/with-c/rust.md:48 +msgid "We can now call this from a C binary:" msgstr "" -#: src/bare-metal/alloc.md:3 -msgid "" -"To use `alloc` you must implement a [global (heap) allocator](https://doc." -"rust-lang.org/stable/std/alloc/trait.GlobalAlloc.html)." +#: src/android/interoperability/with-c/rust.md:50 +msgid "_interoperability/rust/analyze/main.c_" msgstr "" -#: src/bare-metal/alloc.md:6 +#: src/android/interoperability/with-c/rust.md:52 msgid "" -"```rust,editable,compile_fail\n" -"#![no_main]\n" -"#![no_std]\n" -"\n" -"extern crate alloc;\n" -"extern crate panic_halt as _;\n" -"\n" -"use alloc::string::ToString;\n" -"use alloc::vec::Vec;\n" -"use buddy_system_allocator::LockedHeap;\n" -"\n" -"#[global_allocator]\n" -"static HEAP_ALLOCATOR: LockedHeap<32> = LockedHeap::<32>::new();\n" -"\n" -"static mut HEAP: [u8; 65536] = [0; 65536];\n" -"\n" -"pub fn entry() {\n" -" // Safe because `HEAP` is only used here and `entry` is only called " -"once.\n" -" unsafe {\n" -" // Give the allocator some memory to allocate.\n" -" HEAP_ALLOCATOR\n" -" .lock()\n" -" .init(HEAP.as_mut_ptr() as usize, HEAP.len());\n" -" }\n" +"```c\n" +"#include \"analyze.h\"\n" "\n" -" // Now we can do things that require heap allocation.\n" -" let mut v = Vec::new();\n" -" v.push(\"A string\".to_string());\n" +"int main() {\n" +" analyze_numbers(10, 20);\n" +" analyze_numbers(123, 123);\n" +" return 0;\n" "}\n" "```" msgstr "" -#: src/bare-metal/alloc.md:39 +#: src/android/interoperability/with-c/rust.md:62 +msgid "_interoperability/rust/analyze/Android.bp_" +msgstr "" + +#: src/android/interoperability/with-c/rust.md:64 msgid "" -"`buddy_system_allocator` is a third-party crate implementing a basic buddy " -"system allocator. Other crates are available, or you can write your own or " -"hook into your existing allocator." +"```javascript\n" +"cc_binary {\n" +" name: \"analyze_numbers\",\n" +" srcs: [\"main.c\"],\n" +" static_libs: [\"libanalyze_ffi\"],\n" +"}\n" +"```" msgstr "" -#: src/bare-metal/alloc.md:41 +#: src/android/interoperability/with-c/rust.md:75 msgid "" -"The const parameter of `LockedHeap` is the max order of the allocator; i.e. " -"in this case it can allocate regions of up to 2\\*\\*32 bytes." +"```shell\n" +"m analyze_numbers\n" +"adb push \"$ANDROID_PRODUCT_OUT/system/bin/analyze_numbers /data/local/" +"tmp\"\n" +"adb shell /data/local/tmp/analyze_numbers\n" +"```" msgstr "" -#: src/bare-metal/alloc.md:43 +#: src/android/interoperability/with-c/rust.md:83 msgid "" -"If any crate in your dependency tree depends on `alloc` then you must have " -"exactly one global allocator defined in your binary. Usually this is done in " -"the top-level binary crate." +"`#[no_mangle]` disables Rust's usual name mangling, so the exported symbol " +"will just be the name of the function. You can also use `#[export_name = " +"\"some_name\"]` to specify whatever name you want." msgstr "" -#: src/bare-metal/alloc.md:45 +#: src/android/interoperability/cpp.md:3 msgid "" -"`extern crate panic_halt as _` is necessary to ensure that the `panic_halt` " -"crate is linked in so we get its panic handler." +"The [CXX crate](https://cxx.rs/) makes it possible to do safe " +"interoperability between Rust and C++." msgstr "" -#: src/bare-metal/alloc.md:47 -msgid "This example will build but not run, as it doesn't have an entry point." +#: src/android/interoperability/cpp.md:6 +msgid "The overall approach looks like this:" msgstr "" -#: src/bare-metal/microcontrollers.md:3 +#: src/android/interoperability/cpp.md:10 msgid "" -"The `cortex_m_rt` crate provides (among other things) a reset handler for " -"Cortex M microcontrollers." +"See the [CXX tutorial](https://cxx.rs/tutorial.html) for an full example of " +"using this." msgstr "" -#: src/bare-metal/microcontrollers.md:5 +#: src/android/interoperability/cpp.md:14 msgid "" -"```rust,editable,compile_fail\n" -"#![no_main]\n" -"#![no_std]\n" -"\n" -"extern crate panic_halt as _;\n" -"\n" -"mod interrupts;\n" -"\n" -"use cortex_m_rt::entry;\n" -"\n" -"#[entry]\n" -"fn main() -> ! {\n" -" loop {}\n" -"}\n" -"```" +"At this point, the instructor should switch to the [CXX tutorial](https://" +"cxx.rs/tutorial.html)." msgstr "" -#: src/bare-metal/microcontrollers.md:21 +#: src/android/interoperability/cpp.md:16 +msgid "Walk the students through the tutorial step by step." +msgstr "" + +#: src/android/interoperability/cpp.md:18 msgid "" -"Next we'll look at how to access peripherals, with increasing levels of " -"abstraction." +"Highlight how CXX presents a clean interface without unsafe code in _both " +"languages_." msgstr "" -#: src/bare-metal/microcontrollers.md:25 +#: src/android/interoperability/cpp.md:20 msgid "" -"The `cortex_m_rt::entry` macro requires that the function have type `fn() -" -"> !`, because returning to the reset handler doesn't make sense." +"Show the correspondence between [Rust and C++ types](https://cxx.rs/bindings." +"html):" msgstr "" -#: src/bare-metal/microcontrollers.md:27 -msgid "Run the example with `cargo embed --bin minimal`" +#: src/android/interoperability/cpp.md:22 +msgid "" +"Explain how a Rust `String` cannot map to a C++ `std::string` (the latter " +"does not uphold the UTF-8 invariant). Show that despite being different " +"types, `rust::String` in C++ can be easily constructed from a C++ `std::" +"string`, making it very ergonomic to use." msgstr "" -#: src/bare-metal/microcontrollers/mmio.md:3 +#: src/android/interoperability/cpp.md:28 msgid "" -"Most microcontrollers access peripherals via memory-mapped IO. Let's try " -"turning on an LED on our micro:bit:" +"Explain that a Rust function returning `Result` becomes a function " +"which throws a `E` exception in C++ (and vice versa)." msgstr "" -#: src/bare-metal/microcontrollers/mmio.md:6 +#: src/android/interoperability/java.md:1 +msgid "Interoperability with Java" +msgstr "" + +#: src/android/interoperability/java.md:3 msgid "" -"```rust,editable,compile_fail\n" -"#![no_main]\n" -"#![no_std]\n" -"\n" -"extern crate panic_halt as _;\n" -"\n" -"mod interrupts;\n" -"\n" -"use core::mem::size_of;\n" -"use cortex_m_rt::entry;\n" -"\n" -"/// GPIO port 0 peripheral address\n" -"const GPIO_P0: usize = 0x5000_0000;\n" +"Java can load shared objects via [Java Native Interface (JNI)](https://en." +"wikipedia.org/wiki/Java_Native_Interface). The [`jni` crate](https://docs.rs/" +"jni/) allows you to create a compatible library." +msgstr "" + +#: src/android/interoperability/java.md:7 +msgid "First, we create a Rust function to export to Java:" +msgstr "" + +#: src/android/interoperability/java.md:9 +msgid "_interoperability/java/src/lib.rs_:" +msgstr "" + +#: src/android/interoperability/java.md:11 +msgid "" +"```rust,compile_fail\n" +"//! Rust <-> Java FFI demo.\n" "\n" -"// GPIO peripheral offsets\n" -"const PIN_CNF: usize = 0x700;\n" -"const OUTSET: usize = 0x508;\n" -"const OUTCLR: usize = 0x50c;\n" +"use jni::objects::{JClass, JString};\n" +"use jni::sys::jstring;\n" +"use jni::JNIEnv;\n" "\n" -"// PIN_CNF fields\n" -"const DIR_OUTPUT: u32 = 0x1;\n" -"const INPUT_DISCONNECT: u32 = 0x1 << 1;\n" -"const PULL_DISABLED: u32 = 0x0 << 2;\n" -"const DRIVE_S0S1: u32 = 0x0 << 8;\n" -"const SENSE_DISABLED: u32 = 0x0 << 16;\n" -"\n" -"#[entry]\n" -"fn main() -> ! {\n" -" // Configure GPIO 0 pins 21 and 28 as push-pull outputs.\n" -" let pin_cnf_21 = (GPIO_P0 + PIN_CNF + 21 * size_of::()) as *mut " -"u32;\n" -" let pin_cnf_28 = (GPIO_P0 + PIN_CNF + 28 * size_of::()) as *mut " -"u32;\n" -" // Safe because the pointers are to valid peripheral control registers, " -"and\n" -" // no aliases exist.\n" -" unsafe {\n" -" pin_cnf_21.write_volatile(\n" -" DIR_OUTPUT | INPUT_DISCONNECT | PULL_DISABLED | DRIVE_S0S1 | " -"SENSE_DISABLED,\n" -" );\n" -" pin_cnf_28.write_volatile(\n" -" DIR_OUTPUT | INPUT_DISCONNECT | PULL_DISABLED | DRIVE_S0S1 | " -"SENSE_DISABLED,\n" -" );\n" -" }\n" -"\n" -" // Set pin 28 low and pin 21 high to turn the LED on.\n" -" let gpio0_outset = (GPIO_P0 + OUTSET) as *mut u32;\n" -" let gpio0_outclr = (GPIO_P0 + OUTCLR) as *mut u32;\n" -" // Safe because the pointers are to valid peripheral control registers, " -"and\n" -" // no aliases exist.\n" -" unsafe {\n" -" gpio0_outclr.write_volatile(1 << 28);\n" -" gpio0_outset.write_volatile(1 << 21);\n" -" }\n" -"\n" -" loop {}\n" +"/// HelloWorld::hello method implementation.\n" +"#[no_mangle]\n" +"pub extern \"system\" fn Java_HelloWorld_hello(\n" +" env: JNIEnv,\n" +" _class: JClass,\n" +" name: JString,\n" +") -> jstring {\n" +" let input: String = env.get_string(name).unwrap().into();\n" +" let greeting = format!(\"Hello, {input}!\");\n" +" let output = env.new_string(greeting).unwrap();\n" +" output.into_inner()\n" "}\n" "```" msgstr "" -#: src/bare-metal/microcontrollers/mmio.md:64 -msgid "" -"GPIO 0 pin 21 is connected to the first column of the LED matrix, and pin 28 " -"to the first row." -msgstr "" - -#: src/bare-metal/microcontrollers/mmio.md:66 -#: src/bare-metal/microcontrollers/pacs.md:59 -#: src/bare-metal/microcontrollers/hals.md:43 -#: src/bare-metal/microcontrollers/board-support.md:34 -msgid "Run the example with:" +#: src/android/interoperability/java.md:32 +#: src/android/interoperability/java.md:62 +msgid "_interoperability/java/Android.bp_:" msgstr "" -#: src/bare-metal/microcontrollers/mmio.md:68 +#: src/android/interoperability/java.md:34 msgid "" -"```sh\n" -"cargo embed --bin mmio\n" +"```javascript\n" +"rust_ffi_shared {\n" +" name: \"libhello_jni\",\n" +" crate_name: \"hello_jni\",\n" +" srcs: [\"src/lib.rs\"],\n" +" rustlibs: [\"libjni\"],\n" +"}\n" "```" msgstr "" -#: src/bare-metal/microcontrollers/pacs.md:1 -msgid "Peripheral Access Crates" +#: src/android/interoperability/java.md:43 +msgid "Finally, we can call this function from Java:" msgstr "" -#: src/bare-metal/microcontrollers/pacs.md:3 -msgid "" -"[`svd2rust`](https://crates.io/crates/svd2rust) generates mostly-safe Rust " -"wrappers for memory-mapped peripherals from [CMSIS-SVD](https://www.keil.com/" -"pack/doc/CMSIS/SVD/html/index.html) files." +#: src/android/interoperability/java.md:45 +msgid "_interoperability/java/HelloWorld.java_:" msgstr "" -#: src/bare-metal/microcontrollers/pacs.md:7 +#: src/android/interoperability/java.md:47 msgid "" -"```rust,editable,compile_fail\n" -"#![no_main]\n" -"#![no_std]\n" -"\n" -"extern crate panic_halt as _;\n" -"\n" -"use cortex_m_rt::entry;\n" -"use nrf52833_pac::Peripherals;\n" -"\n" -"#[entry]\n" -"fn main() -> ! {\n" -" let p = Peripherals::take().unwrap();\n" -" let gpio0 = p.P0;\n" -"\n" -" // Configure GPIO 0 pins 21 and 28 as push-pull outputs.\n" -" gpio0.pin_cnf[21].write(|w| {\n" -" w.dir().output();\n" -" w.input().disconnect();\n" -" w.pull().disabled();\n" -" w.drive().s0s1();\n" -" w.sense().disabled();\n" -" w\n" -" });\n" -" gpio0.pin_cnf[28].write(|w| {\n" -" w.dir().output();\n" -" w.input().disconnect();\n" -" w.pull().disabled();\n" -" w.drive().s0s1();\n" -" w.sense().disabled();\n" -" w\n" -" });\n" +"```java\n" +"class HelloWorld {\n" +" private static native String hello(String name);\n" "\n" -" // Set pin 28 low and pin 21 high to turn the LED on.\n" -" gpio0.outclr.write(|w| w.pin28().clear());\n" -" gpio0.outset.write(|w| w.pin21().set());\n" +" static {\n" +" System.loadLibrary(\"hello_jni\");\n" +" }\n" "\n" -" loop {}\n" +" public static void main(String[] args) {\n" +" String output = HelloWorld.hello(\"Alice\");\n" +" System.out.println(output);\n" +" }\n" "}\n" "```" msgstr "" -#: src/bare-metal/microcontrollers/pacs.md:49 +#: src/android/interoperability/java.md:64 msgid "" -"SVD (System View Description) files are XML files typically provided by " -"silicon vendors which describe the memory map of the device." +"```javascript\n" +"java_binary {\n" +" name: \"helloworld_jni\",\n" +" srcs: [\"HelloWorld.java\"],\n" +" main_class: \"HelloWorld\",\n" +" required: [\"libhello_jni\"],\n" +"}\n" +"```" msgstr "" -#: src/bare-metal/microcontrollers/pacs.md:51 -msgid "" -"They are organised by peripheral, register, field and value, with names, " -"descriptions, addresses and so on." +#: src/android/interoperability/java.md:73 +msgid "Finally, you can build, sync, and run the binary:" msgstr "" -#: src/bare-metal/microcontrollers/pacs.md:53 +#: src/android/interoperability/java.md:75 msgid "" -"SVD files are often buggy and incomplete, so there are various projects " -"which patch the mistakes, add missing details, and publish the generated " -"crates." -msgstr "" - -#: src/bare-metal/microcontrollers/pacs.md:55 -msgid "`cortex-m-rt` provides the vector table, among other things." +"```shell\n" +"m helloworld_jni\n" +"adb sync # requires adb root && adb remount\n" +"adb shell /system/bin/helloworld_jni\n" +"```" msgstr "" -#: src/bare-metal/microcontrollers/pacs.md:56 +#: src/exercises/android/morning.md:3 msgid "" -"If you `cargo install cargo-binutils` then you can run `cargo objdump --bin " -"pac -- -d --no-show-raw-insn` to see the resulting binary." +"This is a group exercise: We will look at one of the projects you work with " +"and try to integrate some Rust into it. Some suggestions:" msgstr "" -#: src/bare-metal/microcontrollers/pacs.md:61 -msgid "" -"```sh\n" -"cargo embed --bin pac\n" -"```" +#: src/exercises/android/morning.md:6 +msgid "Call your AIDL service with a client written in Rust." msgstr "" -#: src/bare-metal/microcontrollers/hals.md:1 -msgid "HAL crates" +#: src/exercises/android/morning.md:8 +msgid "Move a function from your project to Rust and call it." msgstr "" -#: src/bare-metal/microcontrollers/hals.md:3 +#: src/exercises/android/morning.md:12 msgid "" -"[HAL crates](https://github.com/rust-embedded/awesome-embedded-rust#hal-" -"implementation-crates) for many microcontrollers provide wrappers around " -"various peripherals. These generally implement traits from [`embedded-hal`]" -"(https://crates.io/crates/embedded-hal)." +"No solution is provided here since this is open-ended: it relies on someone " +"in the class having a piece of code which you can turn in to Rust on the fly." msgstr "" -#: src/bare-metal/microcontrollers/hals.md:7 -msgid "" -"```rust,editable,compile_fail\n" -"#![no_main]\n" -"#![no_std]\n" -"\n" -"extern crate panic_halt as _;\n" -"\n" -"use cortex_m_rt::entry;\n" -"use nrf52833_hal::gpio::{p0, Level};\n" -"use nrf52833_hal::pac::Peripherals;\n" -"use nrf52833_hal::prelude::*;\n" -"\n" -"#[entry]\n" -"fn main() -> ! {\n" -" let p = Peripherals::take().unwrap();\n" -"\n" -" // Create HAL wrapper for GPIO port 0.\n" -" let gpio0 = p0::Parts::new(p.P0);\n" -"\n" -" // Configure GPIO 0 pins 21 and 28 as push-pull outputs.\n" -" let mut col1 = gpio0.p0_28.into_push_pull_output(Level::High);\n" -" let mut row1 = gpio0.p0_21.into_push_pull_output(Level::Low);\n" -"\n" -" // Set pin 28 low and pin 21 high to turn the LED on.\n" -" col1.set_low().unwrap();\n" -" row1.set_high().unwrap();\n" -"\n" -" loop {}\n" -"}\n" -"```" +#: src/bare-metal.md:1 +msgid "Welcome to Bare Metal Rust" msgstr "" -#: src/bare-metal/microcontrollers/hals.md:39 +#: src/bare-metal.md:3 msgid "" -"`set_low` and `set_high` are methods on the `embedded_hal` `OutputPin` trait." +"This is a standalone one-day course about bare-metal Rust, aimed at people " +"who are familiar with the basics of Rust (perhaps from completing the " +"Comprehensive Rust course), and ideally also have some experience with bare-" +"metal programming in some other language such as C." msgstr "" -#: src/bare-metal/microcontrollers/hals.md:40 +#: src/bare-metal.md:7 msgid "" -"HAL crates exist for many Cortex-M and RISC-V devices, including various " -"STM32, GD32, nRF, NXP, MSP430, AVR and PIC microcontrollers." +"Today we will talk about 'bare-metal' Rust: running Rust code without an OS " +"underneath us. This will be divided into several parts:" msgstr "" -#: src/bare-metal/microcontrollers/hals.md:45 -msgid "" -"```sh\n" -"cargo embed --bin hal\n" -"```" +#: src/bare-metal.md:10 +msgid "What is `no_std` Rust?" msgstr "" -#: src/bare-metal/microcontrollers/board-support.md:1 -msgid "Board support crates" +#: src/bare-metal.md:11 +msgid "Writing firmware for microcontrollers." msgstr "" -#: src/bare-metal/microcontrollers/board-support.md:3 -msgid "" -"Board support crates provide a further level of wrapping for a specific " -"board for convenience." +#: src/bare-metal.md:12 +msgid "Writing bootloader / kernel code for application processors." msgstr "" -#: src/bare-metal/microcontrollers/board-support.md:5 +#: src/bare-metal.md:13 +msgid "Some useful crates for bare-metal Rust development." +msgstr "" + +#: src/bare-metal.md:15 msgid "" -"```rust,editable,compile_fail\n" -"#![no_main]\n" -"#![no_std]\n" -"\n" -"extern crate panic_halt as _;\n" -"\n" -"use cortex_m_rt::entry;\n" -"use microbit::hal::prelude::*;\n" -"use microbit::Board;\n" -"\n" -"#[entry]\n" -"fn main() -> ! {\n" -" let mut board = Board::take().unwrap();\n" -"\n" -" board.display_pins.col1.set_low().unwrap();\n" -" board.display_pins.row1.set_high().unwrap();\n" -"\n" -" loop {}\n" -"}\n" -"```" +"For the microcontroller part of the course we will use the [BBC micro:bit]" +"(https://microbit.org/) v2 as an example. It's a [development board](https://" +"tech.microbit.org/hardware/) based on the Nordic nRF51822 microcontroller " +"with some LEDs and buttons, an I2C-connected accelerometer and compass, and " +"an on-board SWD debugger." msgstr "" -#: src/bare-metal/microcontrollers/board-support.md:28 +#: src/bare-metal.md:20 msgid "" -"In this case the board support crate is just providing more useful names, " -"and a bit of initialisation." +"To get started, install some tools we'll need later. On gLinux or Debian:" msgstr "" -#: src/bare-metal/microcontrollers/board-support.md:30 +#: src/bare-metal.md:22 msgid "" -"The crate may also include drivers for some on-board devices outside of the " -"microcontroller itself." +"```bash\n" +"sudo apt install gcc-aarch64-linux-gnu gdb-multiarch libudev-dev picocom pkg-" +"config qemu-system-arm\n" +"rustup update\n" +"rustup target add aarch64-unknown-none thumbv7em-none-eabihf\n" +"rustup component add llvm-tools-preview\n" +"cargo install cargo-binutils cargo-embed\n" +"```" msgstr "" -#: src/bare-metal/microcontrollers/board-support.md:32 -msgid "`microbit-v2` includes a simple driver for the LED matrix." +#: src/bare-metal.md:30 +msgid "" +"And give users in the `plugdev` group access to the micro:bit programmer:" msgstr "" -#: src/bare-metal/microcontrollers/board-support.md:36 +#: src/bare-metal.md:32 msgid "" -"```sh\n" -"cargo embed --bin board_support\n" +"```bash\n" +"echo 'SUBSYSTEM==\"usb\", ATTR{idVendor}==\"0d28\", MODE=\"0664\", " +"GROUP=\"plugdev\"' |\\\n" +" sudo tee /etc/udev/rules.d/50-microbit.rules\n" +"sudo udevadm control --reload-rules\n" "```" msgstr "" -#: src/bare-metal/microcontrollers/type-state.md:1 -msgid "The type state pattern" +#: src/bare-metal.md:38 +msgid "On MacOS:" msgstr "" -#: src/bare-metal/microcontrollers/type-state.md:3 +#: src/bare-metal.md:40 msgid "" -"```rust,editable,compile_fail\n" -"#[entry]\n" -"fn main() -> ! {\n" -" let p = Peripherals::take().unwrap();\n" -" let gpio0 = p0::Parts::new(p.P0);\n" -"\n" -" let pin: P0_01 = gpio0.p0_01;\n" -"\n" -" // let gpio0_01_again = gpio0.p0_01; // Error, moved.\n" -" let pin_input: P0_01> = pin.into_floating_input();\n" -" if pin_input.is_high().unwrap() {\n" -" // ...\n" -" }\n" -" let mut pin_output: P0_01> = pin_input\n" -" .into_open_drain_output(OpenDrainConfig::Disconnect0Standard1, " -"Level::Low);\n" -" pin_output.set_high().unwrap();\n" -" // pin_input.is_high(); // Error, moved.\n" -"\n" -" let _pin2: P0_02> = gpio0\n" -" .p0_02\n" -" .into_open_drain_output(OpenDrainConfig::Disconnect0Standard1, " -"Level::Low);\n" -" let _pin3: P0_03> = gpio0.p0_03." -"into_push_pull_output(Level::Low);\n" -"\n" -" loop {}\n" -"}\n" +"```bash\n" +"xcode-select --install\n" +"brew install gdb picocom qemu\n" +"brew install --cask gcc-aarch64-embedded\n" +"rustup update\n" +"rustup target add aarch64-unknown-none thumbv7em-none-eabihf\n" +"rustup component add llvm-tools-preview\n" +"cargo install cargo-binutils cargo-embed\n" "```" msgstr "" -#: src/bare-metal/microcontrollers/type-state.md:32 -msgid "" -"Pins don't implement `Copy` or `Clone`, so only one instance of each can " -"exist. Once a pin is moved out of the port struct nobody else can take it." +#: src/bare-metal/no_std.md:1 +msgid "`no_std`" msgstr "" -#: src/bare-metal/microcontrollers/type-state.md:34 -msgid "" -"Changing the configuration of a pin consumes the old pin instance, so you " -"can’t keep use the old instance afterwards." +#: src/bare-metal/no_std.md:7 +msgid "`core`" msgstr "" -#: src/bare-metal/microcontrollers/type-state.md:36 -msgid "" -"The type of a value indicates the state that it is in: e.g. in this case, " -"the configuration state of a GPIO pin. This encodes the state machine into " -"the type system, and ensures that you don't try to use a pin in a certain " -"way without properly configuring it first. Illegal state transitions are " -"caught at compile time." +#: src/bare-metal/no_std.md:12 src/bare-metal/alloc.md:1 +msgid "`alloc`" msgstr "" -#: src/bare-metal/microcontrollers/type-state.md:40 -msgid "" -"You can call `is_high` on an input pin and `set_high` on an output pin, but " -"not vice-versa." +#: src/bare-metal/no_std.md:17 +msgid "`std`" msgstr "" -#: src/bare-metal/microcontrollers/type-state.md:41 -msgid "Many HAL crates follow this pattern." +#: src/bare-metal/no_std.md:24 +msgid "Slices, `&str`, `CStr`" msgstr "" -#: src/bare-metal/microcontrollers/embedded-hal.md:1 -msgid "`embedded-hal`" +#: src/bare-metal/no_std.md:25 +msgid "`NonZeroU8`..." msgstr "" -#: src/bare-metal/microcontrollers/embedded-hal.md:3 -msgid "" -"The [`embedded-hal`](https://crates.io/crates/embedded-hal) crate provides a " -"number of traits covering common microcontroller peripherals." +#: src/bare-metal/no_std.md:26 +msgid "`Option`, `Result`" msgstr "" -#: src/bare-metal/microcontrollers/embedded-hal.md:6 -msgid "GPIO" +#: src/bare-metal/no_std.md:27 +msgid "`Display`, `Debug`, `write!`..." msgstr "" -#: src/bare-metal/microcontrollers/embedded-hal.md:7 -msgid "ADC" +#: src/bare-metal/no_std.md:29 +msgid "`panic!`, `assert_eq!`..." msgstr "" -#: src/bare-metal/microcontrollers/embedded-hal.md:8 -msgid "I2C, SPI, UART, CAN" +#: src/bare-metal/no_std.md:30 +msgid "`NonNull` and all the usual pointer-related functions" msgstr "" -#: src/bare-metal/microcontrollers/embedded-hal.md:9 -msgid "RNG" +#: src/bare-metal/no_std.md:31 +msgid "`Future` and `async`/`await`" msgstr "" -#: src/bare-metal/microcontrollers/embedded-hal.md:10 -msgid "Timers" +#: src/bare-metal/no_std.md:32 +msgid "`fence`, `AtomicBool`, `AtomicPtr`, `AtomicU32`..." msgstr "" -#: src/bare-metal/microcontrollers/embedded-hal.md:11 -msgid "Watchdogs" +#: src/bare-metal/no_std.md:33 +msgid "`Duration`" msgstr "" -#: src/bare-metal/microcontrollers/embedded-hal.md:13 -msgid "" -"Other crates then implement [drivers](https://github.com/rust-embedded/" -"awesome-embedded-rust#driver-crates) in terms of these traits, e.g. an " -"accelerometer driver might need an I2C or SPI bus implementation." +#: src/bare-metal/no_std.md:38 +msgid "`Box`, `Cow`, `Arc`, `Rc`" msgstr "" -#: src/bare-metal/microcontrollers/embedded-hal.md:19 -msgid "" -"There are implementations for many microcontrollers, as well as other " -"platforms such as Linux on Raspberry Pi." +#: src/bare-metal/no_std.md:39 +msgid "`Vec`, `BinaryHeap`, `BtreeMap`, `LinkedList`, `VecDeque`" msgstr "" -#: src/bare-metal/microcontrollers/embedded-hal.md:21 -msgid "" -"There is work in progress on an `async` version of `embedded-hal`, but it " -"isn't stable yet." +#: src/bare-metal/no_std.md:40 +msgid "`String`, `CString`, `format!`" msgstr "" -#: src/bare-metal/microcontrollers/probe-rs.md:1 -msgid "`probe-rs`, `cargo-embed`" +#: src/bare-metal/no_std.md:45 +msgid "`Error`" msgstr "" -#: src/bare-metal/microcontrollers/probe-rs.md:3 -msgid "" -"[probe-rs](https://probe.rs/) is a handy toolset for embedded debugging, " -"like OpenOCD but better integrated." +#: src/bare-metal/no_std.md:47 +msgid "`Mutex`, `Condvar`, `Barrier`, `Once`, `RwLock`, `mpsc`" msgstr "" -#: src/bare-metal/microcontrollers/probe-rs.md:6 -msgid "SWD" +#: src/bare-metal/no_std.md:48 +msgid "`File` and the rest of `fs`" msgstr "" -#: src/bare-metal/microcontrollers/probe-rs.md:6 -msgid " and JTAG via CMSIS-DAP, ST-Link and J-Link probes" +#: src/bare-metal/no_std.md:49 +msgid "`println!`, `Read`, `Write`, `Stdin`, `Stdout` and the rest of `io`" msgstr "" -#: src/bare-metal/microcontrollers/probe-rs.md:7 -msgid "GDB stub and Microsoft " +#: src/bare-metal/no_std.md:50 +msgid "`Path`, `OsString`" msgstr "" -#: src/bare-metal/microcontrollers/probe-rs.md:7 -msgid "DAP" +#: src/bare-metal/no_std.md:51 +msgid "`net`" msgstr "" -#: src/bare-metal/microcontrollers/probe-rs.md:7 -msgid " server" +#: src/bare-metal/no_std.md:52 +msgid "`Command`, `Child`, `ExitCode`" msgstr "" -#: src/bare-metal/microcontrollers/probe-rs.md:8 -msgid "Cargo integration" +#: src/bare-metal/no_std.md:53 +msgid "`spawn`, `sleep` and the rest of `thread`" msgstr "" -#: src/bare-metal/microcontrollers/probe-rs.md:10 -msgid "`cargo-embed` is a cargo subcommand to build and flash binaries, log " +#: src/bare-metal/no_std.md:54 +msgid "`SystemTime`, `Instant`" msgstr "" -#: src/bare-metal/microcontrollers/probe-rs.md:11 -msgid "RTT" +#: src/bare-metal/no_std.md:62 +msgid "`HashMap` depends on RNG." msgstr "" -#: src/bare-metal/microcontrollers/probe-rs.md:11 -msgid "" -" output and connect GDB. It's configured by an `Embed.toml` file in your " -"project directory." +#: src/bare-metal/no_std.md:63 +msgid "`std` re-exports the contents of both `core` and `alloc`." msgstr "" -#: src/bare-metal/microcontrollers/probe-rs.md:16 -msgid "" -"[CMSIS-DAP](https://arm-software.github.io/CMSIS_5/DAP/html/index.html) is " -"an Arm standard protocol over USB for an in-circuit debugger to access the " -"CoreSight Debug Access Port of various Arm Cortex processors. It's what the " -"on-board debugger on the BBC micro:bit uses." +#: src/bare-metal/minimal.md:1 +msgid "A minimal `no_std` program" msgstr "" -#: src/bare-metal/microcontrollers/probe-rs.md:19 +#: src/bare-metal/minimal.md:3 msgid "" -"ST-Link is a range of in-circuit debuggers from ST Microelectronics, J-Link " -"is a range from SEGGER." +"```rust,editable,compile_fail\n" +"#![no_main]\n" +"#![no_std]\n" +"\n" +"use core::panic::PanicInfo;\n" +"\n" +"#[panic_handler]\n" +"fn panic(_panic: &PanicInfo) -> ! {\n" +" loop {}\n" +"}\n" +"```" msgstr "" -#: src/bare-metal/microcontrollers/probe-rs.md:21 -msgid "" -"The Debug Access Port is usually either a 5-pin JTAG interface or 2-pin " -"Serial Wire Debug." +#: src/bare-metal/minimal.md:17 +msgid "This will compile to an empty binary." msgstr "" -#: src/bare-metal/microcontrollers/probe-rs.md:22 -msgid "" -"probe-rs is a library which you can integrate into your own tools if you " -"want to." +#: src/bare-metal/minimal.md:18 +msgid "`std` provides a panic handler; without it we must provide our own." msgstr "" -#: src/bare-metal/microcontrollers/probe-rs.md:23 -msgid "" -"The [Microsoft Debug Adapter Protocol](https://microsoft.github.io/debug-" -"adapter-protocol/) lets VSCode and other IDEs debug code running on any " -"supported microcontroller." +#: src/bare-metal/minimal.md:19 +msgid "It can also be provided by another crate, such as `panic-halt`." msgstr "" -#: src/bare-metal/microcontrollers/probe-rs.md:25 -msgid "cargo-embed is a binary built using the probe-rs library." +#: src/bare-metal/minimal.md:20 +msgid "" +"Depending on the target, you may need to compile with `panic = \"abort\"` to " +"avoid an error about `eh_personality`." msgstr "" -#: src/bare-metal/microcontrollers/probe-rs.md:26 +#: src/bare-metal/minimal.md:22 msgid "" -"RTT (Real Time Transfers) is a mechanism to transfer data between the debug " -"host and the target through a number of ringbuffers." +"Note that there is no `main` or any other entry point; it's up to you to " +"define your own entry point. This will typically involve a linker script and " +"some assembly code to set things up ready for Rust code to run." msgstr "" -#: src/bare-metal/microcontrollers/debugging.md:3 -msgid "Embed.toml:" +#: src/bare-metal/alloc.md:3 +msgid "" +"To use `alloc` you must implement a [global (heap) allocator](https://doc." +"rust-lang.org/stable/std/alloc/trait.GlobalAlloc.html)." msgstr "" -#: src/bare-metal/microcontrollers/debugging.md:5 +#: src/bare-metal/alloc.md:6 msgid "" -"```toml\n" -"[default.general]\n" -"chip = \"nrf52833_xxAA\"\n" +"```rust,editable,compile_fail\n" +"#![no_main]\n" +"#![no_std]\n" "\n" -"[debug.gdb]\n" -"enabled = true\n" +"extern crate alloc;\n" +"extern crate panic_halt as _;\n" +"\n" +"use alloc::string::ToString;\n" +"use alloc::vec::Vec;\n" +"use buddy_system_allocator::LockedHeap;\n" +"\n" +"#[global_allocator]\n" +"static HEAP_ALLOCATOR: LockedHeap<32> = LockedHeap::<32>::new();\n" +"\n" +"static mut HEAP: [u8; 65536] = [0; 65536];\n" +"\n" +"pub fn entry() {\n" +" // Safe because `HEAP` is only used here and `entry` is only called " +"once.\n" +" unsafe {\n" +" // Give the allocator some memory to allocate.\n" +" HEAP_ALLOCATOR\n" +" .lock()\n" +" .init(HEAP.as_mut_ptr() as usize, HEAP.len());\n" +" }\n" +"\n" +" // Now we can do things that require heap allocation.\n" +" let mut v = Vec::new();\n" +" v.push(\"A string\".to_string());\n" +"}\n" "```" msgstr "" -#: src/bare-metal/microcontrollers/debugging.md:13 -msgid "In one terminal under `src/bare-metal/microcontrollers/examples/`:" +#: src/bare-metal/alloc.md:39 +msgid "" +"`buddy_system_allocator` is a third-party crate implementing a basic buddy " +"system allocator. Other crates are available, or you can write your own or " +"hook into your existing allocator." msgstr "" -#: src/bare-metal/microcontrollers/debugging.md:15 +#: src/bare-metal/alloc.md:41 msgid "" -"```sh\n" -"cargo embed --bin board_support debug\n" -"```" +"The const parameter of `LockedHeap` is the max order of the allocator; i.e. " +"in this case it can allocate regions of up to 2\\*\\*32 bytes." msgstr "" -#: src/bare-metal/microcontrollers/debugging.md:19 -msgid "In another terminal in the same directory:" +#: src/bare-metal/alloc.md:43 +msgid "" +"If any crate in your dependency tree depends on `alloc` then you must have " +"exactly one global allocator defined in your binary. Usually this is done in " +"the top-level binary crate." msgstr "" -#: src/bare-metal/microcontrollers/debugging.md:21 +#: src/bare-metal/alloc.md:45 msgid "" -"```sh\n" -"gdb-multiarch target/thumbv7em-none-eabihf/debug/board_support --eval-" -"command=\"target remote :1337\"\n" -"```" +"`extern crate panic_halt as _` is necessary to ensure that the `panic_halt` " +"crate is linked in so we get its panic handler." msgstr "" -#: src/bare-metal/microcontrollers/debugging.md:27 -msgid "In GDB, try running:" +#: src/bare-metal/alloc.md:47 +msgid "This example will build but not run, as it doesn't have an entry point." msgstr "" -#: src/bare-metal/microcontrollers/debugging.md:29 +#: src/bare-metal/microcontrollers.md:3 msgid "" -"```gdb\n" -"b src/bin/board_support.rs:29\n" -"b src/bin/board_support.rs:30\n" -"b src/bin/board_support.rs:32\n" -"c\n" -"c\n" -"c\n" -"```" -msgstr "" - -#: src/bare-metal/microcontrollers/other-projects.md:1 -#: src/bare-metal/aps/other-projects.md:1 -msgid "Other projects" +"The `cortex_m_rt` crate provides (among other things) a reset handler for " +"Cortex M microcontrollers." msgstr "" -#: src/bare-metal/microcontrollers/other-projects.md:3 -msgid "[RTIC](https://rtic.rs/)" +#: src/bare-metal/microcontrollers.md:5 +msgid "" +"```rust,editable,compile_fail\n" +"#![no_main]\n" +"#![no_std]\n" +"\n" +"extern crate panic_halt as _;\n" +"\n" +"mod interrupts;\n" +"\n" +"use cortex_m_rt::entry;\n" +"\n" +"#[entry]\n" +"fn main() -> ! {\n" +" loop {}\n" +"}\n" +"```" msgstr "" -#: src/bare-metal/microcontrollers/other-projects.md:4 -msgid "\"Real-Time Interrupt-driven Concurrency\"" +#: src/bare-metal/microcontrollers.md:21 +msgid "" +"Next we'll look at how to access peripherals, with increasing levels of " +"abstraction." msgstr "" -#: src/bare-metal/microcontrollers/other-projects.md:5 +#: src/bare-metal/microcontrollers.md:25 msgid "" -"Shared resource management, message passing, task scheduling, timer queue" +"The `cortex_m_rt::entry` macro requires that the function have type `fn() -" +"> !`, because returning to the reset handler doesn't make sense." msgstr "" -#: src/bare-metal/microcontrollers/other-projects.md:6 -msgid "[Embassy](https://embassy.dev/)" +#: src/bare-metal/microcontrollers.md:27 +msgid "Run the example with `cargo embed --bin minimal`" msgstr "" -#: src/bare-metal/microcontrollers/other-projects.md:7 -msgid "`async` executors with priorities, timers, networking, USB" +#: src/bare-metal/microcontrollers/mmio.md:3 +msgid "" +"Most microcontrollers access peripherals via memory-mapped IO. Let's try " +"turning on an LED on our micro:bit:" msgstr "" -#: src/bare-metal/microcontrollers/other-projects.md:8 -msgid "[TockOS](https://www.tockos.org/documentation/getting-started)" +#: src/bare-metal/microcontrollers/mmio.md:6 +msgid "" +"```rust,editable,compile_fail\n" +"#![no_main]\n" +"#![no_std]\n" +"\n" +"extern crate panic_halt as _;\n" +"\n" +"mod interrupts;\n" +"\n" +"use core::mem::size_of;\n" +"use cortex_m_rt::entry;\n" +"\n" +"/// GPIO port 0 peripheral address\n" +"const GPIO_P0: usize = 0x5000_0000;\n" +"\n" +"// GPIO peripheral offsets\n" +"const PIN_CNF: usize = 0x700;\n" +"const OUTSET: usize = 0x508;\n" +"const OUTCLR: usize = 0x50c;\n" +"\n" +"// PIN_CNF fields\n" +"const DIR_OUTPUT: u32 = 0x1;\n" +"const INPUT_DISCONNECT: u32 = 0x1 << 1;\n" +"const PULL_DISABLED: u32 = 0x0 << 2;\n" +"const DRIVE_S0S1: u32 = 0x0 << 8;\n" +"const SENSE_DISABLED: u32 = 0x0 << 16;\n" +"\n" +"#[entry]\n" +"fn main() -> ! {\n" +" // Configure GPIO 0 pins 21 and 28 as push-pull outputs.\n" +" let pin_cnf_21 = (GPIO_P0 + PIN_CNF + 21 * size_of::()) as *mut " +"u32;\n" +" let pin_cnf_28 = (GPIO_P0 + PIN_CNF + 28 * size_of::()) as *mut " +"u32;\n" +" // Safe because the pointers are to valid peripheral control registers, " +"and\n" +" // no aliases exist.\n" +" unsafe {\n" +" pin_cnf_21.write_volatile(\n" +" DIR_OUTPUT | INPUT_DISCONNECT | PULL_DISABLED | DRIVE_S0S1 | " +"SENSE_DISABLED,\n" +" );\n" +" pin_cnf_28.write_volatile(\n" +" DIR_OUTPUT | INPUT_DISCONNECT | PULL_DISABLED | DRIVE_S0S1 | " +"SENSE_DISABLED,\n" +" );\n" +" }\n" +"\n" +" // Set pin 28 low and pin 21 high to turn the LED on.\n" +" let gpio0_outset = (GPIO_P0 + OUTSET) as *mut u32;\n" +" let gpio0_outclr = (GPIO_P0 + OUTCLR) as *mut u32;\n" +" // Safe because the pointers are to valid peripheral control registers, " +"and\n" +" // no aliases exist.\n" +" unsafe {\n" +" gpio0_outclr.write_volatile(1 << 28);\n" +" gpio0_outset.write_volatile(1 << 21);\n" +" }\n" +"\n" +" loop {}\n" +"}\n" +"```" msgstr "" -#: src/bare-metal/microcontrollers/other-projects.md:9 +#: src/bare-metal/microcontrollers/mmio.md:64 msgid "" -"Security-focused RTOS with preemptive scheduling and Memory Protection Unit " -"support" +"GPIO 0 pin 21 is connected to the first column of the LED matrix, and pin 28 " +"to the first row." msgstr "" -#: src/bare-metal/microcontrollers/other-projects.md:10 -msgid "[Hubris](https://hubris.oxide.computer/)" +#: src/bare-metal/microcontrollers/mmio.md:66 +#: src/bare-metal/microcontrollers/pacs.md:59 +#: src/bare-metal/microcontrollers/hals.md:43 +#: src/bare-metal/microcontrollers/board-support.md:34 +msgid "Run the example with:" msgstr "" -#: src/bare-metal/microcontrollers/other-projects.md:11 +#: src/bare-metal/microcontrollers/mmio.md:68 msgid "" -"Microkernel RTOS from Oxide Computer Company with memory protection, " -"unprivileged drivers, IPC" +"```sh\n" +"cargo embed --bin mmio\n" +"```" msgstr "" -#: src/bare-metal/microcontrollers/other-projects.md:12 -msgid "[Bindings for FreeRTOS](https://github.com/lobaro/FreeRTOS-rust)" +#: src/bare-metal/microcontrollers/pacs.md:1 +msgid "Peripheral Access Crates" msgstr "" -#: src/bare-metal/microcontrollers/other-projects.md:13 +#: src/bare-metal/microcontrollers/pacs.md:3 msgid "" -"Some platforms have `std` implementations, e.g. [esp-idf](https://esp-rs." -"github.io/book/overview/using-the-standard-library.html)." -msgstr "" - -#: src/bare-metal/microcontrollers/other-projects.md:18 -msgid "RTIC can be considered either an RTOS or a concurrency framework." +"[`svd2rust`](https://crates.io/crates/svd2rust) generates mostly-safe Rust " +"wrappers for memory-mapped peripherals from [CMSIS-SVD](https://www.keil.com/" +"pack/doc/CMSIS/SVD/html/index.html) files." msgstr "" -#: src/bare-metal/microcontrollers/other-projects.md:19 -msgid "It doesn't include any HALs." +#: src/bare-metal/microcontrollers/pacs.md:7 +msgid "" +"```rust,editable,compile_fail\n" +"#![no_main]\n" +"#![no_std]\n" +"\n" +"extern crate panic_halt as _;\n" +"\n" +"use cortex_m_rt::entry;\n" +"use nrf52833_pac::Peripherals;\n" +"\n" +"#[entry]\n" +"fn main() -> ! {\n" +" let p = Peripherals::take().unwrap();\n" +" let gpio0 = p.P0;\n" +"\n" +" // Configure GPIO 0 pins 21 and 28 as push-pull outputs.\n" +" gpio0.pin_cnf[21].write(|w| {\n" +" w.dir().output();\n" +" w.input().disconnect();\n" +" w.pull().disabled();\n" +" w.drive().s0s1();\n" +" w.sense().disabled();\n" +" w\n" +" });\n" +" gpio0.pin_cnf[28].write(|w| {\n" +" w.dir().output();\n" +" w.input().disconnect();\n" +" w.pull().disabled();\n" +" w.drive().s0s1();\n" +" w.sense().disabled();\n" +" w\n" +" });\n" +"\n" +" // Set pin 28 low and pin 21 high to turn the LED on.\n" +" gpio0.outclr.write(|w| w.pin28().clear());\n" +" gpio0.outset.write(|w| w.pin21().set());\n" +"\n" +" loop {}\n" +"}\n" +"```" msgstr "" -#: src/bare-metal/microcontrollers/other-projects.md:20 +#: src/bare-metal/microcontrollers/pacs.md:49 msgid "" -"It uses the Cortex-M NVIC (Nested Virtual Interrupt Controller) for " -"scheduling rather than a proper kernel." +"SVD (System View Description) files are XML files typically provided by " +"silicon vendors which describe the memory map of the device." msgstr "" -#: src/bare-metal/microcontrollers/other-projects.md:22 -msgid "Cortex-M only." +#: src/bare-metal/microcontrollers/pacs.md:51 +msgid "" +"They are organised by peripheral, register, field and value, with names, " +"descriptions, addresses and so on." msgstr "" -#: src/bare-metal/microcontrollers/other-projects.md:23 +#: src/bare-metal/microcontrollers/pacs.md:53 msgid "" -"Google uses TockOS on the Haven microcontroller for Titan security keys." +"SVD files are often buggy and incomplete, so there are various projects " +"which patch the mistakes, add missing details, and publish the generated " +"crates." msgstr "" -#: src/bare-metal/microcontrollers/other-projects.md:24 -msgid "" -"FreeRTOS is mostly written in C, but there are Rust bindings for writing " -"applications." +#: src/bare-metal/microcontrollers/pacs.md:55 +msgid "`cortex-m-rt` provides the vector table, among other things." msgstr "" -#: src/exercises/bare-metal/morning.md:3 +#: src/bare-metal/microcontrollers/pacs.md:56 msgid "" -"We will read the direction from an I2C compass, and log the readings to a " -"serial port." +"If you `cargo install cargo-binutils` then you can run `cargo objdump --bin " +"pac -- -d --no-show-raw-insn` to see the resulting binary." msgstr "" -#: src/exercises/bare-metal/compass.md:3 +#: src/bare-metal/microcontrollers/pacs.md:61 msgid "" -"We will read the direction from an I2C compass, and log the readings to a " -"serial port. If you have time, try displaying it on the LEDs somehow too, or " -"use the buttons somehow." +"```sh\n" +"cargo embed --bin pac\n" +"```" msgstr "" -#: src/exercises/bare-metal/compass.md:6 -msgid "Hints:" +#: src/bare-metal/microcontrollers/hals.md:1 +msgid "HAL crates" msgstr "" -#: src/exercises/bare-metal/compass.md:8 +#: src/bare-metal/microcontrollers/hals.md:3 msgid "" -"Check the documentation for the [`lsm303agr`](https://docs.rs/lsm303agr/" -"latest/lsm303agr/) and [`microbit-v2`](https://docs.rs/microbit-v2/latest/" -"microbit/) crates, as well as the [micro:bit hardware](https://tech.microbit." -"org/hardware/)." +"[HAL crates](https://github.com/rust-embedded/awesome-embedded-rust#hal-" +"implementation-crates) for many microcontrollers provide wrappers around " +"various peripherals. These generally implement traits from [`embedded-hal`]" +"(https://crates.io/crates/embedded-hal)." msgstr "" -#: src/exercises/bare-metal/compass.md:11 +#: src/bare-metal/microcontrollers/hals.md:7 msgid "" -"The LSM303AGR Inertial Measurement Unit is connected to the internal I2C bus." +"```rust,editable,compile_fail\n" +"#![no_main]\n" +"#![no_std]\n" +"\n" +"extern crate panic_halt as _;\n" +"\n" +"use cortex_m_rt::entry;\n" +"use nrf52833_hal::gpio::{p0, Level};\n" +"use nrf52833_hal::pac::Peripherals;\n" +"use nrf52833_hal::prelude::*;\n" +"\n" +"#[entry]\n" +"fn main() -> ! {\n" +" let p = Peripherals::take().unwrap();\n" +"\n" +" // Create HAL wrapper for GPIO port 0.\n" +" let gpio0 = p0::Parts::new(p.P0);\n" +"\n" +" // Configure GPIO 0 pins 21 and 28 as push-pull outputs.\n" +" let mut col1 = gpio0.p0_28.into_push_pull_output(Level::High);\n" +" let mut row1 = gpio0.p0_21.into_push_pull_output(Level::Low);\n" +"\n" +" // Set pin 28 low and pin 21 high to turn the LED on.\n" +" col1.set_low().unwrap();\n" +" row1.set_high().unwrap();\n" +"\n" +" loop {}\n" +"}\n" +"```" msgstr "" -#: src/exercises/bare-metal/compass.md:12 +#: src/bare-metal/microcontrollers/hals.md:39 msgid "" -"TWI is another name for I2C, so the I2C master peripheral is called TWIM." +"`set_low` and `set_high` are methods on the `embedded_hal` `OutputPin` trait." msgstr "" -#: src/exercises/bare-metal/compass.md:13 +#: src/bare-metal/microcontrollers/hals.md:40 msgid "" -"The LSM303AGR driver needs something implementing the `embedded_hal::" -"blocking::i2c::WriteRead` trait. The [`microbit::hal::Twim`](https://docs.rs/" -"microbit-v2/latest/microbit/hal/struct.Twim.html) struct implements this." +"HAL crates exist for many Cortex-M and RISC-V devices, including various " +"STM32, GD32, nRF, NXP, MSP430, AVR and PIC microcontrollers." msgstr "" -#: src/exercises/bare-metal/compass.md:17 +#: src/bare-metal/microcontrollers/hals.md:45 msgid "" -"You have a [`microbit::Board`](https://docs.rs/microbit-v2/latest/microbit/" -"struct.Board.html) struct with fields for the various pins and peripherals." +"```sh\n" +"cargo embed --bin hal\n" +"```" msgstr "" -#: src/exercises/bare-metal/compass.md:19 -msgid "" -"You can also look at the [nRF52833 datasheet](https://infocenter.nordicsemi." -"com/pdf/nRF52833_PS_v1.5.pdf) if you want, but it shouldn't be necessary for " -"this exercise." +#: src/bare-metal/microcontrollers/board-support.md:1 +msgid "Board support crates" msgstr "" -#: src/exercises/bare-metal/compass.md:23 +#: src/bare-metal/microcontrollers/board-support.md:3 msgid "" -"Download the [exercise template](../../comprehensive-rust-exercises.zip) and " -"look in the `compass` directory for the following files." -msgstr "" - -#: src/exercises/bare-metal/compass.md:26 src/exercises/bare-metal/rtc.md:19 -msgid "`src/main.rs`:" +"Board support crates provide a further level of wrapping for a specific " +"board for convenience." msgstr "" -#: src/exercises/bare-metal/compass.md:30 +#: src/bare-metal/microcontrollers/board-support.md:5 msgid "" -"```rust,compile_fail\n" +"```rust,editable,compile_fail\n" "#![no_main]\n" "#![no_std]\n" "\n" "extern crate panic_halt as _;\n" "\n" -"use core::fmt::Write;\n" "use cortex_m_rt::entry;\n" -"use microbit::{hal::uarte::{Baudrate, Parity, Uarte}, Board};\n" +"use microbit::hal::prelude::*;\n" +"use microbit::Board;\n" "\n" "#[entry]\n" "fn main() -> ! {\n" -" let board = Board::take().unwrap();\n" -"\n" -" // Configure serial port.\n" -" let mut serial = Uarte::new(\n" -" board.UARTE0,\n" -" board.uart.into(),\n" -" Parity::EXCLUDED,\n" -" Baudrate::BAUD115200,\n" -" );\n" -"\n" -" // Set up the I2C controller and Inertial Measurement Unit.\n" -" // TODO\n" +" let mut board = Board::take().unwrap();\n" "\n" -" writeln!(serial, \"Ready.\").unwrap();\n" +" board.display_pins.col1.set_low().unwrap();\n" +" board.display_pins.row1.set_high().unwrap();\n" "\n" -" loop {\n" -" // Read compass data and log it to the serial port.\n" -" // TODO\n" -" }\n" +" loop {}\n" "}\n" "```" msgstr "" -#: src/exercises/bare-metal/compass.md:64 src/exercises/bare-metal/rtc.md:385 -msgid "`Cargo.toml` (you shouldn't need to change this):" +#: src/bare-metal/microcontrollers/board-support.md:28 +msgid "" +"In this case the board support crate is just providing more useful names, " +"and a bit of initialisation." msgstr "" -#: src/exercises/bare-metal/compass.md:68 +#: src/bare-metal/microcontrollers/board-support.md:30 msgid "" -"```toml\n" -"[workspace]\n" -"\n" -"[package]\n" -"name = \"compass\"\n" -"version = \"0.1.0\"\n" -"edition = \"2021\"\n" -"publish = false\n" -"\n" -"[dependencies]\n" -"cortex-m-rt = \"0.7.3\"\n" -"embedded-hal = \"0.2.6\"\n" -"lsm303agr = \"0.2.2\"\n" -"microbit-v2 = \"0.13.0\"\n" -"panic-halt = \"0.2.0\"\n" -"```" +"The crate may also include drivers for some on-board devices outside of the " +"microcontroller itself." msgstr "" -#: src/exercises/bare-metal/compass.md:85 -msgid "`Embed.toml` (you shouldn't need to change this):" +#: src/bare-metal/microcontrollers/board-support.md:32 +msgid "`microbit-v2` includes a simple driver for the LED matrix." msgstr "" -#: src/exercises/bare-metal/compass.md:89 +#: src/bare-metal/microcontrollers/board-support.md:36 msgid "" -"```toml\n" -"[default.general]\n" -"chip = \"nrf52833_xxAA\"\n" -"\n" -"[debug.gdb]\n" -"enabled = true\n" -"\n" -"[debug.reset]\n" -"halt_afterwards = true\n" +"```sh\n" +"cargo embed --bin board_support\n" "```" msgstr "" -#: src/exercises/bare-metal/compass.md:100 src/exercises/bare-metal/rtc.md:985 -msgid "`.cargo/config.toml` (you shouldn't need to change this):" +#: src/bare-metal/microcontrollers/type-state.md:1 +msgid "The type state pattern" msgstr "" -#: src/exercises/bare-metal/compass.md:104 +#: src/bare-metal/microcontrollers/type-state.md:3 msgid "" -"```toml\n" -"[build]\n" -"target = \"thumbv7em-none-eabihf\" # Cortex-M4F\n" +"```rust,editable,compile_fail\n" +"#[entry]\n" +"fn main() -> ! {\n" +" let p = Peripherals::take().unwrap();\n" +" let gpio0 = p0::Parts::new(p.P0);\n" "\n" -"[target.'cfg(all(target_arch = \"arm\", target_os = \"none\"))']\n" -"rustflags = [\"-C\", \"link-arg=-Tlink.x\"]\n" -"```" +" let pin: P0_01 = gpio0.p0_01;\n" +"\n" +" // let gpio0_01_again = gpio0.p0_01; // Error, moved.\n" +" let pin_input: P0_01> = pin.into_floating_input();\n" +" if pin_input.is_high().unwrap() {\n" +" // ...\n" +" }\n" +" let mut pin_output: P0_01> = pin_input\n" +" .into_open_drain_output(OpenDrainConfig::Disconnect0Standard1, " +"Level::Low);\n" +" pin_output.set_high().unwrap();\n" +" // pin_input.is_high(); // Error, moved.\n" +"\n" +" let _pin2: P0_02> = gpio0\n" +" .p0_02\n" +" .into_open_drain_output(OpenDrainConfig::Disconnect0Standard1, " +"Level::Low);\n" +" let _pin3: P0_03> = gpio0.p0_03." +"into_push_pull_output(Level::Low);\n" +"\n" +" loop {}\n" +"}\n" +"```" msgstr "" -#: src/exercises/bare-metal/compass.md:112 -msgid "See the serial output on Linux with:" +#: src/bare-metal/microcontrollers/type-state.md:32 +msgid "" +"Pins don't implement `Copy` or `Clone`, so only one instance of each can " +"exist. Once a pin is moved out of the port struct nobody else can take it." msgstr "" -#: src/exercises/bare-metal/compass.md:114 +#: src/bare-metal/microcontrollers/type-state.md:34 msgid "" -"```sh\n" -"picocom --baud 115200 --imap lfcrlf /dev/ttyACM0\n" -"```" +"Changing the configuration of a pin consumes the old pin instance, so you " +"can’t keep use the old instance afterwards." msgstr "" -#: src/exercises/bare-metal/compass.md:118 +#: src/bare-metal/microcontrollers/type-state.md:36 msgid "" -"Or on Mac OS something like (the device name may be slightly different):" +"The type of a value indicates the state that it is in: e.g. in this case, " +"the configuration state of a GPIO pin. This encodes the state machine into " +"the type system, and ensures that you don't try to use a pin in a certain " +"way without properly configuring it first. Illegal state transitions are " +"caught at compile time." msgstr "" -#: src/exercises/bare-metal/compass.md:120 +#: src/bare-metal/microcontrollers/type-state.md:40 msgid "" -"```sh\n" -"picocom --baud 115200 --imap lfcrlf /dev/tty.usbmodem14502\n" -"```" +"You can call `is_high` on an input pin and `set_high` on an output pin, but " +"not vice-versa." msgstr "" -#: src/exercises/bare-metal/compass.md:124 -msgid "Use Ctrl+A Ctrl+Q to quit picocom." +#: src/bare-metal/microcontrollers/type-state.md:41 +msgid "Many HAL crates follow this pattern." msgstr "" -#: src/bare-metal/aps.md:1 -msgid "Application processors" +#: src/bare-metal/microcontrollers/embedded-hal.md:1 +msgid "`embedded-hal`" msgstr "" -#: src/bare-metal/aps.md:3 +#: src/bare-metal/microcontrollers/embedded-hal.md:3 msgid "" -"So far we've talked about microcontrollers, such as the Arm Cortex-M series. " -"Now let's try writing something for Cortex-A. For simplicity we'll just work " -"with QEMU's aarch64 ['virt'](https://qemu-project.gitlab.io/qemu/system/arm/" -"virt.html) board." +"The [`embedded-hal`](https://crates.io/crates/embedded-hal) crate provides a " +"number of traits covering common microcontroller peripherals." msgstr "" -#: src/bare-metal/aps.md:9 -msgid "" -"Broadly speaking, microcontrollers don't have an MMU or multiple levels of " -"privilege (exception levels on Arm CPUs, rings on x86), while application " -"processors do." +#: src/bare-metal/microcontrollers/embedded-hal.md:6 +msgid "GPIO" msgstr "" -#: src/bare-metal/aps.md:11 -msgid "" -"QEMU supports emulating various different machines or board models for each " -"architecture. The 'virt' board doesn't correspond to any particular real " -"hardware, but is designed purely for virtual machines." +#: src/bare-metal/microcontrollers/embedded-hal.md:7 +msgid "ADC" msgstr "" -#: src/bare-metal/aps/inline-assembly.md:1 -msgid "Inline assembly" +#: src/bare-metal/microcontrollers/embedded-hal.md:8 +msgid "I2C, SPI, UART, CAN" msgstr "" -#: src/bare-metal/aps/inline-assembly.md:3 -msgid "" -"Sometimes we need to use assembly to do things that aren't possible with " -"Rust code. For example, to make an " +#: src/bare-metal/microcontrollers/embedded-hal.md:9 +msgid "RNG" msgstr "" -#: src/bare-metal/aps/inline-assembly.md:4 -msgid "HVC" +#: src/bare-metal/microcontrollers/embedded-hal.md:10 +msgid "Timers" msgstr "" -#: src/bare-metal/aps/inline-assembly.md:4 -msgid " to tell the firmware to power off the system:" +#: src/bare-metal/microcontrollers/embedded-hal.md:11 +msgid "Watchdogs" msgstr "" -#: src/bare-metal/aps/inline-assembly.md:6 +#: src/bare-metal/microcontrollers/embedded-hal.md:13 msgid "" -"```rust,editable,compile_fail\n" -"#![no_main]\n" -"#![no_std]\n" -"\n" -"use core::arch::asm;\n" -"use core::panic::PanicInfo;\n" -"\n" -"mod exceptions;\n" -"\n" -"const PSCI_SYSTEM_OFF: u32 = 0x84000008;\n" -"\n" -"#[no_mangle]\n" -"extern \"C\" fn main(_x0: u64, _x1: u64, _x2: u64, _x3: u64) {\n" -" // Safe because this only uses the declared registers and doesn't do\n" -" // anything with memory.\n" -" unsafe {\n" -" asm!(\"hvc #0\",\n" -" inout(\"w0\") PSCI_SYSTEM_OFF => _,\n" -" inout(\"w1\") 0 => _,\n" -" inout(\"w2\") 0 => _,\n" -" inout(\"w3\") 0 => _,\n" -" inout(\"w4\") 0 => _,\n" -" inout(\"w5\") 0 => _,\n" -" inout(\"w6\") 0 => _,\n" -" inout(\"w7\") 0 => _,\n" -" options(nomem, nostack)\n" -" );\n" -" }\n" -"\n" -" loop {}\n" -"}\n" -"```" +"Other crates then implement [drivers](https://github.com/rust-embedded/" +"awesome-embedded-rust#driver-crates) in terms of these traits, e.g. an " +"accelerometer driver might need an I2C or SPI bus implementation." msgstr "" -#: src/bare-metal/aps/inline-assembly.md:39 +#: src/bare-metal/microcontrollers/embedded-hal.md:19 msgid "" -"(If you actually want to do this, use the [`smccc`](https://crates.io/crates/" -"smccc) crate which has wrappers for all these functions.)" +"There are implementations for many microcontrollers, as well as other " +"platforms such as Linux on Raspberry Pi." msgstr "" -#: src/bare-metal/aps/inline-assembly.md:43 +#: src/bare-metal/microcontrollers/embedded-hal.md:21 msgid "" -"PSCI is the Arm Power State Coordination Interface, a standard set of " -"functions to manage system and CPU power states, among other things. It is " -"implemented by EL3 firmware and hypervisors on many systems." +"There is work in progress on an `async` version of `embedded-hal`, but it " +"isn't stable yet." msgstr "" -#: src/bare-metal/aps/inline-assembly.md:46 -msgid "" -"The `0 => _` syntax means initialise the register to 0 before running the " -"inline assembly code, and ignore its contents afterwards. We need to use " -"`inout` rather than `in` because the call could potentially clobber the " -"contents of the registers." +#: src/bare-metal/microcontrollers/probe-rs.md:1 +msgid "`probe-rs`, `cargo-embed`" msgstr "" -#: src/bare-metal/aps/inline-assembly.md:49 +#: src/bare-metal/microcontrollers/probe-rs.md:3 msgid "" -"This `main` function needs to be `#[no_mangle]` and `extern \"C\"` because " -"it is called from our entry point in `entry.S`." +"[probe-rs](https://probe.rs/) is a handy toolset for embedded debugging, " +"like OpenOCD but better integrated." msgstr "" -#: src/bare-metal/aps/inline-assembly.md:51 -msgid "" -"`_x0`–`_x3` are the values of registers `x0`–`x3`, which are conventionally " -"used by the bootloader to pass things like a pointer to the device tree. " -"According to the standard aarch64 calling convention (which is what `extern " -"\"C\"` specifies to use), registers `x0`–`x7` are used for the first 8 " -"arguments passed to a function, so `entry.S` doesn't need to do anything " -"special except make sure it doesn't change these registers." +#: src/bare-metal/microcontrollers/probe-rs.md:6 +msgid "SWD" msgstr "" -#: src/bare-metal/aps/inline-assembly.md:56 -msgid "" -"Run the example in QEMU with `make qemu_psci` under `src/bare-metal/aps/" -"examples`." +#: src/bare-metal/microcontrollers/probe-rs.md:6 +msgid " and JTAG via CMSIS-DAP, ST-Link and J-Link probes" msgstr "" -#: src/bare-metal/aps/mmio.md:1 -msgid "Volatile memory access for MMIO" +#: src/bare-metal/microcontrollers/probe-rs.md:7 +msgid "GDB stub and Microsoft " msgstr "" -#: src/bare-metal/aps/mmio.md:3 -msgid "Use `pointer::read_volatile` and `pointer::write_volatile`." +#: src/bare-metal/microcontrollers/probe-rs.md:7 +msgid "DAP" msgstr "" -#: src/bare-metal/aps/mmio.md:4 -msgid "Never hold a reference." +#: src/bare-metal/microcontrollers/probe-rs.md:7 +msgid " server" msgstr "" -#: src/bare-metal/aps/mmio.md:5 -msgid "" -"`addr_of!` lets you get fields of structs without creating an intermediate " -"reference." +#: src/bare-metal/microcontrollers/probe-rs.md:8 +msgid "Cargo integration" msgstr "" -#: src/bare-metal/aps/mmio.md:9 +#: src/bare-metal/microcontrollers/probe-rs.md:10 +msgid "`cargo-embed` is a cargo subcommand to build and flash binaries, log " +msgstr "" + +#: src/bare-metal/microcontrollers/probe-rs.md:11 +msgid "RTT" +msgstr "" + +#: src/bare-metal/microcontrollers/probe-rs.md:11 msgid "" -"Volatile access: read or write operations may have side-effects, so prevent " -"the compiler or hardware from reordering, duplicating or eliding them." +" output and connect GDB. It's configured by an `Embed.toml` file in your " +"project directory." msgstr "" -#: src/bare-metal/aps/mmio.md:11 +#: src/bare-metal/microcontrollers/probe-rs.md:16 msgid "" -"Usually if you write and then read, e.g. via a mutable reference, the " -"compiler may assume that the value read is the same as the value just " -"written, and not bother actually reading memory." +"[CMSIS-DAP](https://arm-software.github.io/CMSIS_5/DAP/html/index.html) is " +"an Arm standard protocol over USB for an in-circuit debugger to access the " +"CoreSight Debug Access Port of various Arm Cortex processors. It's what the " +"on-board debugger on the BBC micro:bit uses." msgstr "" -#: src/bare-metal/aps/mmio.md:13 +#: src/bare-metal/microcontrollers/probe-rs.md:19 msgid "" -"Some existing crates for volatile access to hardware do hold references, but " -"this is unsound. Whenever a reference exist, the compiler may choose to " -"dereference it." +"ST-Link is a range of in-circuit debuggers from ST Microelectronics, J-Link " +"is a range from SEGGER." msgstr "" -#: src/bare-metal/aps/mmio.md:15 +#: src/bare-metal/microcontrollers/probe-rs.md:21 msgid "" -"Use the `addr_of!` macro to get struct field pointers from a pointer to the " -"struct." +"The Debug Access Port is usually either a 5-pin JTAG interface or 2-pin " +"Serial Wire Debug." msgstr "" -#: src/bare-metal/aps/uart.md:1 -msgid "Let's write a UART driver" +#: src/bare-metal/microcontrollers/probe-rs.md:22 +msgid "" +"probe-rs is a library which you can integrate into your own tools if you " +"want to." msgstr "" -#: src/bare-metal/aps/uart.md:3 +#: src/bare-metal/microcontrollers/probe-rs.md:23 msgid "" -"The QEMU 'virt' machine has a [PL011](https://developer.arm.com/" -"documentation/ddi0183/g) UART, so let's write a driver for that." +"The [Microsoft Debug Adapter Protocol](https://microsoft.github.io/debug-" +"adapter-protocol/) lets VSCode and other IDEs debug code running on any " +"supported microcontroller." msgstr "" -#: src/bare-metal/aps/uart.md:5 +#: src/bare-metal/microcontrollers/probe-rs.md:25 +msgid "cargo-embed is a binary built using the probe-rs library." +msgstr "" + +#: src/bare-metal/microcontrollers/probe-rs.md:26 msgid "" -"```rust,editable\n" -"const FLAG_REGISTER_OFFSET: usize = 0x18;\n" -"const FR_BUSY: u8 = 1 << 3;\n" -"const FR_TXFF: u8 = 1 << 5;\n" -"\n" -"/// Minimal driver for a PL011 UART.\n" -"#[derive(Debug)]\n" -"pub struct Uart {\n" -" base_address: *mut u8,\n" -"}\n" -"\n" -"impl Uart {\n" -" /// Constructs a new instance of the UART driver for a PL011 device at " -"the\n" -" /// given base address.\n" -" ///\n" -" /// # Safety\n" -" ///\n" -" /// The given base address must point to the 8 MMIO control registers of " -"a\n" -" /// PL011 device, which must be mapped into the address space of the " -"process\n" -" /// as device memory and not have any other aliases.\n" -" pub unsafe fn new(base_address: *mut u8) -> Self {\n" -" Self { base_address }\n" -" }\n" -"\n" -" /// Writes a single byte to the UART.\n" -" pub fn write_byte(&self, byte: u8) {\n" -" // Wait until there is room in the TX buffer.\n" -" while self.read_flag_register() & FR_TXFF != 0 {}\n" -"\n" -" // Safe because we know that the base address points to the control\n" -" // registers of a PL011 device which is appropriately mapped.\n" -" unsafe {\n" -" // Write to the TX buffer.\n" -" self.base_address.write_volatile(byte);\n" -" }\n" -"\n" -" // Wait until the UART is no longer busy.\n" -" while self.read_flag_register() & FR_BUSY != 0 {}\n" -" }\n" -"\n" -" fn read_flag_register(&self) -> u8 {\n" -" // Safe because we know that the base address points to the control\n" -" // registers of a PL011 device which is appropriately mapped.\n" -" unsafe { self.base_address.add(FLAG_REGISTER_OFFSET)." -"read_volatile() }\n" -" }\n" -"}\n" -"```" +"RTT (Real Time Transfers) is a mechanism to transfer data between the debug " +"host and the target through a number of ringbuffers." msgstr "" -#: src/bare-metal/aps/uart.md:55 -msgid "" -"Note that `Uart::new` is unsafe while the other methods are safe. This is " -"because as long as the caller of `Uart::new` guarantees that its safety " -"requirements are met (i.e. that there is only ever one instance of the " -"driver for a given UART, and nothing else aliasing its address space), then " -"it is always safe to call `write_byte` later because we can assume the " -"necessary preconditions." +#: src/bare-metal/microcontrollers/debugging.md:3 +msgid "Embed.toml:" msgstr "" -#: src/bare-metal/aps/uart.md:60 +#: src/bare-metal/microcontrollers/debugging.md:5 msgid "" -"We could have done it the other way around (making `new` safe but " -"`write_byte` unsafe), but that would be much less convenient to use as every " -"place that calls `write_byte` would need to reason about the safety" +"```toml\n" +"[default.general]\n" +"chip = \"nrf52833_xxAA\"\n" +"\n" +"[debug.gdb]\n" +"enabled = true\n" +"```" msgstr "" -#: src/bare-metal/aps/uart.md:63 -msgid "" -"This is a common pattern for writing safe wrappers of unsafe code: moving " -"the burden of proof for soundness from a large number of places to a smaller " -"number of places." +#: src/bare-metal/microcontrollers/debugging.md:13 +msgid "In one terminal under `src/bare-metal/microcontrollers/examples/`:" msgstr "" -#: src/bare-metal/aps/uart/traits.md:1 -msgid "More traits" +#: src/bare-metal/microcontrollers/debugging.md:15 +msgid "" +"```sh\n" +"cargo embed --bin board_support debug\n" +"```" msgstr "" -#: src/bare-metal/aps/uart/traits.md:3 -msgid "" -"We derived the `Debug` trait. It would be useful to implement a few more " -"traits too." +#: src/bare-metal/microcontrollers/debugging.md:19 +msgid "In another terminal in the same directory:" msgstr "" -#: src/bare-metal/aps/uart/traits.md:5 +#: src/bare-metal/microcontrollers/debugging.md:21 msgid "" -"```rust,editable,compile_fail\n" -"use core::fmt::{self, Write};\n" -"\n" -"impl Write for Uart {\n" -" fn write_str(&mut self, s: &str) -> fmt::Result {\n" -" for c in s.as_bytes() {\n" -" self.write_byte(*c);\n" -" }\n" -" Ok(())\n" -" }\n" -"}\n" -"\n" -"// Safe because it just contains a pointer to device memory, which can be\n" -"// accessed from any context.\n" -"unsafe impl Send for Uart {}\n" +"```sh\n" +"gdb-multiarch target/thumbv7em-none-eabihf/debug/board_support --eval-" +"command=\"target remote :1337\"\n" "```" msgstr "" -#: src/bare-metal/aps/uart/traits.md:24 -msgid "" -"Implementing `Write` lets us use the `write!` and `writeln!` macros with our " -"`Uart` type." +#: src/bare-metal/microcontrollers/debugging.md:27 +msgid "In GDB, try running:" msgstr "" -#: src/bare-metal/aps/uart/traits.md:25 +#: src/bare-metal/microcontrollers/debugging.md:29 msgid "" -"Run the example in QEMU with `make qemu_minimal` under `src/bare-metal/aps/" -"examples`." +"```gdb\n" +"b src/bin/board_support.rs:29\n" +"b src/bin/board_support.rs:30\n" +"b src/bin/board_support.rs:32\n" +"c\n" +"c\n" +"c\n" +"```" msgstr "" -#: src/bare-metal/aps/better-uart.md:1 -msgid "A better UART driver" +#: src/bare-metal/microcontrollers/other-projects.md:1 +#: src/bare-metal/aps/other-projects.md:1 +msgid "Other projects" msgstr "" -#: src/bare-metal/aps/better-uart.md:3 -msgid "" -"The PL011 actually has [a bunch more registers](https://developer.arm.com/" -"documentation/ddi0183/g/programmers-model/summary-of-registers), and adding " -"offsets to construct pointers to access them is error-prone and hard to " -"read. Plus, some of them are bit fields which would be nice to access in a " -"structured way." +#: src/bare-metal/microcontrollers/other-projects.md:3 +msgid "[RTIC](https://rtic.rs/)" msgstr "" -#: src/bare-metal/aps/better-uart.md:7 -msgid "Offset" +#: src/bare-metal/microcontrollers/other-projects.md:4 +msgid "\"Real-Time Interrupt-driven Concurrency\"" msgstr "" -#: src/bare-metal/aps/better-uart.md:7 -msgid "Register name" +#: src/bare-metal/microcontrollers/other-projects.md:5 +msgid "" +"Shared resource management, message passing, task scheduling, timer queue" msgstr "" -#: src/bare-metal/aps/better-uart.md:7 -msgid "Width" +#: src/bare-metal/microcontrollers/other-projects.md:6 +msgid "[Embassy](https://embassy.dev/)" msgstr "" -#: src/bare-metal/aps/better-uart.md:9 -msgid "0x00" +#: src/bare-metal/microcontrollers/other-projects.md:7 +msgid "`async` executors with priorities, timers, networking, USB" msgstr "" -#: src/bare-metal/aps/better-uart.md:9 -msgid "DR" +#: src/bare-metal/microcontrollers/other-projects.md:8 +msgid "[TockOS](https://www.tockos.org/documentation/getting-started)" msgstr "" -#: src/bare-metal/aps/better-uart.md:9 -msgid "12" +#: src/bare-metal/microcontrollers/other-projects.md:9 +msgid "" +"Security-focused RTOS with preemptive scheduling and Memory Protection Unit " +"support" msgstr "" -#: src/bare-metal/aps/better-uart.md:10 -msgid "0x04" +#: src/bare-metal/microcontrollers/other-projects.md:10 +msgid "[Hubris](https://hubris.oxide.computer/)" msgstr "" -#: src/bare-metal/aps/better-uart.md:10 -msgid "RSR" +#: src/bare-metal/microcontrollers/other-projects.md:11 +msgid "" +"Microkernel RTOS from Oxide Computer Company with memory protection, " +"unprivileged drivers, IPC" msgstr "" -#: src/bare-metal/aps/better-uart.md:10 -msgid "4" +#: src/bare-metal/microcontrollers/other-projects.md:12 +msgid "[Bindings for FreeRTOS](https://github.com/lobaro/FreeRTOS-rust)" msgstr "" -#: src/bare-metal/aps/better-uart.md:11 -msgid "0x18" +#: src/bare-metal/microcontrollers/other-projects.md:13 +msgid "" +"Some platforms have `std` implementations, e.g. [esp-idf](https://esp-rs." +"github.io/book/overview/using-the-standard-library.html)." msgstr "" -#: src/bare-metal/aps/better-uart.md:11 -msgid "FR" +#: src/bare-metal/microcontrollers/other-projects.md:18 +msgid "RTIC can be considered either an RTOS or a concurrency framework." msgstr "" -#: src/bare-metal/aps/better-uart.md:11 -msgid "9" +#: src/bare-metal/microcontrollers/other-projects.md:19 +msgid "It doesn't include any HALs." msgstr "" -#: src/bare-metal/aps/better-uart.md:12 -msgid "0x20" +#: src/bare-metal/microcontrollers/other-projects.md:20 +msgid "" +"It uses the Cortex-M NVIC (Nested Virtual Interrupt Controller) for " +"scheduling rather than a proper kernel." msgstr "" -#: src/bare-metal/aps/better-uart.md:12 -msgid "ILPR" +#: src/bare-metal/microcontrollers/other-projects.md:22 +msgid "Cortex-M only." msgstr "" -#: src/bare-metal/aps/better-uart.md:12 src/bare-metal/aps/better-uart.md:15 -msgid "8" +#: src/bare-metal/microcontrollers/other-projects.md:23 +msgid "" +"Google uses TockOS on the Haven microcontroller for Titan security keys." msgstr "" -#: src/bare-metal/aps/better-uart.md:13 -msgid "0x24" +#: src/bare-metal/microcontrollers/other-projects.md:24 +msgid "" +"FreeRTOS is mostly written in C, but there are Rust bindings for writing " +"applications." msgstr "" -#: src/bare-metal/aps/better-uart.md:13 -msgid "IBRD" +#: src/exercises/bare-metal/morning.md:3 +msgid "" +"We will read the direction from an I2C compass, and log the readings to a " +"serial port." msgstr "" -#: src/bare-metal/aps/better-uart.md:13 src/bare-metal/aps/better-uart.md:16 -msgid "16" +#: src/exercises/bare-metal/compass.md:3 +msgid "" +"We will read the direction from an I2C compass, and log the readings to a " +"serial port. If you have time, try displaying it on the LEDs somehow too, or " +"use the buttons somehow." msgstr "" -#: src/bare-metal/aps/better-uart.md:14 -msgid "0x28" +#: src/exercises/bare-metal/compass.md:6 +msgid "Hints:" msgstr "" -#: src/bare-metal/aps/better-uart.md:14 -msgid "FBRD" +#: src/exercises/bare-metal/compass.md:8 +msgid "" +"Check the documentation for the [`lsm303agr`](https://docs.rs/lsm303agr/" +"latest/lsm303agr/) and [`microbit-v2`](https://docs.rs/microbit-v2/latest/" +"microbit/) crates, as well as the [micro:bit hardware](https://tech.microbit." +"org/hardware/)." msgstr "" -#: src/bare-metal/aps/better-uart.md:14 src/bare-metal/aps/better-uart.md:17 -msgid "6" +#: src/exercises/bare-metal/compass.md:11 +msgid "" +"The LSM303AGR Inertial Measurement Unit is connected to the internal I2C bus." msgstr "" -#: src/bare-metal/aps/better-uart.md:15 -msgid "0x2c" +#: src/exercises/bare-metal/compass.md:12 +msgid "" +"TWI is another name for I2C, so the I2C master peripheral is called TWIM." msgstr "" -#: src/bare-metal/aps/better-uart.md:15 -msgid "LCR_H" +#: src/exercises/bare-metal/compass.md:13 +msgid "" +"The LSM303AGR driver needs something implementing the `embedded_hal::" +"blocking::i2c::WriteRead` trait. The [`microbit::hal::Twim`](https://docs.rs/" +"microbit-v2/latest/microbit/hal/struct.Twim.html) struct implements this." msgstr "" -#: src/bare-metal/aps/better-uart.md:16 -msgid "0x30" +#: src/exercises/bare-metal/compass.md:17 +msgid "" +"You have a [`microbit::Board`](https://docs.rs/microbit-v2/latest/microbit/" +"struct.Board.html) struct with fields for the various pins and peripherals." msgstr "" -#: src/bare-metal/aps/better-uart.md:16 -msgid "CR" +#: src/exercises/bare-metal/compass.md:19 +msgid "" +"You can also look at the [nRF52833 datasheet](https://infocenter.nordicsemi." +"com/pdf/nRF52833_PS_v1.5.pdf) if you want, but it shouldn't be necessary for " +"this exercise." msgstr "" -#: src/bare-metal/aps/better-uart.md:17 -msgid "0x34" +#: src/exercises/bare-metal/compass.md:23 +msgid "" +"Download the [exercise template](../../comprehensive-rust-exercises.zip) and " +"look in the `compass` directory for the following files." msgstr "" -#: src/bare-metal/aps/better-uart.md:17 -msgid "IFLS" +#: src/exercises/bare-metal/compass.md:26 src/exercises/bare-metal/rtc.md:19 +msgid "`src/main.rs`:" msgstr "" -#: src/bare-metal/aps/better-uart.md:18 -msgid "0x38" +#: src/exercises/bare-metal/compass.md:30 +msgid "" +"```rust,compile_fail\n" +"#![no_main]\n" +"#![no_std]\n" +"\n" +"extern crate panic_halt as _;\n" +"\n" +"use core::fmt::Write;\n" +"use cortex_m_rt::entry;\n" +"use microbit::{hal::uarte::{Baudrate, Parity, Uarte}, Board};\n" +"\n" +"#[entry]\n" +"fn main() -> ! {\n" +" let board = Board::take().unwrap();\n" +"\n" +" // Configure serial port.\n" +" let mut serial = Uarte::new(\n" +" board.UARTE0,\n" +" board.uart.into(),\n" +" Parity::EXCLUDED,\n" +" Baudrate::BAUD115200,\n" +" );\n" +"\n" +" // Set up the I2C controller and Inertial Measurement Unit.\n" +" // TODO\n" +"\n" +" writeln!(serial, \"Ready.\").unwrap();\n" +"\n" +" loop {\n" +" // Read compass data and log it to the serial port.\n" +" // TODO\n" +" }\n" +"}\n" +"```" msgstr "" -#: src/bare-metal/aps/better-uart.md:18 -msgid "IMSC" +#: src/exercises/bare-metal/compass.md:64 src/exercises/bare-metal/rtc.md:385 +msgid "`Cargo.toml` (you shouldn't need to change this):" msgstr "" -#: src/bare-metal/aps/better-uart.md:18 src/bare-metal/aps/better-uart.md:19 -#: src/bare-metal/aps/better-uart.md:20 src/bare-metal/aps/better-uart.md:21 -msgid "11" +#: src/exercises/bare-metal/compass.md:68 +msgid "" +"```toml\n" +"[workspace]\n" +"\n" +"[package]\n" +"name = \"compass\"\n" +"version = \"0.1.0\"\n" +"edition = \"2021\"\n" +"publish = false\n" +"\n" +"[dependencies]\n" +"cortex-m-rt = \"0.7.3\"\n" +"embedded-hal = \"0.2.6\"\n" +"lsm303agr = \"0.2.2\"\n" +"microbit-v2 = \"0.13.0\"\n" +"panic-halt = \"0.2.0\"\n" +"```" msgstr "" -#: src/bare-metal/aps/better-uart.md:19 -msgid "0x3c" +#: src/exercises/bare-metal/compass.md:85 +msgid "`Embed.toml` (you shouldn't need to change this):" msgstr "" -#: src/bare-metal/aps/better-uart.md:19 -msgid "RIS" +#: src/exercises/bare-metal/compass.md:89 +msgid "" +"```toml\n" +"[default.general]\n" +"chip = \"nrf52833_xxAA\"\n" +"\n" +"[debug.gdb]\n" +"enabled = true\n" +"\n" +"[debug.reset]\n" +"halt_afterwards = true\n" +"```" msgstr "" -#: src/bare-metal/aps/better-uart.md:20 -msgid "0x40" +#: src/exercises/bare-metal/compass.md:100 src/exercises/bare-metal/rtc.md:985 +msgid "`.cargo/config.toml` (you shouldn't need to change this):" msgstr "" -#: src/bare-metal/aps/better-uart.md:20 -msgid "MIS" +#: src/exercises/bare-metal/compass.md:104 +msgid "" +"```toml\n" +"[build]\n" +"target = \"thumbv7em-none-eabihf\" # Cortex-M4F\n" +"\n" +"[target.'cfg(all(target_arch = \"arm\", target_os = \"none\"))']\n" +"rustflags = [\"-C\", \"link-arg=-Tlink.x\"]\n" +"```" msgstr "" -#: src/bare-metal/aps/better-uart.md:21 -msgid "0x44" +#: src/exercises/bare-metal/compass.md:112 +msgid "See the serial output on Linux with:" msgstr "" -#: src/bare-metal/aps/better-uart.md:21 -msgid "ICR" +#: src/exercises/bare-metal/compass.md:114 +msgid "" +"```sh\n" +"picocom --baud 115200 --imap lfcrlf /dev/ttyACM0\n" +"```" msgstr "" -#: src/bare-metal/aps/better-uart.md:22 -msgid "0x48" +#: src/exercises/bare-metal/compass.md:118 +msgid "" +"Or on Mac OS something like (the device name may be slightly different):" msgstr "" -#: src/bare-metal/aps/better-uart.md:22 -msgid "DMACR" +#: src/exercises/bare-metal/compass.md:120 +msgid "" +"```sh\n" +"picocom --baud 115200 --imap lfcrlf /dev/tty.usbmodem14502\n" +"```" msgstr "" -#: src/bare-metal/aps/better-uart.md:22 -msgid "3" +#: src/exercises/bare-metal/compass.md:124 +msgid "Use Ctrl+A Ctrl+Q to quit picocom." msgstr "" -#: src/bare-metal/aps/better-uart.md:26 -msgid "There are also some ID registers which have been omitted for brevity." +#: src/bare-metal/aps.md:1 +msgid "Application processors" msgstr "" -#: src/bare-metal/aps/better-uart/bitflags.md:3 +#: src/bare-metal/aps.md:3 msgid "" -"The [`bitflags`](https://crates.io/crates/bitflags) crate is useful for " -"working with bitflags." +"So far we've talked about microcontrollers, such as the Arm Cortex-M series. " +"Now let's try writing something for Cortex-A. For simplicity we'll just work " +"with QEMU's aarch64 ['virt'](https://qemu-project.gitlab.io/qemu/system/arm/" +"virt.html) board." msgstr "" -#: src/bare-metal/aps/better-uart/bitflags.md:5 +#: src/bare-metal/aps.md:9 msgid "" -"```rust,editable,compile_fail\n" -"use bitflags::bitflags;\n" -"\n" -"bitflags! {\n" -" /// Flags from the UART flag register.\n" -" #[repr(transparent)]\n" -" #[derive(Copy, Clone, Debug, Eq, PartialEq)]\n" -" struct Flags: u16 {\n" -" /// Clear to send.\n" -" const CTS = 1 << 0;\n" -" /// Data set ready.\n" -" const DSR = 1 << 1;\n" -" /// Data carrier detect.\n" -" const DCD = 1 << 2;\n" -" /// UART busy transmitting data.\n" -" const BUSY = 1 << 3;\n" -" /// Receive FIFO is empty.\n" -" const RXFE = 1 << 4;\n" -" /// Transmit FIFO is full.\n" -" const TXFF = 1 << 5;\n" -" /// Receive FIFO is full.\n" -" const RXFF = 1 << 6;\n" -" /// Transmit FIFO is empty.\n" -" const TXFE = 1 << 7;\n" -" /// Ring indicator.\n" -" const RI = 1 << 8;\n" -" }\n" -"}\n" -"```" +"Broadly speaking, microcontrollers don't have an MMU or multiple levels of " +"privilege (exception levels on Arm CPUs, rings on x86), while application " +"processors do." msgstr "" -#: src/bare-metal/aps/better-uart/bitflags.md:37 +#: src/bare-metal/aps.md:11 msgid "" -"The `bitflags!` macro creates a newtype something like `Flags(u16)`, along " -"with a bunch of method implementations to get and set flags." +"QEMU supports emulating various different machines or board models for each " +"architecture. The 'virt' board doesn't correspond to any particular real " +"hardware, but is designed purely for virtual machines." msgstr "" -#: src/bare-metal/aps/better-uart/registers.md:1 -msgid "Multiple registers" +#: src/bare-metal/aps/entry-point.md:3 +msgid "" +"Before we can start running Rust code, we need to do some initialisation." msgstr "" -#: src/bare-metal/aps/better-uart/registers.md:3 +#: src/bare-metal/aps/entry-point.md:5 msgid "" -"We can use a struct to represent the memory layout of the UART's registers." +"```armasm\n" +".section .init.entry, \"ax\"\n" +".global entry\n" +"entry:\n" +" /*\n" +" * Load and apply the memory management configuration, ready to enable " +"MMU and\n" +" * caches.\n" +" */\n" +" adrp x30, idmap\n" +" msr ttbr0_el1, x30\n" +"\n" +" mov_i x30, .Lmairval\n" +" msr mair_el1, x30\n" +"\n" +" mov_i x30, .Ltcrval\n" +" /* Copy the supported PA range into TCR_EL1.IPS. */\n" +" mrs x29, id_aa64mmfr0_el1\n" +" bfi x30, x29, #32, #4\n" +"\n" +" msr tcr_el1, x30\n" +"\n" +" mov_i x30, .Lsctlrval\n" +"\n" +" /*\n" +" * Ensure everything before this point has completed, then invalidate " +"any\n" +" * potentially stale local TLB entries before they start being used.\n" +" */\n" +" isb\n" +" tlbi vmalle1\n" +" ic iallu\n" +" dsb nsh\n" +" isb\n" +"\n" +" /*\n" +" * Configure sctlr_el1 to enable MMU and cache and don't proceed until " +"this\n" +" * has completed.\n" +" */\n" +" msr sctlr_el1, x30\n" +" isb\n" +"\n" +" /* Disable trapping floating point access in EL1. */\n" +" mrs x30, cpacr_el1\n" +" orr x30, x30, #(0x3 << 20)\n" +" msr cpacr_el1, x30\n" +" isb\n" +"\n" +" /* Zero out the bss section. */\n" +" adr_l x29, bss_begin\n" +" adr_l x30, bss_end\n" +"0: cmp x29, x30\n" +" b.hs 1f\n" +" stp xzr, xzr, [x29], #16\n" +" b 0b\n" +"\n" +"1: /* Prepare the stack. */\n" +" adr_l x30, boot_stack_end\n" +" mov sp, x30\n" +"\n" +" /* Set up exception vector. */\n" +" adr x30, vector_table_el1\n" +" msr vbar_el1, x30\n" +"\n" +" /* Call into Rust code. */\n" +" bl main\n" +"\n" +" /* Loop forever waiting for interrupts. */\n" +"2: wfi\n" +" b 2b\n" +"```" +msgstr "" + +#: src/bare-metal/aps/entry-point.md:77 +msgid "" +"This is the same as it would be for C: initialising the processor state, " +"zeroing the BSS, and setting up the stack pointer." +msgstr "" + +#: src/bare-metal/aps/entry-point.md:79 +msgid "" +"The BSS (block starting symbol, for historical reasons) is the part of the " +"object file which containing statically allocated variables which are " +"initialised to zero. They are omitted from the image, to avoid wasting space " +"on zeroes. The compiler assumes that the loader will take care of zeroing " +"them." msgstr "" -#: src/bare-metal/aps/better-uart/registers.md:5 +#: src/bare-metal/aps/entry-point.md:83 msgid "" -"```rust,editable,compile_fail\n" -"#[repr(C, align(4))]\n" -"struct Registers {\n" -" dr: u16,\n" -" _reserved0: [u8; 2],\n" -" rsr: ReceiveStatus,\n" -" _reserved1: [u8; 19],\n" -" fr: Flags,\n" -" _reserved2: [u8; 6],\n" -" ilpr: u8,\n" -" _reserved3: [u8; 3],\n" -" ibrd: u16,\n" -" _reserved4: [u8; 2],\n" -" fbrd: u8,\n" -" _reserved5: [u8; 3],\n" -" lcr_h: u8,\n" -" _reserved6: [u8; 3],\n" -" cr: u16,\n" -" _reserved7: [u8; 3],\n" -" ifls: u8,\n" -" _reserved8: [u8; 3],\n" -" imsc: u16,\n" -" _reserved9: [u8; 2],\n" -" ris: u16,\n" -" _reserved10: [u8; 2],\n" -" mis: u16,\n" -" _reserved11: [u8; 2],\n" -" icr: u16,\n" -" _reserved12: [u8; 2],\n" -" dmacr: u8,\n" -" _reserved13: [u8; 3],\n" -"}\n" -"```" +"The BSS may already be zeroed, depending on how memory is initialised and " +"the image is loaded, but we zero it to be sure." msgstr "" -#: src/bare-metal/aps/better-uart/registers.md:41 +#: src/bare-metal/aps/entry-point.md:85 msgid "" -"[`#[repr(C)]`](https://doc.rust-lang.org/reference/type-layout.html#the-c-" -"representation) tells the compiler to lay the struct fields out in order, " -"following the same rules as C. This is necessary for our struct to have a " -"predictable layout, as default Rust representation allows the compiler to " -"(among other things) reorder fields however it sees fit." +"We need to enable the MMU and cache before reading or writing any memory. If " +"we don't:" msgstr "" -#: src/bare-metal/aps/better-uart/driver.md:3 -msgid "Now let's use the new `Registers` struct in our driver." +#: src/bare-metal/aps/entry-point.md:86 +msgid "" +"Unaligned accesses will fault. We build the Rust code for the `aarch64-" +"unknown-none` target which sets `+strict-align` to prevent the compiler " +"generating unaligned accesses, so it should be fine in this case, but this " +"is not necessarily the case in general." msgstr "" -#: src/bare-metal/aps/better-uart/driver.md:5 +#: src/bare-metal/aps/entry-point.md:89 +msgid "" +"If it were running in a VM, this can lead to cache coherency issues. The " +"problem is that the VM is accessing memory directly with the cache disabled, " +"while the host has cachable aliases to the same memory. Even if the host " +"doesn't explicitly access the memory, speculative accesses can lead to cache " +"fills, and then changes from one or the other will get lost when the cache " +"is cleaned or the VM enables the cache. (Cache is keyed by physical address, " +"not VA or IPA.)" +msgstr "" + +#: src/bare-metal/aps/entry-point.md:94 +msgid "" +"For simplicity, we just use a hardcoded pagetable (see `idmap.S`) which " +"identity maps the first 1 GiB of address space for devices, the next 1 GiB " +"for DRAM, and another 1 GiB higher up for more devices. This matches the " +"memory layout that QEMU uses." +msgstr "" + +#: src/bare-metal/aps/entry-point.md:97 +msgid "" +"We also set up the exception vector (`vbar_el1`), which we'll see more about " +"later." +msgstr "" + +#: src/bare-metal/aps/entry-point.md:98 +msgid "" +"All examples this afternoon assume we will be running at exception level 1 " +"(EL1). If you need to run at a different exception level you'll need to " +"modify `entry.S` accordingly." +msgstr "" + +#: src/bare-metal/aps/inline-assembly.md:1 +msgid "Inline assembly" +msgstr "" + +#: src/bare-metal/aps/inline-assembly.md:3 +msgid "" +"Sometimes we need to use assembly to do things that aren't possible with " +"Rust code. For example, to make an " +msgstr "" + +#: src/bare-metal/aps/inline-assembly.md:4 +msgid "HVC" +msgstr "" + +#: src/bare-metal/aps/inline-assembly.md:4 +msgid " to tell the firmware to power off the system:" +msgstr "" + +#: src/bare-metal/aps/inline-assembly.md:6 msgid "" "```rust,editable,compile_fail\n" -"/// Driver for a PL011 UART.\n" +"#![no_main]\n" +"#![no_std]\n" +"\n" +"use core::arch::asm;\n" +"use core::panic::PanicInfo;\n" +"\n" +"mod exceptions;\n" +"\n" +"const PSCI_SYSTEM_OFF: u32 = 0x84000008;\n" +"\n" +"#[no_mangle]\n" +"extern \"C\" fn main(_x0: u64, _x1: u64, _x2: u64, _x3: u64) {\n" +" // Safe because this only uses the declared registers and doesn't do\n" +" // anything with memory.\n" +" unsafe {\n" +" asm!(\"hvc #0\",\n" +" inout(\"w0\") PSCI_SYSTEM_OFF => _,\n" +" inout(\"w1\") 0 => _,\n" +" inout(\"w2\") 0 => _,\n" +" inout(\"w3\") 0 => _,\n" +" inout(\"w4\") 0 => _,\n" +" inout(\"w5\") 0 => _,\n" +" inout(\"w6\") 0 => _,\n" +" inout(\"w7\") 0 => _,\n" +" options(nomem, nostack)\n" +" );\n" +" }\n" +"\n" +" loop {}\n" +"}\n" +"```" +msgstr "" + +#: src/bare-metal/aps/inline-assembly.md:39 +msgid "" +"(If you actually want to do this, use the [`smccc`](https://crates.io/crates/" +"smccc) crate which has wrappers for all these functions.)" +msgstr "" + +#: src/bare-metal/aps/inline-assembly.md:43 +msgid "" +"PSCI is the Arm Power State Coordination Interface, a standard set of " +"functions to manage system and CPU power states, among other things. It is " +"implemented by EL3 firmware and hypervisors on many systems." +msgstr "" + +#: src/bare-metal/aps/inline-assembly.md:46 +msgid "" +"The `0 => _` syntax means initialise the register to 0 before running the " +"inline assembly code, and ignore its contents afterwards. We need to use " +"`inout` rather than `in` because the call could potentially clobber the " +"contents of the registers." +msgstr "" + +#: src/bare-metal/aps/inline-assembly.md:49 +msgid "" +"This `main` function needs to be `#[no_mangle]` and `extern \"C\"` because " +"it is called from our entry point in `entry.S`." +msgstr "" + +#: src/bare-metal/aps/inline-assembly.md:51 +msgid "" +"`_x0`–`_x3` are the values of registers `x0`–`x3`, which are conventionally " +"used by the bootloader to pass things like a pointer to the device tree. " +"According to the standard aarch64 calling convention (which is what `extern " +"\"C\"` specifies to use), registers `x0`–`x7` are used for the first 8 " +"arguments passed to a function, so `entry.S` doesn't need to do anything " +"special except make sure it doesn't change these registers." +msgstr "" + +#: src/bare-metal/aps/inline-assembly.md:56 +msgid "" +"Run the example in QEMU with `make qemu_psci` under `src/bare-metal/aps/" +"examples`." +msgstr "" + +#: src/bare-metal/aps/mmio.md:1 +msgid "Volatile memory access for MMIO" +msgstr "" + +#: src/bare-metal/aps/mmio.md:3 +msgid "Use `pointer::read_volatile` and `pointer::write_volatile`." +msgstr "" + +#: src/bare-metal/aps/mmio.md:4 +msgid "Never hold a reference." +msgstr "" + +#: src/bare-metal/aps/mmio.md:5 +msgid "" +"`addr_of!` lets you get fields of structs without creating an intermediate " +"reference." +msgstr "" + +#: src/bare-metal/aps/mmio.md:9 +msgid "" +"Volatile access: read or write operations may have side-effects, so prevent " +"the compiler or hardware from reordering, duplicating or eliding them." +msgstr "" + +#: src/bare-metal/aps/mmio.md:11 +msgid "" +"Usually if you write and then read, e.g. via a mutable reference, the " +"compiler may assume that the value read is the same as the value just " +"written, and not bother actually reading memory." +msgstr "" + +#: src/bare-metal/aps/mmio.md:13 +msgid "" +"Some existing crates for volatile access to hardware do hold references, but " +"this is unsound. Whenever a reference exist, the compiler may choose to " +"dereference it." +msgstr "" + +#: src/bare-metal/aps/mmio.md:15 +msgid "" +"Use the `addr_of!` macro to get struct field pointers from a pointer to the " +"struct." +msgstr "" + +#: src/bare-metal/aps/uart.md:1 +msgid "Let's write a UART driver" +msgstr "" + +#: src/bare-metal/aps/uart.md:3 +msgid "" +"The QEMU 'virt' machine has a [PL011](https://developer.arm.com/" +"documentation/ddi0183/g) UART, so let's write a driver for that." +msgstr "" + +#: src/bare-metal/aps/uart.md:5 +msgid "" +"```rust,editable\n" +"const FLAG_REGISTER_OFFSET: usize = 0x18;\n" +"const FR_BUSY: u8 = 1 << 3;\n" +"const FR_TXFF: u8 = 1 << 5;\n" +"\n" +"/// Minimal driver for a PL011 UART.\n" "#[derive(Debug)]\n" "pub struct Uart {\n" -" registers: *mut Registers,\n" +" base_address: *mut u8,\n" "}\n" "\n" "impl Uart {\n" @@ -13468,720 +13733,478 @@ msgid "" " /// PL011 device, which must be mapped into the address space of the " "process\n" " /// as device memory and not have any other aliases.\n" -" pub unsafe fn new(base_address: *mut u32) -> Self {\n" -" Self {\n" -" registers: base_address as *mut Registers,\n" -" }\n" +" pub unsafe fn new(base_address: *mut u8) -> Self {\n" +" Self { base_address }\n" " }\n" "\n" " /// Writes a single byte to the UART.\n" " pub fn write_byte(&self, byte: u8) {\n" " // Wait until there is room in the TX buffer.\n" -" while self.read_flag_register().contains(Flags::TXFF) {}\n" +" while self.read_flag_register() & FR_TXFF != 0 {}\n" "\n" -" // Safe because we know that self.registers points to the control\n" +" // Safe because we know that the base address points to the control\n" " // registers of a PL011 device which is appropriately mapped.\n" " unsafe {\n" " // Write to the TX buffer.\n" -" addr_of_mut!((*self.registers).dr).write_volatile(byte.into());\n" +" self.base_address.write_volatile(byte);\n" " }\n" "\n" " // Wait until the UART is no longer busy.\n" -" while self.read_flag_register().contains(Flags::BUSY) {}\n" -" }\n" -"\n" -" /// Reads and returns a pending byte, or `None` if nothing has been " -"received.\n" -" pub fn read_byte(&self) -> Option {\n" -" if self.read_flag_register().contains(Flags::RXFE) {\n" -" None\n" -" } else {\n" -" let data = unsafe { addr_of!((*self.registers).dr)." -"read_volatile() };\n" -" // TODO: Check for error conditions in bits 8-11.\n" -" Some(data as u8)\n" -" }\n" +" while self.read_flag_register() & FR_BUSY != 0 {}\n" " }\n" "\n" -" fn read_flag_register(&self) -> Flags {\n" -" // Safe because we know that self.registers points to the control\n" +" fn read_flag_register(&self) -> u8 {\n" +" // Safe because we know that the base address points to the control\n" " // registers of a PL011 device which is appropriately mapped.\n" -" unsafe { addr_of!((*self.registers).fr).read_volatile() }\n" +" unsafe { self.base_address.add(FLAG_REGISTER_OFFSET)." +"read_volatile() }\n" " }\n" "}\n" "```" msgstr "" -#: src/bare-metal/aps/better-uart/driver.md:64 +#: src/bare-metal/aps/uart.md:55 msgid "" -"Note the use of `addr_of!` / `addr_of_mut!` to get pointers to individual " -"fields without creating an intermediate reference, which would be unsound." +"Note that `Uart::new` is unsafe while the other methods are safe. This is " +"because as long as the caller of `Uart::new` guarantees that its safety " +"requirements are met (i.e. that there is only ever one instance of the " +"driver for a given UART, and nothing else aliasing its address space), then " +"it is always safe to call `write_byte` later because we can assume the " +"necessary preconditions." msgstr "" -#: src/bare-metal/aps/better-uart/using.md:1 -#: src/bare-metal/aps/logging/using.md:1 -msgid "Using it" +#: src/bare-metal/aps/uart.md:60 +msgid "" +"We could have done it the other way around (making `new` safe but " +"`write_byte` unsafe), but that would be much less convenient to use as every " +"place that calls `write_byte` would need to reason about the safety" msgstr "" -#: src/bare-metal/aps/better-uart/using.md:3 +#: src/bare-metal/aps/uart.md:63 msgid "" -"Let's write a small program using our driver to write to the serial console, " -"and echo incoming bytes." +"This is a common pattern for writing safe wrappers of unsafe code: moving " +"the burden of proof for soundness from a large number of places to a smaller " +"number of places." msgstr "" -#: src/bare-metal/aps/better-uart/using.md:6 +#: src/bare-metal/aps/uart/traits.md:1 +msgid "More traits" +msgstr "" + +#: src/bare-metal/aps/uart/traits.md:3 +msgid "" +"We derived the `Debug` trait. It would be useful to implement a few more " +"traits too." +msgstr "" + +#: src/bare-metal/aps/uart/traits.md:5 msgid "" "```rust,editable,compile_fail\n" -"#![no_main]\n" -"#![no_std]\n" -"\n" -"mod exceptions;\n" -"mod pl011;\n" +"use core::fmt::{self, Write};\n" "\n" -"use crate::pl011::Uart;\n" -"use core::fmt::Write;\n" -"use core::panic::PanicInfo;\n" -"use log::error;\n" -"use smccc::psci::system_off;\n" -"use smccc::Hvc;\n" -"\n" -"/// Base address of the primary PL011 UART.\n" -"const PL011_BASE_ADDRESS: *mut u32 = 0x900_0000 as _;\n" -"\n" -"#[no_mangle]\n" -"extern \"C\" fn main(x0: u64, x1: u64, x2: u64, x3: u64) {\n" -" // Safe because `PL011_BASE_ADDRESS` is the base address of a PL011 " -"device,\n" -" // and nothing else accesses that address range.\n" -" let mut uart = unsafe { Uart::new(PL011_BASE_ADDRESS) };\n" -"\n" -" writeln!(uart, \"main({x0:#x}, {x1:#x}, {x2:#x}, {x3:#x})\").unwrap();\n" -"\n" -" loop {\n" -" if let Some(b) = uart.read_byte() {\n" -" uart.write_byte(b);\n" -" match b {\n" -" b'\\r' => {\n" -" uart.write_byte(b'\\n');\n" -" }\n" -" b'q' => break,\n" -" _ => {}\n" -" }\n" +"impl Write for Uart {\n" +" fn write_str(&mut self, s: &str) -> fmt::Result {\n" +" for c in s.as_bytes() {\n" +" self.write_byte(*c);\n" " }\n" +" Ok(())\n" " }\n" -"\n" -" writeln!(uart, \"Bye!\").unwrap();\n" -" system_off::().unwrap();\n" "}\n" +"\n" +"// Safe because it just contains a pointer to device memory, which can be\n" +"// accessed from any context.\n" +"unsafe impl Send for Uart {}\n" "```" msgstr "" -#: src/bare-metal/aps/better-uart/using.md:51 +#: src/bare-metal/aps/uart/traits.md:24 msgid "" -"As in the [inline assembly](../inline-assembly.md) example, this `main` " -"function is called from our entry point code in `entry.S`. See the speaker " -"notes there for details." +"Implementing `Write` lets us use the `write!` and `writeln!` macros with our " +"`Uart` type." msgstr "" -#: src/bare-metal/aps/better-uart/using.md:53 +#: src/bare-metal/aps/uart/traits.md:25 msgid "" -"Run the example in QEMU with `make qemu` under `src/bare-metal/aps/examples`." +"Run the example in QEMU with `make qemu_minimal` under `src/bare-metal/aps/" +"examples`." msgstr "" -#: src/bare-metal/aps/logging.md:3 -msgid "" -"It would be nice to be able to use the logging macros from the [`log`]" -"(https://crates.io/crates/log) crate. We can do this by implementing the " -"`Log` trait." +#: src/bare-metal/aps/better-uart.md:1 +msgid "A better UART driver" msgstr "" -#: src/bare-metal/aps/logging.md:6 +#: src/bare-metal/aps/better-uart.md:3 msgid "" -"```rust,editable,compile_fail\n" -"use crate::pl011::Uart;\n" -"use core::fmt::Write;\n" -"use log::{LevelFilter, Log, Metadata, Record, SetLoggerError};\n" -"use spin::mutex::SpinMutex;\n" -"\n" -"static LOGGER: Logger = Logger {\n" -" uart: SpinMutex::new(None),\n" -"};\n" -"\n" -"struct Logger {\n" -" uart: SpinMutex>,\n" -"}\n" -"\n" -"impl Log for Logger {\n" -" fn enabled(&self, _metadata: &Metadata) -> bool {\n" -" true\n" -" }\n" -"\n" -" fn log(&self, record: &Record) {\n" -" writeln!(\n" -" self.uart.lock().as_mut().unwrap(),\n" -" \"[{}] {}\",\n" -" record.level(),\n" -" record.args()\n" -" )\n" -" .unwrap();\n" -" }\n" -"\n" -" fn flush(&self) {}\n" -"}\n" -"\n" -"/// Initialises UART logger.\n" -"pub fn init(uart: Uart, max_level: LevelFilter) -> Result<(), " -"SetLoggerError> {\n" -" LOGGER.uart.lock().replace(uart);\n" -"\n" -" log::set_logger(&LOGGER)?;\n" -" log::set_max_level(max_level);\n" -" Ok(())\n" -"}\n" -"```" +"The PL011 actually has [a bunch more registers](https://developer.arm.com/" +"documentation/ddi0183/g/programmers-model/summary-of-registers), and adding " +"offsets to construct pointers to access them is error-prone and hard to " +"read. Plus, some of them are bit fields which would be nice to access in a " +"structured way." msgstr "" -#: src/bare-metal/aps/logging.md:50 -msgid "" -"The unwrap in `log` is safe because we initialise `LOGGER` before calling " -"`set_logger`." +#: src/bare-metal/aps/better-uart.md:7 +msgid "Offset" msgstr "" -#: src/bare-metal/aps/logging/using.md:3 -msgid "We need to initialise the logger before we use it." +#: src/bare-metal/aps/better-uart.md:7 +msgid "Register name" msgstr "" -#: src/bare-metal/aps/logging/using.md:5 -msgid "" -"```rust,editable,compile_fail\n" -"#![no_main]\n" -"#![no_std]\n" -"\n" -"mod exceptions;\n" -"mod logger;\n" -"mod pl011;\n" -"\n" -"use crate::pl011::Uart;\n" -"use core::panic::PanicInfo;\n" -"use log::{error, info, LevelFilter};\n" -"use smccc::psci::system_off;\n" -"use smccc::Hvc;\n" -"\n" -"/// Base address of the primary PL011 UART.\n" -"const PL011_BASE_ADDRESS: *mut u32 = 0x900_0000 as _;\n" -"\n" -"#[no_mangle]\n" -"extern \"C\" fn main(x0: u64, x1: u64, x2: u64, x3: u64) {\n" -" // Safe because `PL011_BASE_ADDRESS` is the base address of a PL011 " -"device,\n" -" // and nothing else accesses that address range.\n" -" let uart = unsafe { Uart::new(PL011_BASE_ADDRESS) };\n" -" logger::init(uart, LevelFilter::Trace).unwrap();\n" -"\n" -" info!(\"main({x0:#x}, {x1:#x}, {x2:#x}, {x3:#x})\");\n" -"\n" -" assert_eq!(x1, 42);\n" -"\n" -" system_off::().unwrap();\n" -"}\n" -"\n" -"#[panic_handler]\n" -"fn panic(info: &PanicInfo) -> ! {\n" -" error!(\"{info}\");\n" -" system_off::().unwrap();\n" -" loop {}\n" -"}\n" -"```" +#: src/bare-metal/aps/better-uart.md:7 +msgid "Width" msgstr "" -#: src/bare-metal/aps/logging/using.md:46 -msgid "Note that our panic handler can now log details of panics." +#: src/bare-metal/aps/better-uart.md:9 +msgid "0x00" msgstr "" -#: src/bare-metal/aps/logging/using.md:47 -msgid "" -"Run the example in QEMU with `make qemu_logger` under `src/bare-metal/aps/" -"examples`." +#: src/bare-metal/aps/better-uart.md:9 +msgid "DR" msgstr "" -#: src/bare-metal/aps/other-projects.md:3 -msgid "[oreboot](https://github.com/oreboot/oreboot)" +#: src/bare-metal/aps/better-uart.md:9 +msgid "12" msgstr "" -#: src/bare-metal/aps/other-projects.md:4 -msgid "\"coreboot without the C\"" +#: src/bare-metal/aps/better-uart.md:10 +msgid "0x04" msgstr "" -#: src/bare-metal/aps/other-projects.md:5 -msgid "Supports x86, aarch64 and RISC-V." +#: src/bare-metal/aps/better-uart.md:10 +msgid "RSR" msgstr "" -#: src/bare-metal/aps/other-projects.md:6 -msgid "Relies on LinuxBoot rather than having many drivers itself." +#: src/bare-metal/aps/better-uart.md:10 +msgid "4" msgstr "" -#: src/bare-metal/aps/other-projects.md:7 -msgid "" -"[Rust RaspberryPi OS tutorial](https://github.com/rust-embedded/rust-" -"raspberrypi-OS-tutorials)" +#: src/bare-metal/aps/better-uart.md:11 +msgid "0x18" msgstr "" -#: src/bare-metal/aps/other-projects.md:8 -msgid "" -"Initialisation, UART driver, simple bootloader, JTAG, exception levels, " -"exception handling, page tables" +#: src/bare-metal/aps/better-uart.md:11 +msgid "FR" msgstr "" -#: src/bare-metal/aps/other-projects.md:9 -msgid "Not all very well written, so beware." +#: src/bare-metal/aps/better-uart.md:11 +msgid "9" msgstr "" -#: src/bare-metal/aps/other-projects.md:10 -msgid "[`cargo-call-stack`](https://crates.io/crates/cargo-call-stack)" +#: src/bare-metal/aps/better-uart.md:12 +msgid "0x20" msgstr "" -#: src/bare-metal/aps/other-projects.md:11 -msgid "Static analysis to determine maximum stack usage." +#: src/bare-metal/aps/better-uart.md:12 +msgid "ILPR" msgstr "" -#: src/bare-metal/useful-crates.md:3 -msgid "" -"We'll go over a few crates which solve some common problems in bare-metal " -"programming." +#: src/bare-metal/aps/better-uart.md:12 src/bare-metal/aps/better-uart.md:15 +msgid "8" msgstr "" -#: src/bare-metal/useful-crates/zerocopy.md:1 -msgid "`zerocopy`" +#: src/bare-metal/aps/better-uart.md:13 +msgid "0x24" msgstr "" -#: src/bare-metal/useful-crates/zerocopy.md:3 -msgid "" -"The [`zerocopy`](https://docs.rs/zerocopy/) crate (from Fuchsia) provides " -"traits and macros for safely converting between byte sequences and other " -"types." +#: src/bare-metal/aps/better-uart.md:13 +msgid "IBRD" msgstr "" -#: src/bare-metal/useful-crates/zerocopy.md:6 -msgid "" -"```rust,editable,compile_fail\n" -"use zerocopy::AsBytes;\n" -"\n" -"#[repr(u32)]\n" -"#[derive(AsBytes, Debug, Default)]\n" -"enum RequestType {\n" -" #[default]\n" -" In = 0,\n" -" Out = 1,\n" -" Flush = 4,\n" -"}\n" -"\n" -"#[repr(C)]\n" -"#[derive(AsBytes, Debug, Default)]\n" -"struct VirtioBlockRequest {\n" -" request_type: RequestType,\n" -" reserved: u32,\n" -" sector: u64,\n" -"}\n" -"\n" -"fn main() {\n" -" let request = VirtioBlockRequest {\n" -" request_type: RequestType::Flush,\n" -" sector: 42,\n" -" ..Default::default()\n" -" };\n" -"\n" -" assert_eq!(\n" -" request.as_bytes(),\n" -" &[4, 0, 0, 0, 0, 0, 0, 0, 42, 0, 0, 0, 0, 0, 0, 0]\n" -" );\n" -"}\n" -"```" +#: src/bare-metal/aps/better-uart.md:13 src/bare-metal/aps/better-uart.md:16 +msgid "16" msgstr "" -#: src/bare-metal/useful-crates/zerocopy.md:40 -msgid "" -"This is not suitable for MMIO (as it doesn't use volatile reads and writes), " -"but can be useful for working with structures shared with hardware e.g. by " -"DMA, or sent over some external interface." -msgstr "" - -#: src/bare-metal/useful-crates/zerocopy.md:45 -msgid "" -"`FromBytes` can be implemented for types for which any byte pattern is " -"valid, and so can safely be converted from an untrusted sequence of bytes." +#: src/bare-metal/aps/better-uart.md:14 +msgid "0x28" msgstr "" -#: src/bare-metal/useful-crates/zerocopy.md:47 -msgid "" -"Attempting to derive `FromBytes` for these types would fail, because " -"`RequestType` doesn't use all possible u32 values as discriminants, so not " -"all byte patterns are valid." +#: src/bare-metal/aps/better-uart.md:14 +msgid "FBRD" msgstr "" -#: src/bare-metal/useful-crates/zerocopy.md:49 -msgid "" -"`zerocopy::byteorder` has types for byte-order aware numeric primitives." +#: src/bare-metal/aps/better-uart.md:14 src/bare-metal/aps/better-uart.md:17 +msgid "6" msgstr "" -#: src/bare-metal/useful-crates/zerocopy.md:50 -msgid "" -"Run the example with `cargo run` under `src/bare-metal/useful-crates/" -"zerocopy-example/`. (It won't run in the Playground because of the crate " -"dependency.)" +#: src/bare-metal/aps/better-uart.md:15 +msgid "0x2c" msgstr "" -#: src/bare-metal/useful-crates/aarch64-paging.md:1 -msgid "`aarch64-paging`" +#: src/bare-metal/aps/better-uart.md:15 +msgid "LCR_H" msgstr "" -#: src/bare-metal/useful-crates/aarch64-paging.md:3 -msgid "" -"The [`aarch64-paging`](https://crates.io/crates/aarch64-paging) crate lets " -"you create page tables according to the AArch64 Virtual Memory System " -"Architecture." +#: src/bare-metal/aps/better-uart.md:16 +msgid "0x30" msgstr "" -#: src/bare-metal/useful-crates/aarch64-paging.md:6 -msgid "" -"```rust,editable,compile_fail\n" -"use aarch64_paging::{\n" -" idmap::IdMap,\n" -" paging::{Attributes, MemoryRegion},\n" -"};\n" -"\n" -"const ASID: usize = 1;\n" -"const ROOT_LEVEL: usize = 1;\n" -"\n" -"// Create a new page table with identity mapping.\n" -"let mut idmap = IdMap::new(ASID, ROOT_LEVEL);\n" -"// Map a 2 MiB region of memory as read-only.\n" -"idmap.map_range(\n" -" &MemoryRegion::new(0x80200000, 0x80400000),\n" -" Attributes::NORMAL | Attributes::NON_GLOBAL | Attributes::READ_ONLY,\n" -").unwrap();\n" -"// Set `TTBR0_EL1` to activate the page table.\n" -"idmap.activate();\n" -"```" +#: src/bare-metal/aps/better-uart.md:16 +msgid "CR" msgstr "" -#: src/bare-metal/useful-crates/aarch64-paging.md:28 -msgid "" -"For now it only supports EL1, but support for other exception levels should " -"be straightforward to add." +#: src/bare-metal/aps/better-uart.md:17 +msgid "0x34" msgstr "" -#: src/bare-metal/useful-crates/aarch64-paging.md:30 -msgid "" -"This is used in Android for the [Protected VM Firmware](https://cs.android." -"com/android/platform/superproject/+/master:packages/modules/Virtualization/" -"pvmfw/)." +#: src/bare-metal/aps/better-uart.md:17 +msgid "IFLS" msgstr "" -#: src/bare-metal/useful-crates/aarch64-paging.md:31 -msgid "" -"There's no easy way to run this example, as it needs to run on real hardware " -"or under QEMU." +#: src/bare-metal/aps/better-uart.md:18 +msgid "0x38" msgstr "" -#: src/bare-metal/useful-crates/buddy_system_allocator.md:1 -msgid "`buddy_system_allocator`" +#: src/bare-metal/aps/better-uart.md:18 +msgid "IMSC" msgstr "" -#: src/bare-metal/useful-crates/buddy_system_allocator.md:3 -msgid "" -"[`buddy_system_allocator`](https://crates.io/crates/buddy_system_allocator) " -"is a third-party crate implementing a basic buddy system allocator. It can " -"be used both for [`LockedHeap`](https://docs.rs/buddy_system_allocator/0.9.0/" -"buddy_system_allocator/struct.LockedHeap.html) implementing [`GlobalAlloc`]" -"(https://doc.rust-lang.org/core/alloc/trait.GlobalAlloc.html) so you can use " -"the standard `alloc` crate (as we saw [before](../alloc.md)), or for " -"allocating other address space. For example, we might want to allocate MMIO " -"space for PCI BARs:" +#: src/bare-metal/aps/better-uart.md:18 src/bare-metal/aps/better-uart.md:19 +#: src/bare-metal/aps/better-uart.md:20 src/bare-metal/aps/better-uart.md:21 +msgid "11" msgstr "" -#: src/bare-metal/useful-crates/buddy_system_allocator.md:8 -msgid "" -"```rust,editable,compile_fail\n" -"use buddy_system_allocator::FrameAllocator;\n" -"use core::alloc::Layout;\n" -"\n" -"fn main() {\n" -" let mut allocator = FrameAllocator::<32>::new();\n" -" allocator.add_frame(0x200_0000, 0x400_0000);\n" -"\n" -" let layout = Layout::from_size_align(0x100, 0x100).unwrap();\n" -" let bar = allocator\n" -" .alloc_aligned(layout)\n" -" .expect(\"Failed to allocate 0x100 byte MMIO region\");\n" -" println!(\"Allocated 0x100 byte MMIO region at {:#x}\", bar);\n" -"}\n" -"```" +#: src/bare-metal/aps/better-uart.md:19 +msgid "0x3c" msgstr "" -#: src/bare-metal/useful-crates/buddy_system_allocator.md:26 -msgid "PCI BARs always have alignment equal to their size." +#: src/bare-metal/aps/better-uart.md:19 +msgid "RIS" msgstr "" -#: src/bare-metal/useful-crates/buddy_system_allocator.md:27 -msgid "" -"Run the example with `cargo run` under `src/bare-metal/useful-crates/" -"allocator-example/`. (It won't run in the Playground because of the crate " -"dependency.)" +#: src/bare-metal/aps/better-uart.md:20 +msgid "0x40" msgstr "" -#: src/bare-metal/useful-crates/tinyvec.md:1 -msgid "`tinyvec`" +#: src/bare-metal/aps/better-uart.md:20 +msgid "MIS" msgstr "" -#: src/bare-metal/useful-crates/tinyvec.md:3 -msgid "" -"Sometimes you want something which can be resized like a `Vec`, but without " -"heap allocation. [`tinyvec`](https://crates.io/crates/tinyvec) provides " -"this: a vector backed by an array or slice, which could be statically " -"allocated or on the stack, which keeps track of how many elements are used " -"and panics if you try to use more than are allocated." +#: src/bare-metal/aps/better-uart.md:21 +msgid "0x44" msgstr "" -#: src/bare-metal/useful-crates/tinyvec.md:8 -msgid "" -"```rust,editable,compile_fail\n" -"use tinyvec::{array_vec, ArrayVec};\n" -"\n" -"fn main() {\n" -" let mut numbers: ArrayVec<[u32; 5]> = array_vec!(42, 66);\n" -" println!(\"{numbers:?}\");\n" -" numbers.push(7);\n" -" println!(\"{numbers:?}\");\n" -" numbers.remove(1);\n" -" println!(\"{numbers:?}\");\n" -"}\n" -"```" +#: src/bare-metal/aps/better-uart.md:21 +msgid "ICR" msgstr "" -#: src/bare-metal/useful-crates/tinyvec.md:23 -msgid "" -"`tinyvec` requires that the element type implement `Default` for " -"initialisation." +#: src/bare-metal/aps/better-uart.md:22 +msgid "0x48" msgstr "" -#: src/bare-metal/useful-crates/tinyvec.md:24 -msgid "" -"The Rust Playground includes `tinyvec`, so this example will run fine inline." +#: src/bare-metal/aps/better-uart.md:22 +msgid "DMACR" msgstr "" -#: src/bare-metal/useful-crates/spin.md:1 -msgid "`spin`" +#: src/bare-metal/aps/better-uart.md:22 +msgid "3" msgstr "" -#: src/bare-metal/useful-crates/spin.md:3 -msgid "" -"`std::sync::Mutex` and the other synchronisation primitives from `std::sync` " -"are not available in `core` or `alloc`. How can we manage synchronisation or " -"interior mutability, such as for sharing state between different CPUs?" +#: src/bare-metal/aps/better-uart.md:26 +msgid "There are also some ID registers which have been omitted for brevity." msgstr "" -#: src/bare-metal/useful-crates/spin.md:7 +#: src/bare-metal/aps/better-uart/bitflags.md:3 msgid "" -"The [`spin`](https://crates.io/crates/spin) crate provides spinlock-based " -"equivalents of many of these primitives." +"The [`bitflags`](https://crates.io/crates/bitflags) crate is useful for " +"working with bitflags." msgstr "" -#: src/bare-metal/useful-crates/spin.md:9 +#: src/bare-metal/aps/better-uart/bitflags.md:5 msgid "" "```rust,editable,compile_fail\n" -"use spin::mutex::SpinMutex;\n" -"\n" -"static counter: SpinMutex = SpinMutex::new(0);\n" +"use bitflags::bitflags;\n" "\n" -"fn main() {\n" -" println!(\"count: {}\", counter.lock());\n" -" *counter.lock() += 2;\n" -" println!(\"count: {}\", counter.lock());\n" +"bitflags! {\n" +" /// Flags from the UART flag register.\n" +" #[repr(transparent)]\n" +" #[derive(Copy, Clone, Debug, Eq, PartialEq)]\n" +" struct Flags: u16 {\n" +" /// Clear to send.\n" +" const CTS = 1 << 0;\n" +" /// Data set ready.\n" +" const DSR = 1 << 1;\n" +" /// Data carrier detect.\n" +" const DCD = 1 << 2;\n" +" /// UART busy transmitting data.\n" +" const BUSY = 1 << 3;\n" +" /// Receive FIFO is empty.\n" +" const RXFE = 1 << 4;\n" +" /// Transmit FIFO is full.\n" +" const TXFF = 1 << 5;\n" +" /// Receive FIFO is full.\n" +" const RXFF = 1 << 6;\n" +" /// Transmit FIFO is empty.\n" +" const TXFE = 1 << 7;\n" +" /// Ring indicator.\n" +" const RI = 1 << 8;\n" +" }\n" "}\n" "```" msgstr "" -#: src/bare-metal/useful-crates/spin.md:23 -msgid "Be careful to avoid deadlock if you take locks in interrupt handlers." -msgstr "" - -#: src/bare-metal/useful-crates/spin.md:24 -msgid "" -"`spin` also has a ticket lock mutex implementation; equivalents of `RwLock`, " -"`Barrier` and `Once` from `std::sync`; and `Lazy` for lazy initialisation." -msgstr "" - -#: src/bare-metal/useful-crates/spin.md:26 +#: src/bare-metal/aps/better-uart/bitflags.md:37 msgid "" -"The [`once_cell`](https://crates.io/crates/once_cell) crate also has some " -"useful types for late initialisation with a slightly different approach to " -"`spin::once::Once`." +"The `bitflags!` macro creates a newtype something like `Flags(u16)`, along " +"with a bunch of method implementations to get and set flags." msgstr "" -#: src/bare-metal/useful-crates/spin.md:28 -msgid "" -"The Rust Playground includes `spin`, so this example will run fine inline." +#: src/bare-metal/aps/better-uart/registers.md:1 +msgid "Multiple registers" msgstr "" -#: src/bare-metal/android.md:3 +#: src/bare-metal/aps/better-uart/registers.md:3 msgid "" -"To build a bare-metal Rust binary in AOSP, you need to use a " -"`rust_ffi_static` Soong rule to build your Rust code, then a `cc_binary` " -"with a linker script to produce the binary itself, and then a `raw_binary` " -"to convert the ELF to a raw binary ready to be run." +"We can use a struct to represent the memory layout of the UART's registers." msgstr "" -#: src/bare-metal/android.md:7 +#: src/bare-metal/aps/better-uart/registers.md:5 msgid "" -"```soong\n" -"rust_ffi_static {\n" -" name: \"libvmbase_example\",\n" -" defaults: [\"vmbase_ffi_defaults\"],\n" -" crate_name: \"vmbase_example\",\n" -" srcs: [\"src/main.rs\"],\n" -" rustlibs: [\n" -" \"libvmbase\",\n" -" ],\n" -"}\n" -"\n" -"cc_binary {\n" -" name: \"vmbase_example\",\n" -" defaults: [\"vmbase_elf_defaults\"],\n" -" srcs: [\n" -" \"idmap.S\",\n" -" ],\n" -" static_libs: [\n" -" \"libvmbase_example\",\n" -" ],\n" -" linker_scripts: [\n" -" \"image.ld\",\n" -" \":vmbase_sections\",\n" -" ],\n" -"}\n" -"\n" -"raw_binary {\n" -" name: \"vmbase_example_bin\",\n" -" stem: \"vmbase_example.bin\",\n" -" src: \":vmbase_example\",\n" -" enabled: false,\n" -" target: {\n" -" android_arm64: {\n" -" enabled: true,\n" -" },\n" -" },\n" +"```rust,editable,compile_fail\n" +"#[repr(C, align(4))]\n" +"struct Registers {\n" +" dr: u16,\n" +" _reserved0: [u8; 2],\n" +" rsr: ReceiveStatus,\n" +" _reserved1: [u8; 19],\n" +" fr: Flags,\n" +" _reserved2: [u8; 6],\n" +" ilpr: u8,\n" +" _reserved3: [u8; 3],\n" +" ibrd: u16,\n" +" _reserved4: [u8; 2],\n" +" fbrd: u8,\n" +" _reserved5: [u8; 3],\n" +" lcr_h: u8,\n" +" _reserved6: [u8; 3],\n" +" cr: u16,\n" +" _reserved7: [u8; 3],\n" +" ifls: u8,\n" +" _reserved8: [u8; 3],\n" +" imsc: u16,\n" +" _reserved9: [u8; 2],\n" +" ris: u16,\n" +" _reserved10: [u8; 2],\n" +" mis: u16,\n" +" _reserved11: [u8; 2],\n" +" icr: u16,\n" +" _reserved12: [u8; 2],\n" +" dmacr: u8,\n" +" _reserved13: [u8; 3],\n" "}\n" "```" msgstr "" -#: src/bare-metal/android/vmbase.md:3 +#: src/bare-metal/aps/better-uart/registers.md:41 msgid "" -"For VMs running under crosvm on aarch64, the [vmbase](https://android." -"googlesource.com/platform/packages/modules/Virtualization/+/refs/heads/" -"master/vmbase/) library provides a linker script and useful defaults for the " -"build rules, along with an entry point, UART console logging and more." +"[`#[repr(C)]`](https://doc.rust-lang.org/reference/type-layout.html#the-c-" +"representation) tells the compiler to lay the struct fields out in order, " +"following the same rules as C. This is necessary for our struct to have a " +"predictable layout, as default Rust representation allows the compiler to " +"(among other things) reorder fields however it sees fit." msgstr "" -#: src/bare-metal/android/vmbase.md:6 +#: src/bare-metal/aps/better-uart/driver.md:3 +msgid "Now let's use the new `Registers` struct in our driver." +msgstr "" + +#: src/bare-metal/aps/better-uart/driver.md:5 msgid "" -"```rust,compile_fail\n" -"#![no_main]\n" -"#![no_std]\n" +"```rust,editable,compile_fail\n" +"/// Driver for a PL011 UART.\n" +"#[derive(Debug)]\n" +"pub struct Uart {\n" +" registers: *mut Registers,\n" +"}\n" "\n" -"use vmbase::{main, println};\n" +"impl Uart {\n" +" /// Constructs a new instance of the UART driver for a PL011 device at " +"the\n" +" /// given base address.\n" +" ///\n" +" /// # Safety\n" +" ///\n" +" /// The given base address must point to the 8 MMIO control registers of " +"a\n" +" /// PL011 device, which must be mapped into the address space of the " +"process\n" +" /// as device memory and not have any other aliases.\n" +" pub unsafe fn new(base_address: *mut u32) -> Self {\n" +" Self {\n" +" registers: base_address as *mut Registers,\n" +" }\n" +" }\n" "\n" -"main!(main);\n" +" /// Writes a single byte to the UART.\n" +" pub fn write_byte(&self, byte: u8) {\n" +" // Wait until there is room in the TX buffer.\n" +" while self.read_flag_register().contains(Flags::TXFF) {}\n" "\n" -"pub fn main(arg0: u64, arg1: u64, arg2: u64, arg3: u64) {\n" -" println!(\"Hello world\");\n" +" // Safe because we know that self.registers points to the control\n" +" // registers of a PL011 device which is appropriately mapped.\n" +" unsafe {\n" +" // Write to the TX buffer.\n" +" addr_of_mut!((*self.registers).dr).write_volatile(byte.into());\n" +" }\n" +"\n" +" // Wait until the UART is no longer busy.\n" +" while self.read_flag_register().contains(Flags::BUSY) {}\n" +" }\n" +"\n" +" /// Reads and returns a pending byte, or `None` if nothing has been " +"received.\n" +" pub fn read_byte(&self) -> Option {\n" +" if self.read_flag_register().contains(Flags::RXFE) {\n" +" None\n" +" } else {\n" +" let data = unsafe { addr_of!((*self.registers).dr)." +"read_volatile() };\n" +" // TODO: Check for error conditions in bits 8-11.\n" +" Some(data as u8)\n" +" }\n" +" }\n" +"\n" +" fn read_flag_register(&self) -> Flags {\n" +" // Safe because we know that self.registers points to the control\n" +" // registers of a PL011 device which is appropriately mapped.\n" +" unsafe { addr_of!((*self.registers).fr).read_volatile() }\n" +" }\n" "}\n" "```" msgstr "" -#: src/bare-metal/android/vmbase.md:21 -msgid "" -"The `main!` macro marks your main function, to be called from the `vmbase` " -"entry point." -msgstr "" - -#: src/bare-metal/android/vmbase.md:22 -msgid "" -"The `vmbase` entry point handles console initialisation, and issues a " -"PSCI_SYSTEM_OFF to shutdown the VM if your main function returns." -msgstr "" - -#: src/exercises/bare-metal/afternoon.md:3 -msgid "We will write a driver for the PL031 real-time clock device." -msgstr "" - -#: src/exercises/bare-metal/rtc.md:1 -#: src/exercises/bare-metal/solutions-afternoon.md:3 -msgid "RTC driver" -msgstr "" - -#: src/exercises/bare-metal/rtc.md:3 -msgid "" -"The QEMU aarch64 virt machine has a [PL031](https://developer.arm.com/" -"documentation/ddi0224/c) real-time clock at 0x9010000. For this exercise, " -"you should write a driver for it." -msgstr "" - -#: src/exercises/bare-metal/rtc.md:6 -msgid "" -"Use it to print the current time to the serial console. You can use the " -"[`chrono`](https://crates.io/crates/chrono) crate for date/time formatting." -msgstr "" - -#: src/exercises/bare-metal/rtc.md:8 -msgid "" -"Use the match register and raw interrupt status to busy-wait until a given " -"time, e.g. 3 seconds in the future. (Call [`core::hint::spin_loop`](https://" -"doc.rust-lang.org/core/hint/fn.spin_loop.html) inside the loop.)" -msgstr "" - -#: src/exercises/bare-metal/rtc.md:10 +#: src/bare-metal/aps/better-uart/driver.md:64 msgid "" -"_Extension if you have time:_ Enable and handle the interrupt generated by " -"the RTC match. You can use the driver provided in the [`arm-gic`](https://" -"docs.rs/arm-gic/) crate to configure the Arm Generic Interrupt Controller." -msgstr "" - -#: src/exercises/bare-metal/rtc.md:12 -msgid "Use the RTC interrupt, which is wired to the GIC as `IntId::spi(2)`." +"Note the use of `addr_of!` / `addr_of_mut!` to get pointers to individual " +"fields without creating an intermediate reference, which would be unsound." msgstr "" -#: src/exercises/bare-metal/rtc.md:13 -msgid "" -"Once the interrupt is enabled, you can put the core to sleep via `arm_gic::" -"wfi()`, which will cause the core to sleep until it receives an interrupt." +#: src/bare-metal/aps/better-uart/using.md:1 +#: src/bare-metal/aps/logging/using.md:1 +msgid "Using it" msgstr "" -#: src/exercises/bare-metal/rtc.md:16 +#: src/bare-metal/aps/better-uart/using.md:3 msgid "" -"Download the [exercise template](../../comprehensive-rust-exercises.zip) and " -"look in the `rtc` directory for the following files." +"Let's write a small program using our driver to write to the serial console, " +"and echo incoming bytes." msgstr "" -#: src/exercises/bare-metal/rtc.md:23 +#: src/bare-metal/aps/better-uart/using.md:6 msgid "" -"```rust,compile_fail\n" +"```rust,editable,compile_fail\n" "#![no_main]\n" "#![no_std]\n" "\n" "mod exceptions;\n" -"mod logger;\n" "mod pl011;\n" "\n" "use crate::pl011::Uart;\n" -"use arm_gic::gicv3::GicV3;\n" +"use core::fmt::Write;\n" "use core::panic::PanicInfo;\n" -"use log::{error, info, trace, LevelFilter};\n" +"use log::error;\n" "use smccc::psci::system_off;\n" "use smccc::Hvc;\n" "\n" -"/// Base addresses of the GICv3.\n" -"const GICD_BASE_ADDRESS: *mut u64 = 0x800_0000 as _;\n" -"const GICR_BASE_ADDRESS: *mut u64 = 0x80A_0000 as _;\n" -"\n" "/// Base address of the primary PL011 UART.\n" "const PL011_BASE_ADDRESS: *mut u32 = 0x900_0000 as _;\n" "\n" @@ -14190,137 +14213,51 @@ msgid "" " // Safe because `PL011_BASE_ADDRESS` is the base address of a PL011 " "device,\n" " // and nothing else accesses that address range.\n" -" let uart = unsafe { Uart::new(PL011_BASE_ADDRESS) };\n" -" logger::init(uart, LevelFilter::Trace).unwrap();\n" -"\n" -" info!(\"main({:#x}, {:#x}, {:#x}, {:#x})\", x0, x1, x2, x3);\n" -"\n" -" // Safe because `GICD_BASE_ADDRESS` and `GICR_BASE_ADDRESS` are the " -"base\n" -" // addresses of a GICv3 distributor and redistributor respectively, and\n" -" // nothing else accesses those address ranges.\n" -" let mut gic = unsafe { GicV3::new(GICD_BASE_ADDRESS, " -"GICR_BASE_ADDRESS) };\n" -" gic.setup();\n" -"\n" -" // TODO: Create instance of RTC driver and print current time.\n" +" let mut uart = unsafe { Uart::new(PL011_BASE_ADDRESS) };\n" "\n" -" // TODO: Wait for 3 seconds.\n" +" writeln!(uart, \"main({x0:#x}, {x1:#x}, {x2:#x}, {x3:#x})\").unwrap();\n" "\n" -" system_off::().unwrap();\n" -"}\n" +" loop {\n" +" if let Some(byte) = uart.read_byte() {\n" +" uart.write_byte(byte);\n" +" match byte {\n" +" b'\\r' => {\n" +" uart.write_byte(b'\\n');\n" +" }\n" +" b'q' => break,\n" +" _ => {}\n" +" }\n" +" }\n" +" }\n" "\n" -"#[panic_handler]\n" -"fn panic(info: &PanicInfo) -> ! {\n" -" error!(\"{info}\");\n" +" writeln!(uart, \"Bye!\").unwrap();\n" " system_off::().unwrap();\n" -" loop {}\n" "}\n" "```" msgstr "" -#: src/exercises/bare-metal/rtc.md:75 +#: src/bare-metal/aps/better-uart/using.md:51 msgid "" -"`src/exceptions.rs` (you should only need to change this for the 3rd part of " -"the exercise):" +"As in the [inline assembly](../inline-assembly.md) example, this `main` " +"function is called from our entry point code in `entry.S`. See the speaker " +"notes there for details." msgstr "" -#: src/exercises/bare-metal/rtc.md:79 +#: src/bare-metal/aps/better-uart/using.md:53 msgid "" -"```rust,compile_fail\n" -"// Copyright 2023 Google LLC\n" -"//\n" -"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"// you may not use this file except in compliance with the License.\n" -"// You may obtain a copy of the License at\n" -"//\n" -"// http://www.apache.org/licenses/LICENSE-2.0\n" -"//\n" -"// Unless required by applicable law or agreed to in writing, software\n" -"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"// See the License for the specific language governing permissions and\n" -"// limitations under the License.\n" -"\n" -"use arm_gic::gicv3::GicV3;\n" -"use log::{error, info, trace};\n" -"use smccc::psci::system_off;\n" -"use smccc::Hvc;\n" -"\n" -"#[no_mangle]\n" -"extern \"C\" fn sync_exception_current(_elr: u64, _spsr: u64) {\n" -" error!(\"sync_exception_current\");\n" -" system_off::().unwrap();\n" -"}\n" -"\n" -"#[no_mangle]\n" -"extern \"C\" fn irq_current(_elr: u64, _spsr: u64) {\n" -" trace!(\"irq_current\");\n" -" let intid = GicV3::get_and_acknowledge_interrupt().expect(\"No pending " -"interrupt\");\n" -" info!(\"IRQ {intid:?}\");\n" -"}\n" -"\n" -"#[no_mangle]\n" -"extern \"C\" fn fiq_current(_elr: u64, _spsr: u64) {\n" -" error!(\"fiq_current\");\n" -" system_off::().unwrap();\n" -"}\n" -"\n" -"#[no_mangle]\n" -"extern \"C\" fn serr_current(_elr: u64, _spsr: u64) {\n" -" error!(\"serr_current\");\n" -" system_off::().unwrap();\n" -"}\n" -"\n" -"#[no_mangle]\n" -"extern \"C\" fn sync_lower(_elr: u64, _spsr: u64) {\n" -" error!(\"sync_lower\");\n" -" system_off::().unwrap();\n" -"}\n" -"\n" -"#[no_mangle]\n" -"extern \"C\" fn irq_lower(_elr: u64, _spsr: u64) {\n" -" error!(\"irq_lower\");\n" -" system_off::().unwrap();\n" -"}\n" -"\n" -"#[no_mangle]\n" -"extern \"C\" fn fiq_lower(_elr: u64, _spsr: u64) {\n" -" error!(\"fiq_lower\");\n" -" system_off::().unwrap();\n" -"}\n" -"\n" -"#[no_mangle]\n" -"extern \"C\" fn serr_lower(_elr: u64, _spsr: u64) {\n" -" error!(\"serr_lower\");\n" -" system_off::().unwrap();\n" -"}\n" -"```" +"Run the example in QEMU with `make qemu` under `src/bare-metal/aps/examples`." msgstr "" -#: src/exercises/bare-metal/rtc.md:149 -msgid "`src/logger.rs` (you shouldn't need to change this):" +#: src/bare-metal/aps/logging.md:3 +msgid "" +"It would be nice to be able to use the logging macros from the [`log`]" +"(https://crates.io/crates/log) crate. We can do this by implementing the " +"`Log` trait." msgstr "" -#: src/exercises/bare-metal/rtc.md:153 +#: src/bare-metal/aps/logging.md:6 msgid "" -"```rust,compile_fail\n" -"// Copyright 2023 Google LLC\n" -"//\n" -"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"// you may not use this file except in compliance with the License.\n" -"// You may obtain a copy of the License at\n" -"//\n" -"// http://www.apache.org/licenses/LICENSE-2.0\n" -"//\n" -"// Unless required by applicable law or agreed to in writing, software\n" -"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"// See the License for the specific language governing permissions and\n" -"// limitations under the License.\n" -"\n" -"// ANCHOR: main\n" +"```rust,editable,compile_fail\n" "use crate::pl011::Uart;\n" "use core::fmt::Write;\n" "use log::{LevelFilter, Log, Metadata, Record, SetLoggerError};\n" @@ -14364,3877 +14301,4479 @@ msgid "" "```" msgstr "" -#: src/exercises/bare-metal/rtc.md:210 -msgid "`src/pl011.rs` (you shouldn't need to change this):" +#: src/bare-metal/aps/logging.md:50 +msgid "" +"The unwrap in `log` is safe because we initialise `LOGGER` before calling " +"`set_logger`." msgstr "" -#: src/exercises/bare-metal/rtc.md:214 +#: src/bare-metal/aps/logging/using.md:3 +msgid "We need to initialise the logger before we use it." +msgstr "" + +#: src/bare-metal/aps/logging/using.md:5 msgid "" -"```rust,compile_fail\n" -"// Copyright 2023 Google LLC\n" -"//\n" -"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"// you may not use this file except in compliance with the License.\n" -"// You may obtain a copy of the License at\n" -"//\n" -"// http://www.apache.org/licenses/LICENSE-2.0\n" -"//\n" -"// Unless required by applicable law or agreed to in writing, software\n" -"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"// See the License for the specific language governing permissions and\n" -"// limitations under the License.\n" +"```rust,editable,compile_fail\n" +"#![no_main]\n" +"#![no_std]\n" "\n" -"#![allow(unused)]\n" +"mod exceptions;\n" +"mod logger;\n" +"mod pl011;\n" "\n" -"use core::fmt::{self, Write};\n" -"use core::ptr::{addr_of, addr_of_mut};\n" +"use crate::pl011::Uart;\n" +"use core::panic::PanicInfo;\n" +"use log::{error, info, LevelFilter};\n" +"use smccc::psci::system_off;\n" +"use smccc::Hvc;\n" "\n" -"// ANCHOR: Flags\n" -"use bitflags::bitflags;\n" +"/// Base address of the primary PL011 UART.\n" +"const PL011_BASE_ADDRESS: *mut u32 = 0x900_0000 as _;\n" "\n" -"bitflags! {\n" -" /// Flags from the UART flag register.\n" -" #[repr(transparent)]\n" -" #[derive(Copy, Clone, Debug, Eq, PartialEq)]\n" -" struct Flags: u16 {\n" -" /// Clear to send.\n" -" const CTS = 1 << 0;\n" -" /// Data set ready.\n" -" const DSR = 1 << 1;\n" -" /// Data carrier detect.\n" -" const DCD = 1 << 2;\n" -" /// UART busy transmitting data.\n" -" const BUSY = 1 << 3;\n" -" /// Receive FIFO is empty.\n" -" const RXFE = 1 << 4;\n" -" /// Transmit FIFO is full.\n" -" const TXFF = 1 << 5;\n" -" /// Receive FIFO is full.\n" -" const RXFF = 1 << 6;\n" -" /// Transmit FIFO is empty.\n" -" const TXFE = 1 << 7;\n" -" /// Ring indicator.\n" -" const RI = 1 << 8;\n" -" }\n" -"}\n" -"// ANCHOR_END: Flags\n" +"#[no_mangle]\n" +"extern \"C\" fn main(x0: u64, x1: u64, x2: u64, x3: u64) {\n" +" // Safe because `PL011_BASE_ADDRESS` is the base address of a PL011 " +"device,\n" +" // and nothing else accesses that address range.\n" +" let uart = unsafe { Uart::new(PL011_BASE_ADDRESS) };\n" +" logger::init(uart, LevelFilter::Trace).unwrap();\n" "\n" -"bitflags! {\n" -" /// Flags from the UART Receive Status Register / Error Clear Register.\n" -" #[repr(transparent)]\n" -" #[derive(Copy, Clone, Debug, Eq, PartialEq)]\n" -" struct ReceiveStatus: u16 {\n" -" /// Framing error.\n" -" const FE = 1 << 0;\n" -" /// Parity error.\n" -" const PE = 1 << 1;\n" -" /// Break error.\n" -" const BE = 1 << 2;\n" -" /// Overrun error.\n" -" const OE = 1 << 3;\n" -" }\n" -"}\n" +" info!(\"main({x0:#x}, {x1:#x}, {x2:#x}, {x3:#x})\");\n" "\n" -"// ANCHOR: Registers\n" -"#[repr(C, align(4))]\n" -"struct Registers {\n" -" dr: u16,\n" -" _reserved0: [u8; 2],\n" -" rsr: ReceiveStatus,\n" -" _reserved1: [u8; 19],\n" -" fr: Flags,\n" -" _reserved2: [u8; 6],\n" -" ilpr: u8,\n" -" _reserved3: [u8; 3],\n" -" ibrd: u16,\n" -" _reserved4: [u8; 2],\n" -" fbrd: u8,\n" -" _reserved5: [u8; 3],\n" -" lcr_h: u8,\n" -" _reserved6: [u8; 3],\n" -" cr: u16,\n" -" _reserved7: [u8; 3],\n" -" ifls: u8,\n" -" _reserved8: [u8; 3],\n" -" imsc: u16,\n" -" _reserved9: [u8; 2],\n" -" ris: u16,\n" -" _reserved10: [u8; 2],\n" -" mis: u16,\n" -" _reserved11: [u8; 2],\n" -" icr: u16,\n" -" _reserved12: [u8; 2],\n" -" dmacr: u8,\n" -" _reserved13: [u8; 3],\n" -"}\n" -"// ANCHOR_END: Registers\n" +" assert_eq!(x1, 42);\n" "\n" -"// ANCHOR: Uart\n" -"/// Driver for a PL011 UART.\n" -"#[derive(Debug)]\n" -"pub struct Uart {\n" -" registers: *mut Registers,\n" +" system_off::().unwrap();\n" "}\n" "\n" -"impl Uart {\n" -" /// Constructs a new instance of the UART driver for a PL011 device at " -"the\n" -" /// given base address.\n" -" ///\n" -" /// # Safety\n" -" ///\n" -" /// The given base address must point to the MMIO control registers of " -"a\n" -" /// PL011 device, which must be mapped into the address space of the " -"process\n" -" /// as device memory and not have any other aliases.\n" -" pub unsafe fn new(base_address: *mut u32) -> Self {\n" -" Self {\n" -" registers: base_address as *mut Registers,\n" -" }\n" -" }\n" -"\n" -" /// Writes a single byte to the UART.\n" -" pub fn write_byte(&self, byte: u8) {\n" -" // Wait until there is room in the TX buffer.\n" -" while self.read_flag_register().contains(Flags::TXFF) {}\n" +"#[panic_handler]\n" +"fn panic(info: &PanicInfo) -> ! {\n" +" error!(\"{info}\");\n" +" system_off::().unwrap();\n" +" loop {}\n" +"}\n" +"```" +msgstr "" + +#: src/bare-metal/aps/logging/using.md:46 +msgid "Note that our panic handler can now log details of panics." +msgstr "" + +#: src/bare-metal/aps/logging/using.md:47 +msgid "" +"Run the example in QEMU with `make qemu_logger` under `src/bare-metal/aps/" +"examples`." +msgstr "" + +#: src/bare-metal/aps/exceptions.md:3 +msgid "" +"AArch64 defines an exception vector table with 16 entries, for 4 types of " +"exceptions (synchronous, IRQ, FIQ, SError) from 4 states (current EL with " +"SP0, current EL with SPx, lower EL using AArch64, lower EL using AArch32). " +"We implement this in assembly to save volatile registers to the stack before " +"calling into Rust code:" +msgstr "" + +#: src/bare-metal/aps/exceptions.md:8 +msgid "" +"```rust,editable,compile_fail\n" +"use log::error;\n" +"use smccc::psci::system_off;\n" +"use smccc::Hvc;\n" "\n" -" // Safe because we know that self.registers points to the control\n" -" // registers of a PL011 device which is appropriately mapped.\n" -" unsafe {\n" -" // Write to the TX buffer.\n" -" addr_of_mut!((*self.registers).dr).write_volatile(byte.into());\n" -" }\n" +"#[no_mangle]\n" +"extern \"C\" fn sync_exception_current(_elr: u64, _spsr: u64) {\n" +" error!(\"sync_exception_current\");\n" +" system_off::().unwrap();\n" +"}\n" "\n" -" // Wait until the UART is no longer busy.\n" -" while self.read_flag_register().contains(Flags::BUSY) {}\n" -" }\n" +"#[no_mangle]\n" +"extern \"C\" fn irq_current(_elr: u64, _spsr: u64) {\n" +" error!(\"irq_current\");\n" +" system_off::().unwrap();\n" +"}\n" "\n" -" /// Reads and returns a pending byte, or `None` if nothing has been " -"received.\n" -" pub fn read_byte(&self) -> Option {\n" -" if self.read_flag_register().contains(Flags::RXFE) {\n" -" None\n" -" } else {\n" -" let data = unsafe { addr_of!((*self.registers).dr)." -"read_volatile() };\n" -" // TODO: Check for error conditions in bits 8-11.\n" -" Some(data as u8)\n" -" }\n" -" }\n" +"#[no_mangle]\n" +"extern \"C\" fn fiq_current(_elr: u64, _spsr: u64) {\n" +" error!(\"fiq_current\");\n" +" system_off::().unwrap();\n" +"}\n" "\n" -" fn read_flag_register(&self) -> Flags {\n" -" // Safe because we know that self.registers points to the control\n" -" // registers of a PL011 device which is appropriately mapped.\n" -" unsafe { addr_of!((*self.registers).fr).read_volatile() }\n" -" }\n" +"#[no_mangle]\n" +"extern \"C\" fn serr_current(_elr: u64, _spsr: u64) {\n" +" error!(\"serr_current\");\n" +" system_off::().unwrap();\n" "}\n" -"// ANCHOR_END: Uart\n" "\n" -"impl Write for Uart {\n" -" fn write_str(&mut self, s: &str) -> fmt::Result {\n" -" for c in s.as_bytes() {\n" -" self.write_byte(*c);\n" -" }\n" -" Ok(())\n" -" }\n" +"#[no_mangle]\n" +"extern \"C\" fn sync_lower(_elr: u64, _spsr: u64) {\n" +" error!(\"sync_lower\");\n" +" system_off::().unwrap();\n" "}\n" "\n" -"// Safe because it just contains a pointer to device memory, which can be\n" -"// accessed from any context.\n" -"unsafe impl Send for Uart {}\n" +"#[no_mangle]\n" +"extern \"C\" fn irq_lower(_elr: u64, _spsr: u64) {\n" +" error!(\"irq_lower\");\n" +" system_off::().unwrap();\n" +"}\n" +"\n" +"#[no_mangle]\n" +"extern \"C\" fn fiq_lower(_elr: u64, _spsr: u64) {\n" +" error!(\"fiq_lower\");\n" +" system_off::().unwrap();\n" +"}\n" +"\n" +"#[no_mangle]\n" +"extern \"C\" fn serr_lower(_elr: u64, _spsr: u64) {\n" +" error!(\"serr_lower\");\n" +" system_off::().unwrap();\n" +"}\n" "```" msgstr "" -#: src/exercises/bare-metal/rtc.md:389 +#: src/bare-metal/aps/exceptions.md:64 +msgid "EL is exception level; all our examples this afternoon run in EL1." +msgstr "" + +#: src/bare-metal/aps/exceptions.md:65 msgid "" -"```toml\n" -"[workspace]\n" -"\n" -"[package]\n" -"name = \"rtc\"\n" -"version = \"0.1.0\"\n" -"edition = \"2021\"\n" -"publish = false\n" -"\n" -"[dependencies]\n" -"arm-gic = \"0.1.0\"\n" -"bitflags = \"2.0.0\"\n" -"chrono = { version = \"0.4.24\", default-features = false }\n" -"log = \"0.4.17\"\n" -"smccc = \"0.1.1\"\n" -"spin = \"0.9.8\"\n" -"\n" -"[build-dependencies]\n" -"cc = \"1.0.73\"\n" -"```" +"For simplicity we aren't distinguishing between SP0 and SPx for the current " +"EL exceptions, or between AArch32 and AArch64 for the lower EL exceptions." msgstr "" -#: src/exercises/bare-metal/rtc.md:410 -msgid "`build.rs` (you shouldn't need to change this):" +#: src/bare-metal/aps/exceptions.md:67 +msgid "" +"For this example we just log the exception and power down, as we don't " +"expect any of them to actually happen." msgstr "" -#: src/exercises/bare-metal/rtc.md:414 +#: src/bare-metal/aps/exceptions.md:69 msgid "" -"```rust,compile_fail\n" -"// Copyright 2023 Google LLC\n" -"//\n" -"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"// you may not use this file except in compliance with the License.\n" -"// You may obtain a copy of the License at\n" -"//\n" -"// http://www.apache.org/licenses/LICENSE-2.0\n" -"//\n" -"// Unless required by applicable law or agreed to in writing, software\n" -"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"// See the License for the specific language governing permissions and\n" -"// limitations under the License.\n" +"We can think of exception handlers and our main execution context more or " +"less like different threads. [`Send` and `Sync`](../../concurrency/send-sync." +"md) will control what we can share between them, just like with threads. For " +"example, if we want to share some value between exception handlers and the " +"rest of the program, and it's `Send` but not `Sync`, then we'll need to wrap " +"it in something like a `Mutex` and put it in a static." +msgstr "" + +#: src/bare-metal/aps/other-projects.md:3 +msgid "[oreboot](https://github.com/oreboot/oreboot)" +msgstr "" + +#: src/bare-metal/aps/other-projects.md:4 +msgid "\"coreboot without the C\"" +msgstr "" + +#: src/bare-metal/aps/other-projects.md:5 +msgid "Supports x86, aarch64 and RISC-V." +msgstr "" + +#: src/bare-metal/aps/other-projects.md:6 +msgid "Relies on LinuxBoot rather than having many drivers itself." +msgstr "" + +#: src/bare-metal/aps/other-projects.md:7 +msgid "" +"[Rust RaspberryPi OS tutorial](https://github.com/rust-embedded/rust-" +"raspberrypi-OS-tutorials)" +msgstr "" + +#: src/bare-metal/aps/other-projects.md:8 +msgid "" +"Initialisation, UART driver, simple bootloader, JTAG, exception levels, " +"exception handling, page tables" +msgstr "" + +#: src/bare-metal/aps/other-projects.md:10 +msgid "" +"Some dodginess around cache maintenance and initialisation in Rust, not " +"necessarily a good example to copy for production code." +msgstr "" + +#: src/bare-metal/aps/other-projects.md:12 +msgid "[`cargo-call-stack`](https://crates.io/crates/cargo-call-stack)" +msgstr "" + +#: src/bare-metal/aps/other-projects.md:13 +msgid "Static analysis to determine maximum stack usage." +msgstr "" + +#: src/bare-metal/aps/other-projects.md:17 +msgid "" +"The RaspberryPi OS tutorial runs Rust code before the MMU and caches are " +"enabled. This will read and write memory (e.g. the stack). However:" +msgstr "" + +#: src/bare-metal/aps/other-projects.md:19 +msgid "" +"Without the MMU and cache, unaligned accesses will fault. It builds with " +"`aarch64-unknown-none` which sets `+strict-align` to prevent the compiler " +"generating unaligned accesses so it should be alright, but this is not " +"necessarily the case in general." +msgstr "" + +#: src/bare-metal/aps/other-projects.md:22 +msgid "" +"If it were running in a VM, this can lead to cache coherency issues. The " +"problem is that the VM is accessing memory directly with the cache disabled, " +"while the host has cachable aliases to the same memory. Even if the host " +"doesn't explicitly access the memory, speculative accesses can lead to cache " +"fills, and then changes from one or the other will get lost. Again this is " +"alright in this particular case (running directly on the hardware with no " +"hypervisor), but isn't a good pattern in general." +msgstr "" + +#: src/bare-metal/useful-crates.md:3 +msgid "" +"We'll go over a few crates which solve some common problems in bare-metal " +"programming." +msgstr "" + +#: src/bare-metal/useful-crates/zerocopy.md:1 +msgid "`zerocopy`" +msgstr "" + +#: src/bare-metal/useful-crates/zerocopy.md:3 +msgid "" +"The [`zerocopy`](https://docs.rs/zerocopy/) crate (from Fuchsia) provides " +"traits and macros for safely converting between byte sequences and other " +"types." +msgstr "" + +#: src/bare-metal/useful-crates/zerocopy.md:6 +msgid "" +"```rust,editable,compile_fail\n" +"use zerocopy::AsBytes;\n" "\n" -"use cc::Build;\n" -"use std::env;\n" +"#[repr(u32)]\n" +"#[derive(AsBytes, Debug, Default)]\n" +"enum RequestType {\n" +" #[default]\n" +" In = 0,\n" +" Out = 1,\n" +" Flush = 4,\n" +"}\n" +"\n" +"#[repr(C)]\n" +"#[derive(AsBytes, Debug, Default)]\n" +"struct VirtioBlockRequest {\n" +" request_type: RequestType,\n" +" reserved: u32,\n" +" sector: u64,\n" +"}\n" "\n" "fn main() {\n" -" #[cfg(target_os = \"linux\")]\n" -" env::set_var(\"CROSS_COMPILE\", \"aarch64-linux-gnu\");\n" -" #[cfg(not(target_os = \"linux\"))]\n" -" env::set_var(\"CROSS_COMPILE\", \"aarch64-none-elf\");\n" +" let request = VirtioBlockRequest {\n" +" request_type: RequestType::Flush,\n" +" sector: 42,\n" +" ..Default::default()\n" +" };\n" "\n" -" Build::new()\n" -" .file(\"entry.S\")\n" -" .file(\"exceptions.S\")\n" -" .file(\"idmap.S\")\n" -" .compile(\"empty\")\n" +" assert_eq!(\n" +" request.as_bytes(),\n" +" &[4, 0, 0, 0, 0, 0, 0, 0, 42, 0, 0, 0, 0, 0, 0, 0]\n" +" );\n" "}\n" "```" msgstr "" -#: src/exercises/bare-metal/rtc.md:446 -msgid "`entry.S` (you shouldn't need to change this):" -msgstr "" +#: src/bare-metal/useful-crates/zerocopy.md:40 +msgid "" +"This is not suitable for MMIO (as it doesn't use volatile reads and writes), " +"but can be useful for working with structures shared with hardware e.g. by " +"DMA, or sent over some external interface." +msgstr "" -#: src/exercises/bare-metal/rtc.md:450 +#: src/bare-metal/useful-crates/zerocopy.md:45 msgid "" -"```armasm\n" -"/*\n" -" * Copyright 2023 Google LLC\n" -" *\n" -" * Licensed under the Apache License, Version 2.0 (the \"License\");\n" -" * you may not use this file except in compliance with the License.\n" -" * You may obtain a copy of the License at\n" -" *\n" -" * https://www.apache.org/licenses/LICENSE-2.0\n" -" *\n" -" * Unless required by applicable law or agreed to in writing, software\n" -" * distributed under the License is distributed on an \"AS IS\" BASIS,\n" -" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -" * See the License for the specific language governing permissions and\n" -" * limitations under the License.\n" -" */\n" -"\n" -".macro adr_l, reg:req, sym:req\n" -"\tadrp \\reg, \\sym\n" -"\tadd \\reg, \\reg, :lo12:\\sym\n" -".endm\n" -"\n" -".macro mov_i, reg:req, imm:req\n" -"\tmovz \\reg, :abs_g3:\\imm\n" -"\tmovk \\reg, :abs_g2_nc:\\imm\n" -"\tmovk \\reg, :abs_g1_nc:\\imm\n" -"\tmovk \\reg, :abs_g0_nc:\\imm\n" -".endm\n" -"\n" -".set .L_MAIR_DEV_nGnRE,\t0x04\n" -".set .L_MAIR_MEM_WBWA,\t0xff\n" -".set .Lmairval, .L_MAIR_DEV_nGnRE | (.L_MAIR_MEM_WBWA << 8)\n" -"\n" -"/* 4 KiB granule size for TTBR0_EL1. */\n" -".set .L_TCR_TG0_4KB, 0x0 << 14\n" -"/* 4 KiB granule size for TTBR1_EL1. */\n" -".set .L_TCR_TG1_4KB, 0x2 << 30\n" -"/* Disable translation table walk for TTBR1_EL1, generating a translation " -"fault instead. */\n" -".set .L_TCR_EPD1, 0x1 << 23\n" -"/* Translation table walks for TTBR0_EL1 are inner sharable. */\n" -".set .L_TCR_SH_INNER, 0x3 << 12\n" -"/*\n" -" * Translation table walks for TTBR0_EL1 are outer write-back read-allocate " -"write-allocate\n" -" * cacheable.\n" -" */\n" -".set .L_TCR_RGN_OWB, 0x1 << 10\n" -"/*\n" -" * Translation table walks for TTBR0_EL1 are inner write-back read-allocate " -"write-allocate\n" -" * cacheable.\n" -" */\n" -".set .L_TCR_RGN_IWB, 0x1 << 8\n" -"/* Size offset for TTBR0_EL1 is 2**39 bytes (512 GiB). */\n" -".set .L_TCR_T0SZ_512, 64 - 39\n" -".set .Ltcrval, .L_TCR_TG0_4KB | .L_TCR_TG1_4KB | .L_TCR_EPD1 | ." -"L_TCR_RGN_OWB\n" -".set .Ltcrval, .Ltcrval | .L_TCR_RGN_IWB | .L_TCR_SH_INNER | ." -"L_TCR_T0SZ_512\n" -"\n" -"/* Stage 1 instruction access cacheability is unaffected. */\n" -".set .L_SCTLR_ELx_I, 0x1 << 12\n" -"/* SP alignment fault if SP is not aligned to a 16 byte boundary. */\n" -".set .L_SCTLR_ELx_SA, 0x1 << 3\n" -"/* Stage 1 data access cacheability is unaffected. */\n" -".set .L_SCTLR_ELx_C, 0x1 << 2\n" -"/* EL0 and EL1 stage 1 MMU enabled. */\n" -".set .L_SCTLR_ELx_M, 0x1 << 0\n" -"/* Privileged Access Never is unchanged on taking an exception to EL1. */\n" -".set .L_SCTLR_EL1_SPAN, 0x1 << 23\n" -"/* SETEND instruction disabled at EL0 in aarch32 mode. */\n" -".set .L_SCTLR_EL1_SED, 0x1 << 8\n" -"/* Various IT instructions are disabled at EL0 in aarch32 mode. */\n" -".set .L_SCTLR_EL1_ITD, 0x1 << 7\n" -".set .L_SCTLR_EL1_RES1, (0x1 << 11) | (0x1 << 20) | (0x1 << 22) | (0x1 << " -"28) | (0x1 << 29)\n" -".set .Lsctlrval, .L_SCTLR_ELx_M | .L_SCTLR_ELx_C | .L_SCTLR_ELx_SA | ." -"L_SCTLR_EL1_ITD | .L_SCTLR_EL1_SED\n" -".set .Lsctlrval, .Lsctlrval | .L_SCTLR_ELx_I | .L_SCTLR_EL1_SPAN | ." -"L_SCTLR_EL1_RES1\n" -"\n" -"/**\n" -" * This is a generic entry point for an image. It carries out the operations " -"required to prepare the\n" -" * loaded image to be run. Specifically, it zeroes the bss section using " -"registers x25 and above,\n" -" * prepares the stack, enables floating point, and sets up the exception " -"vector. It preserves x0-x3\n" -" * for the Rust entry point, as these may contain boot parameters.\n" -" */\n" -".section .init.entry, \"ax\"\n" -".global entry\n" -"entry:\n" -"\t/* Load and apply the memory management configuration, ready to enable MMU " -"and caches. */\n" -"\tadrp x30, idmap\n" -"\tmsr ttbr0_el1, x30\n" -"\n" -"\tmov_i x30, .Lmairval\n" -"\tmsr mair_el1, x30\n" -"\n" -"\tmov_i x30, .Ltcrval\n" -"\t/* Copy the supported PA range into TCR_EL1.IPS. */\n" -"\tmrs x29, id_aa64mmfr0_el1\n" -"\tbfi x30, x29, #32, #4\n" -"\n" -"\tmsr tcr_el1, x30\n" -"\n" -"\tmov_i x30, .Lsctlrval\n" -"\n" -"\t/*\n" -"\t * Ensure everything before this point has completed, then invalidate any " -"potentially stale\n" -"\t * local TLB entries before they start being used.\n" -"\t */\n" -"\tisb\n" -"\ttlbi vmalle1\n" -"\tic iallu\n" -"\tdsb nsh\n" -"\tisb\n" -"\n" -"\t/*\n" -"\t * Configure sctlr_el1 to enable MMU and cache and don't proceed until " -"this has completed.\n" -"\t */\n" -"\tmsr sctlr_el1, x30\n" -"\tisb\n" -"\n" -"\t/* Disable trapping floating point access in EL1. */\n" -"\tmrs x30, cpacr_el1\n" -"\torr x30, x30, #(0x3 << 20)\n" -"\tmsr cpacr_el1, x30\n" -"\tisb\n" -"\n" -"\t/* Zero out the bss section. */\n" -"\tadr_l x29, bss_begin\n" -"\tadr_l x30, bss_end\n" -"0:\tcmp x29, x30\n" -"\tb.hs 1f\n" -"\tstp xzr, xzr, [x29], #16\n" -"\tb 0b\n" -"\n" -"1:\t/* Prepare the stack. */\n" -"\tadr_l x30, boot_stack_end\n" -"\tmov sp, x30\n" -"\n" -"\t/* Set up exception vector. */\n" -"\tadr x30, vector_table_el1\n" -"\tmsr vbar_el1, x30\n" +"`FromBytes` can be implemented for types for which any byte pattern is " +"valid, and so can safely be converted from an untrusted sequence of bytes." +msgstr "" + +#: src/bare-metal/useful-crates/zerocopy.md:47 +msgid "" +"Attempting to derive `FromBytes` for these types would fail, because " +"`RequestType` doesn't use all possible u32 values as discriminants, so not " +"all byte patterns are valid." +msgstr "" + +#: src/bare-metal/useful-crates/zerocopy.md:49 +msgid "" +"`zerocopy::byteorder` has types for byte-order aware numeric primitives." +msgstr "" + +#: src/bare-metal/useful-crates/zerocopy.md:50 +msgid "" +"Run the example with `cargo run` under `src/bare-metal/useful-crates/" +"zerocopy-example/`. (It won't run in the Playground because of the crate " +"dependency.)" +msgstr "" + +#: src/bare-metal/useful-crates/aarch64-paging.md:1 +msgid "`aarch64-paging`" +msgstr "" + +#: src/bare-metal/useful-crates/aarch64-paging.md:3 +msgid "" +"The [`aarch64-paging`](https://crates.io/crates/aarch64-paging) crate lets " +"you create page tables according to the AArch64 Virtual Memory System " +"Architecture." +msgstr "" + +#: src/bare-metal/useful-crates/aarch64-paging.md:6 +msgid "" +"```rust,editable,compile_fail\n" +"use aarch64_paging::{\n" +" idmap::IdMap,\n" +" paging::{Attributes, MemoryRegion},\n" +"};\n" "\n" -"\t/* Call into Rust code. */\n" -"\tbl main\n" +"const ASID: usize = 1;\n" +"const ROOT_LEVEL: usize = 1;\n" "\n" -"\t/* Loop forever waiting for interrupts. */\n" -"2:\twfi\n" -"\tb 2b\n" +"// Create a new page table with identity mapping.\n" +"let mut idmap = IdMap::new(ASID, ROOT_LEVEL);\n" +"// Map a 2 MiB region of memory as read-only.\n" +"idmap.map_range(\n" +" &MemoryRegion::new(0x80200000, 0x80400000),\n" +" Attributes::NORMAL | Attributes::NON_GLOBAL | Attributes::READ_ONLY,\n" +").unwrap();\n" +"// Set `TTBR0_EL1` to activate the page table.\n" +"idmap.activate();\n" "```" msgstr "" -#: src/exercises/bare-metal/rtc.md:595 -msgid "`exceptions.S` (you shouldn't need to change this):" +#: src/bare-metal/useful-crates/aarch64-paging.md:28 +msgid "" +"For now it only supports EL1, but support for other exception levels should " +"be straightforward to add." msgstr "" -#: src/exercises/bare-metal/rtc.md:599 +#: src/bare-metal/useful-crates/aarch64-paging.md:30 msgid "" -"```armasm\n" -"/*\n" -" * Copyright 2023 Google LLC\n" -" *\n" -" * Licensed under the Apache License, Version 2.0 (the \"License\");\n" -" * you may not use this file except in compliance with the License.\n" -" * You may obtain a copy of the License at\n" -" *\n" -" * https://www.apache.org/licenses/LICENSE-2.0\n" -" *\n" -" * Unless required by applicable law or agreed to in writing, software\n" -" * distributed under the License is distributed on an \"AS IS\" BASIS,\n" -" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -" * See the License for the specific language governing permissions and\n" -" * limitations under the License.\n" -" */\n" -"\n" -"/**\n" -" * Saves the volatile registers onto the stack. This currently takes 14\n" -" * instructions, so it can be used in exception handlers with 18 " -"instructions\n" -" * left.\n" -" *\n" -" * On return, x0 and x1 are initialised to elr_el2 and spsr_el2 " -"respectively,\n" -" * which can be used as the first and second arguments of a subsequent " -"call.\n" -" */\n" -".macro save_volatile_to_stack\n" -"\t/* Reserve stack space and save registers x0-x18, x29 & x30. */\n" -"\tstp x0, x1, [sp, #-(8 * 24)]!\n" -"\tstp x2, x3, [sp, #8 * 2]\n" -"\tstp x4, x5, [sp, #8 * 4]\n" -"\tstp x6, x7, [sp, #8 * 6]\n" -"\tstp x8, x9, [sp, #8 * 8]\n" -"\tstp x10, x11, [sp, #8 * 10]\n" -"\tstp x12, x13, [sp, #8 * 12]\n" -"\tstp x14, x15, [sp, #8 * 14]\n" -"\tstp x16, x17, [sp, #8 * 16]\n" -"\tstr x18, [sp, #8 * 18]\n" -"\tstp x29, x30, [sp, #8 * 20]\n" -"\n" -"\t/*\n" -"\t * Save elr_el1 & spsr_el1. This such that we can take nested exception\n" -"\t * and still be able to unwind.\n" -"\t */\n" -"\tmrs x0, elr_el1\n" -"\tmrs x1, spsr_el1\n" -"\tstp x0, x1, [sp, #8 * 22]\n" -".endm\n" -"\n" -"/**\n" -" * Restores the volatile registers from the stack. This currently takes 14\n" -" * instructions, so it can be used in exception handlers while still leaving " -"18\n" -" * instructions left; if paired with save_volatile_to_stack, there are 4\n" -" * instructions to spare.\n" -" */\n" -".macro restore_volatile_from_stack\n" -"\t/* Restore registers x2-x18, x29 & x30. */\n" -"\tldp x2, x3, [sp, #8 * 2]\n" -"\tldp x4, x5, [sp, #8 * 4]\n" -"\tldp x6, x7, [sp, #8 * 6]\n" -"\tldp x8, x9, [sp, #8 * 8]\n" -"\tldp x10, x11, [sp, #8 * 10]\n" -"\tldp x12, x13, [sp, #8 * 12]\n" -"\tldp x14, x15, [sp, #8 * 14]\n" -"\tldp x16, x17, [sp, #8 * 16]\n" -"\tldr x18, [sp, #8 * 18]\n" -"\tldp x29, x30, [sp, #8 * 20]\n" -"\n" -"\t/* Restore registers elr_el1 & spsr_el1, using x0 & x1 as scratch. */\n" -"\tldp x0, x1, [sp, #8 * 22]\n" -"\tmsr elr_el1, x0\n" -"\tmsr spsr_el1, x1\n" -"\n" -"\t/* Restore x0 & x1, and release stack space. */\n" -"\tldp x0, x1, [sp], #8 * 24\n" -".endm\n" -"\n" -"/**\n" -" * This is a generic handler for exceptions taken at the current EL while " -"using\n" -" * SP0. It behaves similarly to the SPx case by first switching to SPx, " -"doing\n" -" * the work, then switching back to SP0 before returning.\n" -" *\n" -" * Switching to SPx and calling the Rust handler takes 16 instructions. To\n" -" * restore and return we need an additional 16 instructions, so we can " -"implement\n" -" * the whole handler within the allotted 32 instructions.\n" -" */\n" -".macro current_exception_sp0 handler:req\n" -"\tmsr spsel, #1\n" -"\tsave_volatile_to_stack\n" -"\tbl \\handler\n" -"\trestore_volatile_from_stack\n" -"\tmsr spsel, #0\n" -"\teret\n" -".endm\n" -"\n" -"/**\n" -" * This is a generic handler for exceptions taken at the current EL while " -"using\n" -" * SPx. It saves volatile registers, calls the Rust handler, restores " -"volatile\n" -" * registers, then returns.\n" -" *\n" -" * This also works for exceptions taken from EL0, if we don't care about\n" -" * non-volatile registers.\n" -" *\n" -" * Saving state and jumping to the Rust handler takes 15 instructions, and\n" -" * restoring and returning also takes 15 instructions, so we can fit the " -"whole\n" -" * handler in 30 instructions, under the limit of 32.\n" -" */\n" -".macro current_exception_spx handler:req\n" -"\tsave_volatile_to_stack\n" -"\tbl \\handler\n" -"\trestore_volatile_from_stack\n" -"\teret\n" -".endm\n" -"\n" -".section .text.vector_table_el1, \"ax\"\n" -".global vector_table_el1\n" -".balign 0x800\n" -"vector_table_el1:\n" -"sync_cur_sp0:\n" -"\tcurrent_exception_sp0 sync_exception_current\n" -"\n" -".balign 0x80\n" -"irq_cur_sp0:\n" -"\tcurrent_exception_sp0 irq_current\n" -"\n" -".balign 0x80\n" -"fiq_cur_sp0:\n" -"\tcurrent_exception_sp0 fiq_current\n" -"\n" -".balign 0x80\n" -"serr_cur_sp0:\n" -"\tcurrent_exception_sp0 serr_current\n" -"\n" -".balign 0x80\n" -"sync_cur_spx:\n" -"\tcurrent_exception_spx sync_exception_current\n" -"\n" -".balign 0x80\n" -"irq_cur_spx:\n" -"\tcurrent_exception_spx irq_current\n" -"\n" -".balign 0x80\n" -"fiq_cur_spx:\n" -"\tcurrent_exception_spx fiq_current\n" -"\n" -".balign 0x80\n" -"serr_cur_spx:\n" -"\tcurrent_exception_spx serr_current\n" -"\n" -".balign 0x80\n" -"sync_lower_64:\n" -"\tcurrent_exception_spx sync_lower\n" -"\n" -".balign 0x80\n" -"irq_lower_64:\n" -"\tcurrent_exception_spx irq_lower\n" -"\n" -".balign 0x80\n" -"fiq_lower_64:\n" -"\tcurrent_exception_spx fiq_lower\n" -"\n" -".balign 0x80\n" -"serr_lower_64:\n" -"\tcurrent_exception_spx serr_lower\n" -"\n" -".balign 0x80\n" -"sync_lower_32:\n" -"\tcurrent_exception_spx sync_lower\n" -"\n" -".balign 0x80\n" -"irq_lower_32:\n" -"\tcurrent_exception_spx irq_lower\n" -"\n" -".balign 0x80\n" -"fiq_lower_32:\n" -"\tcurrent_exception_spx fiq_lower\n" -"\n" -".balign 0x80\n" -"serr_lower_32:\n" -"\tcurrent_exception_spx serr_lower\n" -"```" +"This is used in Android for the [Protected VM Firmware](https://cs.android." +"com/android/platform/superproject/+/master:packages/modules/Virtualization/" +"pvmfw/)." msgstr "" -#: src/exercises/bare-metal/rtc.md:780 -msgid "`idmap.S` (you shouldn't need to change this):" +#: src/bare-metal/useful-crates/aarch64-paging.md:31 +msgid "" +"There's no easy way to run this example, as it needs to run on real hardware " +"or under QEMU." msgstr "" -#: src/exercises/bare-metal/rtc.md:784 +#: src/bare-metal/useful-crates/buddy_system_allocator.md:1 +msgid "`buddy_system_allocator`" +msgstr "" + +#: src/bare-metal/useful-crates/buddy_system_allocator.md:3 msgid "" -"```armasm\n" -"/*\n" -" * Copyright 2023 Google LLC\n" -" *\n" -" * Licensed under the Apache License, Version 2.0 (the \"License\");\n" -" * you may not use this file except in compliance with the License.\n" -" * You may obtain a copy of the License at\n" -" *\n" -" * https://www.apache.org/licenses/LICENSE-2.0\n" -" *\n" -" * Unless required by applicable law or agreed to in writing, software\n" -" * distributed under the License is distributed on an \"AS IS\" BASIS,\n" -" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -" * See the License for the specific language governing permissions and\n" -" * limitations under the License.\n" -" */\n" -"\n" -".set .L_TT_TYPE_BLOCK, 0x1\n" -".set .L_TT_TYPE_PAGE, 0x3\n" -".set .L_TT_TYPE_TABLE, 0x3\n" -"\n" -"/* Access flag. */\n" -".set .L_TT_AF, 0x1 << 10\n" -"/* Not global. */\n" -".set .L_TT_NG, 0x1 << 11\n" -".set .L_TT_XN, 0x3 << 53\n" -"\n" -".set .L_TT_MT_DEV, 0x0 << 2\t\t\t// MAIR #0 (DEV_nGnRE)\n" -".set .L_TT_MT_MEM, (0x1 << 2) | (0x3 << 8)\t// MAIR #1 (MEM_WBWA), inner " -"shareable\n" +"[`buddy_system_allocator`](https://crates.io/crates/buddy_system_allocator) " +"is a third-party crate implementing a basic buddy system allocator. It can " +"be used both for [`LockedHeap`](https://docs.rs/buddy_system_allocator/0.9.0/" +"buddy_system_allocator/struct.LockedHeap.html) implementing [`GlobalAlloc`]" +"(https://doc.rust-lang.org/core/alloc/trait.GlobalAlloc.html) so you can use " +"the standard `alloc` crate (as we saw [before](../alloc.md)), or for " +"allocating other address space. For example, we might want to allocate MMIO " +"space for PCI BARs:" +msgstr "" + +#: src/bare-metal/useful-crates/buddy_system_allocator.md:8 +msgid "" +"```rust,editable,compile_fail\n" +"use buddy_system_allocator::FrameAllocator;\n" +"use core::alloc::Layout;\n" "\n" -".set .L_BLOCK_DEV, .L_TT_TYPE_BLOCK | .L_TT_MT_DEV | .L_TT_AF | .L_TT_XN\n" -".set .L_BLOCK_MEM, .L_TT_TYPE_BLOCK | .L_TT_MT_MEM | .L_TT_AF | .L_TT_NG\n" +"fn main() {\n" +" let mut allocator = FrameAllocator::<32>::new();\n" +" allocator.add_frame(0x200_0000, 0x400_0000);\n" "\n" -".section \".rodata.idmap\", \"a\", %progbits\n" -".global idmap\n" -".align 12\n" -"idmap:\n" -"\t/* level 1 */\n" -"\t.quad\t\t.L_BLOCK_DEV | 0x0\t\t // 1 GiB of device mappings\n" -"\t.quad\t\t.L_BLOCK_MEM | 0x40000000\t// 1 GiB of DRAM\n" -"\t.fill\t\t254, 8, 0x0\t\t\t// 254 GiB of unmapped VA space\n" -"\t.quad\t\t.L_BLOCK_DEV | 0x4000000000 // 1 GiB of device mappings\n" -"\t.fill\t\t255, 8, 0x0\t\t\t// 255 GiB of remaining VA space\n" +" let layout = Layout::from_size_align(0x100, 0x100).unwrap();\n" +" let bar = allocator\n" +" .alloc_aligned(layout)\n" +" .expect(\"Failed to allocate 0x100 byte MMIO region\");\n" +" println!(\"Allocated 0x100 byte MMIO region at {:#x}\", bar);\n" +"}\n" "```" msgstr "" -#: src/exercises/bare-metal/rtc.md:829 -msgid "`image.ld` (you shouldn't need to change this):" +#: src/bare-metal/useful-crates/buddy_system_allocator.md:26 +msgid "PCI BARs always have alignment equal to their size." msgstr "" -#: src/exercises/bare-metal/rtc.md:833 +#: src/bare-metal/useful-crates/buddy_system_allocator.md:27 msgid "" -"```ld\n" -"/*\n" -" * Copyright 2023 Google LLC\n" -" *\n" -" * Licensed under the Apache License, Version 2.0 (the \"License\");\n" -" * you may not use this file except in compliance with the License.\n" -" * You may obtain a copy of the License at\n" -" *\n" -" * https://www.apache.org/licenses/LICENSE-2.0\n" -" *\n" -" * Unless required by applicable law or agreed to in writing, software\n" -" * distributed under the License is distributed on an \"AS IS\" BASIS,\n" -" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -" * See the License for the specific language governing permissions and\n" -" * limitations under the License.\n" -" */\n" -"\n" -"/*\n" -" * Code will start running at this symbol which is placed at the start of " -"the\n" -" * image.\n" -" */\n" -"ENTRY(entry)\n" -"\n" -"MEMORY\n" -"{\n" -"\timage : ORIGIN = 0x40080000, LENGTH = 2M\n" -"}\n" -"\n" -"SECTIONS\n" -"{\n" -"\t/*\n" -"\t * Collect together the code.\n" -"\t */\n" -"\t.init : ALIGN(4096) {\n" -"\t\ttext_begin = .;\n" -"\t\t*(.init.entry)\n" -"\t\t*(.init.*)\n" -"\t} >image\n" -"\t.text : {\n" -"\t\t*(.text.*)\n" -"\t} >image\n" -"\ttext_end = .;\n" -"\n" -"\t/*\n" -"\t * Collect together read-only data.\n" -"\t */\n" -"\t.rodata : ALIGN(4096) {\n" -"\t\trodata_begin = .;\n" -"\t\t*(.rodata.*)\n" -"\t} >image\n" -"\t.got : {\n" -"\t\t*(.got)\n" -"\t} >image\n" -"\trodata_end = .;\n" -"\n" -"\t/*\n" -"\t * Collect together the read-write data including .bss at the end which\n" -"\t * will be zero'd by the entry code.\n" -"\t */\n" -"\t.data : ALIGN(4096) {\n" -"\t\tdata_begin = .;\n" -"\t\t*(.data.*)\n" -"\t\t/*\n" -"\t\t * The entry point code assumes that .data is a multiple of 32\n" -"\t\t * bytes long.\n" -"\t\t */\n" -"\t\t. = ALIGN(32);\n" -"\t\tdata_end = .;\n" -"\t} >image\n" -"\n" -"\t/* Everything beyond this point will not be included in the binary. */\n" -"\tbin_end = .;\n" -"\n" -"\t/* The entry point code assumes that .bss is 16-byte aligned. */\n" -"\t.bss : ALIGN(16) {\n" -"\t\tbss_begin = .;\n" -"\t\t*(.bss.*)\n" -"\t\t*(COMMON)\n" -"\t\t. = ALIGN(16);\n" -"\t\tbss_end = .;\n" -"\t} >image\n" -"\n" -"\t.stack (NOLOAD) : ALIGN(4096) {\n" -"\t\tboot_stack_begin = .;\n" -"\t\t. += 40 * 4096;\n" -"\t\t. = ALIGN(4096);\n" -"\t\tboot_stack_end = .;\n" -"\t} >image\n" -"\n" -"\t. = ALIGN(4K);\n" -"\tPROVIDE(dma_region = .);\n" -"\n" -"\t/*\n" -"\t * Remove unused sections from the image.\n" -"\t */\n" -"\t/DISCARD/ : {\n" -"\t\t/* The image loads itself so doesn't need these sections. */\n" -"\t\t*(.gnu.hash)\n" -"\t\t*(.hash)\n" -"\t\t*(.interp)\n" -"\t\t*(.eh_frame_hdr)\n" -"\t\t*(.eh_frame)\n" -"\t\t*(.note.gnu.build-id)\n" -"\t}\n" -"}\n" -"```" +"Run the example with `cargo run` under `src/bare-metal/useful-crates/" +"allocator-example/`. (It won't run in the Playground because of the crate " +"dependency.)" msgstr "" -#: src/exercises/bare-metal/rtc.md:940 -msgid "`Makefile` (you shouldn't need to change this):" +#: src/bare-metal/useful-crates/tinyvec.md:1 +msgid "`tinyvec`" msgstr "" -#: src/exercises/bare-metal/rtc.md:944 +#: src/bare-metal/useful-crates/tinyvec.md:3 msgid "" -"```makefile\n" -"# Copyright 2023 Google LLC\n" -"#\n" -"# Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"# you may not use this file except in compliance with the License.\n" -"# You may obtain a copy of the License at\n" -"#\n" -"# http://www.apache.org/licenses/LICENSE-2.0\n" -"#\n" -"# Unless required by applicable law or agreed to in writing, software\n" -"# distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"# See the License for the specific language governing permissions and\n" -"# limitations under the License.\n" -"\n" -"UNAME := $(shell uname -s)\n" -"ifeq ($(UNAME),Linux)\n" -"\tTARGET = aarch64-linux-gnu\n" -"else\n" -"\tTARGET = aarch64-none-elf\n" -"endif\n" -"OBJCOPY = $(TARGET)-objcopy\n" -"\n" -".PHONY: build qemu_minimal qemu qemu_logger\n" -"\n" -"all: rtc.bin\n" -"\n" -"build:\n" -"\tcargo build\n" -"\n" -"rtc.bin: build\n" -"\t$(OBJCOPY) -O binary target/aarch64-unknown-none/debug/rtc $@\n" -"\n" -"qemu: rtc.bin\n" -"\tqemu-system-aarch64 -machine virt,gic-version=3 -cpu max -serial mon:stdio " -"-display none -kernel $< -s\n" -"\n" -"clean:\n" -"\tcargo clean\n" -"\trm -f *.bin\n" -"```" +"Sometimes you want something which can be resized like a `Vec`, but without " +"heap allocation. [`tinyvec`](https://crates.io/crates/tinyvec) provides " +"this: a vector backed by an array or slice, which could be statically " +"allocated or on the stack, which keeps track of how many elements are used " +"and panics if you try to use more than are allocated." msgstr "" -#: src/exercises/bare-metal/rtc.md:989 +#: src/bare-metal/useful-crates/tinyvec.md:8 msgid "" -"```toml\n" -"[build]\n" -"target = \"aarch64-unknown-none\"\n" -"rustflags = [\"-C\", \"link-arg=-Timage.ld\"]\n" +"```rust,editable,compile_fail\n" +"use tinyvec::{array_vec, ArrayVec};\n" +"\n" +"fn main() {\n" +" let mut numbers: ArrayVec<[u32; 5]> = array_vec!(42, 66);\n" +" println!(\"{numbers:?}\");\n" +" numbers.push(7);\n" +" println!(\"{numbers:?}\");\n" +" numbers.remove(1);\n" +" println!(\"{numbers:?}\");\n" +"}\n" "```" msgstr "" -#: src/exercises/bare-metal/rtc.md:995 -msgid "Run the code in QEMU with `make qemu`." +#: src/bare-metal/useful-crates/tinyvec.md:23 +msgid "" +"`tinyvec` requires that the element type implement `Default` for " +"initialisation." msgstr "" -#: src/concurrency.md:1 -msgid "Welcome to Concurrency in Rust" +#: src/bare-metal/useful-crates/tinyvec.md:24 +msgid "" +"The Rust Playground includes `tinyvec`, so this example will run fine inline." msgstr "" -#: src/concurrency.md:3 -msgid "" -"Rust has full support for concurrency using OS threads with mutexes and " -"channels." +#: src/bare-metal/useful-crates/spin.md:1 +msgid "`spin`" msgstr "" -#: src/concurrency.md:6 +#: src/bare-metal/useful-crates/spin.md:3 msgid "" -"The Rust type system plays an important role in making many concurrency bugs " -"compile time bugs. This is often referred to as _fearless concurrency_ since " -"you can rely on the compiler to ensure correctness at runtime." +"`std::sync::Mutex` and the other synchronisation primitives from `std::sync` " +"are not available in `core` or `alloc`. How can we manage synchronisation or " +"interior mutability, such as for sharing state between different CPUs?" msgstr "" -#: src/concurrency/threads.md:3 -msgid "Rust threads work similarly to threads in other languages:" +#: src/bare-metal/useful-crates/spin.md:7 +msgid "" +"The [`spin`](https://crates.io/crates/spin) crate provides spinlock-based " +"equivalents of many of these primitives." msgstr "" -#: src/concurrency/threads.md:5 +#: src/bare-metal/useful-crates/spin.md:9 msgid "" -"```rust,editable\n" -"use std::thread;\n" -"use std::time::Duration;\n" +"```rust,editable,compile_fail\n" +"use spin::mutex::SpinMutex;\n" "\n" -"fn main() {\n" -" thread::spawn(|| {\n" -" for i in 1..10 {\n" -" println!(\"Count in thread: {i}!\");\n" -" thread::sleep(Duration::from_millis(5));\n" -" }\n" -" });\n" +"static counter: SpinMutex = SpinMutex::new(0);\n" "\n" -" for i in 1..5 {\n" -" println!(\"Main thread: {i}\");\n" -" thread::sleep(Duration::from_millis(5));\n" -" }\n" +"fn main() {\n" +" println!(\"count: {}\", counter.lock());\n" +" *counter.lock() += 2;\n" +" println!(\"count: {}\", counter.lock());\n" "}\n" "```" msgstr "" -#: src/concurrency/threads.md:24 -msgid "Threads are all daemon threads, the main thread does not wait for them." -msgstr "" - -#: src/concurrency/threads.md:25 -msgid "Thread panics are independent of each other." +#: src/bare-metal/useful-crates/spin.md:23 +msgid "Be careful to avoid deadlock if you take locks in interrupt handlers." msgstr "" -#: src/concurrency/threads.md:26 -msgid "Panics can carry a payload, which can be unpacked with `downcast_ref`." +#: src/bare-metal/useful-crates/spin.md:24 +msgid "" +"`spin` also has a ticket lock mutex implementation; equivalents of `RwLock`, " +"`Barrier` and `Once` from `std::sync`; and `Lazy` for lazy initialisation." msgstr "" -#: src/concurrency/threads.md:32 +#: src/bare-metal/useful-crates/spin.md:26 msgid "" -"Notice that the thread is stopped before it reaches 10 — the main thread is " -"not waiting." +"The [`once_cell`](https://crates.io/crates/once_cell) crate also has some " +"useful types for late initialisation with a slightly different approach to " +"`spin::once::Once`." msgstr "" -#: src/concurrency/threads.md:35 +#: src/bare-metal/useful-crates/spin.md:28 msgid "" -"Use `let handle = thread::spawn(...)` and later `handle.join()` to wait for " -"the thread to finish." +"The Rust Playground includes `spin`, so this example will run fine inline." msgstr "" -#: src/concurrency/threads.md:38 -msgid "Trigger a panic in the thread, notice how this doesn't affect `main`." +#: src/bare-metal/android.md:3 +msgid "" +"To build a bare-metal Rust binary in AOSP, you need to use a " +"`rust_ffi_static` Soong rule to build your Rust code, then a `cc_binary` " +"with a linker script to produce the binary itself, and then a `raw_binary` " +"to convert the ELF to a raw binary ready to be run." msgstr "" -#: src/concurrency/threads.md:40 -msgid "" -"Use the `Result` return value from `handle.join()` to get access to the " -"panic payload. This is a good time to talk about [`Any`](https://doc.rust-" -"lang.org/std/any/index.html)." -msgstr "" - -#: src/concurrency/scoped-threads.md:3 -msgid "Normal threads cannot borrow from their environment:" -msgstr "" - -#: src/concurrency/scoped-threads.md:5 +#: src/bare-metal/android.md:7 msgid "" -"```rust,editable,compile_fail\n" -"use std::thread;\n" +"```soong\n" +"rust_ffi_static {\n" +" name: \"libvmbase_example\",\n" +" defaults: [\"vmbase_ffi_defaults\"],\n" +" crate_name: \"vmbase_example\",\n" +" srcs: [\"src/main.rs\"],\n" +" rustlibs: [\n" +" \"libvmbase\",\n" +" ],\n" +"}\n" "\n" -"fn main() {\n" -" let s = String::from(\"Hello\");\n" +"cc_binary {\n" +" name: \"vmbase_example\",\n" +" defaults: [\"vmbase_elf_defaults\"],\n" +" srcs: [\n" +" \"idmap.S\",\n" +" ],\n" +" static_libs: [\n" +" \"libvmbase_example\",\n" +" ],\n" +" linker_scripts: [\n" +" \"image.ld\",\n" +" \":vmbase_sections\",\n" +" ],\n" +"}\n" "\n" -" thread::spawn(|| {\n" -" println!(\"Length: {}\", s.len());\n" -" });\n" +"raw_binary {\n" +" name: \"vmbase_example_bin\",\n" +" stem: \"vmbase_example.bin\",\n" +" src: \":vmbase_example\",\n" +" enabled: false,\n" +" target: {\n" +" android_arm64: {\n" +" enabled: true,\n" +" },\n" +" },\n" "}\n" "```" msgstr "" -#: src/concurrency/scoped-threads.md:17 +#: src/bare-metal/android/vmbase.md:3 msgid "" -"However, you can use a [scoped thread](https://doc.rust-lang.org/std/thread/" -"fn.scope.html) for this:" +"For VMs running under crosvm on aarch64, the [vmbase](https://android." +"googlesource.com/platform/packages/modules/Virtualization/+/refs/heads/" +"master/vmbase/) library provides a linker script and useful defaults for the " +"build rules, along with an entry point, UART console logging and more." msgstr "" -#: src/concurrency/scoped-threads.md:19 +#: src/bare-metal/android/vmbase.md:6 msgid "" -"```rust,editable\n" -"use std::thread;\n" +"```rust,compile_fail\n" +"#![no_main]\n" +"#![no_std]\n" "\n" -"fn main() {\n" -" let s = String::from(\"Hello\");\n" +"use vmbase::{main, println};\n" "\n" -" thread::scope(|scope| {\n" -" scope.spawn(|| {\n" -" println!(\"Length: {}\", s.len());\n" -" });\n" -" });\n" +"main!(main);\n" +"\n" +"pub fn main(arg0: u64, arg1: u64, arg2: u64, arg3: u64) {\n" +" println!(\"Hello world\");\n" "}\n" "```" msgstr "" -#: src/concurrency/scoped-threads.md:37 +#: src/bare-metal/android/vmbase.md:21 msgid "" -"The reason for that is that when the `thread::scope` function completes, all " -"the threads are guaranteed to be joined, so they can return borrowed data." +"The `main!` macro marks your main function, to be called from the `vmbase` " +"entry point." msgstr "" -#: src/concurrency/scoped-threads.md:38 +#: src/bare-metal/android/vmbase.md:22 msgid "" -"Normal Rust borrowing rules apply: you can either borrow mutably by one " -"thread, or immutably by any number of threads." +"The `vmbase` entry point handles console initialisation, and issues a " +"PSCI_SYSTEM_OFF to shutdown the VM if your main function returns." msgstr "" -#: src/concurrency/channels.md:3 +#: src/exercises/bare-metal/afternoon.md:3 +msgid "We will write a driver for the PL031 real-time clock device." +msgstr "" + +#: src/exercises/bare-metal/rtc.md:1 +#: src/exercises/bare-metal/solutions-afternoon.md:3 +msgid "RTC driver" +msgstr "" + +#: src/exercises/bare-metal/rtc.md:3 msgid "" -"Rust channels have two parts: a `Sender` and a `Receiver`. The two " -"parts are connected via the channel, but you only see the end-points." +"The QEMU aarch64 virt machine has a [PL031](https://developer.arm.com/" +"documentation/ddi0224/c) real-time clock at 0x9010000. For this exercise, " +"you should write a driver for it." msgstr "" -#: src/concurrency/channels.md:6 +#: src/exercises/bare-metal/rtc.md:6 msgid "" -"```rust,editable\n" -"use std::sync::mpsc;\n" -"use std::thread;\n" -"\n" -"fn main() {\n" -" let (tx, rx) = mpsc::channel();\n" -"\n" -" tx.send(10).unwrap();\n" -" tx.send(20).unwrap();\n" -"\n" -" println!(\"Received: {:?}\", rx.recv());\n" -" println!(\"Received: {:?}\", rx.recv());\n" -"\n" -" let tx2 = tx.clone();\n" -" tx2.send(30).unwrap();\n" -" println!(\"Received: {:?}\", rx.recv());\n" -"}\n" -"```" +"Use it to print the current time to the serial console. You can use the " +"[`chrono`](https://crates.io/crates/chrono) crate for date/time formatting." msgstr "" -#: src/concurrency/channels.md:27 +#: src/exercises/bare-metal/rtc.md:8 msgid "" -"`mpsc` stands for Multi-Producer, Single-Consumer. `Sender` and `SyncSender` " -"implement `Clone` (so you can make multiple producers) but `Receiver` does " -"not." +"Use the match register and raw interrupt status to busy-wait until a given " +"time, e.g. 3 seconds in the future. (Call [`core::hint::spin_loop`](https://" +"doc.rust-lang.org/core/hint/fn.spin_loop.html) inside the loop.)" msgstr "" -#: src/concurrency/channels.md:29 +#: src/exercises/bare-metal/rtc.md:10 msgid "" -"`send()` and `recv()` return `Result`. If they return `Err`, it means the " -"counterpart `Sender` or `Receiver` is dropped and the channel is closed." +"_Extension if you have time:_ Enable and handle the interrupt generated by " +"the RTC match. You can use the driver provided in the [`arm-gic`](https://" +"docs.rs/arm-gic/) crate to configure the Arm Generic Interrupt Controller." msgstr "" -#: src/concurrency/channels/unbounded.md:3 -msgid "You get an unbounded and asynchronous channel with `mpsc::channel()`:" +#: src/exercises/bare-metal/rtc.md:12 +msgid "Use the RTC interrupt, which is wired to the GIC as `IntId::spi(2)`." msgstr "" -#: src/concurrency/channels/unbounded.md:5 +#: src/exercises/bare-metal/rtc.md:13 msgid "" -"```rust,editable\n" -"use std::sync::mpsc;\n" -"use std::thread;\n" -"use std::time::Duration;\n" -"\n" -"fn main() {\n" -" let (tx, rx) = mpsc::channel();\n" -"\n" -" thread::spawn(move || {\n" -" let thread_id = thread::current().id();\n" -" for i in 1..10 {\n" -" tx.send(format!(\"Message {i}\")).unwrap();\n" -" println!(\"{thread_id:?}: sent Message {i}\");\n" -" }\n" -" println!(\"{thread_id:?}: done\");\n" -" });\n" -" thread::sleep(Duration::from_millis(100));\n" -"\n" -" for msg in rx.iter() {\n" -" println!(\"Main: got {msg}\");\n" -" }\n" -"}\n" -"```" +"Once the interrupt is enabled, you can put the core to sleep via `arm_gic::" +"wfi()`, which will cause the core to sleep until it receives an interrupt." msgstr "" -#: src/concurrency/channels/bounded.md:3 -msgid "Bounded and synchronous channels make `send` block the current thread:" +#: src/exercises/bare-metal/rtc.md:16 +msgid "" +"Download the [exercise template](../../comprehensive-rust-exercises.zip) and " +"look in the `rtc` directory for the following files." msgstr "" -#: src/concurrency/channels/bounded.md:5 +#: src/exercises/bare-metal/rtc.md:23 msgid "" -"```rust,editable\n" -"use std::sync::mpsc;\n" -"use std::thread;\n" -"use std::time::Duration;\n" +"```rust,compile_fail\n" +"#![no_main]\n" +"#![no_std]\n" "\n" -"fn main() {\n" -" let (tx, rx) = mpsc::sync_channel(3);\n" +"mod exceptions;\n" +"mod logger;\n" +"mod pl011;\n" "\n" -" thread::spawn(move || {\n" -" let thread_id = thread::current().id();\n" -" for i in 1..10 {\n" -" tx.send(format!(\"Message {i}\")).unwrap();\n" -" println!(\"{thread_id:?}: sent Message {i}\");\n" -" }\n" -" println!(\"{thread_id:?}: done\");\n" -" });\n" -" thread::sleep(Duration::from_millis(100));\n" +"use crate::pl011::Uart;\n" +"use arm_gic::gicv3::GicV3;\n" +"use core::panic::PanicInfo;\n" +"use log::{error, info, trace, LevelFilter};\n" +"use smccc::psci::system_off;\n" +"use smccc::Hvc;\n" "\n" -" for msg in rx.iter() {\n" -" println!(\"Main: got {msg}\");\n" -" }\n" +"/// Base addresses of the GICv3.\n" +"const GICD_BASE_ADDRESS: *mut u64 = 0x800_0000 as _;\n" +"const GICR_BASE_ADDRESS: *mut u64 = 0x80A_0000 as _;\n" +"\n" +"/// Base address of the primary PL011 UART.\n" +"const PL011_BASE_ADDRESS: *mut u32 = 0x900_0000 as _;\n" +"\n" +"#[no_mangle]\n" +"extern \"C\" fn main(x0: u64, x1: u64, x2: u64, x3: u64) {\n" +" // Safe because `PL011_BASE_ADDRESS` is the base address of a PL011 " +"device,\n" +" // and nothing else accesses that address range.\n" +" let uart = unsafe { Uart::new(PL011_BASE_ADDRESS) };\n" +" logger::init(uart, LevelFilter::Trace).unwrap();\n" +"\n" +" info!(\"main({:#x}, {:#x}, {:#x}, {:#x})\", x0, x1, x2, x3);\n" +"\n" +" // Safe because `GICD_BASE_ADDRESS` and `GICR_BASE_ADDRESS` are the " +"base\n" +" // addresses of a GICv3 distributor and redistributor respectively, and\n" +" // nothing else accesses those address ranges.\n" +" let mut gic = unsafe { GicV3::new(GICD_BASE_ADDRESS, " +"GICR_BASE_ADDRESS) };\n" +" gic.setup();\n" +"\n" +" // TODO: Create instance of RTC driver and print current time.\n" +"\n" +" // TODO: Wait for 3 seconds.\n" +"\n" +" system_off::().unwrap();\n" +"}\n" +"\n" +"#[panic_handler]\n" +"fn panic(info: &PanicInfo) -> ! {\n" +" error!(\"{info}\");\n" +" system_off::().unwrap();\n" +" loop {}\n" "}\n" "```" msgstr "" -#: src/concurrency/send-sync.md:1 -msgid "`Send` and `Sync`" -msgstr "" - -#: src/concurrency/send-sync.md:3 +#: src/exercises/bare-metal/rtc.md:75 msgid "" -"How does Rust know to forbid shared access across thread? The answer is in " -"two traits:" +"`src/exceptions.rs` (you should only need to change this for the 3rd part of " +"the exercise):" msgstr "" -#: src/concurrency/send-sync.md:5 -msgid "" -"[`Send`](https://doc.rust-lang.org/std/marker/trait.Send.html): a type `T` " -"is `Send` if it is safe to move a `T` across a thread boundary." -msgstr "" - -#: src/concurrency/send-sync.md:7 -msgid "" -"[`Sync`](https://doc.rust-lang.org/std/marker/trait.Sync.html): a type `T` " -"is `Sync` if it is safe to move a `&T` across a thread boundary." -msgstr "" - -#: src/concurrency/send-sync.md:10 -msgid "" -"`Send` and `Sync` are [unsafe traits](../unsafe/unsafe-traits.md). The " -"compiler will automatically derive them for your types as long as they only " -"contain `Send` and `Sync` types. You can also implement them manually when " -"you know it is valid." -msgstr "" - -#: src/concurrency/send-sync.md:20 -msgid "" -"One can think of these traits as markers that the type has certain thread-" -"safety properties." -msgstr "" - -#: src/concurrency/send-sync.md:21 -msgid "They can be used in the generic constraints as normal traits." -msgstr "" - -#: src/concurrency/send-sync/send.md:1 -msgid "`Send`" -msgstr "" - -#: src/concurrency/send-sync/send.md:3 -msgid "" -"A type `T` is [`Send`](https://doc.rust-lang.org/std/marker/trait.Send.html) " -"if it is safe to move a `T` value to another thread." -msgstr "" - -#: src/concurrency/send-sync/send.md:5 -msgid "" -"The effect of moving ownership to another thread is that _destructors_ will " -"run in that thread. So the question is when you can allocate a value in one " -"thread and deallocate it in another." -msgstr "" - -#: src/concurrency/send-sync/send.md:13 -msgid "" -"As an example, a connection to the SQLite library must only be accessed from " -"a single thread." -msgstr "" - -#: src/concurrency/send-sync/sync.md:1 -msgid "`Sync`" -msgstr "" - -#: src/concurrency/send-sync/sync.md:3 -msgid "" -"A type `T` is [`Sync`](https://doc.rust-lang.org/std/marker/trait.Sync.html) " -"if it is safe to access a `T` value from multiple threads at the same time." -msgstr "" - -#: src/concurrency/send-sync/sync.md:6 -msgid "More precisely, the definition is:" -msgstr "" - -#: src/concurrency/send-sync/sync.md:8 -msgid "`T` is `Sync` if and only if `&T` is `Send`" -msgstr "" - -#: src/concurrency/send-sync/sync.md:14 -msgid "" -"This statement is essentially a shorthand way of saying that if a type is " -"thread-safe for shared use, it is also thread-safe to pass references of it " -"across threads." -msgstr "" - -#: src/concurrency/send-sync/sync.md:16 +#: src/exercises/bare-metal/rtc.md:79 msgid "" -"This is because if a type is Sync it means that it can be shared across " -"multiple threads without the risk of data races or other synchronization " -"issues, so it is safe to move it to another thread. A reference to the type " -"is also safe to move to another thread, because the data it references can " -"be accessed from any thread safely." -msgstr "" - -#: src/concurrency/send-sync/examples.md:3 -msgid "`Send + Sync`" -msgstr "" - -#: src/concurrency/send-sync/examples.md:5 -msgid "Most types you come across are `Send + Sync`:" -msgstr "" - -#: src/concurrency/send-sync/examples.md:7 -msgid "`i8`, `f32`, `bool`, `char`, `&str`, ..." -msgstr "" - -#: src/concurrency/send-sync/examples.md:8 -msgid "`(T1, T2)`, `[T; N]`, `&[T]`, `struct { x: T }`, ..." -msgstr "" - -#: src/concurrency/send-sync/examples.md:9 -msgid "`String`, `Option`, `Vec`, `Box`, ..." -msgstr "" - -#: src/concurrency/send-sync/examples.md:10 -msgid "`Arc`: Explicitly thread-safe via atomic reference count." -msgstr "" - -#: src/concurrency/send-sync/examples.md:11 -msgid "`Mutex`: Explicitly thread-safe via internal locking." +"```rust,compile_fail\n" +"// Copyright 2023 Google LLC\n" +"//\n" +"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" +"// you may not use this file except in compliance with the License.\n" +"// You may obtain a copy of the License at\n" +"//\n" +"// http://www.apache.org/licenses/LICENSE-2.0\n" +"//\n" +"// Unless required by applicable law or agreed to in writing, software\n" +"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" +"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" +"// See the License for the specific language governing permissions and\n" +"// limitations under the License.\n" +"\n" +"use arm_gic::gicv3::GicV3;\n" +"use log::{error, info, trace};\n" +"use smccc::psci::system_off;\n" +"use smccc::Hvc;\n" +"\n" +"#[no_mangle]\n" +"extern \"C\" fn sync_exception_current(_elr: u64, _spsr: u64) {\n" +" error!(\"sync_exception_current\");\n" +" system_off::().unwrap();\n" +"}\n" +"\n" +"#[no_mangle]\n" +"extern \"C\" fn irq_current(_elr: u64, _spsr: u64) {\n" +" trace!(\"irq_current\");\n" +" let intid = GicV3::get_and_acknowledge_interrupt().expect(\"No pending " +"interrupt\");\n" +" info!(\"IRQ {intid:?}\");\n" +"}\n" +"\n" +"#[no_mangle]\n" +"extern \"C\" fn fiq_current(_elr: u64, _spsr: u64) {\n" +" error!(\"fiq_current\");\n" +" system_off::().unwrap();\n" +"}\n" +"\n" +"#[no_mangle]\n" +"extern \"C\" fn serr_current(_elr: u64, _spsr: u64) {\n" +" error!(\"serr_current\");\n" +" system_off::().unwrap();\n" +"}\n" +"\n" +"#[no_mangle]\n" +"extern \"C\" fn sync_lower(_elr: u64, _spsr: u64) {\n" +" error!(\"sync_lower\");\n" +" system_off::().unwrap();\n" +"}\n" +"\n" +"#[no_mangle]\n" +"extern \"C\" fn irq_lower(_elr: u64, _spsr: u64) {\n" +" error!(\"irq_lower\");\n" +" system_off::().unwrap();\n" +"}\n" +"\n" +"#[no_mangle]\n" +"extern \"C\" fn fiq_lower(_elr: u64, _spsr: u64) {\n" +" error!(\"fiq_lower\");\n" +" system_off::().unwrap();\n" +"}\n" +"\n" +"#[no_mangle]\n" +"extern \"C\" fn serr_lower(_elr: u64, _spsr: u64) {\n" +" error!(\"serr_lower\");\n" +" system_off::().unwrap();\n" +"}\n" +"```" msgstr "" -#: src/concurrency/send-sync/examples.md:12 -msgid "`AtomicBool`, `AtomicU8`, ...: Uses special atomic instructions." +#: src/exercises/bare-metal/rtc.md:149 +msgid "`src/logger.rs` (you shouldn't need to change this):" msgstr "" -#: src/concurrency/send-sync/examples.md:14 +#: src/exercises/bare-metal/rtc.md:153 msgid "" -"The generic types are typically `Send + Sync` when the type parameters are " -"`Send + Sync`." +"```rust,compile_fail\n" +"// Copyright 2023 Google LLC\n" +"//\n" +"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" +"// you may not use this file except in compliance with the License.\n" +"// You may obtain a copy of the License at\n" +"//\n" +"// http://www.apache.org/licenses/LICENSE-2.0\n" +"//\n" +"// Unless required by applicable law or agreed to in writing, software\n" +"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" +"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" +"// See the License for the specific language governing permissions and\n" +"// limitations under the License.\n" +"\n" +"// ANCHOR: main\n" +"use crate::pl011::Uart;\n" +"use core::fmt::Write;\n" +"use log::{LevelFilter, Log, Metadata, Record, SetLoggerError};\n" +"use spin::mutex::SpinMutex;\n" +"\n" +"static LOGGER: Logger = Logger {\n" +" uart: SpinMutex::new(None),\n" +"};\n" +"\n" +"struct Logger {\n" +" uart: SpinMutex>,\n" +"}\n" +"\n" +"impl Log for Logger {\n" +" fn enabled(&self, _metadata: &Metadata) -> bool {\n" +" true\n" +" }\n" +"\n" +" fn log(&self, record: &Record) {\n" +" writeln!(\n" +" self.uart.lock().as_mut().unwrap(),\n" +" \"[{}] {}\",\n" +" record.level(),\n" +" record.args()\n" +" )\n" +" .unwrap();\n" +" }\n" +"\n" +" fn flush(&self) {}\n" +"}\n" +"\n" +"/// Initialises UART logger.\n" +"pub fn init(uart: Uart, max_level: LevelFilter) -> Result<(), " +"SetLoggerError> {\n" +" LOGGER.uart.lock().replace(uart);\n" +"\n" +" log::set_logger(&LOGGER)?;\n" +" log::set_max_level(max_level);\n" +" Ok(())\n" +"}\n" +"```" msgstr "" -#: src/concurrency/send-sync/examples.md:17 -msgid "`Send + !Sync`" +#: src/exercises/bare-metal/rtc.md:210 +msgid "`src/pl011.rs` (you shouldn't need to change this):" msgstr "" -#: src/concurrency/send-sync/examples.md:19 +#: src/exercises/bare-metal/rtc.md:214 msgid "" -"These types can be moved to other threads, but they're not thread-safe. " -"Typically because of interior mutability:" -msgstr "" - -#: src/concurrency/send-sync/examples.md:22 -msgid "`mpsc::Sender`" -msgstr "" - -#: src/concurrency/send-sync/examples.md:23 -msgid "`mpsc::Receiver`" -msgstr "" - -#: src/concurrency/send-sync/examples.md:24 -msgid "`Cell`" +"```rust,compile_fail\n" +"// Copyright 2023 Google LLC\n" +"//\n" +"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" +"// you may not use this file except in compliance with the License.\n" +"// You may obtain a copy of the License at\n" +"//\n" +"// http://www.apache.org/licenses/LICENSE-2.0\n" +"//\n" +"// Unless required by applicable law or agreed to in writing, software\n" +"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" +"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" +"// See the License for the specific language governing permissions and\n" +"// limitations under the License.\n" +"\n" +"#![allow(unused)]\n" +"\n" +"use core::fmt::{self, Write};\n" +"use core::ptr::{addr_of, addr_of_mut};\n" +"\n" +"// ANCHOR: Flags\n" +"use bitflags::bitflags;\n" +"\n" +"bitflags! {\n" +" /// Flags from the UART flag register.\n" +" #[repr(transparent)]\n" +" #[derive(Copy, Clone, Debug, Eq, PartialEq)]\n" +" struct Flags: u16 {\n" +" /// Clear to send.\n" +" const CTS = 1 << 0;\n" +" /// Data set ready.\n" +" const DSR = 1 << 1;\n" +" /// Data carrier detect.\n" +" const DCD = 1 << 2;\n" +" /// UART busy transmitting data.\n" +" const BUSY = 1 << 3;\n" +" /// Receive FIFO is empty.\n" +" const RXFE = 1 << 4;\n" +" /// Transmit FIFO is full.\n" +" const TXFF = 1 << 5;\n" +" /// Receive FIFO is full.\n" +" const RXFF = 1 << 6;\n" +" /// Transmit FIFO is empty.\n" +" const TXFE = 1 << 7;\n" +" /// Ring indicator.\n" +" const RI = 1 << 8;\n" +" }\n" +"}\n" +"// ANCHOR_END: Flags\n" +"\n" +"bitflags! {\n" +" /// Flags from the UART Receive Status Register / Error Clear Register.\n" +" #[repr(transparent)]\n" +" #[derive(Copy, Clone, Debug, Eq, PartialEq)]\n" +" struct ReceiveStatus: u16 {\n" +" /// Framing error.\n" +" const FE = 1 << 0;\n" +" /// Parity error.\n" +" const PE = 1 << 1;\n" +" /// Break error.\n" +" const BE = 1 << 2;\n" +" /// Overrun error.\n" +" const OE = 1 << 3;\n" +" }\n" +"}\n" +"\n" +"// ANCHOR: Registers\n" +"#[repr(C, align(4))]\n" +"struct Registers {\n" +" dr: u16,\n" +" _reserved0: [u8; 2],\n" +" rsr: ReceiveStatus,\n" +" _reserved1: [u8; 19],\n" +" fr: Flags,\n" +" _reserved2: [u8; 6],\n" +" ilpr: u8,\n" +" _reserved3: [u8; 3],\n" +" ibrd: u16,\n" +" _reserved4: [u8; 2],\n" +" fbrd: u8,\n" +" _reserved5: [u8; 3],\n" +" lcr_h: u8,\n" +" _reserved6: [u8; 3],\n" +" cr: u16,\n" +" _reserved7: [u8; 3],\n" +" ifls: u8,\n" +" _reserved8: [u8; 3],\n" +" imsc: u16,\n" +" _reserved9: [u8; 2],\n" +" ris: u16,\n" +" _reserved10: [u8; 2],\n" +" mis: u16,\n" +" _reserved11: [u8; 2],\n" +" icr: u16,\n" +" _reserved12: [u8; 2],\n" +" dmacr: u8,\n" +" _reserved13: [u8; 3],\n" +"}\n" +"// ANCHOR_END: Registers\n" +"\n" +"// ANCHOR: Uart\n" +"/// Driver for a PL011 UART.\n" +"#[derive(Debug)]\n" +"pub struct Uart {\n" +" registers: *mut Registers,\n" +"}\n" +"\n" +"impl Uart {\n" +" /// Constructs a new instance of the UART driver for a PL011 device at " +"the\n" +" /// given base address.\n" +" ///\n" +" /// # Safety\n" +" ///\n" +" /// The given base address must point to the MMIO control registers of " +"a\n" +" /// PL011 device, which must be mapped into the address space of the " +"process\n" +" /// as device memory and not have any other aliases.\n" +" pub unsafe fn new(base_address: *mut u32) -> Self {\n" +" Self {\n" +" registers: base_address as *mut Registers,\n" +" }\n" +" }\n" +"\n" +" /// Writes a single byte to the UART.\n" +" pub fn write_byte(&self, byte: u8) {\n" +" // Wait until there is room in the TX buffer.\n" +" while self.read_flag_register().contains(Flags::TXFF) {}\n" +"\n" +" // Safe because we know that self.registers points to the control\n" +" // registers of a PL011 device which is appropriately mapped.\n" +" unsafe {\n" +" // Write to the TX buffer.\n" +" addr_of_mut!((*self.registers).dr).write_volatile(byte.into());\n" +" }\n" +"\n" +" // Wait until the UART is no longer busy.\n" +" while self.read_flag_register().contains(Flags::BUSY) {}\n" +" }\n" +"\n" +" /// Reads and returns a pending byte, or `None` if nothing has been " +"received.\n" +" pub fn read_byte(&self) -> Option {\n" +" if self.read_flag_register().contains(Flags::RXFE) {\n" +" None\n" +" } else {\n" +" let data = unsafe { addr_of!((*self.registers).dr)." +"read_volatile() };\n" +" // TODO: Check for error conditions in bits 8-11.\n" +" Some(data as u8)\n" +" }\n" +" }\n" +"\n" +" fn read_flag_register(&self) -> Flags {\n" +" // Safe because we know that self.registers points to the control\n" +" // registers of a PL011 device which is appropriately mapped.\n" +" unsafe { addr_of!((*self.registers).fr).read_volatile() }\n" +" }\n" +"}\n" +"// ANCHOR_END: Uart\n" +"\n" +"impl Write for Uart {\n" +" fn write_str(&mut self, s: &str) -> fmt::Result {\n" +" for c in s.as_bytes() {\n" +" self.write_byte(*c);\n" +" }\n" +" Ok(())\n" +" }\n" +"}\n" +"\n" +"// Safe because it just contains a pointer to device memory, which can be\n" +"// accessed from any context.\n" +"unsafe impl Send for Uart {}\n" +"```" msgstr "" -#: src/concurrency/send-sync/examples.md:25 -msgid "`RefCell`" +#: src/exercises/bare-metal/rtc.md:389 +msgid "" +"```toml\n" +"[workspace]\n" +"\n" +"[package]\n" +"name = \"rtc\"\n" +"version = \"0.1.0\"\n" +"edition = \"2021\"\n" +"publish = false\n" +"\n" +"[dependencies]\n" +"arm-gic = \"0.1.0\"\n" +"bitflags = \"2.0.0\"\n" +"chrono = { version = \"0.4.24\", default-features = false }\n" +"log = \"0.4.17\"\n" +"smccc = \"0.1.1\"\n" +"spin = \"0.9.8\"\n" +"\n" +"[build-dependencies]\n" +"cc = \"1.0.73\"\n" +"```" msgstr "" -#: src/concurrency/send-sync/examples.md:27 -msgid "`!Send + Sync`" +#: src/exercises/bare-metal/rtc.md:410 +msgid "`build.rs` (you shouldn't need to change this):" msgstr "" -#: src/concurrency/send-sync/examples.md:29 +#: src/exercises/bare-metal/rtc.md:414 msgid "" -"These types are thread-safe, but they cannot be moved to another thread:" +"```rust,compile_fail\n" +"// Copyright 2023 Google LLC\n" +"//\n" +"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" +"// you may not use this file except in compliance with the License.\n" +"// You may obtain a copy of the License at\n" +"//\n" +"// http://www.apache.org/licenses/LICENSE-2.0\n" +"//\n" +"// Unless required by applicable law or agreed to in writing, software\n" +"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" +"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" +"// See the License for the specific language governing permissions and\n" +"// limitations under the License.\n" +"\n" +"use cc::Build;\n" +"use std::env;\n" +"\n" +"fn main() {\n" +" #[cfg(target_os = \"linux\")]\n" +" env::set_var(\"CROSS_COMPILE\", \"aarch64-linux-gnu\");\n" +" #[cfg(not(target_os = \"linux\"))]\n" +" env::set_var(\"CROSS_COMPILE\", \"aarch64-none-elf\");\n" +"\n" +" Build::new()\n" +" .file(\"entry.S\")\n" +" .file(\"exceptions.S\")\n" +" .file(\"idmap.S\")\n" +" .compile(\"empty\")\n" +"}\n" +"```" msgstr "" -#: src/concurrency/send-sync/examples.md:31 -msgid "" -"`MutexGuard`: Uses OS level primitives which must be deallocated on the " -"thread which created them." +#: src/exercises/bare-metal/rtc.md:446 +msgid "`entry.S` (you shouldn't need to change this):" msgstr "" -#: src/concurrency/send-sync/examples.md:34 -msgid "`!Send + !Sync`" -msgstr "" - -#: src/concurrency/send-sync/examples.md:36 -msgid "These types are not thread-safe and cannot be moved to other threads:" -msgstr "" - -#: src/concurrency/send-sync/examples.md:38 -msgid "" -"`Rc`: each `Rc` has a reference to an `RcBox`, which contains a non-" -"atomic reference count." -msgstr "" - -#: src/concurrency/send-sync/examples.md:40 -msgid "" -"`*const T`, `*mut T`: Rust assumes raw pointers may have special concurrency " -"considerations." -msgstr "" - -#: src/concurrency/shared_state.md:3 -msgid "" -"Rust uses the type system to enforce synchronization of shared data. This is " -"primarily done via two types:" -msgstr "" - -#: src/concurrency/shared_state.md:6 -msgid "" -"[`Arc`](https://doc.rust-lang.org/std/sync/struct.Arc.html), atomic " -"reference counted `T`: handles sharing between threads and takes care to " -"deallocate `T` when the last reference is dropped," -msgstr "" - -#: src/concurrency/shared_state.md:8 -msgid "" -"[`Mutex`](https://doc.rust-lang.org/std/sync/struct.Mutex.html): ensures " -"mutually exclusive access to the `T` value." -msgstr "" - -#: src/concurrency/shared_state/arc.md:1 -msgid "`Arc`" -msgstr "" - -#: src/concurrency/shared_state/arc.md:3 -msgid "" -"[`Arc`](https://doc.rust-lang.org/std/sync/struct.Arc.html) allows shared " -"read-only access via `Arc::clone`:" -msgstr "" - -#: src/concurrency/shared_state/arc.md:5 +#: src/exercises/bare-metal/rtc.md:450 msgid "" -"```rust,editable\n" -"use std::thread;\n" -"use std::sync::Arc;\n" +"```armasm\n" +"/*\n" +" * Copyright 2023 Google LLC\n" +" *\n" +" * Licensed under the Apache License, Version 2.0 (the \"License\");\n" +" * you may not use this file except in compliance with the License.\n" +" * You may obtain a copy of the License at\n" +" *\n" +" * https://www.apache.org/licenses/LICENSE-2.0\n" +" *\n" +" * Unless required by applicable law or agreed to in writing, software\n" +" * distributed under the License is distributed on an \"AS IS\" BASIS,\n" +" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" +" * See the License for the specific language governing permissions and\n" +" * limitations under the License.\n" +" */\n" "\n" -"fn main() {\n" -" let v = Arc::new(vec![10, 20, 30]);\n" -" let mut handles = Vec::new();\n" -" for _ in 1..5 {\n" -" let v = Arc::clone(&v);\n" -" handles.push(thread::spawn(move || {\n" -" let thread_id = thread::current().id();\n" -" println!(\"{thread_id:?}: {v:?}\");\n" -" }));\n" -" }\n" +".macro adr_l, reg:req, sym:req\n" +"\tadrp \\reg, \\sym\n" +"\tadd \\reg, \\reg, :lo12:\\sym\n" +".endm\n" "\n" -" handles.into_iter().for_each(|h| h.join().unwrap());\n" -" println!(\"v: {v:?}\");\n" -"}\n" +".macro mov_i, reg:req, imm:req\n" +"\tmovz \\reg, :abs_g3:\\imm\n" +"\tmovk \\reg, :abs_g2_nc:\\imm\n" +"\tmovk \\reg, :abs_g1_nc:\\imm\n" +"\tmovk \\reg, :abs_g0_nc:\\imm\n" +".endm\n" +"\n" +".set .L_MAIR_DEV_nGnRE,\t0x04\n" +".set .L_MAIR_MEM_WBWA,\t0xff\n" +".set .Lmairval, .L_MAIR_DEV_nGnRE | (.L_MAIR_MEM_WBWA << 8)\n" +"\n" +"/* 4 KiB granule size for TTBR0_EL1. */\n" +".set .L_TCR_TG0_4KB, 0x0 << 14\n" +"/* 4 KiB granule size for TTBR1_EL1. */\n" +".set .L_TCR_TG1_4KB, 0x2 << 30\n" +"/* Disable translation table walk for TTBR1_EL1, generating a translation " +"fault instead. */\n" +".set .L_TCR_EPD1, 0x1 << 23\n" +"/* Translation table walks for TTBR0_EL1 are inner sharable. */\n" +".set .L_TCR_SH_INNER, 0x3 << 12\n" +"/*\n" +" * Translation table walks for TTBR0_EL1 are outer write-back read-allocate " +"write-allocate\n" +" * cacheable.\n" +" */\n" +".set .L_TCR_RGN_OWB, 0x1 << 10\n" +"/*\n" +" * Translation table walks for TTBR0_EL1 are inner write-back read-allocate " +"write-allocate\n" +" * cacheable.\n" +" */\n" +".set .L_TCR_RGN_IWB, 0x1 << 8\n" +"/* Size offset for TTBR0_EL1 is 2**39 bytes (512 GiB). */\n" +".set .L_TCR_T0SZ_512, 64 - 39\n" +".set .Ltcrval, .L_TCR_TG0_4KB | .L_TCR_TG1_4KB | .L_TCR_EPD1 | ." +"L_TCR_RGN_OWB\n" +".set .Ltcrval, .Ltcrval | .L_TCR_RGN_IWB | .L_TCR_SH_INNER | ." +"L_TCR_T0SZ_512\n" +"\n" +"/* Stage 1 instruction access cacheability is unaffected. */\n" +".set .L_SCTLR_ELx_I, 0x1 << 12\n" +"/* SP alignment fault if SP is not aligned to a 16 byte boundary. */\n" +".set .L_SCTLR_ELx_SA, 0x1 << 3\n" +"/* Stage 1 data access cacheability is unaffected. */\n" +".set .L_SCTLR_ELx_C, 0x1 << 2\n" +"/* EL0 and EL1 stage 1 MMU enabled. */\n" +".set .L_SCTLR_ELx_M, 0x1 << 0\n" +"/* Privileged Access Never is unchanged on taking an exception to EL1. */\n" +".set .L_SCTLR_EL1_SPAN, 0x1 << 23\n" +"/* SETEND instruction disabled at EL0 in aarch32 mode. */\n" +".set .L_SCTLR_EL1_SED, 0x1 << 8\n" +"/* Various IT instructions are disabled at EL0 in aarch32 mode. */\n" +".set .L_SCTLR_EL1_ITD, 0x1 << 7\n" +".set .L_SCTLR_EL1_RES1, (0x1 << 11) | (0x1 << 20) | (0x1 << 22) | (0x1 << " +"28) | (0x1 << 29)\n" +".set .Lsctlrval, .L_SCTLR_ELx_M | .L_SCTLR_ELx_C | .L_SCTLR_ELx_SA | ." +"L_SCTLR_EL1_ITD | .L_SCTLR_EL1_SED\n" +".set .Lsctlrval, .Lsctlrval | .L_SCTLR_ELx_I | .L_SCTLR_EL1_SPAN | ." +"L_SCTLR_EL1_RES1\n" +"\n" +"/**\n" +" * This is a generic entry point for an image. It carries out the operations " +"required to prepare the\n" +" * loaded image to be run. Specifically, it zeroes the bss section using " +"registers x25 and above,\n" +" * prepares the stack, enables floating point, and sets up the exception " +"vector. It preserves x0-x3\n" +" * for the Rust entry point, as these may contain boot parameters.\n" +" */\n" +".section .init.entry, \"ax\"\n" +".global entry\n" +"entry:\n" +"\t/* Load and apply the memory management configuration, ready to enable MMU " +"and caches. */\n" +"\tadrp x30, idmap\n" +"\tmsr ttbr0_el1, x30\n" +"\n" +"\tmov_i x30, .Lmairval\n" +"\tmsr mair_el1, x30\n" +"\n" +"\tmov_i x30, .Ltcrval\n" +"\t/* Copy the supported PA range into TCR_EL1.IPS. */\n" +"\tmrs x29, id_aa64mmfr0_el1\n" +"\tbfi x30, x29, #32, #4\n" +"\n" +"\tmsr tcr_el1, x30\n" +"\n" +"\tmov_i x30, .Lsctlrval\n" +"\n" +"\t/*\n" +"\t * Ensure everything before this point has completed, then invalidate any " +"potentially stale\n" +"\t * local TLB entries before they start being used.\n" +"\t */\n" +"\tisb\n" +"\ttlbi vmalle1\n" +"\tic iallu\n" +"\tdsb nsh\n" +"\tisb\n" +"\n" +"\t/*\n" +"\t * Configure sctlr_el1 to enable MMU and cache and don't proceed until " +"this has completed.\n" +"\t */\n" +"\tmsr sctlr_el1, x30\n" +"\tisb\n" +"\n" +"\t/* Disable trapping floating point access in EL1. */\n" +"\tmrs x30, cpacr_el1\n" +"\torr x30, x30, #(0x3 << 20)\n" +"\tmsr cpacr_el1, x30\n" +"\tisb\n" +"\n" +"\t/* Zero out the bss section. */\n" +"\tadr_l x29, bss_begin\n" +"\tadr_l x30, bss_end\n" +"0:\tcmp x29, x30\n" +"\tb.hs 1f\n" +"\tstp xzr, xzr, [x29], #16\n" +"\tb 0b\n" +"\n" +"1:\t/* Prepare the stack. */\n" +"\tadr_l x30, boot_stack_end\n" +"\tmov sp, x30\n" +"\n" +"\t/* Set up exception vector. */\n" +"\tadr x30, vector_table_el1\n" +"\tmsr vbar_el1, x30\n" +"\n" +"\t/* Call into Rust code. */\n" +"\tbl main\n" +"\n" +"\t/* Loop forever waiting for interrupts. */\n" +"2:\twfi\n" +"\tb 2b\n" "```" msgstr "" -#: src/concurrency/shared_state/arc.md:29 -msgid "" -"`Arc` stands for \"Atomic Reference Counted\", a thread safe version of `Rc` " -"that uses atomic operations." -msgstr "" - -#: src/concurrency/shared_state/arc.md:31 -msgid "" -"`Arc` implements `Clone` whether or not `T` does. It implements `Send` " -"and `Sync` iff `T` implements them both." -msgstr "" - -#: src/concurrency/shared_state/arc.md:33 -msgid "" -"`Arc::clone()` has the cost of atomic operations that get executed, but " -"after that the use of the `T` is free." -msgstr "" - -#: src/concurrency/shared_state/arc.md:35 -msgid "" -"Beware of reference cycles, `Arc` does not use a garbage collector to detect " -"them." -msgstr "" - -#: src/concurrency/shared_state/arc.md:36 -msgid "`std::sync::Weak` can help." -msgstr "" - -#: src/concurrency/shared_state/mutex.md:1 -msgid "`Mutex`" +#: src/exercises/bare-metal/rtc.md:595 +msgid "`exceptions.S` (you shouldn't need to change this):" msgstr "" -#: src/concurrency/shared_state/mutex.md:3 +#: src/exercises/bare-metal/rtc.md:599 msgid "" -"[`Mutex`](https://doc.rust-lang.org/std/sync/struct.Mutex.html) ensures " -"mutual exclusion _and_ allows mutable access to `T` behind a read-only " -"interface:" +"```armasm\n" +"/*\n" +" * Copyright 2023 Google LLC\n" +" *\n" +" * Licensed under the Apache License, Version 2.0 (the \"License\");\n" +" * you may not use this file except in compliance with the License.\n" +" * You may obtain a copy of the License at\n" +" *\n" +" * https://www.apache.org/licenses/LICENSE-2.0\n" +" *\n" +" * Unless required by applicable law or agreed to in writing, software\n" +" * distributed under the License is distributed on an \"AS IS\" BASIS,\n" +" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" +" * See the License for the specific language governing permissions and\n" +" * limitations under the License.\n" +" */\n" +"\n" +"/**\n" +" * Saves the volatile registers onto the stack. This currently takes 14\n" +" * instructions, so it can be used in exception handlers with 18 " +"instructions\n" +" * left.\n" +" *\n" +" * On return, x0 and x1 are initialised to elr_el2 and spsr_el2 " +"respectively,\n" +" * which can be used as the first and second arguments of a subsequent " +"call.\n" +" */\n" +".macro save_volatile_to_stack\n" +"\t/* Reserve stack space and save registers x0-x18, x29 & x30. */\n" +"\tstp x0, x1, [sp, #-(8 * 24)]!\n" +"\tstp x2, x3, [sp, #8 * 2]\n" +"\tstp x4, x5, [sp, #8 * 4]\n" +"\tstp x6, x7, [sp, #8 * 6]\n" +"\tstp x8, x9, [sp, #8 * 8]\n" +"\tstp x10, x11, [sp, #8 * 10]\n" +"\tstp x12, x13, [sp, #8 * 12]\n" +"\tstp x14, x15, [sp, #8 * 14]\n" +"\tstp x16, x17, [sp, #8 * 16]\n" +"\tstr x18, [sp, #8 * 18]\n" +"\tstp x29, x30, [sp, #8 * 20]\n" +"\n" +"\t/*\n" +"\t * Save elr_el1 & spsr_el1. This such that we can take nested exception\n" +"\t * and still be able to unwind.\n" +"\t */\n" +"\tmrs x0, elr_el1\n" +"\tmrs x1, spsr_el1\n" +"\tstp x0, x1, [sp, #8 * 22]\n" +".endm\n" +"\n" +"/**\n" +" * Restores the volatile registers from the stack. This currently takes 14\n" +" * instructions, so it can be used in exception handlers while still leaving " +"18\n" +" * instructions left; if paired with save_volatile_to_stack, there are 4\n" +" * instructions to spare.\n" +" */\n" +".macro restore_volatile_from_stack\n" +"\t/* Restore registers x2-x18, x29 & x30. */\n" +"\tldp x2, x3, [sp, #8 * 2]\n" +"\tldp x4, x5, [sp, #8 * 4]\n" +"\tldp x6, x7, [sp, #8 * 6]\n" +"\tldp x8, x9, [sp, #8 * 8]\n" +"\tldp x10, x11, [sp, #8 * 10]\n" +"\tldp x12, x13, [sp, #8 * 12]\n" +"\tldp x14, x15, [sp, #8 * 14]\n" +"\tldp x16, x17, [sp, #8 * 16]\n" +"\tldr x18, [sp, #8 * 18]\n" +"\tldp x29, x30, [sp, #8 * 20]\n" +"\n" +"\t/* Restore registers elr_el1 & spsr_el1, using x0 & x1 as scratch. */\n" +"\tldp x0, x1, [sp, #8 * 22]\n" +"\tmsr elr_el1, x0\n" +"\tmsr spsr_el1, x1\n" +"\n" +"\t/* Restore x0 & x1, and release stack space. */\n" +"\tldp x0, x1, [sp], #8 * 24\n" +".endm\n" +"\n" +"/**\n" +" * This is a generic handler for exceptions taken at the current EL while " +"using\n" +" * SP0. It behaves similarly to the SPx case by first switching to SPx, " +"doing\n" +" * the work, then switching back to SP0 before returning.\n" +" *\n" +" * Switching to SPx and calling the Rust handler takes 16 instructions. To\n" +" * restore and return we need an additional 16 instructions, so we can " +"implement\n" +" * the whole handler within the allotted 32 instructions.\n" +" */\n" +".macro current_exception_sp0 handler:req\n" +"\tmsr spsel, #1\n" +"\tsave_volatile_to_stack\n" +"\tbl \\handler\n" +"\trestore_volatile_from_stack\n" +"\tmsr spsel, #0\n" +"\teret\n" +".endm\n" +"\n" +"/**\n" +" * This is a generic handler for exceptions taken at the current EL while " +"using\n" +" * SPx. It saves volatile registers, calls the Rust handler, restores " +"volatile\n" +" * registers, then returns.\n" +" *\n" +" * This also works for exceptions taken from EL0, if we don't care about\n" +" * non-volatile registers.\n" +" *\n" +" * Saving state and jumping to the Rust handler takes 15 instructions, and\n" +" * restoring and returning also takes 15 instructions, so we can fit the " +"whole\n" +" * handler in 30 instructions, under the limit of 32.\n" +" */\n" +".macro current_exception_spx handler:req\n" +"\tsave_volatile_to_stack\n" +"\tbl \\handler\n" +"\trestore_volatile_from_stack\n" +"\teret\n" +".endm\n" +"\n" +".section .text.vector_table_el1, \"ax\"\n" +".global vector_table_el1\n" +".balign 0x800\n" +"vector_table_el1:\n" +"sync_cur_sp0:\n" +"\tcurrent_exception_sp0 sync_exception_current\n" +"\n" +".balign 0x80\n" +"irq_cur_sp0:\n" +"\tcurrent_exception_sp0 irq_current\n" +"\n" +".balign 0x80\n" +"fiq_cur_sp0:\n" +"\tcurrent_exception_sp0 fiq_current\n" +"\n" +".balign 0x80\n" +"serr_cur_sp0:\n" +"\tcurrent_exception_sp0 serr_current\n" +"\n" +".balign 0x80\n" +"sync_cur_spx:\n" +"\tcurrent_exception_spx sync_exception_current\n" +"\n" +".balign 0x80\n" +"irq_cur_spx:\n" +"\tcurrent_exception_spx irq_current\n" +"\n" +".balign 0x80\n" +"fiq_cur_spx:\n" +"\tcurrent_exception_spx fiq_current\n" +"\n" +".balign 0x80\n" +"serr_cur_spx:\n" +"\tcurrent_exception_spx serr_current\n" +"\n" +".balign 0x80\n" +"sync_lower_64:\n" +"\tcurrent_exception_spx sync_lower\n" +"\n" +".balign 0x80\n" +"irq_lower_64:\n" +"\tcurrent_exception_spx irq_lower\n" +"\n" +".balign 0x80\n" +"fiq_lower_64:\n" +"\tcurrent_exception_spx fiq_lower\n" +"\n" +".balign 0x80\n" +"serr_lower_64:\n" +"\tcurrent_exception_spx serr_lower\n" +"\n" +".balign 0x80\n" +"sync_lower_32:\n" +"\tcurrent_exception_spx sync_lower\n" +"\n" +".balign 0x80\n" +"irq_lower_32:\n" +"\tcurrent_exception_spx irq_lower\n" +"\n" +".balign 0x80\n" +"fiq_lower_32:\n" +"\tcurrent_exception_spx fiq_lower\n" +"\n" +".balign 0x80\n" +"serr_lower_32:\n" +"\tcurrent_exception_spx serr_lower\n" +"```" msgstr "" -#: src/concurrency/shared_state/mutex.md:6 +#: src/exercises/bare-metal/rtc.md:780 +msgid "`idmap.S` (you shouldn't need to change this):" +msgstr "" + +#: src/exercises/bare-metal/rtc.md:784 msgid "" -"```rust,editable\n" -"use std::sync::Mutex;\n" +"```armasm\n" +"/*\n" +" * Copyright 2023 Google LLC\n" +" *\n" +" * Licensed under the Apache License, Version 2.0 (the \"License\");\n" +" * you may not use this file except in compliance with the License.\n" +" * You may obtain a copy of the License at\n" +" *\n" +" * https://www.apache.org/licenses/LICENSE-2.0\n" +" *\n" +" * Unless required by applicable law or agreed to in writing, software\n" +" * distributed under the License is distributed on an \"AS IS\" BASIS,\n" +" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" +" * See the License for the specific language governing permissions and\n" +" * limitations under the License.\n" +" */\n" "\n" -"fn main() {\n" -" let v = Mutex::new(vec![10, 20, 30]);\n" -" println!(\"v: {:?}\", v.lock().unwrap());\n" +".set .L_TT_TYPE_BLOCK, 0x1\n" +".set .L_TT_TYPE_PAGE, 0x3\n" +".set .L_TT_TYPE_TABLE, 0x3\n" "\n" -" {\n" -" let mut guard = v.lock().unwrap();\n" -" guard.push(40);\n" -" }\n" +"/* Access flag. */\n" +".set .L_TT_AF, 0x1 << 10\n" +"/* Not global. */\n" +".set .L_TT_NG, 0x1 << 11\n" +".set .L_TT_XN, 0x3 << 53\n" "\n" -" println!(\"v: {:?}\", v.lock().unwrap());\n" -"}\n" +".set .L_TT_MT_DEV, 0x0 << 2\t\t\t// MAIR #0 (DEV_nGnRE)\n" +".set .L_TT_MT_MEM, (0x1 << 2) | (0x3 << 8)\t// MAIR #1 (MEM_WBWA), inner " +"shareable\n" +"\n" +".set .L_BLOCK_DEV, .L_TT_TYPE_BLOCK | .L_TT_MT_DEV | .L_TT_AF | .L_TT_XN\n" +".set .L_BLOCK_MEM, .L_TT_TYPE_BLOCK | .L_TT_MT_MEM | .L_TT_AF | .L_TT_NG\n" +"\n" +".section \".rodata.idmap\", \"a\", %progbits\n" +".global idmap\n" +".align 12\n" +"idmap:\n" +"\t/* level 1 */\n" +"\t.quad\t\t.L_BLOCK_DEV | 0x0\t\t // 1 GiB of device mappings\n" +"\t.quad\t\t.L_BLOCK_MEM | 0x40000000\t// 1 GiB of DRAM\n" +"\t.fill\t\t254, 8, 0x0\t\t\t// 254 GiB of unmapped VA space\n" +"\t.quad\t\t.L_BLOCK_DEV | 0x4000000000 // 1 GiB of device mappings\n" +"\t.fill\t\t255, 8, 0x0\t\t\t// 255 GiB of remaining VA space\n" "```" msgstr "" -#: src/concurrency/shared_state/mutex.md:22 -msgid "" -"Notice how we have a [`impl Sync for Mutex`](https://doc.rust-" -"lang.org/std/sync/struct.Mutex.html#impl-Sync-for-Mutex%3CT%3E) blanket " -"implementation." +#: src/exercises/bare-metal/rtc.md:829 +msgid "`image.ld` (you shouldn't need to change this):" msgstr "" -#: src/concurrency/shared_state/mutex.md:31 +#: src/exercises/bare-metal/rtc.md:833 msgid "" -"`Mutex` in Rust looks like a collection with just one element - the " -"protected data." +"```ld\n" +"/*\n" +" * Copyright 2023 Google LLC\n" +" *\n" +" * Licensed under the Apache License, Version 2.0 (the \"License\");\n" +" * you may not use this file except in compliance with the License.\n" +" * You may obtain a copy of the License at\n" +" *\n" +" * https://www.apache.org/licenses/LICENSE-2.0\n" +" *\n" +" * Unless required by applicable law or agreed to in writing, software\n" +" * distributed under the License is distributed on an \"AS IS\" BASIS,\n" +" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" +" * See the License for the specific language governing permissions and\n" +" * limitations under the License.\n" +" */\n" +"\n" +"/*\n" +" * Code will start running at this symbol which is placed at the start of " +"the\n" +" * image.\n" +" */\n" +"ENTRY(entry)\n" +"\n" +"MEMORY\n" +"{\n" +"\timage : ORIGIN = 0x40080000, LENGTH = 2M\n" +"}\n" +"\n" +"SECTIONS\n" +"{\n" +"\t/*\n" +"\t * Collect together the code.\n" +"\t */\n" +"\t.init : ALIGN(4096) {\n" +"\t\ttext_begin = .;\n" +"\t\t*(.init.entry)\n" +"\t\t*(.init.*)\n" +"\t} >image\n" +"\t.text : {\n" +"\t\t*(.text.*)\n" +"\t} >image\n" +"\ttext_end = .;\n" +"\n" +"\t/*\n" +"\t * Collect together read-only data.\n" +"\t */\n" +"\t.rodata : ALIGN(4096) {\n" +"\t\trodata_begin = .;\n" +"\t\t*(.rodata.*)\n" +"\t} >image\n" +"\t.got : {\n" +"\t\t*(.got)\n" +"\t} >image\n" +"\trodata_end = .;\n" +"\n" +"\t/*\n" +"\t * Collect together the read-write data including .bss at the end which\n" +"\t * will be zero'd by the entry code.\n" +"\t */\n" +"\t.data : ALIGN(4096) {\n" +"\t\tdata_begin = .;\n" +"\t\t*(.data.*)\n" +"\t\t/*\n" +"\t\t * The entry point code assumes that .data is a multiple of 32\n" +"\t\t * bytes long.\n" +"\t\t */\n" +"\t\t. = ALIGN(32);\n" +"\t\tdata_end = .;\n" +"\t} >image\n" +"\n" +"\t/* Everything beyond this point will not be included in the binary. */\n" +"\tbin_end = .;\n" +"\n" +"\t/* The entry point code assumes that .bss is 16-byte aligned. */\n" +"\t.bss : ALIGN(16) {\n" +"\t\tbss_begin = .;\n" +"\t\t*(.bss.*)\n" +"\t\t*(COMMON)\n" +"\t\t. = ALIGN(16);\n" +"\t\tbss_end = .;\n" +"\t} >image\n" +"\n" +"\t.stack (NOLOAD) : ALIGN(4096) {\n" +"\t\tboot_stack_begin = .;\n" +"\t\t. += 40 * 4096;\n" +"\t\t. = ALIGN(4096);\n" +"\t\tboot_stack_end = .;\n" +"\t} >image\n" +"\n" +"\t. = ALIGN(4K);\n" +"\tPROVIDE(dma_region = .);\n" +"\n" +"\t/*\n" +"\t * Remove unused sections from the image.\n" +"\t */\n" +"\t/DISCARD/ : {\n" +"\t\t/* The image loads itself so doesn't need these sections. */\n" +"\t\t*(.gnu.hash)\n" +"\t\t*(.hash)\n" +"\t\t*(.interp)\n" +"\t\t*(.eh_frame_hdr)\n" +"\t\t*(.eh_frame)\n" +"\t\t*(.note.gnu.build-id)\n" +"\t}\n" +"}\n" +"```" msgstr "" -#: src/concurrency/shared_state/mutex.md:32 -msgid "" -"It is not possible to forget to acquire the mutex before accessing the " -"protected data." +#: src/exercises/bare-metal/rtc.md:940 +msgid "`Makefile` (you shouldn't need to change this):" msgstr "" -#: src/concurrency/shared_state/mutex.md:33 +#: src/exercises/bare-metal/rtc.md:944 msgid "" -"You can get an `&mut T` from an `&Mutex` by taking the lock. The " -"`MutexGuard` ensures that the `&mut T` doesn't outlive the lock being held." +"```makefile\n" +"# Copyright 2023 Google LLC\n" +"#\n" +"# Licensed under the Apache License, Version 2.0 (the \"License\");\n" +"# you may not use this file except in compliance with the License.\n" +"# You may obtain a copy of the License at\n" +"#\n" +"# http://www.apache.org/licenses/LICENSE-2.0\n" +"#\n" +"# Unless required by applicable law or agreed to in writing, software\n" +"# distributed under the License is distributed on an \"AS IS\" BASIS,\n" +"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" +"# See the License for the specific language governing permissions and\n" +"# limitations under the License.\n" +"\n" +"UNAME := $(shell uname -s)\n" +"ifeq ($(UNAME),Linux)\n" +"\tTARGET = aarch64-linux-gnu\n" +"else\n" +"\tTARGET = aarch64-none-elf\n" +"endif\n" +"OBJCOPY = $(TARGET)-objcopy\n" +"\n" +".PHONY: build qemu_minimal qemu qemu_logger\n" +"\n" +"all: rtc.bin\n" +"\n" +"build:\n" +"\tcargo build\n" +"\n" +"rtc.bin: build\n" +"\t$(OBJCOPY) -O binary target/aarch64-unknown-none/debug/rtc $@\n" +"\n" +"qemu: rtc.bin\n" +"\tqemu-system-aarch64 -machine virt,gic-version=3 -cpu max -serial mon:stdio " +"-display none -kernel $< -s\n" +"\n" +"clean:\n" +"\tcargo clean\n" +"\trm -f *.bin\n" +"```" msgstr "" -#: src/concurrency/shared_state/mutex.md:35 -msgid "`Mutex` implements both `Send` and `Sync` iff `T` implements `Send`." +#: src/exercises/bare-metal/rtc.md:989 +msgid "" +"```toml\n" +"[build]\n" +"target = \"aarch64-unknown-none\"\n" +"rustflags = [\"-C\", \"link-arg=-Timage.ld\"]\n" +"```" msgstr "" -#: src/concurrency/shared_state/mutex.md:36 -msgid "A read-write lock counterpart - `RwLock`." +#: src/exercises/bare-metal/rtc.md:995 +msgid "Run the code in QEMU with `make qemu`." msgstr "" -#: src/concurrency/shared_state/mutex.md:37 -msgid "Why does `lock()` return a `Result`? " +#: src/concurrency.md:1 +msgid "Welcome to Concurrency in Rust" msgstr "" -#: src/concurrency/shared_state/mutex.md:38 +#: src/concurrency.md:3 msgid "" -"If the thread that held the `Mutex` panicked, the `Mutex` becomes " -"\"poisoned\" to signal that the data it protected might be in an " -"inconsistent state. Calling `lock()` on a poisoned mutex fails with a " -"[`PoisonError`](https://doc.rust-lang.org/std/sync/struct.PoisonError.html). " -"You can call `into_inner()` on the error to recover the data regardless." -msgstr "" - -#: src/concurrency/shared_state/example.md:3 -msgid "Let us see `Arc` and `Mutex` in action:" +"Rust has full support for concurrency using OS threads with mutexes and " +"channels." msgstr "" -#: src/concurrency/shared_state/example.md:5 +#: src/concurrency.md:6 msgid "" -"```rust,editable,compile_fail\n" -"use std::thread;\n" -"// use std::sync::{Arc, Mutex};\n" -"\n" -"fn main() {\n" -" let v = vec![10, 20, 30];\n" -" let handle = thread::spawn(|| {\n" -" v.push(10);\n" -" });\n" -" v.push(1000);\n" -"\n" -" handle.join().unwrap();\n" -" println!(\"v: {v:?}\");\n" -"}\n" -"```" +"The Rust type system plays an important role in making many concurrency bugs " +"compile time bugs. This is often referred to as _fearless concurrency_ since " +"you can rely on the compiler to ensure correctness at runtime." msgstr "" -#: src/concurrency/shared_state/example.md:23 -msgid "Possible solution:" +#: src/concurrency/threads.md:3 +msgid "Rust threads work similarly to threads in other languages:" msgstr "" -#: src/concurrency/shared_state/example.md:25 +#: src/concurrency/threads.md:5 msgid "" "```rust,editable\n" -"use std::sync::{Arc, Mutex};\n" "use std::thread;\n" +"use std::time::Duration;\n" "\n" "fn main() {\n" -" let v = Arc::new(Mutex::new(vec![10, 20, 30]));\n" -"\n" -" let v2 = Arc::clone(&v);\n" -" let handle = thread::spawn(move || {\n" -" let mut v2 = v2.lock().unwrap();\n" -" v2.push(10);\n" +" thread::spawn(|| {\n" +" for i in 1..10 {\n" +" println!(\"Count in thread: {i}!\");\n" +" thread::sleep(Duration::from_millis(5));\n" +" }\n" " });\n" "\n" -" {\n" -" let mut v = v.lock().unwrap();\n" -" v.push(1000);\n" +" for i in 1..5 {\n" +" println!(\"Main thread: {i}\");\n" +" thread::sleep(Duration::from_millis(5));\n" " }\n" -"\n" -" handle.join().unwrap();\n" -"\n" -" println!(\"v: {v:?}\");\n" "}\n" "```" msgstr "" -#: src/concurrency/shared_state/example.md:49 -msgid "Notable parts:" +#: src/concurrency/threads.md:24 +msgid "Threads are all daemon threads, the main thread does not wait for them." msgstr "" -#: src/concurrency/shared_state/example.md:51 -msgid "" -"`v` is wrapped in both `Arc` and `Mutex`, because their concerns are " -"orthogonal." +#: src/concurrency/threads.md:25 +msgid "Thread panics are independent of each other." msgstr "" -#: src/concurrency/shared_state/example.md:52 -msgid "" -"Wrapping a `Mutex` in an `Arc` is a common pattern to share mutable state " -"between threads." +#: src/concurrency/threads.md:26 +msgid "Panics can carry a payload, which can be unpacked with `downcast_ref`." msgstr "" -#: src/concurrency/shared_state/example.md:53 +#: src/concurrency/threads.md:32 msgid "" -"`v: Arc<_>` needs to be cloned as `v2` before it can be moved into another " -"thread. Note `move` was added to the lambda signature." +"Notice that the thread is stopped before it reaches 10 — the main thread is " +"not waiting." msgstr "" -#: src/concurrency/shared_state/example.md:54 +#: src/concurrency/threads.md:35 msgid "" -"Blocks are introduced to narrow the scope of the `LockGuard` as much as " -"possible." -msgstr "" - -#: src/exercises/concurrency/morning.md:3 -msgid "Let us practice our new concurrency skills with" +"Use `let handle = thread::spawn(...)` and later `handle.join()` to wait for " +"the thread to finish." msgstr "" -#: src/exercises/concurrency/morning.md:5 -msgid "Dining philosophers: a classic problem in concurrency." +#: src/concurrency/threads.md:38 +msgid "Trigger a panic in the thread, notice how this doesn't affect `main`." msgstr "" -#: src/exercises/concurrency/morning.md:7 +#: src/concurrency/threads.md:40 msgid "" -"Multi-threaded link checker: a larger project where you'll use Cargo to " -"download dependencies and then check links in parallel." +"Use the `Result` return value from `handle.join()` to get access to the " +"panic payload. This is a good time to talk about [`Any`](https://doc.rust-" +"lang.org/std/any/index.html)." msgstr "" -#: src/exercises/concurrency/dining-philosophers.md:3 -msgid "The dining philosophers problem is a classic problem in concurrency:" +#: src/concurrency/scoped-threads.md:3 +msgid "Normal threads cannot borrow from their environment:" msgstr "" -#: src/exercises/concurrency/dining-philosophers.md:5 +#: src/concurrency/scoped-threads.md:5 msgid "" -"Five philosophers dine together at the same table. Each philosopher has " -"their own place at the table. There is a fork between each plate. The dish " -"served is a kind of spaghetti which has to be eaten with two forks. Each " -"philosopher can only alternately think and eat. Moreover, a philosopher can " -"only eat their spaghetti when they have both a left and right fork. Thus two " -"forks will only be available when their two nearest neighbors are thinking, " -"not eating. After an individual philosopher finishes eating, they will put " -"down both forks." +"```rust,editable,compile_fail\n" +"use std::thread;\n" +"\n" +"fn foo() {\n" +" let s = String::from(\"Hello\");\n" +" thread::spawn(|| {\n" +" println!(\"Length: {}\", s.len());\n" +" });\n" +"}\n" +"\n" +"fn main() {\n" +" foo();\n" +"}\n" +"```" msgstr "" -#: src/exercises/concurrency/dining-philosophers.md:13 +#: src/concurrency/scoped-threads.md:20 msgid "" -"You will need a local [Cargo installation](../../cargo/running-locally.md) " -"for this exercise. Copy the code below to a file called `src/main.rs`, fill " -"out the blanks, and test that `cargo run` does not deadlock:" +"However, you can use a [scoped thread](https://doc.rust-lang.org/std/thread/" +"fn.scope.html) for this:" msgstr "" -#: src/exercises/concurrency/dining-philosophers.md:19 +#: src/concurrency/scoped-threads.md:22 msgid "" -"```rust,compile_fail\n" -"use std::sync::{mpsc, Arc, Mutex};\n" +"```rust,editable\n" "use std::thread;\n" -"use std::time::Duration;\n" -"\n" -"struct Fork;\n" -"\n" -"struct Philosopher {\n" -" name: String,\n" -" // left_fork: ...\n" -" // right_fork: ...\n" -" // thoughts: ...\n" -"}\n" -"\n" -"impl Philosopher {\n" -" fn think(&self) {\n" -" self.thoughts\n" -" .send(format!(\"Eureka! {} has a new idea!\", &self.name))\n" -" .unwrap();\n" -" }\n" -"\n" -" fn eat(&self) {\n" -" // Pick up forks...\n" -" println!(\"{} is eating...\", &self.name);\n" -" thread::sleep(Duration::from_millis(10));\n" -" }\n" -"}\n" -"\n" -"static PHILOSOPHERS: &[&str] =\n" -" &[\"Socrates\", \"Plato\", \"Aristotle\", \"Thales\", \"Pythagoras\"];\n" "\n" "fn main() {\n" -" // Create forks\n" -"\n" -" // Create philosophers\n" -"\n" -" // Make them think and eat\n" +" let s = String::from(\"Hello\");\n" "\n" -" // Output their thoughts\n" +" thread::scope(|scope| {\n" +" scope.spawn(|| {\n" +" println!(\"Length: {}\", s.len());\n" +" });\n" +" });\n" "}\n" "```" msgstr "" -#: src/exercises/concurrency/dining-philosophers.md:61 -msgid "You can use the following `Cargo.toml`:" -msgstr "" - -#: src/exercises/concurrency/dining-philosophers.md:65 +#: src/concurrency/scoped-threads.md:40 msgid "" -"```toml\n" -"[package]\n" -"name = \"dining-philosophers\"\n" -"version = \"0.1.0\"\n" -"edition = \"2021\"\n" -"```" +"The reason for that is that when the `thread::scope` function completes, all " +"the threads are guaranteed to be joined, so they can return borrowed data." msgstr "" -#: src/exercises/concurrency/link-checker.md:3 +#: src/concurrency/scoped-threads.md:41 msgid "" -"Let us use our new knowledge to create a multi-threaded link checker. It " -"should start at a webpage and check that links on the page are valid. It " -"should recursively check other pages on the same domain and keep doing this " -"until all pages have been validated." +"Normal Rust borrowing rules apply: you can either borrow mutably by one " +"thread, or immutably by any number of threads." msgstr "" -#: src/exercises/concurrency/link-checker.md:8 +#: src/concurrency/channels.md:3 msgid "" -"For this, you will need an HTTP client such as [`reqwest`](https://docs.rs/" -"reqwest/). Create a new Cargo project and `reqwest` it as a dependency with:" +"Rust channels have two parts: a `Sender` and a `Receiver`. The two " +"parts are connected via the channel, but you only see the end-points." msgstr "" -#: src/exercises/concurrency/link-checker.md:11 +#: src/concurrency/channels.md:6 msgid "" -"```shell\n" -"$ cargo new link-checker\n" -"$ cd link-checker\n" -"$ cargo add --features blocking,rustls-tls reqwest\n" +"```rust,editable\n" +"use std::sync::mpsc;\n" +"use std::thread;\n" +"\n" +"fn main() {\n" +" let (tx, rx) = mpsc::channel();\n" +"\n" +" tx.send(10).unwrap();\n" +" tx.send(20).unwrap();\n" +"\n" +" println!(\"Received: {:?}\", rx.recv());\n" +" println!(\"Received: {:?}\", rx.recv());\n" +"\n" +" let tx2 = tx.clone();\n" +" tx2.send(30).unwrap();\n" +" println!(\"Received: {:?}\", rx.recv());\n" +"}\n" "```" msgstr "" -#: src/exercises/concurrency/link-checker.md:17 +#: src/concurrency/channels.md:27 msgid "" -"If `cargo add` fails with `error: no such subcommand`, then please edit the " -"`Cargo.toml` file by hand. Add the dependencies listed below." +"`mpsc` stands for Multi-Producer, Single-Consumer. `Sender` and `SyncSender` " +"implement `Clone` (so you can make multiple producers) but `Receiver` does " +"not." msgstr "" -#: src/exercises/concurrency/link-checker.md:20 +#: src/concurrency/channels.md:29 msgid "" -"You will also need a way to find links. We can use [`scraper`](https://docs." -"rs/scraper/) for that:" +"`send()` and `recv()` return `Result`. If they return `Err`, it means the " +"counterpart `Sender` or `Receiver` is dropped and the channel is closed." msgstr "" -#: src/exercises/concurrency/link-checker.md:22 +#: src/concurrency/channels/unbounded.md:3 +msgid "You get an unbounded and asynchronous channel with `mpsc::channel()`:" +msgstr "" + +#: src/concurrency/channels/unbounded.md:5 msgid "" -"```shell\n" -"$ cargo add scraper\n" +"```rust,editable\n" +"use std::sync::mpsc;\n" +"use std::thread;\n" +"use std::time::Duration;\n" +"\n" +"fn main() {\n" +" let (tx, rx) = mpsc::channel();\n" +"\n" +" thread::spawn(move || {\n" +" let thread_id = thread::current().id();\n" +" for i in 1..10 {\n" +" tx.send(format!(\"Message {i}\")).unwrap();\n" +" println!(\"{thread_id:?}: sent Message {i}\");\n" +" }\n" +" println!(\"{thread_id:?}: done\");\n" +" });\n" +" thread::sleep(Duration::from_millis(100));\n" +"\n" +" for msg in rx.iter() {\n" +" println!(\"Main: got {msg}\");\n" +" }\n" +"}\n" "```" msgstr "" -#: src/exercises/concurrency/link-checker.md:26 +#: src/concurrency/channels/bounded.md:3 msgid "" -"Finally, we'll need some way of handling errors. We use [`thiserror`]" -"(https://docs.rs/thiserror/) for that:" +"With bounded (synchronous) channels, `send` can block the current thread:" msgstr "" -#: src/exercises/concurrency/link-checker.md:29 +#: src/concurrency/channels/bounded.md:5 msgid "" -"```shell\n" -"$ cargo add thiserror\n" +"```rust,editable\n" +"use std::sync::mpsc;\n" +"use std::thread;\n" +"use std::time::Duration;\n" +"\n" +"fn main() {\n" +" let (tx, rx) = mpsc::sync_channel(3);\n" +"\n" +" thread::spawn(move || {\n" +" let thread_id = thread::current().id();\n" +" for i in 1..10 {\n" +" tx.send(format!(\"Message {i}\")).unwrap();\n" +" println!(\"{thread_id:?}: sent Message {i}\");\n" +" }\n" +" println!(\"{thread_id:?}: done\");\n" +" });\n" +" thread::sleep(Duration::from_millis(100));\n" +"\n" +" for msg in rx.iter() {\n" +" println!(\"Main: got {msg}\");\n" +" }\n" +"}\n" "```" msgstr "" -#: src/exercises/concurrency/link-checker.md:33 +#: src/concurrency/channels/bounded.md:31 msgid "" -"The `cargo add` calls will update the `Cargo.toml` file to look like this:" +"Calling `send` will block the current thread until there is space in the " +"channel for the new message. The thread can be blocked indefinitely if there " +"is nobody who reads from the channel." msgstr "" -#: src/exercises/concurrency/link-checker.md:37 +#: src/concurrency/channels/bounded.md:32 msgid "" -"```toml\n" -"[package]\n" -"name = \"link-checker\"\n" -"version = \"0.1.0\"\n" -"edition = \"2021\"\n" -"publish = false\n" -"\n" -"[dependencies]\n" -"reqwest = { version = \"0.11.12\", features = [\"blocking\", \"rustls-" -"tls\"] }\n" -"scraper = \"0.13.0\"\n" -"thiserror = \"1.0.37\"\n" -"```" +"A call to `send` will abort with an error (that is why it returns `Result`) " +"if the channel is closed. A channel is closed when the receiver is dropped." msgstr "" -#: src/exercises/concurrency/link-checker.md:50 +#: src/concurrency/channels/bounded.md:33 msgid "" -"You can now download the start page. Try with a small site such as `https://" -"www.google.org/`." +"A bounded channel with a size of zero is called a \"rendezvous channel\". " +"Every send will block the current thread until another thread calls `read`." msgstr "" -#: src/exercises/concurrency/link-checker.md:53 -msgid "Your `src/main.rs` file should look something like this:" +#: src/concurrency/send-sync.md:1 +msgid "`Send` and `Sync`" msgstr "" -#: src/exercises/concurrency/link-checker.md:57 +#: src/concurrency/send-sync.md:3 msgid "" -"```rust,compile_fail\n" -"use reqwest::blocking::{get, Response};\n" -"use reqwest::Url;\n" -"use scraper::{Html, Selector};\n" -"use thiserror::Error;\n" -"\n" -"#[derive(Error, Debug)]\n" -"enum Error {\n" -" #[error(\"request error: {0}\")]\n" -" ReqwestError(#[from] reqwest::Error),\n" -"}\n" -"\n" -"fn extract_links(response: Response) -> Result, Error> {\n" -" let base_url = response.url().to_owned();\n" -" let document = response.text()?;\n" -" let html = Html::parse_document(&document);\n" -" let selector = Selector::parse(\"a\").unwrap();\n" -"\n" -" let mut valid_urls = Vec::new();\n" -" for element in html.select(&selector) {\n" -" if let Some(href) = element.value().attr(\"href\") {\n" -" match base_url.join(href) {\n" -" Ok(url) => valid_urls.push(url),\n" -" Err(err) => {\n" -" println!(\"On {base_url}: could not parse {href:?}: " -"{err} (ignored)\",);\n" -" }\n" -" }\n" -" }\n" -" }\n" -"\n" -" Ok(valid_urls)\n" -"}\n" -"\n" -"fn main() {\n" -" let start_url = Url::parse(\"https://www.google.org\").unwrap();\n" -" let response = get(start_url).unwrap();\n" -" match extract_links(response) {\n" -" Ok(links) => println!(\"Links: {links:#?}\"),\n" -" Err(err) => println!(\"Could not extract links: {err:#}\"),\n" -" }\n" -"}\n" -"```" +"How does Rust know to forbid shared access across thread? The answer is in " +"two traits:" msgstr "" -#: src/exercises/concurrency/link-checker.md:100 -msgid "Run the code in `src/main.rs` with" +#: src/concurrency/send-sync.md:5 +msgid "" +"[`Send`](https://doc.rust-lang.org/std/marker/trait.Send.html): a type `T` " +"is `Send` if it is safe to move a `T` across a thread boundary." msgstr "" -#: src/exercises/concurrency/link-checker.md:102 +#: src/concurrency/send-sync.md:7 msgid "" -"```shell\n" -"$ cargo run\n" -"```" +"[`Sync`](https://doc.rust-lang.org/std/marker/trait.Sync.html): a type `T` " +"is `Sync` if it is safe to move a `&T` across a thread boundary." msgstr "" -#: src/exercises/concurrency/link-checker.md:108 +#: src/concurrency/send-sync.md:10 msgid "" -"Use threads to check the links in parallel: send the URLs to be checked to a " -"channel and let a few threads check the URLs in parallel." +"`Send` and `Sync` are [unsafe traits](../unsafe/unsafe-traits.md). The " +"compiler will automatically derive them for your types as long as they only " +"contain `Send` and `Sync` types. You can also implement them manually when " +"you know it is valid." msgstr "" -#: src/exercises/concurrency/link-checker.md:110 +#: src/concurrency/send-sync.md:20 msgid "" -"Extend this to recursively extract links from all pages on the `www.google." -"org` domain. Put an upper limit of 100 pages or so so that you don't end up " -"being blocked by the site." +"One can think of these traits as markers that the type has certain thread-" +"safety properties." msgstr "" -#: src/async.md:1 -msgid "Async Rust" +#: src/concurrency/send-sync.md:21 +msgid "They can be used in the generic constraints as normal traits." msgstr "" -#: src/async.md:3 +#: src/concurrency/send-sync/send.md:1 +msgid "`Send`" +msgstr "" + +#: src/concurrency/send-sync/send.md:3 msgid "" -"\"Async\" is a concurrency model where multiple tasks are executed " -"concurrently by executing each task until it would block, then switching to " -"another task that is ready to make progress. The model allows running a " -"larger number of tasks on a limited number of threads. This is because the " -"per-task overhead is typically very low and operating systems provide " -"primitives for efficiently identifying I/O that is able to proceed." +"A type `T` is [`Send`](https://doc.rust-lang.org/std/marker/trait.Send.html) " +"if it is safe to move a `T` value to another thread." msgstr "" -#: src/async.md:10 +#: src/concurrency/send-sync/send.md:5 msgid "" -"Rust's asynchronous operation is based on \"futures\", which represent work " -"that may be completed in the future. Futures are \"polled\" until they " -"signal that they are complete." +"The effect of moving ownership to another thread is that _destructors_ will " +"run in that thread. So the question is when you can allocate a value in one " +"thread and deallocate it in another." msgstr "" -#: src/async.md:14 +#: src/concurrency/send-sync/send.md:13 msgid "" -"Futures are polled by an async runtime, and several different runtimes are " -"available." +"As an example, a connection to the SQLite library must only be accessed from " +"a single thread." msgstr "" -#: src/async.md:17 -msgid "Comparisons" +#: src/concurrency/send-sync/sync.md:1 +msgid "`Sync`" msgstr "" -#: src/async.md:19 +#: src/concurrency/send-sync/sync.md:3 msgid "" -"Python has a similar model in its `asyncio`. However, its `Future` type is " -"callback-based, and not polled. Async Python programs require a \"loop\", " -"similar to a runtime in Rust." +"A type `T` is [`Sync`](https://doc.rust-lang.org/std/marker/trait.Sync.html) " +"if it is safe to access a `T` value from multiple threads at the same time." msgstr "" -#: src/async.md:23 -msgid "" -"JavaScript's `Promise` is similar, but again callback-based. The language " -"runtime implements the event loop, so many of the details of Promise " -"resolution are hidden." +#: src/concurrency/send-sync/sync.md:6 +msgid "More precisely, the definition is:" msgstr "" -#: src/async/async-await.md:1 -msgid "`async`/`await`" +#: src/concurrency/send-sync/sync.md:8 +msgid "`T` is `Sync` if and only if `&T` is `Send`" msgstr "" -#: src/async/async-await.md:3 +#: src/concurrency/send-sync/sync.md:14 msgid "" -"At a high level, async Rust code looks very much like \"normal\" sequential " -"code:" +"This statement is essentially a shorthand way of saying that if a type is " +"thread-safe for shared use, it is also thread-safe to pass references of it " +"across threads." msgstr "" -#: src/async/async-await.md:5 +#: src/concurrency/send-sync/sync.md:16 msgid "" -"```rust,editable,compile_fail\n" -"use futures::executor::block_on;\n" -"\n" -"async fn count_to(count: i32) {\n" -" for i in 1..=count {\n" -" println!(\"Count is: {i}!\");\n" -" }\n" -"}\n" -"\n" -"async fn async_main(count: i32) {\n" -" count_to(count).await;\n" -"}\n" -"\n" -"fn main() {\n" -" block_on(async_main(10));\n" -"}\n" -"```" +"This is because if a type is Sync it means that it can be shared across " +"multiple threads without the risk of data races or other synchronization " +"issues, so it is safe to move it to another thread. A reference to the type " +"is also safe to move to another thread, because the data it references can " +"be accessed from any thread safely." msgstr "" -#: src/async/async-await.md:27 -msgid "" -"Note that this is a simplified example to show the syntax. There is no long " -"running operation or any real concurrency in it!" +#: src/concurrency/send-sync/examples.md:3 +msgid "`Send + Sync`" msgstr "" -#: src/async/async-await.md:30 -msgid "What is the return type of an async call?" +#: src/concurrency/send-sync/examples.md:5 +msgid "Most types you come across are `Send + Sync`:" msgstr "" -#: src/async/async-await.md:31 -msgid "Use `let future: () = async_main(10);` in `main` to see the type." +#: src/concurrency/send-sync/examples.md:7 +msgid "`i8`, `f32`, `bool`, `char`, `&str`, ..." msgstr "" -#: src/async/async-await.md:33 -msgid "" -"The \"async\" keyword is syntactic sugar. The compiler replaces the return " -"type with a future. " +#: src/concurrency/send-sync/examples.md:8 +msgid "`(T1, T2)`, `[T; N]`, `&[T]`, `struct { x: T }`, ..." msgstr "" -#: src/async/async-await.md:36 -msgid "" -"You cannot make `main` async, without additional instructions to the " -"compiler on how to use the returned future." +#: src/concurrency/send-sync/examples.md:9 +msgid "`String`, `Option`, `Vec`, `Box`, ..." msgstr "" -#: src/async/async-await.md:39 -msgid "" -"You need an executor to run async code. `block_on` blocks the current thread " -"until the provided future has run to completion. " +#: src/concurrency/send-sync/examples.md:10 +msgid "`Arc`: Explicitly thread-safe via atomic reference count." msgstr "" -#: src/async/async-await.md:42 -msgid "" -"`.await` asynchronously waits for the completion of another operation. " -"Unlike `block_on`, `.await` doesn't block the current thread." +#: src/concurrency/send-sync/examples.md:11 +msgid "`Mutex`: Explicitly thread-safe via internal locking." msgstr "" -#: src/async/async-await.md:45 -msgid "" -"`.await` can only be used inside an `async` function (or block; these are " -"introduced later). " +#: src/concurrency/send-sync/examples.md:12 +msgid "`AtomicBool`, `AtomicU8`, ...: Uses special atomic instructions." msgstr "" -#: src/async/futures.md:3 +#: src/concurrency/send-sync/examples.md:14 msgid "" -"[`Future`](https://doc.rust-lang.org/std/future/trait.Future.html) is a " -"trait, implemented by objects that represent an operation that may not be " -"complete yet. A future can be polled, and `poll` returns a [`Poll`](https://" -"doc.rust-lang.org/std/task/enum.Poll.html)." +"The generic types are typically `Send + Sync` when the type parameters are " +"`Send + Sync`." msgstr "" -#: src/async/futures.md:8 -msgid "" -"```rust\n" -"use std::pin::Pin;\n" -"use std::task::Context;\n" -"\n" -"pub trait Future {\n" -" type Output;\n" -" fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll;\n" -"}\n" -"\n" -"pub enum Poll {\n" -" Ready(T),\n" -" Pending,\n" -"}\n" -"```" +#: src/concurrency/send-sync/examples.md:17 +msgid "`Send + !Sync`" msgstr "" -#: src/async/futures.md:23 +#: src/concurrency/send-sync/examples.md:19 msgid "" -"An async function returns an `impl Future`. It's also possible (but " -"uncommon) to implement `Future` for your own types. For example, the " -"`JoinHandle` returned from `tokio::spawn` implements `Future` to allow " -"joining to it." +"These types can be moved to other threads, but they're not thread-safe. " +"Typically because of interior mutability:" msgstr "" -#: src/async/futures.md:27 -msgid "" -"The `.await` keyword, applied to a Future, causes the current async function " -"to pause until that Future is ready, and then evaluates to its output." +#: src/concurrency/send-sync/examples.md:22 +msgid "`mpsc::Sender`" msgstr "" -#: src/async/futures.md:32 -msgid "" -"The `Future` and `Poll` types are implemented exactly as shown; click the " -"links to show the implementations in the docs." +#: src/concurrency/send-sync/examples.md:23 +msgid "`mpsc::Receiver`" msgstr "" -#: src/async/futures.md:35 -msgid "" -"We will not get to `Pin` and `Context`, as we will focus on writing async " -"code, rather than building new async primitives. Briefly:" +#: src/concurrency/send-sync/examples.md:24 +msgid "`Cell`" msgstr "" -#: src/async/futures.md:38 -msgid "" -"`Context` allows a Future to schedule itself to be polled again when an " -"event occurs." +#: src/concurrency/send-sync/examples.md:25 +msgid "`RefCell`" msgstr "" -#: src/async/futures.md:41 -msgid "" -"`Pin` ensures that the Future isn't moved in memory, so that pointers into " -"that future remain valid. This is required to allow references to remain " -"valid after an `.await`." +#: src/concurrency/send-sync/examples.md:27 +msgid "`!Send + Sync`" msgstr "" -#: src/async/runtimes.md:3 +#: src/concurrency/send-sync/examples.md:29 msgid "" -"A _runtime_ provides support for performing operations asynchronously (a " -"_reactor_) and is responsible for executing futures (an _executor_). Rust " -"does not have a \"built-in\" runtime, but several options are available:" +"These types are thread-safe, but they cannot be moved to another thread:" msgstr "" -#: src/async/runtimes.md:7 +#: src/concurrency/send-sync/examples.md:31 msgid "" -"[Tokio](https://tokio.rs/) - performant, with a well-developed ecosystem of " -"functionality like [Hyper](https://hyper.rs/) for HTTP or [Tonic](https://" -"github.com/hyperium/tonic) for gRPC." +"`MutexGuard`: Uses OS level primitives which must be deallocated on the " +"thread which created them." msgstr "" -#: src/async/runtimes.md:10 -msgid "" -"[async-std](https://async.rs/) - aims to be a \"std for async\", and " -"includes a basic runtime in `async::task`." +#: src/concurrency/send-sync/examples.md:34 +msgid "`!Send + !Sync`" msgstr "" -#: src/async/runtimes.md:12 -msgid "[smol](https://docs.rs/smol/latest/smol/) - simple and lightweight" +#: src/concurrency/send-sync/examples.md:36 +msgid "These types are not thread-safe and cannot be moved to other threads:" msgstr "" -#: src/async/runtimes.md:14 +#: src/concurrency/send-sync/examples.md:38 msgid "" -"Several larger applications have their own runtimes. For example, [Fuchsia]" -"(https://fuchsia.googlesource.com/fuchsia/+/refs/heads/main/src/lib/fuchsia-" -"async/src/lib.rs) already has one." +"`Rc`: each `Rc` has a reference to an `RcBox`, which contains a non-" +"atomic reference count." msgstr "" -#: src/async/runtimes.md:20 +#: src/concurrency/send-sync/examples.md:40 msgid "" -"Note that of the listed runtimes, only Tokio is supported in the Rust " -"playground. The playground also does not permit any I/O, so most interesting " -"async things can't run in the playground." +"`*const T`, `*mut T`: Rust assumes raw pointers may have special concurrency " +"considerations." msgstr "" -#: src/async/runtimes.md:24 +#: src/concurrency/shared_state.md:3 msgid "" -"Futures are \"inert\" in that they do not do anything (not even start an I/O " -"operation) unless there is an executor polling them. This differs from JS " -"Promises, for example, which will run to completion even if they are never " -"used." +"Rust uses the type system to enforce synchronization of shared data. This is " +"primarily done via two types:" msgstr "" -#: src/async/runtimes/tokio.md:4 -msgid "Tokio provides: " +#: src/concurrency/shared_state.md:6 +msgid "" +"[`Arc`](https://doc.rust-lang.org/std/sync/struct.Arc.html), atomic " +"reference counted `T`: handles sharing between threads and takes care to " +"deallocate `T` when the last reference is dropped," msgstr "" -#: src/async/runtimes/tokio.md:6 -msgid "A multi-threaded runtime for executing asynchronous code." +#: src/concurrency/shared_state.md:8 +msgid "" +"[`Mutex`](https://doc.rust-lang.org/std/sync/struct.Mutex.html): ensures " +"mutually exclusive access to the `T` value." msgstr "" -#: src/async/runtimes/tokio.md:7 -msgid "An asynchronous version of the standard library." +#: src/concurrency/shared_state/arc.md:1 +msgid "`Arc`" msgstr "" -#: src/async/runtimes/tokio.md:8 -msgid "A large ecosystem of libraries." +#: src/concurrency/shared_state/arc.md:3 +msgid "" +"[`Arc`](https://doc.rust-lang.org/std/sync/struct.Arc.html) allows shared " +"read-only access via `Arc::clone`:" msgstr "" -#: src/async/runtimes/tokio.md:10 +#: src/concurrency/shared_state/arc.md:5 msgid "" -"```rust,editable,compile_fail\n" -"use tokio::time;\n" +"```rust,editable\n" +"use std::thread;\n" +"use std::sync::Arc;\n" "\n" -"async fn count_to(count: i32) {\n" -" for i in 1..=count {\n" -" println!(\"Count in task: {i}!\");\n" -" time::sleep(time::Duration::from_millis(5)).await;\n" +"fn main() {\n" +" let v = Arc::new(vec![10, 20, 30]);\n" +" let mut handles = Vec::new();\n" +" for _ in 1..5 {\n" +" let v = Arc::clone(&v);\n" +" handles.push(thread::spawn(move || {\n" +" let thread_id = thread::current().id();\n" +" println!(\"{thread_id:?}: {v:?}\");\n" +" }));\n" " }\n" -"}\n" -"\n" -"#[tokio::main]\n" -"async fn main() {\n" -" tokio::spawn(count_to(10));\n" "\n" -" for i in 1..5 {\n" -" println!(\"Main task: {i}\");\n" -" time::sleep(time::Duration::from_millis(5)).await;\n" -" }\n" +" handles.into_iter().for_each(|h| h.join().unwrap());\n" +" println!(\"v: {v:?}\");\n" "}\n" "```" msgstr "" -#: src/async/runtimes/tokio.md:33 -msgid "With the `tokio::main` macro we can now make `main` async." -msgstr "" - -#: src/async/runtimes/tokio.md:35 -msgid "The `spawn` function creates a new, concurrent \"task\"." -msgstr "" - -#: src/async/runtimes/tokio.md:37 -msgid "Note: `spawn` takes a `Future`, you don't call `.await` on `count_to`." +#: src/concurrency/shared_state/arc.md:29 +msgid "" +"`Arc` stands for \"Atomic Reference Counted\", a thread safe version of `Rc` " +"that uses atomic operations." msgstr "" -#: src/async/runtimes/tokio.md:39 -msgid "**Further exploration:**" +#: src/concurrency/shared_state/arc.md:31 +msgid "" +"`Arc` implements `Clone` whether or not `T` does. It implements `Send` " +"and `Sync` if and only if `T` implements them both." msgstr "" -#: src/async/runtimes/tokio.md:41 +#: src/concurrency/shared_state/arc.md:33 msgid "" -"Why does `count_to` not (usually) get to 10? This is an example of async " -"cancellation. `tokio::spawn` returns a handle which can be awaited to wait " -"until it finishes." +"`Arc::clone()` has the cost of atomic operations that get executed, but " +"after that the use of the `T` is free." msgstr "" -#: src/async/runtimes/tokio.md:45 -msgid "Try `count_to(10).await` instead of spawning." +#: src/concurrency/shared_state/arc.md:35 +msgid "" +"Beware of reference cycles, `Arc` does not use a garbage collector to detect " +"them." msgstr "" -#: src/async/runtimes/tokio.md:47 -msgid "Try awaiting the task returned from `tokio::spawn`." +#: src/concurrency/shared_state/arc.md:36 +msgid "`std::sync::Weak` can help." msgstr "" -#: src/async/tasks.md:3 -msgid "" -"Runtimes have the concept of a \"task\", similar to a thread but much less " -"resource-intensive." +#: src/concurrency/shared_state/mutex.md:1 +msgid "`Mutex`" msgstr "" -#: src/async/tasks.md:6 +#: src/concurrency/shared_state/mutex.md:3 msgid "" -"A task has a single top-level future which the executor polls to make " -"progress. That future may have one or more nested futures that its `poll` " -"method polls, corresponding loosely to a call stack. Concurrency within a " -"task is possible by polling multiple child futures, such as racing a timer " -"and an I/O operation." +"[`Mutex`](https://doc.rust-lang.org/std/sync/struct.Mutex.html) ensures " +"mutual exclusion _and_ allows mutable access to `T` behind a read-only " +"interface:" msgstr "" -#: src/async/tasks.md:11 +#: src/concurrency/shared_state/mutex.md:6 msgid "" -"```rust,compile_fail\n" -"use tokio::io::{self, AsyncReadExt, AsyncWriteExt};\n" -"use tokio::net::TcpListener;\n" -"\n" -"#[tokio::main]\n" -"async fn main() -> io::Result<()> {\n" -" let listener = TcpListener::bind(\"127.0.0.1:6142\").await?;\n" -"\tprintln!(\"listening on port 6142\");\n" -"\n" -" loop {\n" -" let (mut socket, addr) = listener.accept().await?;\n" -"\n" -" println!(\"connection from {addr:?}\");\n" -"\n" -" tokio::spawn(async move {\n" -" if let Err(e) = socket.write_all(b\"Who are you?\\n\").await {\n" -" println!(\"socket error: {e:?}\");\n" -" return;\n" -" }\n" +"```rust,editable\n" +"use std::sync::Mutex;\n" "\n" -" let mut buf = vec![0; 1024];\n" -" let reply = match socket.read(&mut buf).await {\n" -" Ok(n) => {\n" -" let name = std::str::from_utf8(&buf[..n]).unwrap()." -"trim();\n" -" format!(\"Thanks for dialing in, {name}!\\n\")\n" -" }\n" -" Err(e) => {\n" -" println!(\"socket error: {e:?}\");\n" -" return;\n" -" }\n" -" };\n" +"fn main() {\n" +" let v = Mutex::new(vec![10, 20, 30]);\n" +" println!(\"v: {:?}\", v.lock().unwrap());\n" "\n" -" if let Err(e) = socket.write_all(reply.as_bytes()).await {\n" -" println!(\"socket error: {e:?}\");\n" -" }\n" -" });\n" +" {\n" +" let mut guard = v.lock().unwrap();\n" +" guard.push(40);\n" " }\n" +"\n" +" println!(\"v: {:?}\", v.lock().unwrap());\n" "}\n" "```" msgstr "" -#: src/async/tasks.md:53 src/async/control-flow/join.md:36 +#: src/concurrency/shared_state/mutex.md:22 msgid "" -"Copy this example into your prepared `src/main.rs` and run it from there." +"Notice how we have a [`impl Sync for Mutex`](https://doc.rust-" +"lang.org/std/sync/struct.Mutex.html#impl-Sync-for-Mutex%3CT%3E) blanket " +"implementation." msgstr "" -#: src/async/tasks.md:55 +#: src/concurrency/shared_state/mutex.md:31 msgid "" -"Ask students to visualize what the state of the example server would be with " -"a few connected clients. What tasks exist? What are their Futures?" +"`Mutex` in Rust looks like a collection with just one element - the " +"protected data." msgstr "" -#: src/async/tasks.md:58 +#: src/concurrency/shared_state/mutex.md:32 msgid "" -"This is the first time we've seen an `async` block. This is similar to a " -"closure, but does not take any arguments. Its return value is a Future, " -"similar to an `async fn`. " +"It is not possible to forget to acquire the mutex before accessing the " +"protected data." msgstr "" -#: src/async/tasks.md:62 +#: src/concurrency/shared_state/mutex.md:33 msgid "" -"Refactor the async block into a function, and improve the error handling " -"using `?`." +"You can get an `&mut T` from an `&Mutex` by taking the lock. The " +"`MutexGuard` ensures that the `&mut T` doesn't outlive the lock being held." msgstr "" -#: src/async/channels.md:3 +#: src/concurrency/shared_state/mutex.md:35 msgid "" -"Several crates have support for `async`/`await`. For instance `tokio` " -"channels:" +"`Mutex` implements both `Send` and `Sync` iff (if and only if) `T` " +"implements `Send`." msgstr "" -#: src/async/channels.md:5 +#: src/concurrency/shared_state/mutex.md:36 +msgid "A read-write lock counterpart - `RwLock`." +msgstr "" + +#: src/concurrency/shared_state/mutex.md:37 +msgid "Why does `lock()` return a `Result`? " +msgstr "" + +#: src/concurrency/shared_state/mutex.md:38 +msgid "" +"If the thread that held the `Mutex` panicked, the `Mutex` becomes " +"\"poisoned\" to signal that the data it protected might be in an " +"inconsistent state. Calling `lock()` on a poisoned mutex fails with a " +"[`PoisonError`](https://doc.rust-lang.org/std/sync/struct.PoisonError.html). " +"You can call `into_inner()` on the error to recover the data regardless." +msgstr "" + +#: src/concurrency/shared_state/example.md:3 +msgid "Let us see `Arc` and `Mutex` in action:" +msgstr "" + +#: src/concurrency/shared_state/example.md:5 msgid "" "```rust,editable,compile_fail\n" -"use tokio::sync::mpsc::{self, Receiver};\n" -"\n" -"async fn ping_handler(mut input: Receiver<()>) {\n" -" let mut count: usize = 0;\n" -"\n" -" while let Some(_) = input.recv().await {\n" -" count += 1;\n" -" println!(\"Received {count} pings so far.\");\n" -" }\n" -"\n" -" println!(\"ping_handler complete\");\n" -"}\n" +"use std::thread;\n" +"// use std::sync::{Arc, Mutex};\n" "\n" -"#[tokio::main]\n" -"async fn main() {\n" -" let (sender, receiver) = mpsc::channel(32);\n" -" let ping_handler_task = tokio::spawn(ping_handler(receiver));\n" -" for i in 0..10 {\n" -" sender.send(()).await.expect(\"Failed to send ping.\");\n" -" println!(\"Sent {} pings so far.\", i + 1);\n" -" }\n" +"fn main() {\n" +" let v = vec![10, 20, 30];\n" +" let handle = thread::spawn(|| {\n" +" v.push(10);\n" +" });\n" +" v.push(1000);\n" "\n" -" std::mem::drop(sender);\n" -" ping_handler_task.await.expect(\"Something went wrong in ping handler " -"task.\");\n" +" handle.join().unwrap();\n" +" println!(\"v: {v:?}\");\n" "}\n" "```" msgstr "" -#: src/async/channels.md:35 -msgid "Change the channel size to `3` and see how it affects the execution." +#: src/concurrency/shared_state/example.md:23 +msgid "Possible solution:" msgstr "" -#: src/async/channels.md:37 +#: src/concurrency/shared_state/example.md:25 msgid "" -"Overall, the interface is similar to the `sync` channels as seen in the " -"[morning class](concurrency/channels.md)." +"```rust,editable\n" +"use std::sync::{Arc, Mutex};\n" +"use std::thread;\n" +"\n" +"fn main() {\n" +" let v = Arc::new(Mutex::new(vec![10, 20, 30]));\n" +"\n" +" let v2 = Arc::clone(&v);\n" +" let handle = thread::spawn(move || {\n" +" let mut v2 = v2.lock().unwrap();\n" +" v2.push(10);\n" +" });\n" +"\n" +" {\n" +" let mut v = v.lock().unwrap();\n" +" v.push(1000);\n" +" }\n" +"\n" +" handle.join().unwrap();\n" +"\n" +" println!(\"v: {v:?}\");\n" +"}\n" +"```" msgstr "" -#: src/async/channels.md:40 -msgid "Try removing the `std::mem::drop` call. What happens? Why?" +#: src/concurrency/shared_state/example.md:49 +msgid "Notable parts:" msgstr "" -#: src/async/channels.md:42 +#: src/concurrency/shared_state/example.md:51 msgid "" -"The [Flume](https://docs.rs/flume/latest/flume/) crate has channels that " -"implement both `sync` and `async` `send` and `recv`. This can be convenient " -"for complex applications with both IO and heavy CPU processing tasks." +"`v` is wrapped in both `Arc` and `Mutex`, because their concerns are " +"orthogonal." msgstr "" -#: src/async/channels.md:46 +#: src/concurrency/shared_state/example.md:52 msgid "" -"What makes working with `async` channels preferable is the ability to " -"combine them with other `future`s to combine them and create complex control " -"flow." -msgstr "" - -#: src/async/control-flow.md:1 -msgid "Futures Control Flow" +"Wrapping a `Mutex` in an `Arc` is a common pattern to share mutable state " +"between threads." msgstr "" -#: src/async/control-flow.md:3 +#: src/concurrency/shared_state/example.md:53 msgid "" -"Futures can be combined together to produce concurrent compute flow graphs. " -"We have already seen tasks, that function as independent threads of " -"execution." -msgstr "" - -#: src/async/control-flow.md:6 -msgid "[Join](control-flow/join.md)" -msgstr "" - -#: src/async/control-flow.md:7 -msgid "[Select](control-flow/select.md)" +"`v: Arc<_>` needs to be cloned as `v2` before it can be moved into another " +"thread. Note `move` was added to the lambda signature." msgstr "" -#: src/async/control-flow/join.md:3 +#: src/concurrency/shared_state/example.md:54 msgid "" -"A join operation waits until all of a set of futures are ready, and returns " -"a collection of their results. This is similar to `Promise.all` in " -"JavaScript or `asyncio.gather` in Python." +"Blocks are introduced to narrow the scope of the `LockGuard` as much as " +"possible." msgstr "" -#: src/async/control-flow/join.md:7 -msgid "" -"```rust,editable,compile_fail\n" -"use anyhow::Result;\n" -"use futures::future;\n" -"use reqwest;\n" -"use std::collections::HashMap;\n" -"\n" -"async fn size_of_page(url: &str) -> Result {\n" -" let resp = reqwest::get(url).await?;\n" -" Ok(resp.text().await?.len())\n" -"}\n" -"\n" -"#[tokio::main]\n" -"async fn main() {\n" -" let urls: [&str; 4] = [\n" -" \"https://google.com\",\n" -" \"https://httpbin.org/ip\",\n" -" \"https://play.rust-lang.org/\",\n" -" \"BAD_URL\",\n" -" ];\n" -" let futures_iter = urls.into_iter().map(size_of_page);\n" -" let results = future::join_all(futures_iter).await;\n" -" let page_sizes_dict: HashMap<&str, Result> =\n" -" urls.into_iter().zip(results.into_iter()).collect();\n" -" println!(\"{:?}\", page_sizes_dict);\n" -"}\n" -"```" +#: src/exercises/concurrency/morning.md:3 +msgid "Let us practice our new concurrency skills with" msgstr "" -#: src/async/control-flow/join.md:38 -msgid "" -"For multiple futures of disjoint types, you can use `std::future::join!` but " -"you must know how many futures you will have at compile time. This is " -"currently in the `futures` crate, soon to be stabilised in `std::future`." +#: src/exercises/concurrency/morning.md:5 +msgid "Dining philosophers: a classic problem in concurrency." msgstr "" -#: src/async/control-flow/join.md:42 +#: src/exercises/concurrency/morning.md:7 msgid "" -"The risk of `join` is that one of the futures may never resolve, this would " -"cause your program to stall. " +"Multi-threaded link checker: a larger project where you'll use Cargo to " +"download dependencies and then check links in parallel." msgstr "" -#: src/async/control-flow/join.md:45 -msgid "" -"You can also combine `join_all` with `join!` for instance to join all " -"requests to an http service as well as a database query. Try adding a " -"`tokio::time::sleep` to the future, using `futures::join!`. This is not a " -"timeout (that requires `select!`, explained in the next chapter), but " -"demonstrates `join!`." +#: src/exercises/concurrency/dining-philosophers.md:3 +msgid "The dining philosophers problem is a classic problem in concurrency:" msgstr "" -#: src/async/control-flow/select.md:3 +#: src/exercises/concurrency/dining-philosophers.md:5 msgid "" -"A select operation waits until any of a set of futures is ready, and " -"responds to that future's result. In JavaScript, this is similar to `Promise." -"race`. In Python, it compares to `asyncio.wait(task_set, return_when=asyncio." -"FIRST_COMPLETED)`." +"Five philosophers dine together at the same table. Each philosopher has " +"their own place at the table. There is a fork between each plate. The dish " +"served is a kind of spaghetti which has to be eaten with two forks. Each " +"philosopher can only alternately think and eat. Moreover, a philosopher can " +"only eat their spaghetti when they have both a left and right fork. Thus two " +"forks will only be available when their two nearest neighbors are thinking, " +"not eating. After an individual philosopher finishes eating, they will put " +"down both forks." msgstr "" -#: src/async/control-flow/select.md:8 +#: src/exercises/concurrency/dining-philosophers.md:13 msgid "" -"This is usually a macro, similar to match, with each arm of the form " -"`pattern = future => statement`. When the future is ready, the statement is " -"executed with the variable bound to the future's result." +"You will need a local [Cargo installation](../../cargo/running-locally.md) " +"for this exercise. Copy the code below to a file called `src/main.rs`, fill " +"out the blanks, and test that `cargo run` does not deadlock:" msgstr "" -#: src/async/control-flow/select.md:12 +#: src/exercises/concurrency/dining-philosophers.md:19 msgid "" -"```rust,editable,compile_fail\n" -"use tokio::sync::mpsc::{self, Receiver};\n" -"use tokio::time::{sleep, Duration};\n" +"```rust,compile_fail\n" +"use std::sync::{mpsc, Arc, Mutex};\n" +"use std::thread;\n" +"use std::time::Duration;\n" "\n" -"#[derive(Debug, PartialEq)]\n" -"enum Animal {\n" -" Cat { name: String },\n" -" Dog { name: String },\n" +"struct Fork;\n" +"\n" +"struct Philosopher {\n" +" name: String,\n" +" // left_fork: ...\n" +" // right_fork: ...\n" +" // thoughts: ...\n" "}\n" "\n" -"async fn first_animal_to_finish_race(\n" -" mut cat_rcv: Receiver,\n" -" mut dog_rcv: Receiver,\n" -") -> Option {\n" -" tokio::select! {\n" -" cat_name = cat_rcv.recv() => Some(Animal::Cat { name: cat_name? }),\n" -" dog_name = dog_rcv.recv() => Some(Animal::Dog { name: dog_name? })\n" +"impl Philosopher {\n" +" fn think(&self) {\n" +" self.thoughts\n" +" .send(format!(\"Eureka! {} has a new idea!\", &self.name))\n" +" .unwrap();\n" +" }\n" +"\n" +" fn eat(&self) {\n" +" // Pick up forks...\n" +" println!(\"{} is eating...\", &self.name);\n" +" thread::sleep(Duration::from_millis(10));\n" " }\n" "}\n" "\n" -"#[tokio::main]\n" -"async fn main() {\n" -" let (cat_sender, cat_receiver) = mpsc::channel(32);\n" -" let (dog_sender, dog_receiver) = mpsc::channel(32);\n" -" tokio::spawn(async move {\n" -" sleep(Duration::from_millis(500)).await;\n" -" cat_sender\n" -" .send(String::from(\"Felix\"))\n" -" .await\n" -" .expect(\"Failed to send cat.\");\n" -" });\n" -" tokio::spawn(async move {\n" -" sleep(Duration::from_millis(50)).await;\n" -" dog_sender\n" -" .send(String::from(\"Rex\"))\n" -" .await\n" -" .expect(\"Failed to send dog.\");\n" -" });\n" +"static PHILOSOPHERS: &[&str] =\n" +" &[\"Socrates\", \"Plato\", \"Aristotle\", \"Thales\", \"Pythagoras\"];\n" "\n" -" let winner = first_animal_to_finish_race(cat_receiver, dog_receiver)\n" -" .await\n" -" .expect(\"Failed to receive winner\");\n" +"fn main() {\n" +" // Create forks\n" "\n" -" println!(\"Winner is {winner:?}\");\n" +" // Create philosophers\n" +"\n" +" // Make each of them think and eat 100 times\n" +"\n" +" // Output their thoughts\n" "}\n" "```" msgstr "" -#: src/async/control-flow/select.md:61 +#: src/exercises/concurrency/dining-philosophers.md:61 +msgid "You can use the following `Cargo.toml`:" +msgstr "" + +#: src/exercises/concurrency/dining-philosophers.md:65 msgid "" -"In this example, we have a race between a cat and a dog. " -"`first_animal_to_finish_race` listens to both channels and will pick " -"whichever arrives first. Since the dog takes 50ms, it wins against the cat " -"that take 500ms seconds." +"```toml\n" +"[package]\n" +"name = \"dining-philosophers\"\n" +"version = \"0.1.0\"\n" +"edition = \"2021\"\n" +"```" msgstr "" -#: src/async/control-flow/select.md:66 +#: src/exercises/concurrency/link-checker.md:3 msgid "" -"You can use `oneshot` channels in this example as the channels are supposed " -"to receive only one `send`." +"Let us use our new knowledge to create a multi-threaded link checker. It " +"should start at a webpage and check that links on the page are valid. It " +"should recursively check other pages on the same domain and keep doing this " +"until all pages have been validated." msgstr "" -#: src/async/control-flow/select.md:69 +#: src/exercises/concurrency/link-checker.md:8 msgid "" -"Try adding a deadline to the race, demonstrating selecting different sorts " -"of futures." +"For this, you will need an HTTP client such as [`reqwest`](https://docs.rs/" +"reqwest/). Create a new Cargo project and `reqwest` it as a dependency with:" msgstr "" -#: src/async/control-flow/select.md:72 +#: src/exercises/concurrency/link-checker.md:11 msgid "" -"Note that `select!` moves the values it is given. It is easiest to use when " -"every execution of `select!` creates new futures. An alternative is to pass " -"`&mut future` instead of the future itself, but this can lead to issues, " -"further discussed in the pinning slide." +"```shell\n" +"cargo new link-checker\n" +"cd link-checker\n" +"cargo add --features blocking,rustls-tls reqwest\n" +"```" msgstr "" -#: src/async/pitfalls.md:1 -msgid "Pitfalls of async/await" +#: src/exercises/concurrency/link-checker.md:17 +msgid "" +"If `cargo add` fails with `error: no such subcommand`, then please edit the " +"`Cargo.toml` file by hand. Add the dependencies listed below." msgstr "" -#: src/async/pitfalls.md:3 +#: src/exercises/concurrency/link-checker.md:20 msgid "" -"Async / await provides convenient and efficient abstraction for concurrent " -"asynchronous programming. However, the async/await model in Rust also comes " -"with its share of pitfalls and footguns. We illustrate some of them in this " -"chapter:" +"You will also need a way to find links. We can use [`scraper`](https://docs." +"rs/scraper/) for that:" msgstr "" -#: src/async/pitfalls.md:5 -msgid "[Blocking the Executor](pitfalls/blocking-executor.md)" +#: src/exercises/concurrency/link-checker.md:22 +msgid "" +"```shell\n" +"cargo add scraper\n" +"```" msgstr "" -#: src/async/pitfalls.md:6 -msgid "[Pin](pitfalls/pin.md)" +#: src/exercises/concurrency/link-checker.md:26 +msgid "" +"Finally, we'll need some way of handling errors. We use [`thiserror`]" +"(https://docs.rs/thiserror/) for that:" msgstr "" -#: src/async/pitfalls.md:7 -msgid "[Async Traits](pitfall/async-traits.md)" +#: src/exercises/concurrency/link-checker.md:29 +msgid "" +"```shell\n" +"cargo add thiserror\n" +"```" msgstr "" -#: src/async/pitfalls/blocking-executor.md:1 -msgid "Blocking the executor" +#: src/exercises/concurrency/link-checker.md:33 +msgid "" +"The `cargo add` calls will update the `Cargo.toml` file to look like this:" msgstr "" -#: src/async/pitfalls/blocking-executor.md:3 +#: src/exercises/concurrency/link-checker.md:37 msgid "" -"Most async runtimes only allow IO tasks to run concurrently. This means that " -"CPU blocking tasks will block the executor and prevent other tasks from " -"being executed. An easy workaround is to use async equivalent methods where " -"possible." +"```toml\n" +"[package]\n" +"name = \"link-checker\"\n" +"version = \"0.1.0\"\n" +"edition = \"2021\"\n" +"publish = false\n" +"\n" +"[dependencies]\n" +"reqwest = { version = \"0.11.12\", features = [\"blocking\", \"rustls-" +"tls\"] }\n" +"scraper = \"0.13.0\"\n" +"thiserror = \"1.0.37\"\n" +"```" msgstr "" -#: src/async/pitfalls/blocking-executor.md:7 +#: src/exercises/concurrency/link-checker.md:50 msgid "" -"```rust,editable,compile_fail\n" -"use futures::future::join_all;\n" -"use std::time::Instant;\n" +"You can now download the start page. Try with a small site such as `https://" +"www.google.org/`." +msgstr "" + +#: src/exercises/concurrency/link-checker.md:53 +msgid "Your `src/main.rs` file should look something like this:" +msgstr "" + +#: src/exercises/concurrency/link-checker.md:57 +msgid "" +"```rust,compile_fail\n" +"use reqwest::{blocking::Client, Url};\n" +"use scraper::{Html, Selector};\n" +"use thiserror::Error;\n" "\n" -"async fn sleep_ms(start: &Instant, id: u64, duration_ms: u64) {\n" -" std::thread::sleep(std::time::Duration::from_millis(duration_ms));\n" -" println!(\n" -" \"future {id} slept for {duration_ms}ms, finished after {}ms\",\n" -" start.elapsed().as_millis()\n" -" );\n" +"#[derive(Error, Debug)]\n" +"enum Error {\n" +" #[error(\"request error: {0}\")]\n" +" ReqwestError(#[from] reqwest::Error),\n" +" #[error(\"bad http response: {0}\")]\n" +" BadResponse(String),\n" "}\n" "\n" -"#[tokio::main(flavor = \"current_thread\")]\n" -"async fn main() {\n" -" let start = Instant::now();\n" -" let sleep_futures = (1..=10).map(|t| sleep_ms(&start, t, t * 10));\n" -" join_all(sleep_futures).await;\n" +"#[derive(Debug)]\n" +"struct CrawlCommand {\n" +" url: Url,\n" +" extract_links: bool,\n" +"}\n" +"\n" +"fn visit_page(client: &Client, command: &CrawlCommand) -> Result, " +"Error> {\n" +" println!(\"Checking {:#}\", command.url);\n" +" let response = client.get(command.url.clone()).send()?;\n" +" if !response.status().is_success() {\n" +" return Err(Error::BadResponse(response.status().to_string()));\n" +" }\n" +"\n" +" let mut link_urls = Vec::new();\n" +" if !command.extract_links {\n" +" return Ok(link_urls);\n" +" }\n" +"\n" +" let base_url = response.url().to_owned();\n" +" let body_text = response.text()?;\n" +" let document = Html::parse_document(&body_text);\n" +"\n" +" let selector = Selector::parse(\"a\").unwrap();\n" +" let href_values = document\n" +" .select(&selector)\n" +" .filter_map(|element| element.value().attr(\"href\"));\n" +" for href in href_values {\n" +" match base_url.join(href) {\n" +" Ok(link_url) => {\n" +" link_urls.push(link_url);\n" +" }\n" +" Err(err) => {\n" +" println!(\"On {base_url:#}: ignored unparsable {href:?}: " +"{err}\");\n" +" }\n" +" }\n" +" }\n" +" Ok(link_urls)\n" +"}\n" +"\n" +"fn main() {\n" +" let client = Client::new();\n" +" let start_url = Url::parse(\"https://www.google.org\").unwrap();\n" +" let crawl_command = CrawlCommand{ url: start_url, extract_links: " +"true };\n" +" match visit_page(&client, &crawl_command) {\n" +" Ok(links) => println!(\"Links: {links:#?}\"),\n" +" Err(err) => println!(\"Could not extract links: {err:#}\"),\n" +" }\n" "}\n" "```" msgstr "" -#: src/async/pitfalls/blocking-executor.md:29 +#: src/exercises/concurrency/link-checker.md:120 +msgid "Run the code in `src/main.rs` with" +msgstr "" + +#: src/exercises/concurrency/link-checker.md:122 msgid "" -"Run the code and see that the sleeps happen consecutively rather than " -"concurrently." +"```shell\n" +"cargo run\n" +"```" msgstr "" -#: src/async/pitfalls/blocking-executor.md:32 +#: src/exercises/concurrency/link-checker.md:128 msgid "" -"The `\"current_thread\"` flavor puts all tasks on a single thread. This " -"makes the effect more obvious, but the bug is still present in the multi-" -"threaded flavor." +"Use threads to check the links in parallel: send the URLs to be checked to a " +"channel and let a few threads check the URLs in parallel." msgstr "" -#: src/async/pitfalls/blocking-executor.md:36 +#: src/exercises/concurrency/link-checker.md:130 msgid "" -"Switch the `std::thread::sleep` to `tokio::time::sleep` and await its result." +"Extend this to recursively extract links from all pages on the `www.google." +"org` domain. Put an upper limit of 100 pages or so so that you don't end up " +"being blocked by the site." msgstr "" -#: src/async/pitfalls/blocking-executor.md:38 +#: src/async.md:1 +msgid "Async Rust" +msgstr "" + +#: src/async.md:3 msgid "" -"Another fix would be to `tokio::task::spawn_blocking` which spawns an actual " -"thread and transforms its handle into a future without blocking the executor." +"\"Async\" is a concurrency model where multiple tasks are executed " +"concurrently by executing each task until it would block, then switching to " +"another task that is ready to make progress. The model allows running a " +"larger number of tasks on a limited number of threads. This is because the " +"per-task overhead is typically very low and operating systems provide " +"primitives for efficiently identifying I/O that is able to proceed." msgstr "" -#: src/async/pitfalls/blocking-executor.md:41 +#: src/async.md:10 msgid "" -"You should not think of tasks as OS threads. They do not map 1 to 1 and most " -"executors will allow many tasks to run on a single OS thread. This is " -"particularly problematic when interacting with other libraries via FFI, " -"where that library might depend on thread-local storage or map to specific " -"OS threads (e.g., CUDA). Prefer `tokio::task::spawn_blocking` in such " -"situations." +"Rust's asynchronous operation is based on \"futures\", which represent work " +"that may be completed in the future. Futures are \"polled\" until they " +"signal that they are complete." msgstr "" -#: src/async/pitfalls/blocking-executor.md:47 +#: src/async.md:14 msgid "" -"Use sync mutexes with care. Holding a mutex over an `.await` may cause " -"another task to block, and that task may be running on the same thread." +"Futures are polled by an async runtime, and several different runtimes are " +"available." msgstr "" -#: src/async/pitfalls/pin.md:3 +#: src/async.md:17 +msgid "Comparisons" +msgstr "" + +#: src/async.md:19 msgid "" -"When you await a future, all local variables (that would ordinarily be " -"stored on a stack frame) are instead stored in the Future for the current " -"async block. If your future has pointers to data on the stack, those " -"pointers might get invalidated. This is unsafe." +"Python has a similar model in its `asyncio`. However, its `Future` type is " +"callback-based, and not polled. Async Python programs require a \"loop\", " +"similar to a runtime in Rust." msgstr "" -#: src/async/pitfalls/pin.md:8 +#: src/async.md:23 msgid "" -"Therefore, you must guarantee that the addresses your future points to don't " -"change. That is why we need to `pin` futures. Using the same future " -"repeatedly in a `select!` often leads to issues with pinned values." +"JavaScript's `Promise` is similar, but again callback-based. The language " +"runtime implements the event loop, so many of the details of Promise " +"resolution are hidden." msgstr "" -#: src/async/pitfalls/pin.md:12 +#: src/async/async-await.md:1 +msgid "`async`/`await`" +msgstr "" + +#: src/async/async-await.md:3 +msgid "" +"At a high level, async Rust code looks very much like \"normal\" sequential " +"code:" +msgstr "" + +#: src/async/async-await.md:5 msgid "" "```rust,editable,compile_fail\n" -"use tokio::sync::{mpsc, oneshot};\n" -"use tokio::task::spawn;\n" -"use tokio::time::{sleep, Duration};\n" -"\n" -"// A work item. In this case, just sleep for the given time and respond\n" -"// with a message on the `respond_on` channel.\n" -"#[derive(Debug)]\n" -"struct Work {\n" -" input: u32,\n" -" respond_on: oneshot::Sender,\n" -"}\n" +"use futures::executor::block_on;\n" "\n" -"// A worker which listens for work on a queue and performs it.\n" -"async fn worker(mut work_queue: mpsc::Receiver) {\n" -" let mut iterations = 0;\n" -" loop {\n" -" tokio::select! {\n" -" Some(work) = work_queue.recv() => {\n" -" sleep(Duration::from_millis(10)).await; // Pretend to work.\n" -" work.respond_on\n" -" .send(work.input * 1000)\n" -" .expect(\"failed to send response\");\n" -" iterations += 1;\n" -" }\n" -" // TODO: report number of iterations every 100ms\n" -" }\n" +"async fn count_to(count: i32) {\n" +" for i in 1..=count {\n" +" println!(\"Count is: {i}!\");\n" " }\n" "}\n" "\n" -"// A requester which requests work and waits for it to complete.\n" -"async fn do_work(work_queue: &mpsc::Sender, input: u32) -> u32 {\n" -" let (tx, rx) = oneshot::channel();\n" -" work_queue\n" -" .send(Work {\n" -" input,\n" -" respond_on: tx,\n" -" })\n" -" .await\n" -" .expect(\"failed to send on work queue\");\n" -" rx.await.expect(\"failed waiting for response\")\n" +"async fn async_main(count: i32) {\n" +" count_to(count).await;\n" "}\n" "\n" -"#[tokio::main]\n" -"async fn main() {\n" -" let (tx, rx) = mpsc::channel(10);\n" -" spawn(worker(rx));\n" -" for i in 0..100 {\n" -" let resp = do_work(&tx, i).await;\n" -" println!(\"work result for iteration {i}: {resp}\");\n" -" }\n" +"fn main() {\n" +" block_on(async_main(10));\n" "}\n" "```" msgstr "" -#: src/async/pitfalls/pin.md:68 +#: src/async/async-await.md:27 msgid "" -"You may recognize this as an example of the actor pattern. Actors typically " -"call `select!` in a loop." +"Note that this is a simplified example to show the syntax. There is no long " +"running operation or any real concurrency in it!" msgstr "" -#: src/async/pitfalls/pin.md:71 -msgid "" -"This serves as a summation of a few of the previous lessons, so take your " -"time with it." +#: src/async/async-await.md:30 +msgid "What is the return type of an async call?" msgstr "" -#: src/async/pitfalls/pin.md:74 +#: src/async/async-await.md:31 +msgid "Use `let future: () = async_main(10);` in `main` to see the type." +msgstr "" + +#: src/async/async-await.md:33 msgid "" -"Naively add a `_ = sleep(Duration::from_millis(100)) => { println!(..) }` to " -"the `select!`. This will never execute. Why?" +"The \"async\" keyword is syntactic sugar. The compiler replaces the return " +"type with a future. " msgstr "" -#: src/async/pitfalls/pin.md:77 +#: src/async/async-await.md:36 msgid "" -"Instead, add a `timeout_fut` containing that future outside of the `loop`:" +"You cannot make `main` async, without additional instructions to the " +"compiler on how to use the returned future." msgstr "" -#: src/async/pitfalls/pin.md:79 +#: src/async/async-await.md:39 msgid "" -"```rust,compile_fail\n" -"let mut timeout_fut = sleep(Duration::from_millis(100));\n" -"loop {\n" -" select! {\n" -" ..,\n" -" _ = timeout_fut => { println!(..); },\n" -" }\n" -"}\n" -"```" +"You need an executor to run async code. `block_on` blocks the current thread " +"until the provided future has run to completion. " msgstr "" -#: src/async/pitfalls/pin.md:88 +#: src/async/async-await.md:42 msgid "" -"This still doesn't work. Follow the compiler errors, adding `&mut` to the " -"`timeout_fut` in the `select!` to work around the move, then using `Box::" -"pin`:" +"`.await` asynchronously waits for the completion of another operation. " +"Unlike `block_on`, `.await` doesn't block the current thread." msgstr "" -#: src/async/pitfalls/pin.md:92 +#: src/async/async-await.md:45 msgid "" -"```rust,compile_fail\n" -"let mut timeout_fut = Box::pin(sleep(Duration::from_millis(100)));\n" -"loop {\n" -" select! {\n" -" ..,\n" -" _ = &mut timeout_fut => { println!(..); },\n" -" }\n" +"`.await` can only be used inside an `async` function (or block; these are " +"introduced later). " +msgstr "" + +#: src/async/futures.md:3 +msgid "" +"[`Future`](https://doc.rust-lang.org/std/future/trait.Future.html) is a " +"trait, implemented by objects that represent an operation that may not be " +"complete yet. A future can be polled, and `poll` returns a [`Poll`](https://" +"doc.rust-lang.org/std/task/enum.Poll.html)." +msgstr "" + +#: src/async/futures.md:8 +msgid "" +"```rust\n" +"use std::pin::Pin;\n" +"use std::task::Context;\n" +"\n" +"pub trait Future {\n" +" type Output;\n" +" fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll;\n" +"}\n" +"\n" +"pub enum Poll {\n" +" Ready(T),\n" +" Pending,\n" "}\n" "```" msgstr "" -#: src/async/pitfalls/pin.md:102 +#: src/async/futures.md:23 msgid "" -"This compiles, but once the timeout expires it is `Poll::Ready` on every " -"iteration (a fused future would help with this). Update to reset " -"`timeout_fut` every time it expires." +"An async function returns an `impl Future`. It's also possible (but " +"uncommon) to implement `Future` for your own types. For example, the " +"`JoinHandle` returned from `tokio::spawn` implements `Future` to allow " +"joining to it." msgstr "" -#: src/async/pitfalls/pin.md:106 +#: src/async/futures.md:27 msgid "" -"Box allocates on the heap. In some cases, `std::pin::pin!` (only recently " -"stabilized, with older code often using `tokio::pin!`) is also an option, " -"but that is difficult to use for a future that is reassigned." +"The `.await` keyword, applied to a Future, causes the current async function " +"to pause until that Future is ready, and then evaluates to its output." msgstr "" -#: src/async/pitfalls/pin.md:110 +#: src/async/futures.md:32 msgid "" -"Another alternative is to not use `pin` at all but spawn another task that " -"will send to a `oneshot` channel every 100ms." +"The `Future` and `Poll` types are implemented exactly as shown; click the " +"links to show the implementations in the docs." msgstr "" -#: src/async/pitfalls/async-traits.md:3 +#: src/async/futures.md:35 msgid "" -"Async methods in traits are not yet supported in the stable channel ([An " -"experimental feature exists in nightly and should be stabilized in the mid " -"term.](https://blog.rust-lang.org/inside-rust/2022/11/17/async-fn-in-trait-" -"nightly.html))" +"We will not get to `Pin` and `Context`, as we will focus on writing async " +"code, rather than building new async primitives. Briefly:" msgstr "" -#: src/async/pitfalls/async-traits.md:5 +#: src/async/futures.md:38 msgid "" -"The crate [async_trait](https://docs.rs/async-trait/latest/async_trait/) " -"provides a workaround through a macro:" +"`Context` allows a Future to schedule itself to be polled again when an " +"event occurs." msgstr "" -#: src/async/pitfalls/async-traits.md:7 +#: src/async/futures.md:41 msgid "" -"```rust,editable,compile_fail\n" -"use async_trait::async_trait;\n" -"use std::time::Instant;\n" -"use tokio::time::{sleep, Duration};\n" -"\n" -"#[async_trait]\n" -"trait Sleeper {\n" -" async fn sleep(&self);\n" -"}\n" -"\n" -"struct FixedSleeper {\n" -" sleep_ms: u64,\n" -"}\n" -"\n" -"#[async_trait]\n" -"impl Sleeper for FixedSleeper {\n" -" async fn sleep(&self) {\n" -" sleep(Duration::from_millis(self.sleep_ms)).await;\n" -" }\n" -"}\n" -"\n" -"async fn run_all_sleepers_multiple_times(sleepers: Vec>, " -"n_times: usize) {\n" -" for _ in 0..n_times {\n" -" println!(\"running all sleepers..\");\n" -" for sleeper in &sleepers {\n" -" let start = Instant::now();\n" -" sleeper.sleep().await;\n" -" println!(\"slept for {}ms\", start.elapsed().as_millis());\n" -" }\n" -" }\n" -"}\n" -"\n" -"#[tokio::main]\n" -"async fn main() {\n" -" let sleepers: Vec> = vec![\n" -" Box::new(FixedSleeper { sleep_ms: 50 }),\n" -" Box::new(FixedSleeper { sleep_ms: 100 }),\n" -" ];\n" -" run_all_sleepers_multiple_times(sleepers, 5).await;\n" -"}\n" -"```" +"`Pin` ensures that the Future isn't moved in memory, so that pointers into " +"that future remain valid. This is required to allow references to remain " +"valid after an `.await`." msgstr "" -#: src/async/pitfalls/async-traits.md:51 +#: src/async/runtimes.md:3 msgid "" -"`async_trait` is easy to use, but note that it's using heap allocations to " -"achieve this. This heap allocation has performance overhead." +"A _runtime_ provides support for performing operations asynchronously (a " +"_reactor_) and is responsible for executing futures (an _executor_). Rust " +"does not have a \"built-in\" runtime, but several options are available:" msgstr "" -#: src/async/pitfalls/async-traits.md:54 +#: src/async/runtimes.md:7 msgid "" -"The challenges in language support for `async trait` are deep Rust and " -"probably not worth describing in-depth. Niko Matsakis did a good job of " -"explaining them in [this post](https://smallcultfollowing.com/babysteps/" -"blog/2019/10/26/async-fn-in-traits-are-hard/) if you are interested in " -"digging deeper." +"[Tokio](https://tokio.rs/): performant, with a well-developed ecosystem of " +"functionality like [Hyper](https://hyper.rs/) for HTTP or [Tonic](https://" +"github.com/hyperium/tonic) for gRPC." msgstr "" -#: src/async/pitfalls/async-traits.md:60 +#: src/async/runtimes.md:10 msgid "" -"Try creating a new sleeper struct that will sleep for a random amount of " -"time and adding it to the Vec." +"[async-std](https://async.rs/): aims to be a \"std for async\", and includes " +"a basic runtime in `async::task`." msgstr "" -#: src/exercises/concurrency/afternoon.md:3 +#: src/async/runtimes.md:12 +msgid "[smol](https://docs.rs/smol/latest/smol/): simple and lightweight" +msgstr "" + +#: src/async/runtimes.md:14 msgid "" -"To practice your Async Rust skills, we have again two exercises for you:" +"Several larger applications have their own runtimes. For example, [Fuchsia]" +"(https://fuchsia.googlesource.com/fuchsia/+/refs/heads/main/src/lib/fuchsia-" +"async/src/lib.rs) already has one." msgstr "" -#: src/exercises/concurrency/afternoon.md:5 +#: src/async/runtimes.md:20 msgid "" -"Dining philosophers: we already saw this problem in the morning. This time " -"you are going to implement it with Async Rust." +"Note that of the listed runtimes, only Tokio is supported in the Rust " +"playground. The playground also does not permit any I/O, so most interesting " +"async things can't run in the playground." msgstr "" -#: src/exercises/concurrency/afternoon.md:8 +#: src/async/runtimes.md:24 msgid "" -"A Broadcast Chat Application: this is a larger project that allows you " -"experiment with more advanced Async Rust features." +"Futures are \"inert\" in that they do not do anything (not even start an I/O " +"operation) unless there is an executor polling them. This differs from JS " +"Promises, for example, which will run to completion even if they are never " +"used." msgstr "" -#: src/exercises/concurrency/dining-philosophers-async.md:1 -#: src/exercises/concurrency/solutions-afternoon.md:3 -msgid "Dining Philosophers - Async" +#: src/async/runtimes/tokio.md:4 +msgid "Tokio provides: " msgstr "" -#: src/exercises/concurrency/dining-philosophers-async.md:3 -msgid "" -"See [dining philosophers](dining-philosophers.md) for a description of the " -"problem." +#: src/async/runtimes/tokio.md:6 +msgid "A multi-threaded runtime for executing asynchronous code." msgstr "" -#: src/exercises/concurrency/dining-philosophers-async.md:6 -msgid "" -"As before, you will need a local [Cargo installation](../../cargo/running-" -"locally.md) for this exercise. Copy the code below to a file called `src/" -"main.rs`, fill out the blanks, and test that `cargo run` does not deadlock:" +#: src/async/runtimes/tokio.md:7 +msgid "An asynchronous version of the standard library." msgstr "" -#: src/exercises/concurrency/dining-philosophers-async.md:13 +#: src/async/runtimes/tokio.md:8 +msgid "A large ecosystem of libraries." +msgstr "" + +#: src/async/runtimes/tokio.md:10 msgid "" -"```rust,compile_fail\n" -"use std::sync::Arc;\n" +"```rust,editable,compile_fail\n" "use tokio::time;\n" -"use tokio::sync::mpsc::{self, Sender};\n" -"use tokio::sync::Mutex;\n" -"\n" -"struct Fork;\n" -"\n" -"struct Philosopher {\n" -" name: String,\n" -" // left_fork: ...\n" -" // right_fork: ...\n" -" // thoughts: ...\n" -"}\n" -"\n" -"impl Philosopher {\n" -" async fn think(&self) {\n" -" self.thoughts\n" -" .send(format!(\"Eureka! {} has a new idea!\", &self.name))." -"await\n" -" .unwrap();\n" -" }\n" "\n" -" async fn eat(&self) {\n" -" // Pick up forks...\n" -" println!(\"{} is eating...\", &self.name);\n" +"async fn count_to(count: i32) {\n" +" for i in 1..=count {\n" +" println!(\"Count in task: {i}!\");\n" " time::sleep(time::Duration::from_millis(5)).await;\n" " }\n" "}\n" "\n" -"static PHILOSOPHERS: &[&str] =\n" -" &[\"Socrates\", \"Plato\", \"Aristotle\", \"Thales\", \"Pythagoras\"];\n" -"\n" "#[tokio::main]\n" "async fn main() {\n" -" // Create forks\n" -"\n" -" // Create philosophers\n" -"\n" -" // Make them think and eat\n" +" tokio::spawn(count_to(10));\n" "\n" -" // Output their thoughts\n" +" for i in 1..5 {\n" +" println!(\"Main task: {i}\");\n" +" time::sleep(time::Duration::from_millis(5)).await;\n" +" }\n" "}\n" "```" msgstr "" -#: src/exercises/concurrency/dining-philosophers-async.md:57 -msgid "" -"Since this time you are using Async Rust, you'll need a `tokio` dependency. " -"You can use the following `Cargo.toml`:" +#: src/async/runtimes/tokio.md:33 +msgid "With the `tokio::main` macro we can now make `main` async." msgstr "" -#: src/exercises/concurrency/dining-philosophers-async.md:62 -msgid "" -"```toml\n" -"[package]\n" -"name = \"dining-philosophers-async-dine\"\n" -"version = \"0.1.0\"\n" -"edition = \"2021\"\n" -"\n" -"[dependencies]\n" -"tokio = {version = \"1.26.0\", features = [\"sync\", \"time\", \"macros\", " -"\"rt-multi-thread\"]}\n" -"```" -msgstr "" - -#: src/exercises/concurrency/dining-philosophers-async.md:72 -msgid "" -"Also note that this time you have to use the `Mutex` and the `mpsc` module " -"from the `tokio` crate." +#: src/async/runtimes/tokio.md:35 +msgid "The `spawn` function creates a new, concurrent \"task\"." msgstr "" -#: src/exercises/concurrency/dining-philosophers-async.md:77 -msgid "Can you make your implementation single-threaded? " +#: src/async/runtimes/tokio.md:37 +msgid "Note: `spawn` takes a `Future`, you don't call `.await` on `count_to`." msgstr "" -#: src/exercises/concurrency/chat-app.md:3 -msgid "" -"In this exercise, we want to use our new knowledge to implement a broadcast " -"chat application. We have a chat server that the clients connect to and " -"publish their messages. The client reads user messages from the standard " -"input, and sends them to the server. The chat server broadcasts each message " -"that it receives to all the clients." +#: src/async/runtimes/tokio.md:39 +msgid "**Further exploration:**" msgstr "" -#: src/exercises/concurrency/chat-app.md:9 +#: src/async/runtimes/tokio.md:41 msgid "" -"For this, we use [a broadcast channel](https://docs.rs/tokio/latest/tokio/" -"sync/broadcast/fn.channel.html) on the server, and [`tokio_websockets`]" -"(https://docs.rs/tokio-websockets/0.3.2/tokio_websockets/) for the " -"communication between the client and the server." -msgstr "" - -#: src/exercises/concurrency/chat-app.md:13 -msgid "Create a new Cargo project and add the following dependencies:" +"Why does `count_to` not (usually) get to 10? This is an example of async " +"cancellation. `tokio::spawn` returns a handle which can be awaited to wait " +"until it finishes." msgstr "" -#: src/exercises/concurrency/chat-app.md:15 -msgid "`Cargo.toml`:" +#: src/async/runtimes/tokio.md:45 +msgid "Try `count_to(10).await` instead of spawning." msgstr "" -#: src/exercises/concurrency/chat-app.md:19 -msgid "" -"```toml\n" -"[package]\n" -"name = \"chat-async\"\n" -"version = \"0.1.0\"\n" -"edition = \"2021\"\n" -"\n" -"[dependencies]\n" -"futures-util = \"0.3.28\"\n" -"http = \"0.2.9\"\n" -"tokio = { version = \"1.28.1\", features = [\"full\"] }\n" -"tokio-websockets = \"0.3.2\"\n" -"```" +#: src/async/runtimes/tokio.md:47 +msgid "Try awaiting the task returned from `tokio::spawn`." msgstr "" -#: src/exercises/concurrency/chat-app.md:32 -msgid "The required APIs" +#: src/async/tasks.md:3 +msgid "Rust has a task system, which is a form of lightweight threading." msgstr "" -#: src/exercises/concurrency/chat-app.md:33 +#: src/async/tasks.md:5 msgid "" -"You are going to need the following functions from `tokio` and " -"[`tokio_websockets`](https://docs.rs/tokio-websockets/0.3.2/" -"tokio_websockets/). Spend a few minutes to familiarize yourself with the " -"API. " +"A task has a single top-level future which the executor polls to make " +"progress. That future may have one or more nested futures that its `poll` " +"method polls, corresponding loosely to a call stack. Concurrency within a " +"task is possible by polling multiple child futures, such as racing a timer " +"and an I/O operation." msgstr "" -#: src/exercises/concurrency/chat-app.md:37 +#: src/async/tasks.md:10 msgid "" -"[WebsocketStream::next()](https://docs.rs/tokio-websockets/0.3.2/" -"tokio_websockets/proto/struct.WebsocketStream.html#method.next): for " -"asynchronously reading messages from a Websocket Stream." +"```rust,compile_fail\n" +"use tokio::io::{self, AsyncReadExt, AsyncWriteExt};\n" +"use tokio::net::TcpListener;\n" +"\n" +"#[tokio::main]\n" +"async fn main() -> io::Result<()> {\n" +" let listener = TcpListener::bind(\"127.0.0.1:6142\").await?;\n" +"\tprintln!(\"listening on port 6142\");\n" +"\n" +" loop {\n" +" let (mut socket, addr) = listener.accept().await?;\n" +"\n" +" println!(\"connection from {addr:?}\");\n" +"\n" +" tokio::spawn(async move {\n" +" if let Err(e) = socket.write_all(b\"Who are you?\\n\").await {\n" +" println!(\"socket error: {e:?}\");\n" +" return;\n" +" }\n" +"\n" +" let mut buf = vec![0; 1024];\n" +" let reply = match socket.read(&mut buf).await {\n" +" Ok(n) => {\n" +" let name = std::str::from_utf8(&buf[..n]).unwrap()." +"trim();\n" +" format!(\"Thanks for dialing in, {name}!\\n\")\n" +" }\n" +" Err(e) => {\n" +" println!(\"socket error: {e:?}\");\n" +" return;\n" +" }\n" +" };\n" +"\n" +" if let Err(e) = socket.write_all(reply.as_bytes()).await {\n" +" println!(\"socket error: {e:?}\");\n" +" }\n" +" });\n" +" }\n" +"}\n" +"```" msgstr "" -#: src/exercises/concurrency/chat-app.md:39 +#: src/async/tasks.md:52 src/async/control-flow/join.md:36 msgid "" -"[SinkExt::send()](https://docs.rs/futures-util/0.3.28/futures_util/sink/" -"trait.SinkExt.html#method.send) implemented by `WebsocketStream`: for " -"asynchronously sending messages on a Websocket Stream." +"Copy this example into your prepared `src/main.rs` and run it from there." msgstr "" -#: src/exercises/concurrency/chat-app.md:41 +#: src/async/tasks.md:54 msgid "" -"[BufReader::read_line()](https://docs.rs/tokio/latest/tokio/io/struct.Lines." -"html#method.next_line): for asynchronously reading user messages from the " -"standard input." +"Ask students to visualize what the state of the example server would be with " +"a few connected clients. What tasks exist? What are their Futures?" msgstr "" -#: src/exercises/concurrency/chat-app.md:43 +#: src/async/tasks.md:57 msgid "" -"[Sender::subscribe()](https://docs.rs/tokio/latest/tokio/sync/broadcast/" -"struct.Sender.html#method.subscribe): for subscribing to a broadcast channel." -msgstr "" - -#: src/exercises/concurrency/chat-app.md:46 -msgid "Two binaries" +"This is the first time we've seen an `async` block. This is similar to a " +"closure, but does not take any arguments. Its return value is a Future, " +"similar to an `async fn`. " msgstr "" -#: src/exercises/concurrency/chat-app.md:48 +#: src/async/tasks.md:61 msgid "" -"Normally in a Cargo project, you can have only one binary, and one `src/main." -"rs` file. In this project, we need two binaries. One for the client, and one " -"for the server. You could potentially make them two separate Cargo projects, " -"but we are going to put them in a single Cargo project with two binaries. " -"For this to work, the client and the server code should go under `src/bin` " -"(see the [documentation](https://doc.rust-lang.org/cargo/reference/cargo-" -"targets.html#binaries)). " +"Refactor the async block into a function, and improve the error handling " +"using `?`." msgstr "" -#: src/exercises/concurrency/chat-app.md:55 +#: src/async/channels.md:3 msgid "" -"Copy the following server and client code into `src/bin/server.rs` and `src/" -"bin/client.rs`, respectively. Your task is to complete these files as " -"described below. " +"Several crates have support for asynchronous channels. For instance `tokio`:" msgstr "" -#: src/exercises/concurrency/chat-app.md:59 -#: src/exercises/concurrency/solutions-afternoon.md:117 -msgid "`src/bin/server.rs`:" -msgstr "" - -#: src/exercises/concurrency/chat-app.md:63 +#: src/async/channels.md:5 msgid "" -"```rust,compile_fail\n" -"use futures_util::sink::SinkExt;\n" -"use std::error::Error;\n" -"use std::net::SocketAddr;\n" -"use tokio::net::{TcpListener, TcpStream};\n" -"use tokio::sync::broadcast::{channel, Sender};\n" -"use tokio_websockets::{Message, ServerBuilder, WebsocketStream};\n" +"```rust,editable,compile_fail\n" +"use tokio::sync::mpsc::{self, Receiver};\n" "\n" -"async fn handle_connection(\n" -" addr: SocketAddr,\n" -" mut ws_stream: WebsocketStream,\n" -" bcast_tx: Sender,\n" -") -> Result<(), Box> {\n" +"async fn ping_handler(mut input: Receiver<()>) {\n" +" let mut count: usize = 0;\n" "\n" -" // TODO: For a hint, see the description of the task below.\n" +" while let Some(_) = input.recv().await {\n" +" count += 1;\n" +" println!(\"Received {count} pings so far.\");\n" +" }\n" "\n" +" println!(\"ping_handler complete\");\n" "}\n" "\n" "#[tokio::main]\n" -"async fn main() -> Result<(), Box> {\n" -" let (bcast_tx, _) = channel(16);\n" -"\n" -" let listener = TcpListener::bind(\"127.0.0.1:2000\").await?;\n" -" println!(\"listening on port 2000\");\n" -"\n" -" loop {\n" -" let (socket, addr) = listener.accept().await?;\n" -" println!(\"New connection from {addr:?}\");\n" -" let bcast_tx = bcast_tx.clone();\n" -" tokio::spawn(async move {\n" -" // Wrap the raw TCP stream into a websocket.\n" -" let ws_stream = ServerBuilder::new().accept(socket).await?;\n" -"\n" -" handle_connection(addr, ws_stream, bcast_tx).await\n" -" });\n" +"async fn main() {\n" +" let (sender, receiver) = mpsc::channel(32);\n" +" let ping_handler_task = tokio::spawn(ping_handler(receiver));\n" +" for i in 0..10 {\n" +" sender.send(()).await.expect(\"Failed to send ping.\");\n" +" println!(\"Sent {} pings so far.\", i + 1);\n" " }\n" +"\n" +" drop(sender);\n" +" ping_handler_task.await.expect(\"Something went wrong in ping handler " +"task.\");\n" "}\n" "```" msgstr "" -#: src/exercises/concurrency/chat-app.md:102 -#: src/exercises/concurrency/solutions-afternoon.md:202 -msgid "`src/bin/client.rs`:" +#: src/async/channels.md:35 +msgid "Change the channel size to `3` and see how it affects the execution." msgstr "" -#: src/exercises/concurrency/chat-app.md:106 +#: src/async/channels.md:37 msgid "" -"```rust,compile_fail\n" -"use futures_util::SinkExt;\n" -"use http::Uri;\n" -"use tokio::io::{AsyncBufReadExt, BufReader};\n" -"use tokio_websockets::{ClientBuilder, Message};\n" -"\n" -"#[tokio::main]\n" -"async fn main() -> Result<(), tokio_websockets::Error> {\n" -" let mut ws_stream = ClientBuilder::from_uri(Uri::" -"from_static(\"ws://127.0.0.1:2000\"))\n" -" .connect()\n" -" .await?;\n" -"\n" -" let stdin = tokio::io::stdin();\n" -" let mut stdin = BufReader::new(stdin);\n" -"\n" -"\n" -" // TODO: For a hint, see the description of the task below.\n" -"\n" -"}\n" -"```" +"Overall, the interface is similar to the `sync` channels as seen in the " +"[morning class](concurrency/channels.md)." msgstr "" -#: src/exercises/concurrency/chat-app.md:127 -msgid "Running the binaries" +#: src/async/channels.md:40 +msgid "Try removing the `std::mem::drop` call. What happens? Why?" msgstr "" -#: src/exercises/concurrency/chat-app.md:128 -msgid "Run the server with:" +#: src/async/channels.md:42 +msgid "" +"The [Flume](https://docs.rs/flume/latest/flume/) crate has channels that " +"implement both `sync` and `async` `send` and `recv`. This can be convenient " +"for complex applications with both IO and heavy CPU processing tasks." msgstr "" -#: src/exercises/concurrency/chat-app.md:130 +#: src/async/channels.md:46 msgid "" -"```shell\n" -"$ cargo run --bin server\n" -"```" +"What makes working with `async` channels preferable is the ability to " +"combine them with other `future`s to combine them and create complex control " +"flow." msgstr "" -#: src/exercises/concurrency/chat-app.md:134 -msgid "and the client with:" +#: src/async/control-flow.md:1 +msgid "Futures Control Flow" msgstr "" -#: src/exercises/concurrency/chat-app.md:136 +#: src/async/control-flow.md:3 msgid "" -"```shell\n" -"$ cargo run --bin client\n" -"```" +"Futures can be combined together to produce concurrent compute flow graphs. " +"We have already seen tasks, that function as independent threads of " +"execution." msgstr "" -#: src/exercises/concurrency/chat-app.md:142 -msgid "Implement the `handle_connection` function in `src/bin/server.rs`." +#: src/async/control-flow.md:6 +msgid "[Join](control-flow/join.md)" msgstr "" -#: src/exercises/concurrency/chat-app.md:143 -msgid "" -"Hint: Use `tokio::select!` for concurrently performing two tasks in a " -"continuous loop. One task receives messages from the client and broadcasts " -"them. The other sends messages received by the server to the client." +#: src/async/control-flow.md:7 +msgid "[Select](control-flow/select.md)" msgstr "" -#: src/exercises/concurrency/chat-app.md:146 -msgid "Complete the main function in `src/bin/client.rs`." +#: src/async/control-flow/join.md:3 +msgid "" +"A join operation waits until all of a set of futures are ready, and returns " +"a collection of their results. This is similar to `Promise.all` in " +"JavaScript or `asyncio.gather` in Python." msgstr "" -#: src/exercises/concurrency/chat-app.md:147 +#: src/async/control-flow/join.md:7 msgid "" -"Hint: As before, use `tokio::select!` in a continuous loop for concurrently " -"performing two tasks: (1) reading user messages from standard input and " -"sending them to the server, and (2) receiving messages from the server, and " -"displaying them for the user." +"```rust,editable,compile_fail\n" +"use anyhow::Result;\n" +"use futures::future;\n" +"use reqwest;\n" +"use std::collections::HashMap;\n" +"\n" +"async fn size_of_page(url: &str) -> Result {\n" +" let resp = reqwest::get(url).await?;\n" +" Ok(resp.text().await?.len())\n" +"}\n" +"\n" +"#[tokio::main]\n" +"async fn main() {\n" +" let urls: [&str; 4] = [\n" +" \"https://google.com\",\n" +" \"https://httpbin.org/ip\",\n" +" \"https://play.rust-lang.org/\",\n" +" \"BAD_URL\",\n" +" ];\n" +" let futures_iter = urls.into_iter().map(size_of_page);\n" +" let results = future::join_all(futures_iter).await;\n" +" let page_sizes_dict: HashMap<&str, Result> =\n" +" urls.into_iter().zip(results.into_iter()).collect();\n" +" println!(\"{:?}\", page_sizes_dict);\n" +"}\n" +"```" msgstr "" -#: src/exercises/concurrency/chat-app.md:151 +#: src/async/control-flow/join.md:38 msgid "" -"Optional: Once you are done, change the code to broadcast messages to all " -"clients, but the sender of the message." +"For multiple futures of disjoint types, you can use `std::future::join!` but " +"you must know how many futures you will have at compile time. This is " +"currently in the `futures` crate, soon to be stabilised in `std::future`." msgstr "" -#: src/thanks.md:3 +#: src/async/control-flow/join.md:42 msgid "" -"_Thank you for taking Comprehensive Rust 🦀!_ We hope you enjoyed it and " -"that it was useful." +"The risk of `join` is that one of the futures may never resolve, this would " +"cause your program to stall. " msgstr "" -#: src/thanks.md:6 +#: src/async/control-flow/join.md:45 msgid "" -"We've had a lot of fun putting the course together. The course is not " -"perfect, so if you spotted any mistakes or have ideas for improvements, " -"please get in [contact with us on GitHub](https://github.com/google/" -"comprehensive-rust/discussions). We would love to hear from you." +"You can also combine `join_all` with `join!` for instance to join all " +"requests to an http service as well as a database query. Try adding a " +"`tokio::time::sleep` to the future, using `futures::join!`. This is not a " +"timeout (that requires `select!`, explained in the next chapter), but " +"demonstrates `join!`." msgstr "" -#: src/other-resources.md:1 -msgid "Other Rust Resources" +#: src/async/control-flow/select.md:3 +msgid "" +"A select operation waits until any of a set of futures is ready, and " +"responds to that future's result. In JavaScript, this is similar to `Promise." +"race`. In Python, it compares to `asyncio.wait(task_set, return_when=asyncio." +"FIRST_COMPLETED)`." msgstr "" -#: src/other-resources.md:3 +#: src/async/control-flow/select.md:8 msgid "" -"The Rust community has created a wealth of high-quality and free resources " -"online." +"Similar to a match statement, the body of `select!` has a number of arms, " +"each of the form `pattern = future => statement`. When the `future` is " +"ready, the `statement` is executed with the variables in `pattern` bound to " +"the `future`'s result." msgstr "" -#: src/other-resources.md:6 -msgid "Official Documentation" +#: src/async/control-flow/select.md:13 +msgid "" +"```rust,editable,compile_fail\n" +"use tokio::sync::mpsc::{self, Receiver};\n" +"use tokio::time::{sleep, Duration};\n" +"\n" +"#[derive(Debug, PartialEq)]\n" +"enum Animal {\n" +" Cat { name: String },\n" +" Dog { name: String },\n" +"}\n" +"\n" +"async fn first_animal_to_finish_race(\n" +" mut cat_rcv: Receiver,\n" +" mut dog_rcv: Receiver,\n" +") -> Option {\n" +" tokio::select! {\n" +" cat_name = cat_rcv.recv() => Some(Animal::Cat { name: cat_name? }),\n" +" dog_name = dog_rcv.recv() => Some(Animal::Dog { name: dog_name? })\n" +" }\n" +"}\n" +"\n" +"#[tokio::main]\n" +"async fn main() {\n" +" let (cat_sender, cat_receiver) = mpsc::channel(32);\n" +" let (dog_sender, dog_receiver) = mpsc::channel(32);\n" +" tokio::spawn(async move {\n" +" sleep(Duration::from_millis(500)).await;\n" +" cat_sender\n" +" .send(String::from(\"Felix\"))\n" +" .await\n" +" .expect(\"Failed to send cat.\");\n" +" });\n" +" tokio::spawn(async move {\n" +" sleep(Duration::from_millis(50)).await;\n" +" dog_sender\n" +" .send(String::from(\"Rex\"))\n" +" .await\n" +" .expect(\"Failed to send dog.\");\n" +" });\n" +"\n" +" let winner = first_animal_to_finish_race(cat_receiver, dog_receiver)\n" +" .await\n" +" .expect(\"Failed to receive winner\");\n" +"\n" +" println!(\"Winner is {winner:?}\");\n" +"}\n" +"```" msgstr "" -#: src/other-resources.md:8 -msgid "The Rust project hosts many resources. These cover Rust in general:" +#: src/async/control-flow/select.md:62 +msgid "" +"In this example, we have a race between a cat and a dog. " +"`first_animal_to_finish_race` listens to both channels and will pick " +"whichever arrives first. Since the dog takes 50ms, it wins against the cat " +"that take 500ms seconds." msgstr "" -#: src/other-resources.md:10 +#: src/async/control-flow/select.md:67 msgid "" -"[The Rust Programming Language](https://doc.rust-lang.org/book/): the " -"canonical free book about Rust. Covers the language in detail and includes a " -"few projects for people to build." +"You can use `oneshot` channels in this example as the channels are supposed " +"to receive only one `send`." msgstr "" -#: src/other-resources.md:13 +#: src/async/control-flow/select.md:70 msgid "" -"[Rust By Example](https://doc.rust-lang.org/rust-by-example/): covers the " -"Rust syntax via a series of examples which showcase different constructs. " -"Sometimes includes small exercises where you are asked to expand on the code " -"in the examples." +"Try adding a deadline to the race, demonstrating selecting different sorts " +"of futures." msgstr "" -#: src/other-resources.md:17 +#: src/async/control-flow/select.md:73 msgid "" -"[Rust Standard Library](https://doc.rust-lang.org/std/): full documentation " -"of the standard library for Rust." +"Note that `select!` drops unmatched branches, which cancels their futures. " +"It is easiest to use when every execution of `select!` creates new futures." msgstr "" -#: src/other-resources.md:19 +#: src/async/control-flow/select.md:76 msgid "" -"[The Rust Reference](https://doc.rust-lang.org/reference/): an incomplete " -"book which describes the Rust grammar and memory model." +"An alternative is to pass `&mut future` instead of the future itself, but " +"this can lead to issues, further discussed in the pinning slide." msgstr "" -#: src/other-resources.md:22 -msgid "More specialized guides hosted on the official Rust site:" +#: src/async/pitfalls.md:1 +msgid "Pitfalls of async/await" msgstr "" -#: src/other-resources.md:24 +#: src/async/pitfalls.md:3 msgid "" -"[The Rustonomicon](https://doc.rust-lang.org/nomicon/): covers unsafe Rust, " -"including working with raw pointers and interfacing with other languages " -"(FFI)." +"Async / await provides convenient and efficient abstraction for concurrent " +"asynchronous programming. However, the async/await model in Rust also comes " +"with its share of pitfalls and footguns. We illustrate some of them in this " +"chapter:" msgstr "" -#: src/other-resources.md:27 -msgid "" -"[Asynchronous Programming in Rust](https://rust-lang.github.io/async-book/): " -"covers the new asynchronous programming model which was introduced after the " -"Rust Book was written." +#: src/async/pitfalls.md:5 +msgid "[Blocking the Executor](pitfalls/blocking-executor.md)" msgstr "" -#: src/other-resources.md:30 -msgid "" -"[The Embedded Rust Book](https://doc.rust-lang.org/stable/embedded-book/): " -"an introduction to using Rust on embedded devices without an operating " -"system." +#: src/async/pitfalls.md:6 +msgid "[Pin](pitfalls/pin.md)" msgstr "" -#: src/other-resources.md:33 -msgid "Unofficial Learning Material" +#: src/async/pitfalls.md:7 +msgid "[Async Traits](pitfalls/async-traits.md)" msgstr "" -#: src/other-resources.md:35 -msgid "A small selection of other guides and tutorial for Rust:" +#: src/async/pitfalls.md:8 +msgid "[Cancellation](pitfalls/cancellation.md)" msgstr "" -#: src/other-resources.md:37 -msgid "" -"[Learn Rust the Dangerous Way](http://cliffle.com/p/dangerust/): covers Rust " -"from the perspective of low-level C programmers." +#: src/async/pitfalls/blocking-executor.md:1 +msgid "Blocking the executor" msgstr "" -#: src/other-resources.md:39 +#: src/async/pitfalls/blocking-executor.md:3 msgid "" -"[Rust for Embedded C Programmers](https://docs.opentitan.org/doc/ug/" -"rust_for_c/): covers Rust from the perspective of developers who write " -"firmware in C." +"Most async runtimes only allow IO tasks to run concurrently. This means that " +"CPU blocking tasks will block the executor and prevent other tasks from " +"being executed. An easy workaround is to use async equivalent methods where " +"possible." msgstr "" -#: src/other-resources.md:42 +#: src/async/pitfalls/blocking-executor.md:7 msgid "" -"[Rust for professionals](https://overexact.com/rust-for-professionals/): " -"covers the syntax of Rust using side-by-side comparisons with other " -"languages such as C, C++, Java, JavaScript, and Python." +"```rust,editable,compile_fail\n" +"use futures::future::join_all;\n" +"use std::time::Instant;\n" +"\n" +"async fn sleep_ms(start: &Instant, id: u64, duration_ms: u64) {\n" +" std::thread::sleep(std::time::Duration::from_millis(duration_ms));\n" +" println!(\n" +" \"future {id} slept for {duration_ms}ms, finished after {}ms\",\n" +" start.elapsed().as_millis()\n" +" );\n" +"}\n" +"\n" +"#[tokio::main(flavor = \"current_thread\")]\n" +"async fn main() {\n" +" let start = Instant::now();\n" +" let sleep_futures = (1..=10).map(|t| sleep_ms(&start, t, t * 10));\n" +" join_all(sleep_futures).await;\n" +"}\n" +"```" msgstr "" -#: src/other-resources.md:45 +#: src/async/pitfalls/blocking-executor.md:29 msgid "" -"[Rust on Exercism](https://exercism.org/tracks/rust): 100+ exercises to help " -"you learn Rust." +"Run the code and see that the sleeps happen consecutively rather than " +"concurrently." msgstr "" -#: src/other-resources.md:47 +#: src/async/pitfalls/blocking-executor.md:32 msgid "" -"[Ferrous Teaching Material](https://ferrous-systems.github.io/teaching-" -"material/index.html): a series of small presentations covering both basic " -"and advanced part of the Rust language. Other topics such as WebAssembly, " -"and async/await are also covered." +"The `\"current_thread\"` flavor puts all tasks on a single thread. This " +"makes the effect more obvious, but the bug is still present in the multi-" +"threaded flavor." msgstr "" -#: src/other-resources.md:52 +#: src/async/pitfalls/blocking-executor.md:36 msgid "" -"[Beginner's Series to Rust](https://docs.microsoft.com/en-us/shows/beginners-" -"series-to-rust/) and [Take your first steps with Rust](https://docs." -"microsoft.com/en-us/learn/paths/rust-first-steps/): two Rust guides aimed at " -"new developers. The first is a set of 35 videos and the second is a set of " -"11 modules which covers Rust syntax and basic constructs." +"Switch the `std::thread::sleep` to `tokio::time::sleep` and await its result." msgstr "" -#: src/other-resources.md:58 +#: src/async/pitfalls/blocking-executor.md:38 msgid "" -"[Learn Rust With Entirely Too Many Linked Lists](https://rust-unofficial." -"github.io/too-many-lists/): in-depth exploration of Rust's memory management " -"rules, through implementing a few different types of list structures." +"Another fix would be to `tokio::task::spawn_blocking` which spawns an actual " +"thread and transforms its handle into a future without blocking the executor." msgstr "" -#: src/other-resources.md:63 +#: src/async/pitfalls/blocking-executor.md:41 msgid "" -"Please see the [Little Book of Rust Books](https://lborb.github.io/book/) " -"for even more Rust books." +"You should not think of tasks as OS threads. They do not map 1 to 1 and most " +"executors will allow many tasks to run on a single OS thread. This is " +"particularly problematic when interacting with other libraries via FFI, " +"where that library might depend on thread-local storage or map to specific " +"OS threads (e.g., CUDA). Prefer `tokio::task::spawn_blocking` in such " +"situations." msgstr "" -#: src/credits.md:3 +#: src/async/pitfalls/blocking-executor.md:47 msgid "" -"The material here builds on top of the many great sources of Rust " -"documentation. See the page on [other resources](other-resources.md) for a " -"full list of useful resources." +"Use sync mutexes with care. Holding a mutex over an `.await` may cause " +"another task to block, and that task may be running on the same thread." msgstr "" -#: src/credits.md:7 +#: src/async/pitfalls/pin.md:3 msgid "" -"The material of Comprehensive Rust is licensed under the terms of the Apache " -"2.0 license, please see [`LICENSE`](../LICENSE) for details." +"When you await a future, all local variables (that would ordinarily be " +"stored on a stack frame) are instead stored in the Future for the current " +"async block. If your future has pointers to data on the stack, those " +"pointers might get invalidated. This is unsafe." msgstr "" -#: src/credits.md:10 -msgid "Rust by Example" +#: src/async/pitfalls/pin.md:8 +msgid "" +"Therefore, you must guarantee that the addresses your future points to don't " +"change. That is why we need to `pin` futures. Using the same future " +"repeatedly in a `select!` often leads to issues with pinned values." msgstr "" -#: src/credits.md:12 +#: src/async/pitfalls/pin.md:12 msgid "" -"Some examples and exercises have been copied and adapted from [Rust by " -"Example](https://doc.rust-lang.org/rust-by-example/). Please see the " -"`third_party/rust-by-example/` directory for details, including the license " -"terms." +"```rust,editable,compile_fail\n" +"use tokio::sync::{mpsc, oneshot};\n" +"use tokio::task::spawn;\n" +"use tokio::time::{sleep, Duration};\n" +"\n" +"// A work item. In this case, just sleep for the given time and respond\n" +"// with a message on the `respond_on` channel.\n" +"#[derive(Debug)]\n" +"struct Work {\n" +" input: u32,\n" +" respond_on: oneshot::Sender,\n" +"}\n" +"\n" +"// A worker which listens for work on a queue and performs it.\n" +"async fn worker(mut work_queue: mpsc::Receiver) {\n" +" let mut iterations = 0;\n" +" loop {\n" +" tokio::select! {\n" +" Some(work) = work_queue.recv() => {\n" +" sleep(Duration::from_millis(10)).await; // Pretend to work.\n" +" work.respond_on\n" +" .send(work.input * 1000)\n" +" .expect(\"failed to send response\");\n" +" iterations += 1;\n" +" }\n" +" // TODO: report number of iterations every 100ms\n" +" }\n" +" }\n" +"}\n" +"\n" +"// A requester which requests work and waits for it to complete.\n" +"async fn do_work(work_queue: &mpsc::Sender, input: u32) -> u32 {\n" +" let (tx, rx) = oneshot::channel();\n" +" work_queue\n" +" .send(Work {\n" +" input,\n" +" respond_on: tx,\n" +" })\n" +" .await\n" +" .expect(\"failed to send on work queue\");\n" +" rx.await.expect(\"failed waiting for response\")\n" +"}\n" +"\n" +"#[tokio::main]\n" +"async fn main() {\n" +" let (tx, rx) = mpsc::channel(10);\n" +" spawn(worker(rx));\n" +" for i in 0..100 {\n" +" let resp = do_work(&tx, i).await;\n" +" println!(\"work result for iteration {i}: {resp}\");\n" +" }\n" +"}\n" +"```" msgstr "" -#: src/credits.md:17 -msgid "Rust on Exercism" +#: src/async/pitfalls/pin.md:68 +msgid "" +"You may recognize this as an example of the actor pattern. Actors typically " +"call `select!` in a loop." msgstr "" -#: src/credits.md:19 +#: src/async/pitfalls/pin.md:71 msgid "" -"Some exercises have been copied and adapted from [Rust on Exercism](https://" -"exercism.org/tracks/rust). Please see the `third_party/rust-on-exercism/` " -"directory for details, including the license terms." +"This serves as a summation of a few of the previous lessons, so take your " +"time with it." msgstr "" -#: src/credits.md:24 -msgid "CXX" +#: src/async/pitfalls/pin.md:74 +msgid "" +"Naively add a `_ = sleep(Duration::from_millis(100)) => { println!(..) }` to " +"the `select!`. This will never execute. Why?" msgstr "" -#: src/credits.md:26 +#: src/async/pitfalls/pin.md:77 msgid "" -"The [Interoperability with C++](android/interoperability/cpp.md) section " -"uses an image from [CXX](https://cxx.rs/). Please see the `third_party/cxx/` " -"directory for details, including the license terms." +"Instead, add a `timeout_fut` containing that future outside of the `loop`:" msgstr "" -#: src/exercises/solutions.md:3 -msgid "You will find solutions to the exercises on the following pages." +#: src/async/pitfalls/pin.md:79 +msgid "" +"```rust,compile_fail\n" +"let mut timeout_fut = sleep(Duration::from_millis(100));\n" +"loop {\n" +" select! {\n" +" ..,\n" +" _ = timeout_fut => { println!(..); },\n" +" }\n" +"}\n" +"```" msgstr "" -#: src/exercises/solutions.md:5 +#: src/async/pitfalls/pin.md:88 msgid "" -"Feel free to ask questions about the solutions [on GitHub](https://github." -"com/google/comprehensive-rust/discussions). Let us know if you have a " -"different or better solution than what is presented here." +"This still doesn't work. Follow the compiler errors, adding `&mut` to the " +"`timeout_fut` in the `select!` to work around the move, then using `Box::" +"pin`:" msgstr "" -#: src/exercises/solutions.md:10 +#: src/async/pitfalls/pin.md:92 msgid "" -"**Note:** Please ignore the `// ANCHOR: label` and `// ANCHOR_END: label` " -"comments you see in the solutions. They are there to make it possible to re-" -"use parts of the solutions as the exercises." +"```rust,compile_fail\n" +"let mut timeout_fut = Box::pin(sleep(Duration::from_millis(100)));\n" +"loop {\n" +" select! {\n" +" ..,\n" +" _ = &mut timeout_fut => { println!(..); },\n" +" }\n" +"}\n" +"```" msgstr "" -#: src/exercises/day-1/solutions-morning.md:1 -msgid "Day 1 Morning Exercises" +#: src/async/pitfalls/pin.md:102 +msgid "" +"This compiles, but once the timeout expires it is `Poll::Ready` on every " +"iteration (a fused future would help with this). Update to reset " +"`timeout_fut` every time it expires." msgstr "" -#: src/exercises/day-1/solutions-morning.md:5 -msgid "([back to exercise](for-loops.md))" +#: src/async/pitfalls/pin.md:106 +msgid "" +"Box allocates on the heap. In some cases, `std::pin::pin!` (only recently " +"stabilized, with older code often using `tokio::pin!`) is also an option, " +"but that is difficult to use for a future that is reassigned." msgstr "" -#: src/exercises/day-1/solutions-morning.md:7 +#: src/async/pitfalls/pin.md:110 msgid "" -"```rust\n" -"// Copyright 2022 Google LLC\n" -"//\n" -"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"// you may not use this file except in compliance with the License.\n" -"// You may obtain a copy of the License at\n" -"//\n" -"// http://www.apache.org/licenses/LICENSE-2.0\n" -"//\n" -"// Unless required by applicable law or agreed to in writing, software\n" -"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"// See the License for the specific language governing permissions and\n" -"// limitations under the License.\n" +"Another alternative is to not use `pin` at all but spawn another task that " +"will send to a `oneshot` channel every 100ms." +msgstr "" + +#: src/async/pitfalls/async-traits.md:3 +msgid "" +"Async methods in traits are not yet supported in the stable channel ([An " +"experimental feature exists in nightly and should be stabilized in the mid " +"term.](https://blog.rust-lang.org/inside-rust/2022/11/17/async-fn-in-trait-" +"nightly.html))" +msgstr "" + +#: src/async/pitfalls/async-traits.md:5 +msgid "" +"The crate [async_trait](https://docs.rs/async-trait/latest/async_trait/) " +"provides a workaround through a macro:" +msgstr "" + +#: src/async/pitfalls/async-traits.md:7 +msgid "" +"```rust,editable,compile_fail\n" +"use async_trait::async_trait;\n" +"use std::time::Instant;\n" +"use tokio::time::{sleep, Duration};\n" "\n" -"// ANCHOR: transpose\n" -"fn transpose(matrix: [[i32; 3]; 3]) -> [[i32; 3]; 3] {\n" -" // ANCHOR_END: transpose\n" -" let mut result = [[0; 3]; 3];\n" -" for i in 0..3 {\n" -" for j in 0..3 {\n" -" result[j][i] = matrix[i][j];\n" -" }\n" +"#[async_trait]\n" +"trait Sleeper {\n" +" async fn sleep(&self);\n" +"}\n" +"\n" +"struct FixedSleeper {\n" +" sleep_ms: u64,\n" +"}\n" +"\n" +"#[async_trait]\n" +"impl Sleeper for FixedSleeper {\n" +" async fn sleep(&self) {\n" +" sleep(Duration::from_millis(self.sleep_ms)).await;\n" " }\n" -" return result;\n" "}\n" "\n" -"// ANCHOR: pretty_print\n" -"fn pretty_print(matrix: &[[i32; 3]; 3]) {\n" -" // ANCHOR_END: pretty_print\n" -" for row in matrix {\n" -" println!(\"{row:?}\");\n" +"async fn run_all_sleepers_multiple_times(sleepers: Vec>, " +"n_times: usize) {\n" +" for _ in 0..n_times {\n" +" println!(\"running all sleepers..\");\n" +" for sleeper in &sleepers {\n" +" let start = Instant::now();\n" +" sleeper.sleep().await;\n" +" println!(\"slept for {}ms\", start.elapsed().as_millis());\n" +" }\n" " }\n" "}\n" "\n" -"// ANCHOR: tests\n" -"#[test]\n" -"fn test_transpose() {\n" -" let matrix = [\n" -" [101, 102, 103], //\n" -" [201, 202, 203],\n" -" [301, 302, 303],\n" +"#[tokio::main]\n" +"async fn main() {\n" +" let sleepers: Vec> = vec![\n" +" Box::new(FixedSleeper { sleep_ms: 50 }),\n" +" Box::new(FixedSleeper { sleep_ms: 100 }),\n" " ];\n" -" let transposed = transpose(matrix);\n" -" assert_eq!(\n" -" transposed,\n" -" [\n" -" [101, 201, 301], //\n" -" [102, 202, 302],\n" -" [103, 203, 303],\n" -" ]\n" -" );\n" +" run_all_sleepers_multiple_times(sleepers, 5).await;\n" "}\n" -"// ANCHOR_END: tests\n" +"```" +msgstr "" + +#: src/async/pitfalls/async-traits.md:51 +msgid "" +"`async_trait` is easy to use, but note that it's using heap allocations to " +"achieve this. This heap allocation has performance overhead." +msgstr "" + +#: src/async/pitfalls/async-traits.md:54 +msgid "" +"The challenges in language support for `async trait` are deep Rust and " +"probably not worth describing in-depth. Niko Matsakis did a good job of " +"explaining them in [this post](https://smallcultfollowing.com/babysteps/" +"blog/2019/10/26/async-fn-in-traits-are-hard/) if you are interested in " +"digging deeper." +msgstr "" + +#: src/async/pitfalls/async-traits.md:60 +msgid "" +"Try creating a new sleeper struct that will sleep for a random amount of " +"time and adding it to the Vec." +msgstr "" + +#: src/async/pitfalls/cancellation.md:3 +msgid "" +"Dropping a future implies it can never be polled again. This is called " +"_cancellation_ and it can occur at any `await` point. Care is needed to " +"ensure the system works correctly even when futures are cancelled. For " +"example, it shouldn't deadlock or lose data." +msgstr "" + +#: src/async/pitfalls/cancellation.md:8 +msgid "" +"```rust,editable,compile_fail\n" +"use std::io::{self, ErrorKind};\n" +"use std::time::Duration;\n" +"use tokio::io::{AsyncReadExt, AsyncWriteExt, DuplexStream};\n" "\n" -"// ANCHOR: main\n" -"fn main() {\n" -" let matrix = [\n" -" [101, 102, 103], // <-- the comment makes rustfmt add a newline\n" -" [201, 202, 203],\n" -" [301, 302, 303],\n" -" ];\n" +"struct LinesReader {\n" +" stream: DuplexStream,\n" +"}\n" "\n" -" println!(\"matrix:\");\n" -" pretty_print(&matrix);\n" +"impl LinesReader {\n" +" fn new(stream: DuplexStream) -> Self {\n" +" Self { stream }\n" +" }\n" "\n" -" let transposed = transpose(matrix);\n" -" println!(\"transposed:\");\n" -" pretty_print(&transposed);\n" +" async fn next(&mut self) -> io::Result> {\n" +" let mut bytes = Vec::new();\n" +" let mut buf = [0];\n" +" while self.stream.read(&mut buf[..]).await? != 0 {\n" +" bytes.push(buf[0]);\n" +" if buf[0] == b'\\n' {\n" +" break;\n" +" }\n" +" }\n" +" if bytes.is_empty() {\n" +" return Ok(None)\n" +" }\n" +" let s = String::from_utf8(bytes)\n" +" .map_err(|_| io::Error::new(ErrorKind::InvalidData, \"not " +"UTF-8\"))?;\n" +" Ok(Some(s))\n" +" }\n" +"}\n" +"\n" +"async fn slow_copy(source: String, mut dest: DuplexStream) -> std::io::" +"Result<()> {\n" +" for b in source.bytes() {\n" +" dest.write_u8(b).await?;\n" +" tokio::time::sleep(Duration::from_millis(10)).await\n" +" }\n" +" Ok(())\n" +"}\n" +"\n" +"#[tokio::main]\n" +"async fn main() -> std::io::Result<()> {\n" +" let (client, server) = tokio::io::duplex(5);\n" +" let handle = tokio::spawn(slow_copy(\"hi\\nthere\\n\".to_owned(), " +"client));\n" +"\n" +" let mut lines = LinesReader::new(server);\n" +" let mut interval = tokio::time::interval(Duration::from_millis(60));\n" +" loop {\n" +" tokio::select! {\n" +" _ = interval.tick() => println!(\"tick!\"),\n" +" line = lines.next() => if let Some(l) = line? {\n" +" print!(\"{}\", l)\n" +" } else {\n" +" break\n" +" },\n" +" }\n" +" }\n" +" handle.await.unwrap()?;\n" +" Ok(())\n" "}\n" "```" msgstr "" -#: src/exercises/day-1/solutions-morning.md:78 -msgid "Bonus question" +#: src/async/pitfalls/cancellation.md:72 +msgid "" +"The compiler doesn't help with cancellation-safety. You need to read API " +"documentation and consider what state your `async fn` holds." msgstr "" -#: src/exercises/day-1/solutions-morning.md:80 +#: src/async/pitfalls/cancellation.md:75 msgid "" -"It requires more advanced concepts. It might seem that we could use a slice-" -"of-slices (`&[&[i32]]`) as the input type to transpose and thus make our " -"function handle any size of matrix. However, this quickly breaks down: the " -"return type cannot be `&[&[i32]]` since it needs to own the data you return." +"Unlike `panic` and `?`, cancellation is part of normal control flow (vs " +"error-handling)." msgstr "" -#: src/exercises/day-1/solutions-morning.md:82 +#: src/async/pitfalls/cancellation.md:78 +msgid "The example loses parts of the string." +msgstr "" + +#: src/async/pitfalls/cancellation.md:80 msgid "" -"You can attempt to use something like `Vec>`, but this doesn't work " -"out-of-the-box either: it's hard to convert from `Vec>` to " -"`&[&[i32]]` so now you cannot easily use `pretty_print` either." +"Whenever the `tick()` branch finishes first, `next()` and its `buf` are " +"dropped." msgstr "" -#: src/exercises/day-1/solutions-morning.md:84 +#: src/async/pitfalls/cancellation.md:82 msgid "" -"Once we get to traits and generics, we'll be able to use the [`std::convert::" -"AsRef`](https://doc.rust-lang.org/std/convert/trait.AsRef.html) trait to " -"abstract over anything that can be referenced as a slice." +"`LinesReader` can be made cancellation-safe by makeing `buf` part of the " +"struct:" msgstr "" -#: src/exercises/day-1/solutions-morning.md:86 +#: src/async/pitfalls/cancellation.md:83 msgid "" -"```rust\n" -"use std::convert::AsRef;\n" -"use std::fmt::Debug;\n" -"\n" -"fn pretty_print(matrix: Matrix)\n" -"where\n" -" T: Debug,\n" -" // A line references a slice of items\n" -" Line: AsRef<[T]>,\n" -" // A matrix references a slice of lines\n" -" Matrix: AsRef<[Line]>\n" -"{\n" -" for row in matrix.as_ref() {\n" -" println!(\"{:?}\", row.as_ref());\n" -" }\n" +"```rust,compile_fail\n" +"struct LinesReader {\n" +" stream: DuplexStream,\n" +" bytes: Vec,\n" +" buf: [u8; 1],\n" "}\n" "\n" -"fn main() {\n" -" // &[&[i32]]\n" -" pretty_print(&[&[1, 2, 3], &[4, 5, 6], &[7, 8, 9]]);\n" -" // [[&str; 2]; 2]\n" -" pretty_print([[\"a\", \"b\"], [\"c\", \"d\"]]);\n" -" // Vec>\n" -" pretty_print(vec![vec![1, 2], vec![3, 4]]);\n" +"impl LinesReader {\n" +" fn new(stream: DuplexStream) -> Self {\n" +" Self { stream, bytes: Vec::new(), buf: [0] }\n" +" }\n" +" async fn next(&mut self) -> io::Result> {\n" +" // prefix buf and bytes with self.\n" +" // ...\n" +" let raw = std::mem::take(&mut self.bytes);\n" +" let s = String::from_utf8(raw)\n" +" // ...\n" +" }\n" "}\n" "```" msgstr "" -#: src/exercises/day-1/solutions-morning.md:113 +#: src/async/pitfalls/cancellation.md:104 msgid "" -"In addition, the type itself would not enforce that the child slices are of " -"the same length, so such variable could contain an invalid matrix." +"[`Interval::tick`](https://docs.rs/tokio/latest/tokio/time/struct.Interval." +"html#method.tick) is cancellation-safe because it keeps track of whether a " +"tick has been 'delivered'." msgstr "" -#: src/exercises/day-1/solutions-afternoon.md:1 -msgid "Day 1 Afternoon Exercises" +#: src/async/pitfalls/cancellation.md:107 +msgid "" +"[`AsyncReadExt::read`](https://docs.rs/tokio/latest/tokio/io/trait." +"AsyncReadExt.html#method.read) is cancellation-safe because it either " +"returns or doesn't read data." msgstr "" -#: src/exercises/day-1/solutions-afternoon.md:5 -msgid "([back to exercise](book-library.md))" +#: src/async/pitfalls/cancellation.md:110 +msgid "" +"[`AsyncBufReadExt::read_line`](https://docs.rs/tokio/latest/tokio/io/trait." +"AsyncBufReadExt.html#method.read_line) is similar to the example and _isn't_ " +"cancellation-safe. See its documentation for details and alternatives." msgstr "" -#: src/exercises/day-1/solutions-afternoon.md:7 +#: src/exercises/concurrency/afternoon.md:3 msgid "" -"```rust\n" -"// Copyright 2022 Google LLC\n" -"//\n" -"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"// you may not use this file except in compliance with the License.\n" -"// You may obtain a copy of the License at\n" -"//\n" -"// http://www.apache.org/licenses/LICENSE-2.0\n" -"//\n" -"// Unless required by applicable law or agreed to in writing, software\n" -"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"// See the License for the specific language governing permissions and\n" -"// limitations under the License.\n" +"To practice your Async Rust skills, we have again two exercises for you:" +msgstr "" + +#: src/exercises/concurrency/afternoon.md:5 +msgid "" +"Dining philosophers: we already saw this problem in the morning. This time " +"you are going to implement it with Async Rust." +msgstr "" + +#: src/exercises/concurrency/afternoon.md:8 +msgid "" +"A Broadcast Chat Application: this is a larger project that allows you " +"experiment with more advanced Async Rust features." +msgstr "" + +#: src/exercises/concurrency/dining-philosophers-async.md:1 +#: src/exercises/concurrency/solutions-afternoon.md:3 +msgid "Dining Philosophers - Async" +msgstr "" + +#: src/exercises/concurrency/dining-philosophers-async.md:3 +msgid "" +"See [dining philosophers](dining-philosophers.md) for a description of the " +"problem." +msgstr "" + +#: src/exercises/concurrency/dining-philosophers-async.md:6 +msgid "" +"As before, you will need a local [Cargo installation](../../cargo/running-" +"locally.md) for this exercise. Copy the code below to a file called `src/" +"main.rs`, fill out the blanks, and test that `cargo run` does not deadlock:" +msgstr "" + +#: src/exercises/concurrency/dining-philosophers-async.md:13 +msgid "" +"```rust,compile_fail\n" +"use std::sync::Arc;\n" +"use tokio::time;\n" +"use tokio::sync::mpsc::{self, Sender};\n" +"use tokio::sync::Mutex;\n" "\n" -"// ANCHOR: setup\n" -"struct Library {\n" -" books: Vec,\n" -"}\n" +"struct Fork;\n" "\n" -"struct Book {\n" -" title: String,\n" -" year: u16,\n" +"struct Philosopher {\n" +" name: String,\n" +" // left_fork: ...\n" +" // right_fork: ...\n" +" // thoughts: ...\n" "}\n" "\n" -"impl Book {\n" -" // This is a constructor, used below.\n" -" fn new(title: &str, year: u16) -> Book {\n" -" Book {\n" -" title: String::from(title),\n" -" year,\n" -" }\n" +"impl Philosopher {\n" +" async fn think(&self) {\n" +" self.thoughts\n" +" .send(format!(\"Eureka! {} has a new idea!\", &self.name))." +"await\n" +" .unwrap();\n" +" }\n" +"\n" +" async fn eat(&self) {\n" +" // Pick up forks...\n" +" println!(\"{} is eating...\", &self.name);\n" +" time::sleep(time::Duration::from_millis(5)).await;\n" " }\n" "}\n" "\n" -"// Implement the methods below. Update the `self` parameter to\n" -"// indicate the method's required level of ownership over the object:\n" -"//\n" -"// - `&self` for shared read-only access,\n" -"// - `&mut self` for unique and mutable access,\n" -"// - `self` for unique access by value.\n" -"impl Library {\n" -" // ANCHOR_END: setup\n" +"static PHILOSOPHERS: &[&str] =\n" +" &[\"Socrates\", \"Plato\", \"Aristotle\", \"Thales\", \"Pythagoras\"];\n" "\n" -" // ANCHOR: Library_new\n" -" fn new() -> Library {\n" -" // ANCHOR_END: Library_new\n" -" Library { books: Vec::new() }\n" -" }\n" +"#[tokio::main]\n" +"async fn main() {\n" +" // Create forks\n" "\n" -" // ANCHOR: Library_len\n" -" //fn len(self) -> usize {\n" -" // todo!(\"Return the length of `self.books`\")\n" -" //}\n" -" // ANCHOR_END: Library_len\n" -" fn len(&self) -> usize {\n" -" self.books.len()\n" -" }\n" +" // Create philosophers\n" "\n" -" // ANCHOR: Library_is_empty\n" -" //fn is_empty(self) -> bool {\n" -" // todo!(\"Return `true` if `self.books` is empty\")\n" -" //}\n" -" // ANCHOR_END: Library_is_empty\n" -" fn is_empty(&self) -> bool {\n" -" self.books.is_empty()\n" -" }\n" +" // Make them think and eat\n" "\n" -" // ANCHOR: Library_add_book\n" -" //fn add_book(self, book: Book) {\n" -" // todo!(\"Add a new book to `self.books`\")\n" -" //}\n" -" // ANCHOR_END: Library_add_book\n" -" fn add_book(&mut self, book: Book) {\n" -" self.books.push(book)\n" -" }\n" -"\n" -" // ANCHOR: Library_print_books\n" -" //fn print_books(self) {\n" -" // todo!(\"Iterate over `self.books` and each book's title and " -"year\")\n" -" //}\n" -" // ANCHOR_END: Library_print_books\n" -" fn print_books(&self) {\n" -" for book in &self.books {\n" -" println!(\"{}, published in {}\", book.title, book.year);\n" -" }\n" -" }\n" -"\n" -" // ANCHOR: Library_oldest_book\n" -" //fn oldest_book(self) -> Option<&Book> {\n" -" // todo!(\"Return a reference to the oldest book (if any)\")\n" -" //}\n" -" // ANCHOR_END: Library_oldest_book\n" -" fn oldest_book(&self) -> Option<&Book> {\n" -" // Using a closure and a built-in method:\n" -" // self.books.iter().min_by_key(|book| book.year)\n" -"\n" -" // Longer hand-written solution:\n" -" let mut oldest: Option<&Book> = None;\n" -" for book in self.books.iter() {\n" -" if oldest.is_none() || book.year < oldest.unwrap().year {\n" -" oldest = Some(book);\n" -" }\n" -" }\n" -"\n" -" oldest\n" -" }\n" -"}\n" -"\n" -"// ANCHOR: main\n" -"// This shows the desired behavior. Uncomment the code below and\n" -"// implement the missing methods. You will need to update the\n" -"// method signatures, including the \"self\" parameter! You may\n" -"// also need to update the variable bindings within main.\n" -"fn main() {\n" -" let library = Library::new();\n" -"\n" -" //println!(\"The library is empty: {}\", library.is_empty());\n" -" //\n" -" //library.add_book(Book::new(\"Lord of the Rings\", 1954));\n" -" //library.add_book(Book::new(\"Alice's Adventures in Wonderland\", " -"1865));\n" -" //\n" -" //println!(\"The library is no longer empty: {}\", library.is_empty());\n" -" //\n" -" //\n" -" //library.print_books();\n" -" //\n" -" //match library.oldest_book() {\n" -" // Some(book) => println!(\"The oldest book is {}\", book.title),\n" -" // None => println!(\"The library is empty!\"),\n" -" //}\n" -" //\n" -" //println!(\"The library has {} books\", library.len());\n" -" //library.print_books();\n" -"}\n" -"// ANCHOR_END: main\n" -"\n" -"#[test]\n" -"fn test_library_len() {\n" -" let mut library = Library::new();\n" -" assert_eq!(library.len(), 0);\n" -" assert!(library.is_empty());\n" -"\n" -" library.add_book(Book::new(\"Lord of the Rings\", 1954));\n" -" library.add_book(Book::new(\"Alice's Adventures in Wonderland\", " -"1865));\n" -" assert_eq!(library.len(), 2);\n" -" assert!(!library.is_empty());\n" -"}\n" -"\n" -"#[test]\n" -"fn test_library_is_empty() {\n" -" let mut library = Library::new();\n" -" assert!(library.is_empty());\n" -"\n" -" library.add_book(Book::new(\"Lord of the Rings\", 1954));\n" -" assert!(!library.is_empty());\n" -"}\n" -"\n" -"#[test]\n" -"fn test_library_print_books() {\n" -" let mut library = Library::new();\n" -" library.add_book(Book::new(\"Lord of the Rings\", 1954));\n" -" library.add_book(Book::new(\"Alice's Adventures in Wonderland\", " -"1865));\n" -" // We could try and capture stdout, but let us just call the\n" -" // method to start with.\n" -" library.print_books();\n" +" // Output their thoughts\n" "}\n" +"```" +msgstr "" + +#: src/exercises/concurrency/dining-philosophers-async.md:57 +msgid "" +"Since this time you are using Async Rust, you'll need a `tokio` dependency. " +"You can use the following `Cargo.toml`:" +msgstr "" + +#: src/exercises/concurrency/dining-philosophers-async.md:62 +msgid "" +"```toml\n" +"[package]\n" +"name = \"dining-philosophers-async-dine\"\n" +"version = \"0.1.0\"\n" +"edition = \"2021\"\n" "\n" -"#[test]\n" -"fn test_library_oldest_book() {\n" -" let mut library = Library::new();\n" -" assert!(library.oldest_book().is_none());\n" -"\n" -" library.add_book(Book::new(\"Lord of the Rings\", 1954));\n" -" assert_eq!(\n" -" library.oldest_book().map(|b| b.title.as_str()),\n" -" Some(\"Lord of the Rings\")\n" -" );\n" -"\n" -" library.add_book(Book::new(\"Alice's Adventures in Wonderland\", " -"1865));\n" -" assert_eq!(\n" -" library.oldest_book().map(|b| b.title.as_str()),\n" -" Some(\"Alice's Adventures in Wonderland\")\n" -" );\n" -"}\n" +"[dependencies]\n" +"tokio = {version = \"1.26.0\", features = [\"sync\", \"time\", \"macros\", " +"\"rt-multi-thread\"]}\n" "```" msgstr "" -#: src/exercises/day-2/solutions-morning.md:1 -msgid "Day 2 Morning Exercises" +#: src/exercises/concurrency/dining-philosophers-async.md:72 +msgid "" +"Also note that this time you have to use the `Mutex` and the `mpsc` module " +"from the `tokio` crate." msgstr "" -#: src/exercises/day-2/solutions-morning.md:5 -msgid "([back to exercise](points-polygons.md))" +#: src/exercises/concurrency/dining-philosophers-async.md:77 +msgid "Can you make your implementation single-threaded? " msgstr "" -#: src/exercises/day-2/solutions-morning.md:7 +#: src/exercises/concurrency/chat-app.md:3 msgid "" -"```rust\n" -"// Copyright 2022 Google LLC\n" -"//\n" -"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"// you may not use this file except in compliance with the License.\n" -"// You may obtain a copy of the License at\n" -"//\n" -"// http://www.apache.org/licenses/LICENSE-2.0\n" -"//\n" -"// Unless required by applicable law or agreed to in writing, software\n" -"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"// See the License for the specific language governing permissions and\n" -"// limitations under the License.\n" -"\n" -"#[derive(Debug, Copy, Clone, PartialEq, Eq)]\n" -"// ANCHOR: Point\n" -"pub struct Point {\n" -" // ANCHOR_END: Point\n" -" x: i32,\n" -" y: i32,\n" -"}\n" -"\n" -"// ANCHOR: Point-impl\n" -"impl Point {\n" -" // ANCHOR_END: Point-impl\n" -" pub fn new(x: i32, y: i32) -> Point {\n" -" Point { x, y }\n" -" }\n" -"\n" -" pub fn magnitude(self) -> f64 {\n" -" f64::from(self.x.pow(2) + self.y.pow(2)).sqrt()\n" -" }\n" -"\n" -" pub fn dist(self, other: Point) -> f64 {\n" -" (self - other).magnitude()\n" -" }\n" -"}\n" -"\n" -"impl std::ops::Add for Point {\n" -" type Output = Self;\n" -"\n" -" fn add(self, other: Self) -> Self::Output {\n" -" Self {\n" -" x: self.x + other.x,\n" -" y: self.y + other.y,\n" -" }\n" -" }\n" -"}\n" -"\n" -"impl std::ops::Sub for Point {\n" -" type Output = Self;\n" -"\n" -" fn sub(self, other: Self) -> Self::Output {\n" -" Self {\n" -" x: self.x - other.x,\n" -" y: self.y - other.y,\n" -" }\n" -" }\n" -"}\n" -"\n" -"// ANCHOR: Polygon\n" -"pub struct Polygon {\n" -" // ANCHOR_END: Polygon\n" -" points: Vec,\n" -"}\n" -"\n" -"// ANCHOR: Polygon-impl\n" -"impl Polygon {\n" -" // ANCHOR_END: Polygon-impl\n" -" pub fn new() -> Polygon {\n" -" Polygon { points: Vec::new() }\n" -" }\n" +"In this exercise, we want to use our new knowledge to implement a broadcast " +"chat application. We have a chat server that the clients connect to and " +"publish their messages. The client reads user messages from the standard " +"input, and sends them to the server. The chat server broadcasts each message " +"that it receives to all the clients." +msgstr "" + +#: src/exercises/concurrency/chat-app.md:9 +msgid "" +"For this, we use [a broadcast channel](https://docs.rs/tokio/latest/tokio/" +"sync/broadcast/fn.channel.html) on the server, and [`tokio_websockets`]" +"(https://docs.rs/tokio-websockets/0.3.2/tokio_websockets/) for the " +"communication between the client and the server." +msgstr "" + +#: src/exercises/concurrency/chat-app.md:13 +msgid "Create a new Cargo project and add the following dependencies:" +msgstr "" + +#: src/exercises/concurrency/chat-app.md:15 +msgid "`Cargo.toml`:" +msgstr "" + +#: src/exercises/concurrency/chat-app.md:19 +msgid "" +"```toml\n" +"[package]\n" +"name = \"chat-async\"\n" +"version = \"0.1.0\"\n" +"edition = \"2021\"\n" "\n" -" pub fn add_point(&mut self, point: Point) {\n" -" self.points.push(point);\n" -" }\n" +"[dependencies]\n" +"futures-util = \"0.3.28\"\n" +"http = \"0.2.9\"\n" +"tokio = { version = \"1.28.1\", features = [\"full\"] }\n" +"tokio-websockets = \"0.3.2\"\n" +"```" +msgstr "" + +#: src/exercises/concurrency/chat-app.md:32 +msgid "The required APIs" +msgstr "" + +#: src/exercises/concurrency/chat-app.md:33 +msgid "" +"You are going to need the following functions from `tokio` and " +"[`tokio_websockets`](https://docs.rs/tokio-websockets/0.3.2/" +"tokio_websockets/). Spend a few minutes to familiarize yourself with the " +"API. " +msgstr "" + +#: src/exercises/concurrency/chat-app.md:37 +msgid "" +"[WebsocketStream::next()](https://docs.rs/tokio-websockets/0.3.2/" +"tokio_websockets/proto/struct.WebsocketStream.html#method.next): for " +"asynchronously reading messages from a Websocket Stream." +msgstr "" + +#: src/exercises/concurrency/chat-app.md:39 +msgid "" +"[SinkExt::send()](https://docs.rs/futures-util/0.3.28/futures_util/sink/" +"trait.SinkExt.html#method.send) implemented by `WebsocketStream`: for " +"asynchronously sending messages on a Websocket Stream." +msgstr "" + +#: src/exercises/concurrency/chat-app.md:41 +msgid "" +"[Lines::next_line()](https://docs.rs/tokio/latest/tokio/io/struct.Lines." +"html#method.next_line): for asynchronously reading user messages from the " +"standard input." +msgstr "" + +#: src/exercises/concurrency/chat-app.md:43 +msgid "" +"[Sender::subscribe()](https://docs.rs/tokio/latest/tokio/sync/broadcast/" +"struct.Sender.html#method.subscribe): for subscribing to a broadcast channel." +msgstr "" + +#: src/exercises/concurrency/chat-app.md:46 +msgid "Two binaries" +msgstr "" + +#: src/exercises/concurrency/chat-app.md:48 +msgid "" +"Normally in a Cargo project, you can have only one binary, and one `src/main." +"rs` file. In this project, we need two binaries. One for the client, and one " +"for the server. You could potentially make them two separate Cargo projects, " +"but we are going to put them in a single Cargo project with two binaries. " +"For this to work, the client and the server code should go under `src/bin` " +"(see the [documentation](https://doc.rust-lang.org/cargo/reference/cargo-" +"targets.html#binaries)). " +msgstr "" + +#: src/exercises/concurrency/chat-app.md:55 +msgid "" +"Copy the following server and client code into `src/bin/server.rs` and `src/" +"bin/client.rs`, respectively. Your task is to complete these files as " +"described below. " +msgstr "" + +#: src/exercises/concurrency/chat-app.md:59 +#: src/exercises/concurrency/solutions-afternoon.md:123 +msgid "`src/bin/server.rs`:" +msgstr "" + +#: src/exercises/concurrency/chat-app.md:63 +msgid "" +"```rust,compile_fail\n" +"use futures_util::sink::SinkExt;\n" +"use std::error::Error;\n" +"use std::net::SocketAddr;\n" +"use tokio::net::{TcpListener, TcpStream};\n" +"use tokio::sync::broadcast::{channel, Sender};\n" +"use tokio_websockets::{Message, ServerBuilder, WebsocketStream};\n" "\n" -" pub fn left_most_point(&self) -> Option {\n" -" self.points.iter().min_by_key(|p| p.x).copied()\n" -" }\n" +"async fn handle_connection(\n" +" addr: SocketAddr,\n" +" mut ws_stream: WebsocketStream,\n" +" bcast_tx: Sender,\n" +") -> Result<(), Box> {\n" "\n" -" pub fn iter(&self) -> impl Iterator {\n" -" self.points.iter()\n" +" // TODO: For a hint, see the description of the task below.\n" +"\n" +"}\n" +"\n" +"#[tokio::main]\n" +"async fn main() -> Result<(), Box> {\n" +" let (bcast_tx, _) = channel(16);\n" +"\n" +" let listener = TcpListener::bind(\"127.0.0.1:2000\").await?;\n" +" println!(\"listening on port 2000\");\n" +"\n" +" loop {\n" +" let (socket, addr) = listener.accept().await?;\n" +" println!(\"New connection from {addr:?}\");\n" +" let bcast_tx = bcast_tx.clone();\n" +" tokio::spawn(async move {\n" +" // Wrap the raw TCP stream into a websocket.\n" +" let ws_stream = ServerBuilder::new().accept(socket).await?;\n" +"\n" +" handle_connection(addr, ws_stream, bcast_tx).await\n" +" });\n" " }\n" +"}\n" +"```" +msgstr "" + +#: src/exercises/concurrency/chat-app.md:102 +#: src/exercises/concurrency/solutions-afternoon.md:208 +msgid "`src/bin/client.rs`:" +msgstr "" + +#: src/exercises/concurrency/chat-app.md:106 +msgid "" +"```rust,compile_fail\n" +"use futures_util::SinkExt;\n" +"use http::Uri;\n" +"use tokio::io::{AsyncBufReadExt, BufReader};\n" +"use tokio_websockets::{ClientBuilder, Message};\n" "\n" -" pub fn length(&self) -> f64 {\n" -" if self.points.is_empty() {\n" -" return 0.0;\n" -" }\n" +"#[tokio::main]\n" +"async fn main() -> Result<(), tokio_websockets::Error> {\n" +" let mut ws_stream = ClientBuilder::from_uri(Uri::" +"from_static(\"ws://127.0.0.1:2000\"))\n" +" .connect()\n" +" .await?;\n" +"\n" +" let stdin = tokio::io::stdin();\n" +" let mut stdin = BufReader::new(stdin).lines();\n" +"\n" +"\n" +" // TODO: For a hint, see the description of the task below.\n" +"\n" +"}\n" +"```" +msgstr "" + +#: src/exercises/concurrency/chat-app.md:127 +msgid "Running the binaries" +msgstr "" + +#: src/exercises/concurrency/chat-app.md:128 +msgid "Run the server with:" +msgstr "" + +#: src/exercises/concurrency/chat-app.md:130 +msgid "" +"```shell\n" +"cargo run --bin server\n" +"```" +msgstr "" + +#: src/exercises/concurrency/chat-app.md:134 +msgid "and the client with:" +msgstr "" + +#: src/exercises/concurrency/chat-app.md:136 +msgid "" +"```shell\n" +"cargo run --bin client\n" +"```" +msgstr "" + +#: src/exercises/concurrency/chat-app.md:142 +msgid "Implement the `handle_connection` function in `src/bin/server.rs`." +msgstr "" + +#: src/exercises/concurrency/chat-app.md:143 +msgid "" +"Hint: Use `tokio::select!` for concurrently performing two tasks in a " +"continuous loop. One task receives messages from the client and broadcasts " +"them. The other sends messages received by the server to the client." +msgstr "" + +#: src/exercises/concurrency/chat-app.md:146 +msgid "Complete the main function in `src/bin/client.rs`." +msgstr "" + +#: src/exercises/concurrency/chat-app.md:147 +msgid "" +"Hint: As before, use `tokio::select!` in a continuous loop for concurrently " +"performing two tasks: (1) reading user messages from standard input and " +"sending them to the server, and (2) receiving messages from the server, and " +"displaying them for the user." +msgstr "" + +#: src/exercises/concurrency/chat-app.md:151 +msgid "" +"Optional: Once you are done, change the code to broadcast messages to all " +"clients, but the sender of the message." +msgstr "" + +#: src/thanks.md:3 +msgid "" +"_Thank you for taking Comprehensive Rust 🦀!_ We hope you enjoyed it and " +"that it was useful." +msgstr "" + +#: src/thanks.md:6 +msgid "" +"We've had a lot of fun putting the course together. The course is not " +"perfect, so if you spotted any mistakes or have ideas for improvements, " +"please get in [contact with us on GitHub](https://github.com/google/" +"comprehensive-rust/discussions). We would love to hear from you." +msgstr "" + +#: src/other-resources.md:1 +msgid "Other Rust Resources" +msgstr "" + +#: src/other-resources.md:3 +msgid "" +"The Rust community has created a wealth of high-quality and free resources " +"online." +msgstr "" + +#: src/other-resources.md:6 +msgid "Official Documentation" +msgstr "" + +#: src/other-resources.md:8 +msgid "The Rust project hosts many resources. These cover Rust in general:" +msgstr "" + +#: src/other-resources.md:10 +msgid "" +"[The Rust Programming Language](https://doc.rust-lang.org/book/): the " +"canonical free book about Rust. Covers the language in detail and includes a " +"few projects for people to build." +msgstr "" + +#: src/other-resources.md:13 +msgid "" +"[Rust By Example](https://doc.rust-lang.org/rust-by-example/): covers the " +"Rust syntax via a series of examples which showcase different constructs. " +"Sometimes includes small exercises where you are asked to expand on the code " +"in the examples." +msgstr "" + +#: src/other-resources.md:17 +msgid "" +"[Rust Standard Library](https://doc.rust-lang.org/std/): full documentation " +"of the standard library for Rust." +msgstr "" + +#: src/other-resources.md:19 +msgid "" +"[The Rust Reference](https://doc.rust-lang.org/reference/): an incomplete " +"book which describes the Rust grammar and memory model." +msgstr "" + +#: src/other-resources.md:22 +msgid "More specialized guides hosted on the official Rust site:" +msgstr "" + +#: src/other-resources.md:24 +msgid "" +"[The Rustonomicon](https://doc.rust-lang.org/nomicon/): covers unsafe Rust, " +"including working with raw pointers and interfacing with other languages " +"(FFI)." +msgstr "" + +#: src/other-resources.md:27 +msgid "" +"[Asynchronous Programming in Rust](https://rust-lang.github.io/async-book/): " +"covers the new asynchronous programming model which was introduced after the " +"Rust Book was written." +msgstr "" + +#: src/other-resources.md:30 +msgid "" +"[The Embedded Rust Book](https://doc.rust-lang.org/stable/embedded-book/): " +"an introduction to using Rust on embedded devices without an operating " +"system." +msgstr "" + +#: src/other-resources.md:33 +msgid "Unofficial Learning Material" +msgstr "" + +#: src/other-resources.md:35 +msgid "A small selection of other guides and tutorial for Rust:" +msgstr "" + +#: src/other-resources.md:37 +msgid "" +"[Learn Rust the Dangerous Way](http://cliffle.com/p/dangerust/): covers Rust " +"from the perspective of low-level C programmers." +msgstr "" + +#: src/other-resources.md:39 +msgid "" +"[Rust for Embedded C Programmers](https://docs.opentitan.org/doc/ug/" +"rust_for_c/): covers Rust from the perspective of developers who write " +"firmware in C." +msgstr "" + +#: src/other-resources.md:42 +msgid "" +"[Rust for professionals](https://overexact.com/rust-for-professionals/): " +"covers the syntax of Rust using side-by-side comparisons with other " +"languages such as C, C++, Java, JavaScript, and Python." +msgstr "" + +#: src/other-resources.md:45 +msgid "" +"[Rust on Exercism](https://exercism.org/tracks/rust): 100+ exercises to help " +"you learn Rust." +msgstr "" + +#: src/other-resources.md:47 +msgid "" +"[Ferrous Teaching Material](https://ferrous-systems.github.io/teaching-" +"material/index.html): a series of small presentations covering both basic " +"and advanced part of the Rust language. Other topics such as WebAssembly, " +"and async/await are also covered." +msgstr "" + +#: src/other-resources.md:52 +msgid "" +"[Beginner's Series to Rust](https://docs.microsoft.com/en-us/shows/beginners-" +"series-to-rust/) and [Take your first steps with Rust](https://docs." +"microsoft.com/en-us/learn/paths/rust-first-steps/): two Rust guides aimed at " +"new developers. The first is a set of 35 videos and the second is a set of " +"11 modules which covers Rust syntax and basic constructs." +msgstr "" + +#: src/other-resources.md:58 +msgid "" +"[Learn Rust With Entirely Too Many Linked Lists](https://rust-unofficial." +"github.io/too-many-lists/): in-depth exploration of Rust's memory management " +"rules, through implementing a few different types of list structures." +msgstr "" + +#: src/other-resources.md:63 +msgid "" +"Please see the [Little Book of Rust Books](https://lborb.github.io/book/) " +"for even more Rust books." +msgstr "" + +#: src/credits.md:3 +msgid "" +"The material here builds on top of the many great sources of Rust " +"documentation. See the page on [other resources](other-resources.md) for a " +"full list of useful resources." +msgstr "" + +#: src/credits.md:7 +msgid "" +"The material of Comprehensive Rust is licensed under the terms of the Apache " +"2.0 license, please see [`LICENSE`](https://github.com/google/comprehensive-" +"rust/blob/main/LICENSE) for details." +msgstr "" + +#: src/credits.md:12 +msgid "Rust by Example" +msgstr "" + +#: src/credits.md:14 +msgid "" +"Some examples and exercises have been copied and adapted from [Rust by " +"Example](https://doc.rust-lang.org/rust-by-example/). Please see the " +"`third_party/rust-by-example/` directory for details, including the license " +"terms." +msgstr "" + +#: src/credits.md:19 +msgid "Rust on Exercism" +msgstr "" + +#: src/credits.md:21 +msgid "" +"Some exercises have been copied and adapted from [Rust on Exercism](https://" +"exercism.org/tracks/rust). Please see the `third_party/rust-on-exercism/` " +"directory for details, including the license terms." +msgstr "" + +#: src/credits.md:26 +msgid "CXX" +msgstr "" + +#: src/credits.md:28 +msgid "" +"The [Interoperability with C++](android/interoperability/cpp.md) section " +"uses an image from [CXX](https://cxx.rs/). Please see the `third_party/cxx/` " +"directory for details, including the license terms." +msgstr "" + +#: src/exercises/solutions.md:3 +msgid "You will find solutions to the exercises on the following pages." +msgstr "" + +#: src/exercises/solutions.md:5 +msgid "" +"Feel free to ask questions about the solutions [on GitHub](https://github." +"com/google/comprehensive-rust/discussions). Let us know if you have a " +"different or better solution than what is presented here." +msgstr "" + +#: src/exercises/solutions.md:10 +msgid "" +"**Note:** Please ignore the `// ANCHOR: label` and `// ANCHOR_END: label` " +"comments you see in the solutions. They are there to make it possible to re-" +"use parts of the solutions as the exercises." +msgstr "" + +#: src/exercises/day-1/solutions-morning.md:1 +msgid "Day 1 Morning Exercises" +msgstr "" + +#: src/exercises/day-1/solutions-morning.md:5 +msgid "([back to exercise](for-loops.md))" +msgstr "" + +#: src/exercises/day-1/solutions-morning.md:7 +msgid "" +"```rust\n" +"// Copyright 2022 Google LLC\n" +"//\n" +"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" +"// you may not use this file except in compliance with the License.\n" +"// You may obtain a copy of the License at\n" +"//\n" +"// http://www.apache.org/licenses/LICENSE-2.0\n" +"//\n" +"// Unless required by applicable law or agreed to in writing, software\n" +"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" +"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" +"// See the License for the specific language governing permissions and\n" +"// limitations under the License.\n" "\n" -" let mut result = 0.0;\n" -" let mut last_point = self.points[0];\n" -" for point in &self.points[1..] {\n" -" result += last_point.dist(*point);\n" -" last_point = *point;\n" +"// ANCHOR: transpose\n" +"fn transpose(matrix: [[i32; 3]; 3]) -> [[i32; 3]; 3] {\n" +" // ANCHOR_END: transpose\n" +" let mut result = [[0; 3]; 3];\n" +" for i in 0..3 {\n" +" for j in 0..3 {\n" +" result[j][i] = matrix[i][j];\n" " }\n" -" result += last_point.dist(self.points[0]);\n" -" result\n" " }\n" +" return result;\n" "}\n" "\n" -"// ANCHOR: Circle\n" -"pub struct Circle {\n" -" // ANCHOR_END: Circle\n" -" center: Point,\n" -" radius: i32,\n" -"}\n" -"\n" -"// ANCHOR: Circle-impl\n" -"impl Circle {\n" -" // ANCHOR_END: Circle-impl\n" -" pub fn new(center: Point, radius: i32) -> Circle {\n" -" Circle { center, radius }\n" -" }\n" -"\n" -" pub fn circumference(&self) -> f64 {\n" -" 2.0 * std::f64::consts::PI * f64::from(self.radius)\n" -" }\n" -"\n" -" pub fn dist(&self, other: &Self) -> f64 {\n" -" self.center.dist(other.center)\n" +"// ANCHOR: pretty_print\n" +"fn pretty_print(matrix: &[[i32; 3]; 3]) {\n" +" // ANCHOR_END: pretty_print\n" +" for row in matrix {\n" +" println!(\"{row:?}\");\n" " }\n" "}\n" "\n" -"// ANCHOR: Shape\n" -"pub enum Shape {\n" -" Polygon(Polygon),\n" -" Circle(Circle),\n" +"// ANCHOR: tests\n" +"#[test]\n" +"fn test_transpose() {\n" +" let matrix = [\n" +" [101, 102, 103], //\n" +" [201, 202, 203],\n" +" [301, 302, 303],\n" +" ];\n" +" let transposed = transpose(matrix);\n" +" assert_eq!(\n" +" transposed,\n" +" [\n" +" [101, 201, 301], //\n" +" [102, 202, 302],\n" +" [103, 203, 303],\n" +" ]\n" +" );\n" "}\n" -"// ANCHOR_END: Shape\n" +"// ANCHOR_END: tests\n" "\n" -"impl From for Shape {\n" -" fn from(poly: Polygon) -> Self {\n" -" Shape::Polygon(poly)\n" -" }\n" -"}\n" +"// ANCHOR: main\n" +"fn main() {\n" +" let matrix = [\n" +" [101, 102, 103], // <-- the comment makes rustfmt add a newline\n" +" [201, 202, 203],\n" +" [301, 302, 303],\n" +" ];\n" "\n" -"impl From for Shape {\n" -" fn from(circle: Circle) -> Self {\n" -" Shape::Circle(circle)\n" -" }\n" -"}\n" +" println!(\"matrix:\");\n" +" pretty_print(&matrix);\n" "\n" -"impl Shape {\n" -" pub fn perimeter(&self) -> f64 {\n" -" match self {\n" -" Shape::Polygon(poly) => poly.length(),\n" -" Shape::Circle(circle) => circle.circumference(),\n" -" }\n" -" }\n" +" let transposed = transpose(matrix);\n" +" println!(\"transposed:\");\n" +" pretty_print(&transposed);\n" "}\n" -"\n" -"// ANCHOR: unit-tests\n" -"#[cfg(test)]\n" -"mod tests {\n" -" use super::*;\n" -"\n" -" fn round_two_digits(x: f64) -> f64 {\n" -" (x * 100.0).round() / 100.0\n" -" }\n" -"\n" -" #[test]\n" -" fn test_point_magnitude() {\n" -" let p1 = Point::new(12, 13);\n" -" assert_eq!(round_two_digits(p1.magnitude()), 17.69);\n" -" }\n" -"\n" -" #[test]\n" -" fn test_point_dist() {\n" -" let p1 = Point::new(10, 10);\n" -" let p2 = Point::new(14, 13);\n" -" assert_eq!(round_two_digits(p1.dist(p2)), 5.00);\n" -" }\n" -"\n" -" #[test]\n" -" fn test_point_add() {\n" -" let p1 = Point::new(16, 16);\n" -" let p2 = p1 + Point::new(-4, 3);\n" -" assert_eq!(p2, Point::new(12, 19));\n" -" }\n" -"\n" -" #[test]\n" -" fn test_polygon_left_most_point() {\n" -" let p1 = Point::new(12, 13);\n" -" let p2 = Point::new(16, 16);\n" -"\n" -" let mut poly = Polygon::new();\n" -" poly.add_point(p1);\n" -" poly.add_point(p2);\n" -" assert_eq!(poly.left_most_point(), Some(p1));\n" -" }\n" -"\n" -" #[test]\n" -" fn test_polygon_iter() {\n" -" let p1 = Point::new(12, 13);\n" -" let p2 = Point::new(16, 16);\n" -"\n" -" let mut poly = Polygon::new();\n" -" poly.add_point(p1);\n" -" poly.add_point(p2);\n" -"\n" -" let points = poly.iter().cloned().collect::>();\n" -" assert_eq!(points, vec![Point::new(12, 13), Point::new(16, 16)]);\n" -" }\n" -"\n" -" #[test]\n" -" fn test_shape_perimeters() {\n" -" let mut poly = Polygon::new();\n" -" poly.add_point(Point::new(12, 13));\n" -" poly.add_point(Point::new(17, 11));\n" -" poly.add_point(Point::new(16, 16));\n" -" let shapes = vec![\n" -" Shape::from(poly),\n" -" Shape::from(Circle::new(Point::new(10, 20), 5)),\n" -" ];\n" -" let perimeters = shapes\n" -" .iter()\n" -" .map(Shape::perimeter)\n" -" .map(round_two_digits)\n" -" .collect::>();\n" -" assert_eq!(perimeters, vec![15.48, 31.42]);\n" +"```" +msgstr "" + +#: src/exercises/day-1/solutions-morning.md:78 +msgid "Bonus question" +msgstr "" + +#: src/exercises/day-1/solutions-morning.md:80 +msgid "" +"It requires more advanced concepts. It might seem that we could use a slice-" +"of-slices (`&[&[i32]]`) as the input type to transpose and thus make our " +"function handle any size of matrix. However, this quickly breaks down: the " +"return type cannot be `&[&[i32]]` since it needs to own the data you return." +msgstr "" + +#: src/exercises/day-1/solutions-morning.md:82 +msgid "" +"You can attempt to use something like `Vec>`, but this doesn't work " +"out-of-the-box either: it's hard to convert from `Vec>` to " +"`&[&[i32]]` so now you cannot easily use `pretty_print` either." +msgstr "" + +#: src/exercises/day-1/solutions-morning.md:84 +msgid "" +"Once we get to traits and generics, we'll be able to use the [`std::convert::" +"AsRef`](https://doc.rust-lang.org/std/convert/trait.AsRef.html) trait to " +"abstract over anything that can be referenced as a slice." +msgstr "" + +#: src/exercises/day-1/solutions-morning.md:86 +msgid "" +"```rust\n" +"use std::convert::AsRef;\n" +"use std::fmt::Debug;\n" +"\n" +"fn pretty_print(matrix: Matrix)\n" +"where\n" +" T: Debug,\n" +" // A line references a slice of items\n" +" Line: AsRef<[T]>,\n" +" // A matrix references a slice of lines\n" +" Matrix: AsRef<[Line]>\n" +"{\n" +" for row in matrix.as_ref() {\n" +" println!(\"{:?}\", row.as_ref());\n" " }\n" "}\n" -"// ANCHOR_END: unit-tests\n" "\n" -"fn main() {}\n" +"fn main() {\n" +" // &[&[i32]]\n" +" pretty_print(&[&[1, 2, 3], &[4, 5, 6], &[7, 8, 9]]);\n" +" // [[&str; 2]; 2]\n" +" pretty_print([[\"a\", \"b\"], [\"c\", \"d\"]]);\n" +" // Vec>\n" +" pretty_print(vec![vec![1, 2], vec![3, 4]]);\n" +"}\n" "```" msgstr "" -#: src/exercises/day-2/solutions-afternoon.md:1 -msgid "Day 2 Afternoon Exercises" +#: src/exercises/day-1/solutions-morning.md:113 +msgid "" +"In addition, the type itself would not enforce that the child slices are of " +"the same length, so such variable could contain an invalid matrix." msgstr "" -#: src/exercises/day-2/solutions-afternoon.md:5 +#: src/exercises/day-1/solutions-afternoon.md:1 +msgid "Day 1 Afternoon Exercises" +msgstr "" + +#: src/exercises/day-1/solutions-afternoon.md:5 msgid "([back to exercise](luhn.md))" msgstr "" -#: src/exercises/day-2/solutions-afternoon.md:7 +#: src/exercises/day-1/solutions-afternoon.md:7 msgid "" "```rust\n" "// Copyright 2022 Google LLC\n" @@ -18324,15 +18863,237 @@ msgid "" " assert!(!luhn(\"4539 3195 0343 6476\"));\n" " assert!(!luhn(\"8273 1232 7352 0569\"));\n" "}\n" -"// ANCHOR_END: unit-tests\n" +"// ANCHOR_END: unit-tests\n" +"```" +msgstr "" + +#: src/exercises/day-1/solutions-afternoon.md:97 +#, fuzzy +msgid "Pattern matching" +msgstr "Şablon Eşleştirme" + +#: src/exercises/day-1/solutions-afternoon.md:99 +msgid "TBD." +msgstr "" + +#: src/exercises/day-2/solutions-morning.md:1 +msgid "Day 2 Morning Exercises" +msgstr "" + +#: src/exercises/day-2/solutions-morning.md:3 +msgid "Designing a Library" +msgstr "Kütüphane Tasarlama" + +#: src/exercises/day-2/solutions-morning.md:5 +msgid "([back to exercise](book-library.md))" +msgstr "" + +#: src/exercises/day-2/solutions-morning.md:7 +msgid "" +"```rust\n" +"// Copyright 2022 Google LLC\n" +"//\n" +"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" +"// you may not use this file except in compliance with the License.\n" +"// You may obtain a copy of the License at\n" +"//\n" +"// http://www.apache.org/licenses/LICENSE-2.0\n" +"//\n" +"// Unless required by applicable law or agreed to in writing, software\n" +"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" +"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" +"// See the License for the specific language governing permissions and\n" +"// limitations under the License.\n" +"\n" +"// ANCHOR: setup\n" +"struct Library {\n" +" books: Vec,\n" +"}\n" +"\n" +"struct Book {\n" +" title: String,\n" +" year: u16,\n" +"}\n" +"\n" +"impl Book {\n" +" // This is a constructor, used below.\n" +" fn new(title: &str, year: u16) -> Book {\n" +" Book {\n" +" title: String::from(title),\n" +" year,\n" +" }\n" +" }\n" +"}\n" +"\n" +"// Implement the methods below. Update the `self` parameter to\n" +"// indicate the method's required level of ownership over the object:\n" +"//\n" +"// - `&self` for shared read-only access,\n" +"// - `&mut self` for unique and mutable access,\n" +"// - `self` for unique access by value.\n" +"impl Library {\n" +" // ANCHOR_END: setup\n" +"\n" +" // ANCHOR: Library_new\n" +" fn new() -> Library {\n" +" // ANCHOR_END: Library_new\n" +" Library { books: Vec::new() }\n" +" }\n" +"\n" +" // ANCHOR: Library_len\n" +" //fn len(self) -> usize {\n" +" // todo!(\"Return the length of `self.books`\")\n" +" //}\n" +" // ANCHOR_END: Library_len\n" +" fn len(&self) -> usize {\n" +" self.books.len()\n" +" }\n" +"\n" +" // ANCHOR: Library_is_empty\n" +" //fn is_empty(self) -> bool {\n" +" // todo!(\"Return `true` if `self.books` is empty\")\n" +" //}\n" +" // ANCHOR_END: Library_is_empty\n" +" fn is_empty(&self) -> bool {\n" +" self.books.is_empty()\n" +" }\n" +"\n" +" // ANCHOR: Library_add_book\n" +" //fn add_book(self, book: Book) {\n" +" // todo!(\"Add a new book to `self.books`\")\n" +" //}\n" +" // ANCHOR_END: Library_add_book\n" +" fn add_book(&mut self, book: Book) {\n" +" self.books.push(book)\n" +" }\n" +"\n" +" // ANCHOR: Library_print_books\n" +" //fn print_books(self) {\n" +" // todo!(\"Iterate over `self.books` and each book's title and " +"year\")\n" +" //}\n" +" // ANCHOR_END: Library_print_books\n" +" fn print_books(&self) {\n" +" for book in &self.books {\n" +" println!(\"{}, published in {}\", book.title, book.year);\n" +" }\n" +" }\n" +"\n" +" // ANCHOR: Library_oldest_book\n" +" //fn oldest_book(self) -> Option<&Book> {\n" +" // todo!(\"Return a reference to the oldest book (if any)\")\n" +" //}\n" +" // ANCHOR_END: Library_oldest_book\n" +" fn oldest_book(&self) -> Option<&Book> {\n" +" // Using a closure and a built-in method:\n" +" // self.books.iter().min_by_key(|book| book.year)\n" +"\n" +" // Longer hand-written solution:\n" +" let mut oldest: Option<&Book> = None;\n" +" for book in self.books.iter() {\n" +" if oldest.is_none() || book.year < oldest.unwrap().year {\n" +" oldest = Some(book);\n" +" }\n" +" }\n" +"\n" +" oldest\n" +" }\n" +"}\n" +"\n" +"// ANCHOR: main\n" +"// This shows the desired behavior. Uncomment the code below and\n" +"// implement the missing methods. You will need to update the\n" +"// method signatures, including the \"self\" parameter! You may\n" +"// also need to update the variable bindings within main.\n" +"fn main() {\n" +" let library = Library::new();\n" +"\n" +" //println!(\"The library is empty: library.is_empty() -> {}\", library." +"is_empty());\n" +" //\n" +" //library.add_book(Book::new(\"Lord of the Rings\", 1954));\n" +" //library.add_book(Book::new(\"Alice's Adventures in Wonderland\", " +"1865));\n" +" //\n" +" //println!(\"The library is no longer empty: library.is_empty() -> {}\", " +"library.is_empty());\n" +" //\n" +" //\n" +" //library.print_books();\n" +" //\n" +" //match library.oldest_book() {\n" +" // Some(book) => println!(\"The oldest book is {}\", book.title),\n" +" // None => println!(\"The library is empty!\"),\n" +" //}\n" +" //\n" +" //println!(\"The library has {} books\", library.len());\n" +" //library.print_books();\n" +"}\n" +"// ANCHOR_END: main\n" +"\n" +"#[test]\n" +"fn test_library_len() {\n" +" let mut library = Library::new();\n" +" assert_eq!(library.len(), 0);\n" +" assert!(library.is_empty());\n" +"\n" +" library.add_book(Book::new(\"Lord of the Rings\", 1954));\n" +" library.add_book(Book::new(\"Alice's Adventures in Wonderland\", " +"1865));\n" +" assert_eq!(library.len(), 2);\n" +" assert!(!library.is_empty());\n" +"}\n" +"\n" +"#[test]\n" +"fn test_library_is_empty() {\n" +" let mut library = Library::new();\n" +" assert!(library.is_empty());\n" +"\n" +" library.add_book(Book::new(\"Lord of the Rings\", 1954));\n" +" assert!(!library.is_empty());\n" +"}\n" +"\n" +"#[test]\n" +"fn test_library_print_books() {\n" +" let mut library = Library::new();\n" +" library.add_book(Book::new(\"Lord of the Rings\", 1954));\n" +" library.add_book(Book::new(\"Alice's Adventures in Wonderland\", " +"1865));\n" +" // We could try and capture stdout, but let us just call the\n" +" // method to start with.\n" +" library.print_books();\n" +"}\n" +"\n" +"#[test]\n" +"fn test_library_oldest_book() {\n" +" let mut library = Library::new();\n" +" assert!(library.oldest_book().is_none());\n" +"\n" +" library.add_book(Book::new(\"Lord of the Rings\", 1954));\n" +" assert_eq!(\n" +" library.oldest_book().map(|b| b.title.as_str()),\n" +" Some(\"Lord of the Rings\")\n" +" );\n" +"\n" +" library.add_book(Book::new(\"Alice's Adventures in Wonderland\", " +"1865));\n" +" assert_eq!(\n" +" library.oldest_book().map(|b| b.title.as_str()),\n" +" Some(\"Alice's Adventures in Wonderland\")\n" +" );\n" +"}\n" "```" msgstr "" -#: src/exercises/day-2/solutions-afternoon.md:99 +#: src/exercises/day-2/solutions-afternoon.md:1 +msgid "Day 2 Afternoon Exercises" +msgstr "" + +#: src/exercises/day-2/solutions-afternoon.md:5 msgid "([back to exercise](strings-iterators.md))" msgstr "" -#: src/exercises/day-2/solutions-afternoon.md:101 +#: src/exercises/day-2/solutions-afternoon.md:7 msgid "" "```rust\n" "// Copyright 2022 Google LLC\n" @@ -18352,23 +19113,30 @@ msgid "" "// ANCHOR: prefix_matches\n" "pub fn prefix_matches(prefix: &str, request_path: &str) -> bool {\n" " // ANCHOR_END: prefix_matches\n" -" let prefixes = prefix.split('/');\n" -" let request_paths = request_path\n" -" .split('/')\n" -" .map(|p| Some(p))\n" -" .chain(std::iter::once(None));\n" -"\n" -" for (prefix, request_path) in prefixes.zip(request_paths) {\n" -" match request_path {\n" -" Some(request_path) => {\n" -" if (prefix != \"*\") && (prefix != request_path) {\n" -" return false;\n" -" }\n" -" }\n" -" None => return false,\n" +"\n" +" let mut request_segments = request_path.split('/');\n" +"\n" +" for prefix_segment in prefix.split('/') {\n" +" let Some(request_segment) = request_segments.next() else {\n" +" return false;\n" +" };\n" +" if request_segment != prefix_segment && prefix_segment != \"*\" {\n" +" return false;\n" " }\n" " }\n" " true\n" +"\n" +" // Alternatively, Iterator::zip() lets us iterate simultaneously over " +"prefix\n" +" // and request segments. The zip() iterator is finished as soon as one " +"of\n" +" // the source iterators is finished, but we need to iterate over all " +"request\n" +" // segments. A neat trick that makes zip() work is to use map() and " +"chain()\n" +" // to produce an iterator that returns Some(str) for each pattern " +"segments,\n" +" // and then returns None indefinitely.\n" "}\n" "\n" "// ANCHOR: unit-tests\n" @@ -18481,116 +19249,363 @@ msgid "" " }\n" "}\n" "\n" -"pub struct Window {\n" -" title: String,\n" -" widgets: Vec>,\n" +"pub struct Window {\n" +" title: String,\n" +" widgets: Vec>,\n" +"}\n" +"\n" +"impl Window {\n" +" fn new(title: &str) -> Window {\n" +" Window {\n" +" title: title.to_owned(),\n" +" widgets: Vec::new(),\n" +" }\n" +" }\n" +"\n" +" fn add_widget(&mut self, widget: Box) {\n" +" self.widgets.push(widget);\n" +" }\n" +"\n" +" fn inner_width(&self) -> usize {\n" +" std::cmp::max(\n" +" self.title.chars().count(),\n" +" self.widgets.iter().map(|w| w.width()).max().unwrap_or(0),\n" +" )\n" +" }\n" +"}\n" +"\n" +"// ANCHOR_END: setup\n" +"\n" +"// ANCHOR: Window-width\n" +"impl Widget for Window {\n" +" fn width(&self) -> usize {\n" +" // ANCHOR_END: Window-width\n" +" // Add 4 paddings for borders\n" +" self.inner_width() + 4\n" +" }\n" +"\n" +" // ANCHOR: Window-draw_into\n" +" fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {\n" +" // ANCHOR_END: Window-draw_into\n" +" let mut inner = String::new();\n" +" for widget in &self.widgets {\n" +" widget.draw_into(&mut inner);\n" +" }\n" +"\n" +" let inner_width = self.inner_width();\n" +"\n" +" // TODO: after learning about error handling, you can change\n" +" // draw_into to return Result<(), std::fmt::Error>. Then use\n" +" // the ?-operator here instead of .unwrap().\n" +" writeln!(buffer, \"+-{:- usize {\n" +" // ANCHOR_END: Button-width\n" +" self.label.width() + 8 // add a bit of padding\n" +" }\n" +"\n" +" // ANCHOR: Button-draw_into\n" +" fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {\n" +" // ANCHOR_END: Button-draw_into\n" +" let width = self.width();\n" +" let mut label = String::new();\n" +" self.label.draw_into(&mut label);\n" +"\n" +" writeln!(buffer, \"+{:- usize {\n" +" // ANCHOR_END: Label-width\n" +" self.label\n" +" .lines()\n" +" .map(|line| line.chars().count())\n" +" .max()\n" +" .unwrap_or(0)\n" +" }\n" +"\n" +" // ANCHOR: Label-draw_into\n" +" fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {\n" +" // ANCHOR_END: Label-draw_into\n" +" writeln!(buffer, \"{}\", &self.label).unwrap();\n" +" }\n" +"}\n" +"\n" +"// ANCHOR: main\n" +"fn main() {\n" +" let mut window = Window::new(\"Rust GUI Demo 1.23\");\n" +" window.add_widget(Box::new(Label::new(\"This is a small text GUI demo." +"\")));\n" +" window.add_widget(Box::new(Button::new(\n" +" \"Click me!\",\n" +" Box::new(|| println!(\"You clicked the button!\")),\n" +" )));\n" +" window.draw();\n" +"}\n" +"// ANCHOR_END: main\n" +"```" +msgstr "" + +#: src/exercises/day-3/solutions-morning.md:177 +msgid "([back to exercise](points-polygons.md))" +msgstr "" + +#: src/exercises/day-3/solutions-morning.md:179 +msgid "" +"```rust\n" +"// Copyright 2022 Google LLC\n" +"//\n" +"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" +"// you may not use this file except in compliance with the License.\n" +"// You may obtain a copy of the License at\n" +"//\n" +"// http://www.apache.org/licenses/LICENSE-2.0\n" +"//\n" +"// Unless required by applicable law or agreed to in writing, software\n" +"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" +"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" +"// See the License for the specific language governing permissions and\n" +"// limitations under the License.\n" +"\n" +"#[derive(Debug, Copy, Clone, PartialEq, Eq)]\n" +"// ANCHOR: Point\n" +"pub struct Point {\n" +" // ANCHOR_END: Point\n" +" x: i32,\n" +" y: i32,\n" +"}\n" +"\n" +"// ANCHOR: Point-impl\n" +"impl Point {\n" +" // ANCHOR_END: Point-impl\n" +" pub fn new(x: i32, y: i32) -> Point {\n" +" Point { x, y }\n" +" }\n" +"\n" +" pub fn magnitude(self) -> f64 {\n" +" f64::from(self.x.pow(2) + self.y.pow(2)).sqrt()\n" +" }\n" +"\n" +" pub fn dist(self, other: Point) -> f64 {\n" +" (self - other).magnitude()\n" +" }\n" +"}\n" +"\n" +"impl std::ops::Add for Point {\n" +" type Output = Self;\n" +"\n" +" fn add(self, other: Self) -> Self::Output {\n" +" Self {\n" +" x: self.x + other.x,\n" +" y: self.y + other.y,\n" +" }\n" +" }\n" +"}\n" +"\n" +"impl std::ops::Sub for Point {\n" +" type Output = Self;\n" +"\n" +" fn sub(self, other: Self) -> Self::Output {\n" +" Self {\n" +" x: self.x - other.x,\n" +" y: self.y - other.y,\n" +" }\n" +" }\n" +"}\n" +"\n" +"// ANCHOR: Polygon\n" +"pub struct Polygon {\n" +" // ANCHOR_END: Polygon\n" +" points: Vec,\n" +"}\n" +"\n" +"// ANCHOR: Polygon-impl\n" +"impl Polygon {\n" +" // ANCHOR_END: Polygon-impl\n" +" pub fn new() -> Polygon {\n" +" Polygon { points: Vec::new() }\n" +" }\n" +"\n" +" pub fn add_point(&mut self, point: Point) {\n" +" self.points.push(point);\n" +" }\n" +"\n" +" pub fn left_most_point(&self) -> Option {\n" +" self.points.iter().min_by_key(|p| p.x).copied()\n" +" }\n" +"\n" +" pub fn iter(&self) -> impl Iterator {\n" +" self.points.iter()\n" +" }\n" +"\n" +" pub fn length(&self) -> f64 {\n" +" if self.points.is_empty() {\n" +" return 0.0;\n" +" }\n" +"\n" +" let mut result = 0.0;\n" +" let mut last_point = self.points[0];\n" +" for point in &self.points[1..] {\n" +" result += last_point.dist(*point);\n" +" last_point = *point;\n" +" }\n" +" result += last_point.dist(self.points[0]);\n" +" result\n" +" // Alternatively, Iterator::zip() lets us iterate over the points as " +"pairs\n" +" // but we need to pair each point with the next one, and the last " +"point\n" +" // with the first point. The zip() iterator is finished as soon as " +"one of \n" +" // the source iterators is finished, a neat trick is to combine " +"Iterator::cycle\n" +" // with Iterator::skip to create the second iterator for the zip and " +"using map \n" +" // and sum to calculate the total length.\n" +" }\n" +"}\n" +"\n" +"// ANCHOR: Circle\n" +"pub struct Circle {\n" +" // ANCHOR_END: Circle\n" +" center: Point,\n" +" radius: i32,\n" +"}\n" +"\n" +"// ANCHOR: Circle-impl\n" +"impl Circle {\n" +" // ANCHOR_END: Circle-impl\n" +" pub fn new(center: Point, radius: i32) -> Circle {\n" +" Circle { center, radius }\n" +" }\n" +"\n" +" pub fn circumference(&self) -> f64 {\n" +" 2.0 * std::f64::consts::PI * f64::from(self.radius)\n" +" }\n" +"\n" +" pub fn dist(&self, other: &Self) -> f64 {\n" +" self.center.dist(other.center)\n" +" }\n" +"}\n" +"\n" +"// ANCHOR: Shape\n" +"pub enum Shape {\n" +" Polygon(Polygon),\n" +" Circle(Circle),\n" "}\n" +"// ANCHOR_END: Shape\n" "\n" -"impl Window {\n" -" fn new(title: &str) -> Window {\n" -" Window {\n" -" title: title.to_owned(),\n" -" widgets: Vec::new(),\n" -" }\n" +"impl From for Shape {\n" +" fn from(poly: Polygon) -> Self {\n" +" Shape::Polygon(poly)\n" " }\n" +"}\n" "\n" -" fn add_widget(&mut self, widget: Box) {\n" -" self.widgets.push(widget);\n" +"impl From for Shape {\n" +" fn from(circle: Circle) -> Self {\n" +" Shape::Circle(circle)\n" " }\n" +"}\n" "\n" -" fn inner_width(&self) -> usize {\n" -" std::cmp::max(\n" -" self.title.chars().count(),\n" -" self.widgets.iter().map(|w| w.width()).max().unwrap_or(0),\n" -" )\n" +"impl Shape {\n" +" pub fn perimeter(&self) -> f64 {\n" +" match self {\n" +" Shape::Polygon(poly) => poly.length(),\n" +" Shape::Circle(circle) => circle.circumference(),\n" +" }\n" " }\n" "}\n" "\n" -"// ANCHOR_END: setup\n" +"// ANCHOR: unit-tests\n" +"#[cfg(test)]\n" +"mod tests {\n" +" use super::*;\n" "\n" -"// ANCHOR: Window-width\n" -"impl Widget for Window {\n" -" fn width(&self) -> usize {\n" -" // ANCHOR_END: Window-width\n" -" // Add 4 paddings for borders\n" -" self.inner_width() + 4\n" +" fn round_two_digits(x: f64) -> f64 {\n" +" (x * 100.0).round() / 100.0\n" " }\n" "\n" -" // ANCHOR: Window-draw_into\n" -" fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {\n" -" // ANCHOR_END: Window-draw_into\n" -" let mut inner = String::new();\n" -" for widget in &self.widgets {\n" -" widget.draw_into(&mut inner);\n" -" }\n" -"\n" -" let inner_width = self.inner_width();\n" +" #[test]\n" +" fn test_point_magnitude() {\n" +" let p1 = Point::new(12, 13);\n" +" assert_eq!(round_two_digits(p1.magnitude()), 17.69);\n" +" }\n" "\n" -" // TODO: after learning about error handling, you can change\n" -" // draw_into to return Result<(), std::fmt::Error>. Then use\n" -" // the ?-operator here instead of .unwrap().\n" -" writeln!(buffer, \"+-{:- usize {\n" -" // ANCHOR_END: Button-width\n" -" self.label.width() + 8 // add a bit of padding\n" +" #[test]\n" +" fn test_point_add() {\n" +" let p1 = Point::new(16, 16);\n" +" let p2 = p1 + Point::new(-4, 3);\n" +" assert_eq!(p2, Point::new(12, 19));\n" " }\n" "\n" -" // ANCHOR: Button-draw_into\n" -" fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {\n" -" // ANCHOR_END: Button-draw_into\n" -" let width = self.width();\n" -" let mut label = String::new();\n" -" self.label.draw_into(&mut label);\n" +" #[test]\n" +" fn test_polygon_left_most_point() {\n" +" let p1 = Point::new(12, 13);\n" +" let p2 = Point::new(16, 16);\n" "\n" -" writeln!(buffer, \"+{:- usize {\n" -" // ANCHOR_END: Label-width\n" -" self.label\n" -" .lines()\n" -" .map(|line| line.chars().count())\n" -" .max()\n" -" .unwrap_or(0)\n" +" #[test]\n" +" fn test_polygon_iter() {\n" +" let p1 = Point::new(12, 13);\n" +" let p2 = Point::new(16, 16);\n" +"\n" +" let mut poly = Polygon::new();\n" +" poly.add_point(p1);\n" +" poly.add_point(p2);\n" +"\n" +" let points = poly.iter().cloned().collect::>();\n" +" assert_eq!(points, vec![Point::new(12, 13), Point::new(16, 16)]);\n" " }\n" "\n" -" // ANCHOR: Label-draw_into\n" -" fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {\n" -" // ANCHOR_END: Label-draw_into\n" -" writeln!(buffer, \"{}\", &self.label).unwrap();\n" +" #[test]\n" +" fn test_shape_perimeters() {\n" +" let mut poly = Polygon::new();\n" +" poly.add_point(Point::new(12, 13));\n" +" poly.add_point(Point::new(17, 11));\n" +" poly.add_point(Point::new(16, 16));\n" +" let shapes = vec![\n" +" Shape::from(poly),\n" +" Shape::from(Circle::new(Point::new(10, 20), 5)),\n" +" ];\n" +" let perimeters = shapes\n" +" .iter()\n" +" .map(Shape::perimeter)\n" +" .map(round_two_digits)\n" +" .collect::>();\n" +" assert_eq!(perimeters, vec![15.48, 31.42]);\n" " }\n" "}\n" +"// ANCHOR_END: unit-tests\n" "\n" -"// ANCHOR: main\n" -"fn main() {\n" -" let mut window = Window::new(\"Rust GUI Demo 1.23\");\n" -" window.add_widget(Box::new(Label::new(\"This is a small text GUI demo." -"\")));\n" -" window.add_widget(Box::new(Button::new(\n" -" \"Click me!\",\n" -" Box::new(|| println!(\"You clicked the button!\")),\n" -" )));\n" -" window.draw();\n" -"}\n" -"// ANCHOR_END: main\n" +"fn main() {}\n" "```" msgstr "" @@ -18623,7 +19638,7 @@ msgid "" "mod ffi {\n" " use std::os::raw::{c_char, c_int};\n" " #[cfg(not(target_os = \"macos\"))]\n" -" use std::os::raw::{c_long, c_ulong, c_ushort};\n" +" use std::os::raw::{c_long, c_ulong, c_ushort, c_uchar};\n" "\n" " // Opaque type. See https://doc.rust-lang.org/nomicon/ffi.html.\n" " #[repr(C)]\n" @@ -18633,23 +19648,25 @@ msgid "" "PhantomPinned)>,\n" " }\n" "\n" -" // Layout as per readdir(3) and definitions in /usr/include/x86_64-linux-" -"gnu.\n" +" // Layout according to the Linux man page for readdir(3), where ino_t " +"and\n" +" // off_t are resolved according to the definitions in\n" +" // /usr/include/x86_64-linux-gnu/{sys/types.h, bits/typesizes.h}.\n" " #[cfg(not(target_os = \"macos\"))]\n" " #[repr(C)]\n" " pub struct dirent {\n" -" pub d_ino: c_long,\n" -" pub d_off: c_ulong,\n" +" pub d_ino: c_ulong,\n" +" pub d_off: c_long,\n" " pub d_reclen: c_ushort,\n" -" pub d_type: c_char,\n" +" pub d_type: c_uchar,\n" " pub d_name: [c_char; 256],\n" " }\n" "\n" -" // Layout as per man entry for dirent\n" -" #[cfg(target_os = \"macos\")]\n" +" // Layout according to the macOS man page for dir(5).\n" +" #[cfg(all(target_os = \"macos\"))]\n" " #[repr(C)]\n" " pub struct dirent {\n" -" pub d_ino: u64,\n" +" pub d_fileno: u64,\n" " pub d_seekoff: u64,\n" " pub d_reclen: u16,\n" " pub d_namlen: u16,\n" @@ -18659,7 +19676,22 @@ msgid "" "\n" " extern \"C\" {\n" " pub fn opendir(s: *const c_char) -> *mut DIR;\n" +"\n" +" #[cfg(not(all(target_os = \"macos\", target_arch = \"x86_64\")))]\n" +" pub fn readdir(s: *mut DIR) -> *const dirent;\n" +"\n" +" // See https://github.com/rust-lang/libc/issues/414 and the section " +"on\n" +" // _DARWIN_FEATURE_64_BIT_INODE in the macOS man page for stat(2).\n" +" //\n" +" // \"Platforms that existed before these updates were available\" " +"refers\n" +" // to macOS (as opposed to iOS / wearOS / etc.) on Intel and " +"PowerPC.\n" +" #[cfg(all(target_os = \"macos\", target_arch = \"x86_64\"))]\n" +" #[link_name = \"readdir$INODE64\"]\n" " pub fn readdir(s: *mut DIR) -> *const dirent;\n" +"\n" " pub fn closedir(s: *mut DIR) -> c_int;\n" " }\n" "}\n" @@ -19208,8 +20240,8 @@ msgid "" "\n" " /// Returns whether there is currently an interrupt pending.\n" " ///\n" -" /// This should be true iff `matched` returns true and the interrupt is\n" -" /// masked.\n" +" /// This should be true if and only if `matched` returns true and the\n" +" /// interrupt is masked.\n" " pub fn interrupt_pending(&self) -> bool {\n" " // Safe because we know that self.registers points to the control\n" " // registers of a PL031 device which is appropriately mapped.\n" @@ -19320,8 +20352,8 @@ msgid "" "\n" " for i in 0..forks.len() {\n" " let tx = tx.clone();\n" -" let mut left_fork = forks[i].clone();\n" -" let mut right_fork = forks[(i + 1) % forks.len()].clone();\n" +" let mut left_fork = Arc::clone(&forks[i]);\n" +" let mut right_fork = Arc::clone(&forks[(i + 1) % forks.len()]);\n" "\n" " // To avoid a deadlock, we have to break the symmetry\n" " // somewhere. This will swap the forks without deinitializing\n" @@ -19353,6 +20385,209 @@ msgid "" "```" msgstr "" +#: src/exercises/concurrency/solutions-morning.md:104 +msgid "Link Checker" +msgstr "" + +#: src/exercises/concurrency/solutions-morning.md:106 +msgid "([back to exercise](link-checker.md))" +msgstr "" + +#: src/exercises/concurrency/solutions-morning.md:108 +msgid "" +"```rust,compile_fail\n" +"// Copyright 2022 Google LLC\n" +"//\n" +"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" +"// you may not use this file except in compliance with the License.\n" +"// You may obtain a copy of the License at\n" +"//\n" +"// http://www.apache.org/licenses/LICENSE-2.0\n" +"//\n" +"// Unless required by applicable law or agreed to in writing, software\n" +"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" +"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" +"// See the License for the specific language governing permissions and\n" +"// limitations under the License.\n" +"\n" +"use std::{sync::Arc, sync::Mutex, sync::mpsc, thread};\n" +"\n" +"// ANCHOR: setup\n" +"use reqwest::{blocking::Client, Url};\n" +"use scraper::{Html, Selector};\n" +"use thiserror::Error;\n" +"\n" +"#[derive(Error, Debug)]\n" +"enum Error {\n" +" #[error(\"request error: {0}\")]\n" +" ReqwestError(#[from] reqwest::Error),\n" +" #[error(\"bad http response: {0}\")]\n" +" BadResponse(String),\n" +"}\n" +"// ANCHOR_END: setup\n" +"\n" +"// ANCHOR: visit_page\n" +"#[derive(Debug)]\n" +"struct CrawlCommand {\n" +" url: Url,\n" +" extract_links: bool,\n" +"}\n" +"\n" +"fn visit_page(client: &Client, command: &CrawlCommand) -> Result, " +"Error> {\n" +" println!(\"Checking {:#}\", command.url);\n" +" let response = client.get(command.url.clone()).send()?;\n" +" if !response.status().is_success() {\n" +" return Err(Error::BadResponse(response.status().to_string()));\n" +" }\n" +"\n" +" let mut link_urls = Vec::new();\n" +" if !command.extract_links {\n" +" return Ok(link_urls);\n" +" }\n" +"\n" +" let base_url = response.url().to_owned();\n" +" let body_text = response.text()?;\n" +" let document = Html::parse_document(&body_text);\n" +"\n" +" let selector = Selector::parse(\"a\").unwrap();\n" +" let href_values = document\n" +" .select(&selector)\n" +" .filter_map(|element| element.value().attr(\"href\"));\n" +" for href in href_values {\n" +" match base_url.join(href) {\n" +" Ok(link_url) => {\n" +" link_urls.push(link_url);\n" +" }\n" +" Err(err) => {\n" +" println!(\"On {base_url:#}: ignored unparsable {href:?}: " +"{err}\");\n" +" }\n" +" }\n" +" }\n" +" Ok(link_urls)\n" +"}\n" +"// ANCHOR_END: visit_page\n" +"\n" +"struct CrawlState {\n" +" domain: String,\n" +" visited_pages: std::collections::HashSet,\n" +"}\n" +"\n" +"impl CrawlState {\n" +" fn new(start_url: &Url) -> CrawlState {\n" +" let mut visited_pages = std::collections::HashSet::new();\n" +" visited_pages.insert(start_url.as_str().to_string());\n" +" CrawlState {\n" +" domain: start_url.domain().unwrap().to_string(),\n" +" visited_pages,\n" +" }\n" +" }\n" +"\n" +" /// Determine whether links within the given page should be extracted.\n" +" fn should_extract_links(&self, url: &Url) -> bool {\n" +" let Some(url_domain) = url.domain() else {\n" +" return false;\n" +" };\n" +" url_domain == self.domain\n" +" }\n" +"\n" +" /// Mark the given page as visited, returning true if it had already\n" +" /// been visited.\n" +" fn mark_visited(&mut self, url: &Url) -> bool {\n" +" self.visited_pages.insert(url.as_str().to_string())\n" +" }\n" +"}\n" +"\n" +"type CrawlResult = Result, (Url, Error)>;\n" +"fn spawn_crawler_threads(\n" +" command_receiver: mpsc::Receiver,\n" +" result_sender: mpsc::Sender,\n" +" thread_count: u32,\n" +") {\n" +" let command_receiver = Arc::new(Mutex::new(command_receiver));\n" +"\n" +" for _ in 0..thread_count {\n" +" let result_sender = result_sender.clone();\n" +" let command_receiver = command_receiver.clone();\n" +" thread::spawn(move || {\n" +" let client = Client::new();\n" +" loop {\n" +" let command_result = {\n" +" let receiver_guard = command_receiver.lock().unwrap();\n" +" receiver_guard.recv()\n" +" };\n" +" let Ok(crawl_command) = command_result else {\n" +" // The sender got dropped. No more commands coming in.\n" +" break;\n" +" };\n" +" let crawl_result = match visit_page(&client, &crawl_command) " +"{\n" +" Ok(link_urls) => Ok(link_urls),\n" +" Err(error) => Err((crawl_command.url, error)),\n" +" };\n" +" result_sender.send(crawl_result).unwrap();\n" +" }\n" +" });\n" +" }\n" +"}\n" +"\n" +"fn control_crawl(\n" +" start_url: Url,\n" +" command_sender: mpsc::Sender,\n" +" result_receiver: mpsc::Receiver,\n" +") -> Vec {\n" +" let mut crawl_state = CrawlState::new(&start_url);\n" +" let start_command = CrawlCommand { url: start_url, extract_links: " +"true };\n" +" command_sender.send(start_command).unwrap();\n" +" let mut pending_urls = 1;\n" +"\n" +" let mut bad_urls = Vec::new();\n" +" while pending_urls > 0 {\n" +" let crawl_result = result_receiver.recv().unwrap();\n" +" pending_urls -= 1;\n" +"\n" +" match crawl_result {\n" +" Ok(link_urls) => {\n" +" for url in link_urls {\n" +" if crawl_state.mark_visited(&url) {\n" +" let extract_links = crawl_state." +"should_extract_links(&url);\n" +" let crawl_command = CrawlCommand { url, " +"extract_links };\n" +" command_sender.send(crawl_command).unwrap();\n" +" pending_urls += 1;\n" +" }\n" +" }\n" +" }\n" +" Err((url, error)) => {\n" +" bad_urls.push(url);\n" +" println!(\"Got crawling error: {:#}\", error);\n" +" continue;\n" +" }\n" +" }\n" +" }\n" +" bad_urls\n" +"}\n" +"\n" +"fn check_links(start_url: Url) -> Vec {\n" +" let (result_sender, result_receiver) = mpsc::channel::();\n" +" let (command_sender, command_receiver) = mpsc::channel::" +"();\n" +" spawn_crawler_threads(command_receiver, result_sender, 16);\n" +" control_crawl(start_url, command_sender, result_receiver)\n" +"}\n" +"\n" +"fn main() {\n" +" let start_url = reqwest::Url::parse(\"https://www.google.org\")." +"unwrap();\n" +" let bad_urls = check_links(start_url);\n" +" println!(\"Bad URLs: {:#?}\", bad_urls);\n" +"}\n" +"```" +msgstr "" + #: src/exercises/concurrency/solutions-afternoon.md:1 msgid "Concurrency Afternoon Exercise" msgstr "" @@ -19441,14 +20676,19 @@ msgid "" " let mut philosophers = vec![];\n" " let (tx, rx) = mpsc::channel(10);\n" " for (i, name) in PHILOSOPHERS.iter().enumerate() {\n" -" let left_fork = forks[i].clone();\n" -" let right_fork = forks[(i + 1) % PHILOSOPHERS.len()].clone();\n" +" let left_fork = Arc::clone(&forks[i]);\n" +" let right_fork = Arc::clone(&forks[(i + 1) % PHILOSOPHERS." +"len()]);\n" +" // To avoid a deadlock, we have to break the symmetry\n" +" // somewhere. This will swap the forks without deinitializing\n" +" // either of them.\n" +" if i == 0 {\n" +" std::mem::swap(&mut left_fork, &mut right_fork);\n" +" }\n" " philosophers.push(Philosopher {\n" " name: name.to_string(),\n" -" left_fork: if i % 2 == 0 { left_fork.clone() } else " -"{ right_fork.clone() },\n" -" right_fork: if i % 2 == 0 { right_fork } else " -"{ left_fork },\n" +" left_fork,\n" +" right_fork,\n" " thoughts: tx.clone(),\n" " });\n" " }\n" @@ -19475,11 +20715,11 @@ msgid "" "```" msgstr "" -#: src/exercises/concurrency/solutions-afternoon.md:115 +#: src/exercises/concurrency/solutions-afternoon.md:121 msgid "([back to exercise](chat-app.md))" msgstr "" -#: src/exercises/concurrency/solutions-afternoon.md:119 +#: src/exercises/concurrency/solutions-afternoon.md:125 msgid "" "```rust,compile_fail\n" "// Copyright 2023 Google LLC\n" @@ -19566,7 +20806,7 @@ msgid "" "```" msgstr "" -#: src/exercises/concurrency/solutions-afternoon.md:204 +#: src/exercises/concurrency/solutions-afternoon.md:210 msgid "" "```rust,compile_fail\n" "// Copyright 2023 Google LLC\n" @@ -19597,12 +20837,11 @@ msgid "" " .await?;\n" "\n" " let stdin = tokio::io::stdin();\n" -" let mut stdin = BufReader::new(stdin);\n" +" let mut stdin = BufReader::new(stdin).lines();\n" "\n" " // ANCHOR_END: setup\n" " // Continuous loop for concurrently sending and receiving messages.\n" " loop {\n" -" let mut line = String::new();\n" " tokio::select! {\n" " incoming = ws_stream.next() => {\n" " match incoming {\n" @@ -19612,10 +20851,10 @@ msgid "" " None => return Ok(()),\n" " }\n" " }\n" -" res = stdin.read_line(&mut line) => {\n" +" res = stdin.next_line() => {\n" " match res {\n" -" Ok(0) => return Ok(()),\n" -" Ok(_) => ws_stream.send(Message::text(line.trim_end()." +" Ok(None) => return Ok(()),\n" +" Ok(Some(line)) => ws_stream.send(Message::text(line." "to_string())).await?,\n" " Err(err) => return Err(err.into()),\n" " }\n"