From 2e002b61766f99b78f722a964fda8e5ca43c477a Mon Sep 17 00:00:00 2001 From: Mateusz Stomski Date: Mon, 30 Nov 2026 22:30:53 +0100 Subject: [PATCH] feat: reorganize workbook into 3 tracks (core, engineering-2026, ecosystems) --- AGENTS.md | 90 +-- Cargo.lock | 703 +++++++++++++++++- Cargo.toml | 8 +- Makefile | 33 +- README.md | 73 +- exercises/01-basics/README.md | 18 - exercises/01-basics/src/lib.rs | 53 -- exercises/{ => 01-core}/01-basics/Cargo.toml | 2 +- exercises/01-core/01-basics/README.md | 20 + exercises/01-core/01-basics/src/lib.rs | 77 ++ .../{ => 01-core}/02-ownership/Cargo.toml | 2 +- .../{ => 01-core}/02-ownership/README.md | 6 +- .../{ => 01-core}/02-ownership/src/lib.rs | 0 .../03-structs-enums}/Cargo.toml | 2 +- .../{ => 01-core}/03-structs-enums/README.md | 6 +- .../{ => 01-core}/03-structs-enums/src/lib.rs | 0 .../01-core/04-collections-errors/Cargo.toml | 4 + .../04-collections-errors/README.md | 8 +- .../04-collections-errors/src/lib.rs | 0 .../01-core/05-generics-traits/Cargo.toml | 4 + .../01-core/05-generics-traits/README.md | 16 + .../05-generics-traits/src/lib.rs | 0 .../01-core/06-iterators-closures/Cargo.toml | 4 + .../01-core/06-iterators-closures/README.md | 16 + .../01-core/06-iterators-closures/src/lib.rs | 39 + .../01-core/07-data-structures/Cargo.toml | 4 + .../01-core/07-data-structures/README.md | 16 + .../01-core/07-data-structures/src/lib.rs | 122 +++ .../01-core/08-oop-composition/Cargo.toml | 4 + .../01-core/08-oop-composition/README.md | 16 + .../01-core/08-oop-composition/src/lib.rs | 100 +++ .../01-core/09-design-patterns/Cargo.toml | 4 + .../01-core/09-design-patterns/README.md | 18 + .../01-core/09-design-patterns/src/lib.rs | 132 ++++ .../01-core/10-crud-repository/Cargo.toml | 4 + .../01-core/10-crud-repository/README.md | 20 + .../01-core/10-crud-repository/src/lib.rs | 85 +++ .../01-ai-code-audit}/Cargo.toml | 2 +- .../01-ai-code-audit/README.md | 19 + .../01-ai-code-audit/src/lib.rs | 51 ++ .../02-type-driven-design}/Cargo.toml | 2 +- .../02-type-driven-design/README.md | 12 + .../02-type-driven-design/src/lib.rs | 92 +++ .../03-cross-platform/Cargo.toml | 4 + .../03-cross-platform/README.md | 16 + .../03-cross-platform/src/lib.rs | 40 + .../04-best-practices/Cargo.toml | 4 + .../04-best-practices/README.md | 16 + .../04-best-practices/src/lib.rs | 50 ++ .../03-ecosystems/01-cli-clap/Cargo.toml | 7 + exercises/03-ecosystems/01-cli-clap/README.md | 18 + .../03-ecosystems/01-cli-clap/src/lib.rs | 78 ++ .../02-web-backend-axum/Cargo.toml | 14 + .../02-web-backend-axum/README.md | 18 + .../02-web-backend-axum/src/lib.rs | 110 +++ .../03-shared-core-ffi/Cargo.toml | 8 + .../03-shared-core-ffi/README.md | 17 + .../03-shared-core-ffi/src/lib.rs | 66 ++ .../03-ecosystems/04-wasm-logic/Cargo.toml | 8 + .../03-ecosystems/04-wasm-logic/README.md | 13 + .../03-ecosystems/04-wasm-logic/src/lib.rs | 44 ++ exercises/05-generics-traits/README.md | 16 - notes/01-rust-ecosystem-2026.md | 56 ++ notes/README.md | 1 + 64 files changed, 2295 insertions(+), 196 deletions(-) delete mode 100644 exercises/01-basics/README.md delete mode 100644 exercises/01-basics/src/lib.rs rename exercises/{ => 01-core}/01-basics/Cargo.toml (66%) create mode 100644 exercises/01-core/01-basics/README.md create mode 100644 exercises/01-core/01-basics/src/lib.rs rename exercises/{ => 01-core}/02-ownership/Cargo.toml (63%) rename exercises/{ => 01-core}/02-ownership/README.md (76%) rename exercises/{ => 01-core}/02-ownership/src/lib.rs (100%) rename exercises/{05-generics-traits => 01-core/03-structs-enums}/Cargo.toml (60%) rename exercises/{ => 01-core}/03-structs-enums/README.md (67%) rename exercises/{ => 01-core}/03-structs-enums/src/lib.rs (100%) create mode 100644 exercises/01-core/04-collections-errors/Cargo.toml rename exercises/{ => 01-core}/04-collections-errors/README.md (59%) rename exercises/{ => 01-core}/04-collections-errors/src/lib.rs (100%) create mode 100644 exercises/01-core/05-generics-traits/Cargo.toml create mode 100644 exercises/01-core/05-generics-traits/README.md rename exercises/{ => 01-core}/05-generics-traits/src/lib.rs (100%) create mode 100644 exercises/01-core/06-iterators-closures/Cargo.toml create mode 100644 exercises/01-core/06-iterators-closures/README.md create mode 100644 exercises/01-core/06-iterators-closures/src/lib.rs create mode 100644 exercises/01-core/07-data-structures/Cargo.toml create mode 100644 exercises/01-core/07-data-structures/README.md create mode 100644 exercises/01-core/07-data-structures/src/lib.rs create mode 100644 exercises/01-core/08-oop-composition/Cargo.toml create mode 100644 exercises/01-core/08-oop-composition/README.md create mode 100644 exercises/01-core/08-oop-composition/src/lib.rs create mode 100644 exercises/01-core/09-design-patterns/Cargo.toml create mode 100644 exercises/01-core/09-design-patterns/README.md create mode 100644 exercises/01-core/09-design-patterns/src/lib.rs create mode 100644 exercises/01-core/10-crud-repository/Cargo.toml create mode 100644 exercises/01-core/10-crud-repository/README.md create mode 100644 exercises/01-core/10-crud-repository/src/lib.rs rename exercises/{03-structs-enums => 02-engineering-2026/01-ai-code-audit}/Cargo.toml (60%) create mode 100644 exercises/02-engineering-2026/01-ai-code-audit/README.md create mode 100644 exercises/02-engineering-2026/01-ai-code-audit/src/lib.rs rename exercises/{04-collections-errors => 02-engineering-2026/02-type-driven-design}/Cargo.toml (56%) create mode 100644 exercises/02-engineering-2026/02-type-driven-design/README.md create mode 100644 exercises/02-engineering-2026/02-type-driven-design/src/lib.rs create mode 100644 exercises/02-engineering-2026/03-cross-platform/Cargo.toml create mode 100644 exercises/02-engineering-2026/03-cross-platform/README.md create mode 100644 exercises/02-engineering-2026/03-cross-platform/src/lib.rs create mode 100644 exercises/02-engineering-2026/04-best-practices/Cargo.toml create mode 100644 exercises/02-engineering-2026/04-best-practices/README.md create mode 100644 exercises/02-engineering-2026/04-best-practices/src/lib.rs create mode 100644 exercises/03-ecosystems/01-cli-clap/Cargo.toml create mode 100644 exercises/03-ecosystems/01-cli-clap/README.md create mode 100644 exercises/03-ecosystems/01-cli-clap/src/lib.rs create mode 100644 exercises/03-ecosystems/02-web-backend-axum/Cargo.toml create mode 100644 exercises/03-ecosystems/02-web-backend-axum/README.md create mode 100644 exercises/03-ecosystems/02-web-backend-axum/src/lib.rs create mode 100644 exercises/03-ecosystems/03-shared-core-ffi/Cargo.toml create mode 100644 exercises/03-ecosystems/03-shared-core-ffi/README.md create mode 100644 exercises/03-ecosystems/03-shared-core-ffi/src/lib.rs create mode 100644 exercises/03-ecosystems/04-wasm-logic/Cargo.toml create mode 100644 exercises/03-ecosystems/04-wasm-logic/README.md create mode 100644 exercises/03-ecosystems/04-wasm-logic/src/lib.rs delete mode 100644 exercises/05-generics-traits/README.md create mode 100644 notes/01-rust-ecosystem-2026.md diff --git a/AGENTS.md b/AGENTS.md index 325e5b6..e226795 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,75 +1,63 @@ -# AGENTS.md — Instrukcje dla agentów AI (Rust Learning Workbook) +# AGENTS.md — Instrukcje dla agentów AI (Rust Learning Workbook — Era 2026) -Ten projekt to **zeszyt ćwiczeń do samodzielnej nauki języka Rust**. Twoim głównym celem jako agenta AI jest wspieranie procesu nauki (tryb mentora), ochrona czystości szablonu w Gicie oraz zachowanie izolacji środowiska w kontenerze. +Ten projekt to **zeszyt ćwiczeń do nauki Rusta zaprojektowany pod realia 2026 roku**. +W 2026 roku samo ręczne pisanie boilerplate'u ma niską wartość — kluczowe są: **model mentalny języka** (ownership, typy, błędy), **projektowanie kontraktów (*Type-Driven Design*)**, **audyt kodu generowanego przez AI** oraz **świadome decyzje architektoniczne**. --- -## 1. Tryb pracy: Mentor, nie generator gotowców +## 1. Trzy tryby pracy agenta (dopasowane do ścieżki) -1. **Nie rozwiązuj zadań za użytkownika domyślnie:** - * Nigdy nie nadpisuj funkcji w `exercises/*/src/lib.rs` gotowym rozwiązaniem, chyba że użytkownik wyraźnie o to poprosi (np. *"pokaż pełne rozwiązanie"*, *"napisz to za mnie"*). -2. **Stopniowane podpowiedzi (metoda sokratejska):** - * **Poziom 1 (Naprowadzenie):** Wyjaśnij komunikat kompilatora / borrow checkera ludzkim językiem i wskaż koncepcję lub metodę ze standardowej biblioteki (`std`), która pomoże ruszyć dalej. - * **Poziom 2 (Analogiczny przykład):** Jeśli użytkownik nadal utknął, pokaż krótki przykład na *innym* typie lub problemie — nie wklejaj gotowej odpowiedzi do bieżącego ćwiczenia. - * **Poziom 3 (Pełne rozwiązanie):** Dopiero na wyraźną prośbę użytkownika. -3. **Code review rozwiązań użytkownika:** - * Po przejściu testów w danym rozdziale możesz (na prośbę lub jako krótką sugestię) ocenić kod pod kątem idiomatycznego Rusta: - * czy usunięto tymczasowe `#![allow(unused_variables, dead_code)]`, - * czy `make clippy` przechodzi bez ostrzeżeń, - * czy nie ma zbędnych `.clone()` lub nieidiomatycznych pętli tam, gdzie czytelniejszy jest iterator / `match`. +Zamiast jednego sztywnego zachowania, dopasuj tryb mentoringu do ścieżki, nad którą pracuje użytkownik: + +### A. `exercises/01-core/` — Tryb Sokratejski (Rdzeń języka) +* **Nie rozwiązuj zadań za użytkownika domyślnie.** Tutaj budowana jest intuicja dotycząca ownershipu, borrow checkera, typów i iteratorów. +* Stosuj stopniowane podpowiedzi: + 1. **Naprowadzenie:** wyjaśnij błąd kompilatora ludzkim językiem, wskaż właściwą koncepcję lub metodę z `std`. + 2. **Analogiczny przykład:** pokaż krótki przykład na *innym* problemie (nie gotowiec do bieżącego zadania). + 3. **Pełne rozwiązanie:** wyłącznie na wyraźną prośbę użytkownika. +* Po przejściu testów zaproponuj krótkie **code review** (idiomatyczność, `clippy`, brak zbędnych `.clone()`, usunięcie tymczasowego `#![allow(...)]`). + +### B. `exercises/02-engineering-2026/` — Tryb Specyfikacja → Audyt / Review (Era AI) +* Tutaj celem nie jest wkuwanie składni, lecz **myślenie inżynierskie i kontrola jakości nad AI**. +* W `01-ai-code-audit` pomagaj użytkownikowi analizować ryzyka (paniki, `.unwrap()`, przypadki brzegowe, sygnatury API), pytając *"co może pójść nie tak dla wejścia X?"*. +* W `02-type-driven-design` możesz działać w modelu odwróconym: jeśli użytkownik zaprojektuje typy, kontrakty i testy, możesz na jego prośbę wygenerować implementację, a potem wspólnie ją zrecenzować. +* W `03-cross-platform` i `04-best-practices` pilnuj przenośności (`PathBuf`, brak hardcodowanych `/`/`\`), czytelnych błędów i braku `panic!` na granicach API. + +### C. `exercises/03-ecosystems/` — Tryb Architekta i Przewodnika po Ekosystemie +* Skup się na **dlaczego i kiedy** używa się danego narzędzia (`clap`, `axum`, `tokio`, `serde`, `thiserror`, `UniFFI`, `Tauri`, `WASM`) oraz jakie są trade-offy (w tym: kiedy *nie* wybierać Rusta). +* Nie każ użytkownikowi wkuwać na pamięć atrybutów makr czy konfiguracji — tłumacz architekturę, przepływ danych i granice modułów, a naprowadzaj przy logice i testach. --- ## 2. Model A — Architektura gałęzi Git (Zasada krytyczna) -Repozytorium celowo oddziela **szablon zadań** od **rozwiązań użytkownika**, aby można było wrócić do kursu w przyszłości i zacząć od zera: - * **`main` (Czysty szablon — NIE commituj tu rozwiązań):** - * Zawiera wyłącznie nierozwiązane zadania (`exercises/` ze stubami `todo!()` i testami), konfigurację kontenera (`Containerfile`, `Makefile`), `AGENTS.md` oraz wspólne notatki (`notes/`). + * Zawiera nierozwiązane zadania (`exercises/` ze stubami `todo!()` lub celowo wadliwym kodem do audytu), konfigurację kontenera, `AGENTS.md` oraz wspólne notatki (`notes/`). * **`attempt/` (Gałąź robocza podejścia):** * Tutaj użytkownik rozwiązuje zadania i commituj postępy (np. `attempt/2026-11`). * **Obowiązkowa kontrola przed edycją:** - * Zanim pomożesz edytować pliki w `exercises/` w ramach rozwiązywania zadań, sprawdź bieżącą gałąź (`git branch --show-current`). Jeśli użytkownik znajduje się na `main`, ostrzeż go i zaproponuj przełączenie na gałąź `attempt/*`. + * Zanim pomożesz edytować zadania, sprawdź `git branch --show-current`. Jeśli użytkownik jest na `main`, ostrzeż go i zaproponuj przełączenie na `attempt/*`. * **Rozbudowa kursu i notatek:** - * Nowe rozdziały zadań oraz ogólne notatki w `notes/` dodawaj na `main`, a następnie dołączaj do aktywnej gałęzi `attempt/*` (`git merge main`). + * Nowe rozdziały oraz notatki w `notes/` trafiają na `main`, a potem są dołączane do aktywnej gałęzi (`git merge main`). --- ## 3. Zero Host Pollution (Wyłącznie kontener Podman) -* **Zakaz uruchamiania toolchainu na hoście:** Nie instaluj `rustup`/`cargo`/`rustc` na hoście i nie uruchamiaj `cargo` bezpośrednio na systemie gospodarza. -* **Używaj wyłącznie `Makefile` (Podman):** - * `make image` — budowa obrazu `rust-learning:latest` (jeśli jeszcze nie istnieje) - * `make check` — sprawdzenie kompilacji całego workspace - * `make test PKG=` — uruchomienie testów wybranego rozdziału (np. `make test PKG=ex01-basics`) - * `make test` — uruchomienie wszystkich testów w workspace - * `make clippy` — uruchomienie lintera Clippy - * `make fmt` / `make fmt-check` — formatowanie kodu (`rustfmt`) - * `make shell` — interaktywna powłoka w kontenerze +* **Zakaz uruchamiania `cargo`/`rustc` na hoście** i zakaz instalowania toolchainu na systemie gospodarza. +* Używaj wyłącznie `Makefile`: + * `make check` — szybki check `01-core` + `02-engineering-2026` (czyste `std`, <1s) + * `make check-all` — pełny check z `03-ecosystems` + * `make test PKG=` — testy wybranego rozdziału (np. `make test PKG=core01-basics`, `make test PKG=eco01-cli-clap`) + * `make clippy` / `make clippy-all` — linter Clippy + * `make fmt` / `make fmt-check` — formatowanie `rustfmt` --- -## 4. Jak dodawać nowe rozdziały i ćwiczenia +## 4. Jak dodawać nowe rozdziały i notatki -Gdy użytkownik poprosi o nowy temat (np. iteratory, smart pointery, współbieżność, async, mini-projekt): - -1. Upewnij się, że pracujesz na gałęzi `main` (lub wyraźnie ustal to z użytkownikiem). -2. Utwórz katalog `exercises/-/` (workspace w root `Cargo.toml` automatycznie wykrywa `exercises/*`). -3. Każdy rozdział musi zawierać: - * `Cargo.toml` z nazwą `ex-` i `edition = "2021"`. - * `README.md` z krótkim zakresem materiału, opisem zadań i komendą `make test PKG=ex-`. - * `src/lib.rs` ze szkieletami funkcji (`todo!("...")`), tymczasowym `#![allow(unused_variables, dead_code)]` oraz zestawem testów jednostkowych (`#[cfg(test)]`) obejmujących przypadki standardowe i brzegowe. -4. Dopisz nowy rozdział do checklisty w głównym `README.md`. -5. Zweryfikuj czystość szablonu w kontenerze: - ```bash - make check && make clippy && make fmt-check - ``` - Szablon musi kompilować się bez ostrzeżeń (a `make test` ma wykazywać niezaimplementowane `todo!()`). - ---- - -## 5. Praca z notatkami (`notes/`) - -* Katalog `notes/` służy na własne notatki użytkownika, ściągawki oraz analizę błędów kompilatora (np. `E0382`, `E0502`, lifetimes). -* Gdy użytkownik prosi o zanotowanie wniosku lub stworzenie ściągawki, dodawaj zwięzłe pliki Markdown w `notes/` i aktualizuj link w `notes/README.md`. -* Pisz notatki i komunikaty po polsku, zachowując angielskie nazwy terminów technicznych Rusta (*ownership*, *borrowing*, *lifetime*, *trait*, *slice*), aby ułatwić czytanie oficjalnej dokumentacji i komunikatów `rustc`. +1. Nowy rozdział dodawaj na `main` w odpowiedniej ścieżce (`exercises/01-core/`, `exercises/02-engineering-2026/` lub `exercises/03-ecosystems/`). +2. Konwencja nazw crate'ów: `core-`, `eng-`, `eco-`. +3. Każdy rozdział zawiera `Cargo.toml`, `README.md` (zakres + zadania + komenda `make test PKG=...`) oraz `src/lib.rs` (szkielet + testy). +4. Zaktualizuj checklistę w `README.md` i zweryfikuj przez `make check-all && make clippy-all && make fmt-check`. +5. Notatki umieszczaj w `notes/` (po polsku z angielską terminologią Rusta) i dopisuj do `notes/README.md`. diff --git a/Cargo.lock b/Cargo.lock index d5860b5..d9b9435 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3,21 +3,714 @@ version = 4 [[package]] -name = "ex01-basics" +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "clap" +version = "4.6.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "core01-basics" version = "0.1.0" [[package]] -name = "ex02-ownership" +name = "core02-ownership" version = "0.1.0" [[package]] -name = "ex03-structs-enums" +name = "core03-structs-enums" version = "0.1.0" [[package]] -name = "ex04-collections-errors" +name = "core04-collections-errors" version = "0.1.0" [[package]] -name = "ex05-generics-traits" +name = "core05-generics-traits" version = "0.1.0" + +[[package]] +name = "core06-iterators-closures" +version = "0.1.0" + +[[package]] +name = "core07-data-structures" +version = "0.1.0" + +[[package]] +name = "core08-oop-composition" +version = "0.1.0" + +[[package]] +name = "core09-design-patterns" +version = "0.1.0" + +[[package]] +name = "core10-crud-repository" +version = "0.1.0" + +[[package]] +name = "eco01-cli-clap" +version = "0.1.0" +dependencies = [ + "clap", +] + +[[package]] +name = "eco02-web-backend-axum" +version = "0.1.0" +dependencies = [ + "axum", + "http-body-util", + "serde", + "serde_json", + "tokio", + "tower", +] + +[[package]] +name = "eco03-shared-core-ffi" +version = "0.1.0" +dependencies = [ + "serde", + "thiserror", +] + +[[package]] +name = "eco04-wasm-logic" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "eng01-ai-code-audit" +version = "0.1.0" + +[[package]] +name = "eng02-type-driven-design" +version = "0.1.0" + +[[package]] +name = "eng03-cross-platform" +version = "0.1.0" + +[[package]] +name = "eng04-best-practices" +version = "0.1.0" + +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "229c6ff5584df4c6becbfe00567128bac768c8cd32ebc8a8366bd81ed072e8f3" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "bytes", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "wasi", + "windows-sys", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml index 4c6d3d5..93c1cdc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,11 @@ [workspace] resolver = "2" members = [ - "exercises/*", + "exercises/01-core/*", + "exercises/02-engineering-2026/*", + "exercises/03-ecosystems/*", +] +default-members = [ + "exercises/01-core/*", + "exercises/02-engineering-2026/*", ] diff --git a/Makefile b/Makefile index 984725c..aa3cd4d 100644 --- a/Makefile +++ b/Makefile @@ -9,33 +9,46 @@ RUN_CONTAINER = $(ENGINE) run --rm \ -w /workspace \ $(IMAGE) -.PHONY: help image check test clippy fmt fmt-check shell clean +.PHONY: help image check check-all test test-all clippy clippy-all fmt fmt-check shell clean help: @echo "Dostępne komendy:" - @echo " make image - Zbuduj obraz kontenera Rust (jednorazowo)" - @echo " make check - Sprawdź kompilację całego workspace" - @echo " make test - Uruchom testy wszystkich ćwiczeń" - @echo " make test PKG=ex01-basics - Uruchom testy wybranego rozdziału" - @echo " make clippy - Uruchom linter Clippy" - @echo " make fmt - Sformatuj kod (rustfmt)" - @echo " make shell - Otwórz powłokę bash wewnątrz kontenera" - @echo " make clean - Usuń katalog target/" + @echo " make image - Zbuduj obraz kontenera Rust (jednorazowo)" + @echo " make check - Szybki check 01-core + 02-engineering-2026 (czyste std)" + @echo " make check-all - Pełny check całego workspace (razem z 03-ecosystems)" + @echo " make test PKG=core01-basics - Uruchom testy wybranego rozdziału" + @echo " make test - Uruchom testy domyślnych ścieżek (01 + 02)" + @echo " make test-all - Uruchom testy całego workspace (01 + 02 + 03)" + @echo " make clippy - Linter Clippy dla 01-core + 02-engineering-2026" + @echo " make clippy-all - Linter Clippy dla całego workspace" + @echo " make fmt - Sformatuj kod (rustfmt)" + @echo " make fmt-check - Sprawdź formatowanie kodu" + @echo " make shell - Otwórz powłokę bash wewnątrz kontenera" + @echo " make clean - Usuń katalog target/" image: $(ENGINE) build -t $(IMAGE) -f Containerfile . check: + $(RUN_CONTAINER) cargo check --tests + +check-all: $(RUN_CONTAINER) cargo check --workspace --tests test: ifdef PKG $(RUN_CONTAINER) cargo test -p $(PKG) -- --nocapture else - $(RUN_CONTAINER) cargo test --workspace + $(RUN_CONTAINER) cargo test endif +test-all: + $(RUN_CONTAINER) cargo test --workspace + clippy: + $(RUN_CONTAINER) cargo clippy --all-targets + +clippy-all: $(RUN_CONTAINER) cargo clippy --workspace --all-targets fmt: diff --git a/README.md b/README.md index 03f0c2b..61bd5c4 100644 --- a/README.md +++ b/README.md @@ -1,57 +1,76 @@ -# Rust Learning Workbook +# Rust Learning Workbook (2026 Edition) -Zeszyt ćwiczeń do nauki języka Rust oparty na **Cargo Workspace** i izolowanym środowisku **Podman** (Zero Host Pollution). +Zeszyt ćwiczeń do nauki języka Rust oparty na **Cargo Workspace**, izolowanym środowisku **Podman** (Zero Host Pollution) i podejściu dopasowanym do **2026 roku** — nacisk na model mentalny, projektowanie typów, audyt kodu AI oraz świadome korzystanie z ekosystemu. ## Architektura pracy (Model A — podział na gałęzie) -* **`main`** — czysty szablon: nierozwiązane zadania (`exercises/`) oraz wspólne notatki (`notes/`). **Nie commituj tutaj rozwiązań zadań.** -* **`attempt/`** — gałąź robocza dla konkretnego podejścia do kursu (np. `attempt/2026-11`). Tutaj rozwiązujesz ćwiczenia i commitujesz postępy. +* **`main`** — czysty szablon: nierozwiązane zadania (`exercises/`), wspólne notatki (`notes/`), `AGENTS.md`. **Nie commituj tutaj rozwiązań zadań.** +* **`attempt/`** — gałąź robocza dla konkretnego podejścia (np. `attempt/2026-11`). * **Powrót po czasie / start od nowa:** ```bash git checkout main git checkout -b attempt/2027-01 ``` - Twoje poprzednie podejścia zostają bezpiecznie w historii gałęzi na Gitei, a nowe zaczynasz z czystym zestawem zadań. -* **Notatki (`notes/`):** możesz je rozwijać na `main` (albo cherry-pickować / merge'ować między gałęziami), żeby zawsze były wspólne i aktualne. ## Szybki start (Podman) -Nie musisz instalować Rusta ani `cargo` na hoście — wszystko uruchamia się w kontenerze: - ```bash # 1. Zbuduj lokalny obraz z rustc, cargo, clippy i rustfmt (raz) make image -# 2. Sprawdź, czy cały workspace się kompiluje +# 2. Szybki check rdzenia (01-core + 02-engineering-2026, czyste std) make check # 3. Uruchom testy wybranego rozdziału -make test PKG=ex01-basics +make test PKG=core01-basics +make test PKG=eng01-ai-code-audit +make test PKG=eco01-cli-clap -# 4. Sformatuj kod i sprawdź podpowiedzi lintera +# 4. Pełny check razem z modułami ekosystemu (03-ecosystems) +make check-all +make clippy-all make fmt -make clippy ``` -Gdy rozwiązujesz zadanie w pliku `exercises//src/lib.rs`, usuń z góry pliku `#![allow(unused_variables, dead_code)]`, żeby kompilator i `clippy` pilnowały czystości kodu. +--- -## Spis rozdziałów i postęp +## Ścieżki i checklista postępów -- [ ] `ex01-basics` — [01-basics](exercises/01-basics/README.md): zmienne, typy, funkcje, przepływ sterowania -- [ ] `ex02-ownership` — [02-ownership](exercises/02-ownership/README.md): ownership, borrowing, slices -- [ ] `ex03-structs-enums` — [03-structs-enums](exercises/03-structs-enums/README.md): struktury, enumy, `match`, `Option`, `Result` -- [ ] `ex04-collections-errors` — [04-collections-errors](exercises/04-collections-errors/README.md): `Vec`, `HashMap`, `String`, propagacja błędów (`?`) -- [ ] `ex05-generics-traits` — [05-generics-traits](exercises/05-generics-traits/README.md): generyki, traity, lifetimes +### Ścieżka 1: `01-core/` — Rdzeń języka (czyste `std`) +- [ ] `core01-basics` — [01-basics](exercises/01-core/01-basics/README.md): zmienne, pętle (`loop`/`while`/`for`), warunki, `match` z zakresami, funkcje +- [ ] `core02-ownership` — [02-ownership](exercises/01-core/02-ownership/README.md): ownership, borrowing, slices +- [ ] `core03-structs-enums` — [03-structs-enums](exercises/01-core/03-structs-enums/README.md): struktury, enumy, `match`, `Option` +- [ ] `core04-collections-errors` — [04-collections-errors](exercises/01-core/04-collections-errors/README.md): `Vec`, `HashMap`, `String`, `Result` i `?` +- [ ] `core05-generics-traits` — [05-generics-traits](exercises/01-core/05-generics-traits/README.md): generyki, traity, lifetimes +- [ ] `core06-iterators-closures` — [06-iterators-closures](exercises/01-core/06-iterators-closures/README.md): iteratory i domknięcia +- [ ] `core07-data-structures` — [07-data-structures](exercises/01-core/07-data-structures/README.md): `Stack`, `Queue`, `LinkedList` na `Box` +- [ ] `core08-oop-composition` — [08-oop-composition](exercises/01-core/08-oop-composition/README.md): „OOP po rustowemu” — enkapsulacja, kompozycja, `Box` +- [ ] `core09-design-patterns` — [09-design-patterns](exercises/01-core/09-design-patterns/README.md): Newtype, Builder, Typestate, Strategy +- [ ] `core10-crud-repository` — [10-crud-repository](exercises/01-core/10-crud-repository/README.md): pełny CRUD w pamięci + walidacja i błędy -## Notatki +### Ścieżka 2: `02-engineering-2026/` — Dobre praktyki i umiejętności ery AI +- [ ] `eng01-ai-code-audit` — [01-ai-code-audit](exercises/02-engineering-2026/01-ai-code-audit/README.md): audyt i refaktoryzacja kodu wygenerowanego przez AI +- [ ] `eng02-type-driven-design` — [02-type-driven-design](exercises/02-engineering-2026/02-type-driven-design/README.md): walidacja w typach (`Email`, `Money`) +- [ ] `eng03-cross-platform` — [03-cross-platform](exercises/02-engineering-2026/03-cross-platform/README.md): Linux / Windows / macOS (`PathBuf`, `#[cfg(target_os)]`) +- [ ] `eng04-best-practices` — [04-best-practices](exercises/02-engineering-2026/04-best-practices/README.md): `Display`, `Error`, `From`, brak panik na granicach + +### Ścieżka 3: `03-ecosystems/` — CLI, Web, Mobile/Desktop i WASM +- [ ] `eco01-cli-clap` — [01-cli-clap](exercises/03-ecosystems/01-cli-clap/README.md): parsowanie argumentów CLI z `clap` +- [ ] `eco02-web-backend-axum` — [02-web-backend-axum](exercises/03-ecosystems/02-web-backend-axum/README.md): REST API w `axum` + `tokio` + `serde` +- [ ] `eco03-shared-core-ffi` — [03-shared-core-ffi](exercises/03-ecosystems/03-shared-core-ffi/README.md): wspólny rdzeń pod iOS/Android (`UniFFI`) i Desktop (`Tauri`) z `thiserror` +- [ ] `eco04-wasm-logic` — [04-wasm-logic](exercises/03-ecosystems/04-wasm-logic/README.md): moduł logiki pod WebAssembly (Frontend) + +--- + +## Notatki i Mapa Ekosystemu * [Indeks notatek](notes/README.md) -* [Ściągawka Rust & Cargo](notes/00-cheatsheet.md) +* [00 — Ściągawka Rust & Cargo](notes/00-cheatsheet.md) +* [01 — Ekosystem Rusta i najważniejsze biblioteki (2026)](notes/01-rust-ecosystem-2026.md) -## Nauka z asystentem AI (metoda sokratejska) +## Nauka z asystentem AI (metoda sokratejska i era 2026) -Repozytorium zawiera plik [AGENTS.md](AGENTS.md), który konfiguruje agentów AI do pracy w **trybie mentora** zamiast generatora gotowego kodu: - -* **Metoda sokratejska (stopniowane podpowiedzi):** zamiast podawać gotowe rozwiązanie, asystent najpierw tłumaczy komunikat kompilatora / borrow checkera i naprowadza pytaniami lub wskazaniem właściwej koncepcji z `std`, następnie może pokazać analogiczny przykład na innym problemie, a pełne rozwiązanie podaje dopiero na wyraźną prośbę. -* **Code review po przejściu testów:** sprawdzenie idiomatyczności kodu, ostrzeżeń `clippy`, zbędnych `.clone()` i alternatywnych podejść (np. iteratorów). -* **Ochrona struktury repozytorium:** pilnowanie rozdziału gałęzi (`main` jako czysty szablon vs `attempt/*` na rozwiązania) oraz uruchamiania wszystkich komend wyłącznie przez kontener Podman (`Makefile`). +Repozytorium zawiera plik [AGENTS.md](AGENTS.md), który konfiguruje agentów AI do pracy w **3 trybach dopasowanych do ścieżki**: +* **Tryb Sokratejski (`01-core/`)** — stopniowane podpowiedzi zamiast gotowców + code review po przejściu testów. +* **Tryb Specyfikacja → Audyt (`02-engineering-2026/`)** — nacisk na krytyczny przegląd kodu AI, bezpieczeństwo typów i przenośność. +* **Tryb Architekta (`03-ecosystems/`)** — zrozumienie frameworków, granic modułów i świadomego doboru narzędzi. diff --git a/exercises/01-basics/README.md b/exercises/01-basics/README.md deleted file mode 100644 index c07ec0b..0000000 --- a/exercises/01-basics/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# 01 — Podstawy (Basics) - -## Zakres -* Zmienne (`let`, `let mut`), shadowing -* Typy skalarne (`i32`, `u32`, `f64`, `bool`, `char`) -* Funkcje, wyrażenia vs instrukcje (*expressions vs statements*) -* Przepływ sterowania (`if`, `loop`, `while`, `for`) - -## Zadania (`src/lib.rs`) -1. `celsius_to_fahrenheit(c: f64) -> f64` — przelicz temperaturę ze stopni Celsjusza na Fahrenheita ($F = C \cdot 1.8 + 32$). -2. `is_even(n: i32) -> bool` — zwróć `true`, jeśli liczba jest parzysta. -3. `sum_up_to(n: u32) -> u32` — oblicz sumę liczb od `1` do `n` włącznie (dla `0` zwróć `0`). -4. `fizzbuzz_label(n: u32) -> String` — klasyczny FizzBuzz dla pojedynczej liczby (`"Fizz"`, `"Buzz"`, `"FizzBuzz"` lub zapis liczby). - -## Uruchomienie testów -```bash -make test PKG=ex01-basics -``` diff --git a/exercises/01-basics/src/lib.rs b/exercises/01-basics/src/lib.rs deleted file mode 100644 index 615b959..0000000 --- a/exercises/01-basics/src/lib.rs +++ /dev/null @@ -1,53 +0,0 @@ -#![allow(unused_variables, dead_code)] - -pub fn celsius_to_fahrenheit(c: f64) -> f64 { - todo!("Przelicz stopnie Celsjusza na Fahrenheita: c * 1.8 + 32.0") -} - -pub fn is_even(n: i32) -> bool { - todo!("Zwróć true jeśli n jest parzyste") -} - -pub fn sum_up_to(n: u32) -> u32 { - todo!("Zsumuj liczby od 1 do n włącznie") -} - -pub fn fizzbuzz_label(n: u32) -> String { - todo!("Zwróć Fizz / Buzz / FizzBuzz lub n.to_string()") -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn converts_temperatures() { - assert!((celsius_to_fahrenheit(0.0) - 32.0).abs() < f64::EPSILON); - assert!((celsius_to_fahrenheit(100.0) - 212.0).abs() < f64::EPSILON); - assert!((celsius_to_fahrenheit(-40.0) - (-40.0)).abs() < f64::EPSILON); - } - - #[test] - fn checks_even_numbers() { - assert!(is_even(0)); - assert!(is_even(42)); - assert!(is_even(-8)); - assert!(!is_even(7)); - assert!(!is_even(-3)); - } - - #[test] - fn sums_range() { - assert_eq!(sum_up_to(0), 0); - assert_eq!(sum_up_to(1), 1); - assert_eq!(sum_up_to(10), 55); - } - - #[test] - fn formats_fizzbuzz() { - assert_eq!(fizzbuzz_label(1), "1"); - assert_eq!(fizzbuzz_label(3), "Fizz"); - assert_eq!(fizzbuzz_label(5), "Buzz"); - assert_eq!(fizzbuzz_label(15), "FizzBuzz"); - } -} diff --git a/exercises/01-basics/Cargo.toml b/exercises/01-core/01-basics/Cargo.toml similarity index 66% rename from exercises/01-basics/Cargo.toml rename to exercises/01-core/01-basics/Cargo.toml index 8f2d2fe..3bbf303 100644 --- a/exercises/01-basics/Cargo.toml +++ b/exercises/01-core/01-basics/Cargo.toml @@ -1,4 +1,4 @@ [package] -name = "ex01-basics" +name = "core01-basics" version = "0.1.0" edition = "2021" diff --git a/exercises/01-core/01-basics/README.md b/exercises/01-core/01-basics/README.md new file mode 100644 index 0000000..322aa7d --- /dev/null +++ b/exercises/01-core/01-basics/README.md @@ -0,0 +1,20 @@ +# 01 — Podstawy, pętle, warunki i funkcje + +## Zakres +* Zmienne (`let`, `let mut`), shadowing, typy skalarne, krotki i tablice +* Funkcje, wyrażenia vs instrukcje (*expressions vs statements*) +* Instrukcje warunkowe (`if` jako wyrażenie, `match` z zakresami i strażnikami `if`) +* Pętle (`loop` zwracające wartość, `while`, `for`) + +## Zadania (`src/lib.rs`) +1. `celsius_to_fahrenheit(c: f64) -> f64` — przelicz temperaturę ($F = C \cdot 1.8 + 32$). +2. `classify_score(score: u8) -> &'static str` — użyj `match` z zakresami: `0..=49` -> `"fail"`, `50..=74` -> `"pass"`, `75..=89` -> `"good"`, `90..=100` -> `"excellent"`, powyżej `100` -> `"invalid"`. +3. `sum_up_to(n: u32) -> u32` — suma liczb od `1` do `n` włącznie (pętla `for`). +4. `first_power_of_two_gte(target: u32) -> u32` — znajdź najmniejszą potęgę dwójki $\ge \text{target}$ używając pętli `loop` lub `while` (np. dla `1` -> `1`, dla `5` -> `8`, dla `16` -> `16`). +5. `min_max(values: &[i32]) -> Option<(i32, i32)>` — zwróć krotkę `(min, max)` dla niepustego wycinka lub `None` dla pustego. +6. `fizzbuzz_label(n: u32) -> String` — `"Fizz"`, `"Buzz"`, `"FizzBuzz"` lub zapis liczby. + +## Uruchomienie testów +```bash +make test PKG=core01-basics +``` diff --git a/exercises/01-core/01-basics/src/lib.rs b/exercises/01-core/01-basics/src/lib.rs new file mode 100644 index 0000000..c145b95 --- /dev/null +++ b/exercises/01-core/01-basics/src/lib.rs @@ -0,0 +1,77 @@ +#![allow(unused_variables, dead_code)] + +pub fn celsius_to_fahrenheit(c: f64) -> f64 { + todo!("Przelicz stopnie Celsjusza na Fahrenheita: c * 1.8 + 32.0") +} + +pub fn classify_score(score: u8) -> &'static str { + todo!("Użyj match z zakresami 0..=49, 50..=74, 75..=89, 90..=100, _") +} + +pub fn sum_up_to(n: u32) -> u32 { + todo!("Zsumuj liczby od 1 do n włącznie") +} + +pub fn first_power_of_two_gte(target: u32) -> u32 { + todo!("Znajdź najmniejszą potęgę dwójki >= target (dla 0 lub 1 zwróć 1)") +} + +pub fn min_max(values: &[i32]) -> Option<(i32, i32)> { + todo!("Zwróć Some((min, max)) lub None dla pustego wycinka") +} + +pub fn fizzbuzz_label(n: u32) -> String { + todo!("Zwróć Fizz / Buzz / FizzBuzz lub n.to_string()") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn converts_temperatures() { + assert!((celsius_to_fahrenheit(0.0) - 32.0).abs() < f64::EPSILON); + assert!((celsius_to_fahrenheit(100.0) - 212.0).abs() < f64::EPSILON); + assert!((celsius_to_fahrenheit(-40.0) - (-40.0)).abs() < f64::EPSILON); + } + + #[test] + fn classifies_scores_with_ranges() { + assert_eq!(classify_score(0), "fail"); + assert_eq!(classify_score(49), "fail"); + assert_eq!(classify_score(50), "pass"); + assert_eq!(classify_score(80), "good"); + assert_eq!(classify_score(95), "excellent"); + assert_eq!(classify_score(101), "invalid"); + } + + #[test] + fn sums_range() { + assert_eq!(sum_up_to(0), 0); + assert_eq!(sum_up_to(1), 1); + assert_eq!(sum_up_to(10), 55); + } + + #[test] + fn finds_power_of_two() { + assert_eq!(first_power_of_two_gte(0), 1); + assert_eq!(first_power_of_two_gte(1), 1); + assert_eq!(first_power_of_two_gte(5), 8); + assert_eq!(first_power_of_two_gte(16), 16); + } + + #[test] + fn computes_min_and_max() { + assert_eq!(min_max(&[]), None); + assert_eq!(min_max(&[42]), Some((42, 42))); + assert_eq!(min_max(&[3, -10, 7, 25, 0]), Some((-10, 25))); + } + + #[test] + fn formats_fizzbuzz() { + assert_eq!(fizzbuzz_label(1), "1"); + assert_eq!(fizzbuzz_label(3), "Fizz"); + assert_eq!(fizzbuzz_label(5), "Buzz"); + assert_eq!(fizzbuzz_label(15), "FizzBuzz"); + } +} diff --git a/exercises/02-ownership/Cargo.toml b/exercises/01-core/02-ownership/Cargo.toml similarity index 63% rename from exercises/02-ownership/Cargo.toml rename to exercises/01-core/02-ownership/Cargo.toml index fa48cfc..9dd2b72 100644 --- a/exercises/02-ownership/Cargo.toml +++ b/exercises/01-core/02-ownership/Cargo.toml @@ -1,4 +1,4 @@ [package] -name = "ex02-ownership" +name = "core02-ownership" version = "0.1.0" edition = "2021" diff --git a/exercises/02-ownership/README.md b/exercises/01-core/02-ownership/README.md similarity index 76% rename from exercises/02-ownership/README.md rename to exercises/01-core/02-ownership/README.md index 7eeb7d7..97b21a6 100644 --- a/exercises/02-ownership/README.md +++ b/exercises/01-core/02-ownership/README.md @@ -6,11 +6,11 @@ * Wycinki (*slices*): `&str`, `&[T]` ## Zadania (`src/lib.rs`) -1. `first_word(s: &str) -> &str` — zwróć pierwsze słowo (do pierwszej spacji) lub cały napis, jeśli brak spacji. -2. `append_exclamation(s: &mut String)` — dopisz `'!'` na końcu przekazanego `String` bez przejmowania jego własności. +1. `first_word(s: &str) -> &str` — zwróć pierwsze słowo (do pierwszej spacji) lub cały napis. +2. `append_exclamation(s: &mut String)` — dopisz `'!'` na końcu przekazanego `String` bez przejmowania własności. 3. `sum_slice(values: &[i32]) -> i32` — policz sumę elementów wycinka `&[i32]`. ## Uruchomienie testów ```bash -make test PKG=ex02-ownership +make test PKG=core02-ownership ``` diff --git a/exercises/02-ownership/src/lib.rs b/exercises/01-core/02-ownership/src/lib.rs similarity index 100% rename from exercises/02-ownership/src/lib.rs rename to exercises/01-core/02-ownership/src/lib.rs diff --git a/exercises/05-generics-traits/Cargo.toml b/exercises/01-core/03-structs-enums/Cargo.toml similarity index 60% rename from exercises/05-generics-traits/Cargo.toml rename to exercises/01-core/03-structs-enums/Cargo.toml index 6cd838d..840d659 100644 --- a/exercises/05-generics-traits/Cargo.toml +++ b/exercises/01-core/03-structs-enums/Cargo.toml @@ -1,4 +1,4 @@ [package] -name = "ex05-generics-traits" +name = "core03-structs-enums" version = "0.1.0" edition = "2021" diff --git a/exercises/03-structs-enums/README.md b/exercises/01-core/03-structs-enums/README.md similarity index 67% rename from exercises/03-structs-enums/README.md rename to exercises/01-core/03-structs-enums/README.md index e7aca20..c9df434 100644 --- a/exercises/03-structs-enums/README.md +++ b/exercises/01-core/03-structs-enums/README.md @@ -3,14 +3,14 @@ ## Zakres * Definiowanie `struct` oraz metod w blokach `impl` * `enum` z danymi (*algebraic data types*) -* `match`, `Option`, `Result` +* `match`, `Option` ## Zadania (`src/lib.rs`) 1. `Rectangle::area(&self) -> u32` oraz `Rectangle::can_hold(&self, other: &Rectangle) -> bool`. 2. `Shape::area(&self) -> f64` dla enuma `Shape` (`Circle(f64)` oraz `Rect { width: f64, height: f64 }`). -3. `safe_divide(a: f64, b: f64) -> Option` — zwróć `None` przy dzieleniu przez `0.0`, w przeciwnym razie `Some(a / b)`. +3. `safe_divide(a: f64, b: f64) -> Option` — `None` przy dzieleniu przez `0.0`, w przeciwnym razie `Some(a / b)`. ## Uruchomienie testów ```bash -make test PKG=ex03-structs-enums +make test PKG=core03-structs-enums ``` diff --git a/exercises/03-structs-enums/src/lib.rs b/exercises/01-core/03-structs-enums/src/lib.rs similarity index 100% rename from exercises/03-structs-enums/src/lib.rs rename to exercises/01-core/03-structs-enums/src/lib.rs diff --git a/exercises/01-core/04-collections-errors/Cargo.toml b/exercises/01-core/04-collections-errors/Cargo.toml new file mode 100644 index 0000000..42ae277 --- /dev/null +++ b/exercises/01-core/04-collections-errors/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "core04-collections-errors" +version = "0.1.0" +edition = "2021" diff --git a/exercises/04-collections-errors/README.md b/exercises/01-core/04-collections-errors/README.md similarity index 59% rename from exercises/04-collections-errors/README.md rename to exercises/01-core/04-collections-errors/README.md index 939fb11..f4b958a 100644 --- a/exercises/04-collections-errors/README.md +++ b/exercises/01-core/04-collections-errors/README.md @@ -6,11 +6,11 @@ * Własne typy błędów (`enum`) ## Zadania (`src/lib.rs`) -1. `word_counts(text: &str) -> HashMap` — policz wystąpienia słów (case-insensitive, po podziale po białych znakach). -2. `parse_positive_i32(input: &str) -> Result` — sparsuj tekst do `i32` i odrzuć wartości `<= 0` odpowiednim wariantem błędu. -3. `sum_parsed_positives(inputs: &[&str]) -> Result` — zsumuj listę tekstów, propagując pierwszy napotkany błąd przez `?`. +1. `word_counts(text: &str) -> HashMap` — policz wystąpienia słów (case-insensitive). +2. `parse_positive_i32(input: &str) -> Result` — sparsuj tekst do `i32` i odrzuć wartości `<= 0`. +3. `sum_parsed_positives(inputs: &[&str]) -> Result` — zsumuj listę tekstów, propagując pierwszy błąd przez `?`. ## Uruchomienie testów ```bash -make test PKG=ex04-collections-errors +make test PKG=core04-collections-errors ``` diff --git a/exercises/04-collections-errors/src/lib.rs b/exercises/01-core/04-collections-errors/src/lib.rs similarity index 100% rename from exercises/04-collections-errors/src/lib.rs rename to exercises/01-core/04-collections-errors/src/lib.rs diff --git a/exercises/01-core/05-generics-traits/Cargo.toml b/exercises/01-core/05-generics-traits/Cargo.toml new file mode 100644 index 0000000..08aa531 --- /dev/null +++ b/exercises/01-core/05-generics-traits/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "core05-generics-traits" +version = "0.1.0" +edition = "2021" diff --git a/exercises/01-core/05-generics-traits/README.md b/exercises/01-core/05-generics-traits/README.md new file mode 100644 index 0000000..608df3a --- /dev/null +++ b/exercises/01-core/05-generics-traits/README.md @@ -0,0 +1,16 @@ +# 05 — Generyki, Traity i Lifetimes + +## Zakres +* Funkcje i typy generyczne (``) +* Definiowanie i implementowanie traitów (`trait Summary`) +* Podstawowe adnotacje czasu życia (`'a`) + +## Zadania (`src/lib.rs`) +1. `largest(items: &[T]) -> Option<&T>` — referencja do największego elementu lub `None`. +2. Zaimplementuj trait `Summary` dla `Article`. +3. `longest<'a>(x: &'a str, y: &'a str) -> &'a str` — dłuższy napis (przy równej długości zwróć `x`). + +## Uruchomienie testów +```bash +make test PKG=core05-generics-traits +``` diff --git a/exercises/05-generics-traits/src/lib.rs b/exercises/01-core/05-generics-traits/src/lib.rs similarity index 100% rename from exercises/05-generics-traits/src/lib.rs rename to exercises/01-core/05-generics-traits/src/lib.rs diff --git a/exercises/01-core/06-iterators-closures/Cargo.toml b/exercises/01-core/06-iterators-closures/Cargo.toml new file mode 100644 index 0000000..0153592 --- /dev/null +++ b/exercises/01-core/06-iterators-closures/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "core06-iterators-closures" +version = "0.1.0" +edition = "2021" diff --git a/exercises/01-core/06-iterators-closures/README.md b/exercises/01-core/06-iterators-closures/README.md new file mode 100644 index 0000000..d33922c --- /dev/null +++ b/exercises/01-core/06-iterators-closures/README.md @@ -0,0 +1,16 @@ +# 06 — Iteratory i Domknięcia (Closures) + +## Zakres +* Domknięcia i traity `Fn`, `FnMut`, `FnOnce` +* Łańcuchy iteratorów: `iter()`, `filter()`, `map()`, `fold()`, `collect()` +* Przetwarzanie bez zbędnych alokacji pośrednich + +## Zadania (`src/lib.rs`) +1. `sum_of_even_squares(nums: &[i32]) -> i32` — wybierz liczby parzyste, podnieś do kwadratu i zsumuj używając iteratorów. +2. `filter_and_transform(items: &[i32], predicate: F) -> Vec` — odfiltruj elementy spełniające `predicate` i pomnóż każdy przez 2. +3. `non_empty_trimmed(lines: &[&str]) -> Vec` — przytnij białe znaki (`trim`) i odrzuć puste linie. + +## Uruchomienie testów +```bash +make test PKG=core06-iterators-closures +``` diff --git a/exercises/01-core/06-iterators-closures/src/lib.rs b/exercises/01-core/06-iterators-closures/src/lib.rs new file mode 100644 index 0000000..325e716 --- /dev/null +++ b/exercises/01-core/06-iterators-closures/src/lib.rs @@ -0,0 +1,39 @@ +#![allow(unused_variables, dead_code)] + +pub fn sum_of_even_squares(nums: &[i32]) -> i32 { + todo!("Użyj iter().filter(...).map(...).sum()") +} + +pub fn filter_and_transform(items: &[i32], predicate: F) -> Vec +where + F: Fn(i32) -> bool, +{ + todo!("Odfiltruj items przez predicate i pomnóż każdy przez 2") +} + +pub fn non_empty_trimmed(lines: &[&str]) -> Vec { + todo!("Przytnij białe znaki i zwróć tylko niepuste linie jako Vec") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sums_even_squares() { + assert_eq!(sum_of_even_squares(&[1, 2, 3, 4, 5]), 20); + assert_eq!(sum_of_even_squares(&[1, 3, 5]), 0); + } + + #[test] + fn applies_closure_predicate() { + let result = filter_and_transform(&[1, 5, 10, 15], |x| x >= 5); + assert_eq!(result, vec![10, 20, 30]); + } + + #[test] + fn trims_and_drops_empty_lines() { + let input = [" rust ", "", " ", "\tcargo\n"]; + assert_eq!(non_empty_trimmed(&input), vec!["rust", "cargo"]); + } +} diff --git a/exercises/01-core/07-data-structures/Cargo.toml b/exercises/01-core/07-data-structures/Cargo.toml new file mode 100644 index 0000000..424bc43 --- /dev/null +++ b/exercises/01-core/07-data-structures/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "core07-data-structures" +version = "0.1.0" +edition = "2021" diff --git a/exercises/01-core/07-data-structures/README.md b/exercises/01-core/07-data-structures/README.md new file mode 100644 index 0000000..240c560 --- /dev/null +++ b/exercises/01-core/07-data-structures/README.md @@ -0,0 +1,16 @@ +# 07 — Struktury Danych (Data Structures) + +## Zakres +* Własny stos generyczny `Stack` na bazie `Vec` +* Kolejka `Queue` na bazie `VecDeque` +* Jednokierunkowa lista łączona `LinkedList` z użyciem `Option>>` (świetny trening dla `Option::take()` i ownershipu na stercie) + +## Zadania (`src/lib.rs`) +1. Zaimplementuj `Stack`: `new`, `push`, `pop`, `peek`, `is_empty`. +2. Zaimplementuj `Queue`: `new`, `enqueue`, `dequeue`, `len`. +3. Zaimplementuj `LinkedList`: `new`, `push_front`, `pop_front`. + +## Uruchomienie testów +```bash +make test PKG=core07-data-structures +``` diff --git a/exercises/01-core/07-data-structures/src/lib.rs b/exercises/01-core/07-data-structures/src/lib.rs new file mode 100644 index 0000000..aa5b051 --- /dev/null +++ b/exercises/01-core/07-data-structures/src/lib.rs @@ -0,0 +1,122 @@ +#![allow(unused_variables, dead_code)] + +use std::collections::VecDeque; + +#[derive(Debug, Default)] +pub struct Stack { + items: Vec, +} + +impl Stack { + pub fn new() -> Self { + todo!("Utwórz pusty stos") + } + + pub fn push(&mut self, value: T) { + todo!("Dodaj element na wierzch stosu") + } + + pub fn pop(&mut self) -> Option { + todo!("Zdejmij element z wierzchu stosu") + } + + pub fn peek(&self) -> Option<&T> { + todo!("Zwróć referencję do wierzchu stosu bez zdejmowania") + } + + pub fn is_empty(&self) -> bool { + todo!("Sprawdź, czy stos jest pusty") + } +} + +#[derive(Debug, Default)] +pub struct Queue { + items: VecDeque, +} + +impl Queue { + pub fn new() -> Self { + todo!("Utwórz pustą kolejkę") + } + + pub fn enqueue(&mut self, value: T) { + todo!("Dodaj element na koniec kolejki (push_back)") + } + + pub fn dequeue(&mut self) -> Option { + todo!("Pobierz element z początku kolejki (pop_front)") + } + + pub fn len(&self) -> usize { + todo!("Zwróć liczbę elementów w kolejce") + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} + +struct Node { + value: T, + next: Option>>, +} + +#[derive(Default)] +pub struct LinkedList { + head: Option>>, +} + +impl LinkedList { + pub fn new() -> Self { + todo!("Utwórz pustą listę") + } + + pub fn push_front(&mut self, value: T) { + todo!("Wstaw nowy węzeł na początek listy używając self.head.take()") + } + + pub fn pop_front(&mut self) -> Option { + todo!("Zdejmij pierwszy węzeł używając self.head.take()") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn stack_lifo_behavior() { + let mut stack = Stack::new(); + assert!(stack.is_empty()); + stack.push(10); + stack.push(20); + assert_eq!(stack.peek(), Some(&20)); + assert_eq!(stack.pop(), Some(20)); + assert_eq!(stack.pop(), Some(10)); + assert_eq!(stack.pop(), None); + } + + #[test] + fn queue_fifo_behavior() { + let mut queue = Queue::new(); + queue.enqueue("first"); + queue.enqueue("second"); + assert_eq!(queue.len(), 2); + assert_eq!(queue.dequeue(), Some("first")); + assert_eq!(queue.dequeue(), Some("second")); + assert_eq!(queue.dequeue(), None); + } + + #[test] + fn linked_list_push_and_pop_front() { + let mut list = LinkedList::new(); + assert_eq!(list.pop_front(), None); + list.push_front(1); + list.push_front(2); + list.push_front(3); + assert_eq!(list.pop_front(), Some(3)); + assert_eq!(list.pop_front(), Some(2)); + assert_eq!(list.pop_front(), Some(1)); + assert_eq!(list.pop_front(), None); + } +} diff --git a/exercises/01-core/08-oop-composition/Cargo.toml b/exercises/01-core/08-oop-composition/Cargo.toml new file mode 100644 index 0000000..2de91ca --- /dev/null +++ b/exercises/01-core/08-oop-composition/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "core08-oop-composition" +version = "0.1.0" +edition = "2021" diff --git a/exercises/01-core/08-oop-composition/README.md b/exercises/01-core/08-oop-composition/README.md new file mode 100644 index 0000000..78cc3d2 --- /dev/null +++ b/exercises/01-core/08-oop-composition/README.md @@ -0,0 +1,16 @@ +# 08 — Obiektowość po Rustowemu (Kompozycja zamiast Dziedziczenia) + +Rust celowo **nie posiada dziedziczenia klas** (`extends`). Zamiast tego łączy: +* **enkapsulację** (prywatne pola + publiczne metody), +* **kompozycję** (struktura posiada inne struktury), +* **polimorfizm oparty o traity** (zarówno statyczny, jak i dynamiczny `Box`). + +## Zadania (`src/lib.rs`) +1. `BankAccount` — enkapsulacja salda (`balance` prywatne): `new`, `deposit`, `withdraw` (zwraca `bool`), `balance`. +2. `Notifier` trait z domyślną metodą `prefix(&self) -> &str` oraz implementacje `EmailNotifier` i `SmsNotifier`. +3. `AlertService` — kompozycja z heterogeniczną listą `Vec>`: metoda `broadcast(&self, msg: &str) -> Vec`. + +## Uruchomienie testów +```bash +make test PKG=core08-oop-composition +``` diff --git a/exercises/01-core/08-oop-composition/src/lib.rs b/exercises/01-core/08-oop-composition/src/lib.rs new file mode 100644 index 0000000..d3715c2 --- /dev/null +++ b/exercises/01-core/08-oop-composition/src/lib.rs @@ -0,0 +1,100 @@ +#![allow(unused_variables, dead_code)] + +pub struct BankAccount { + balance: u64, +} + +impl BankAccount { + pub fn new(initial_balance: u64) -> Self { + todo!("Zainicjalizuj konto z initial_balance") + } + + pub fn deposit(&mut self, amount: u64) { + todo!("Dodaj amount do salda") + } + + pub fn withdraw(&mut self, amount: u64) -> bool { + todo!("Wypłać amount jeśli balance >= amount i zwróć true; inaczej false") + } + + pub fn balance(&self) -> u64 { + todo!("Zwróć aktualne saldo") + } +} + +pub trait Notifier { + fn channel(&self) -> &str; + + fn format_message(&self, msg: &str) -> String { + format!("[{}] {}", self.channel(), msg) + } +} + +pub struct EmailNotifier { + pub address: String, +} + +impl Notifier for EmailNotifier { + fn channel(&self) -> &str { + todo!("Zwróć \"email\"") + } +} + +pub struct SmsNotifier { + pub phone: String, +} + +impl Notifier for SmsNotifier { + fn channel(&self) -> &str { + todo!("Zwróć \"sms\"") + } +} + +#[derive(Default)] +pub struct AlertService { + notifiers: Vec>, +} + +impl AlertService { + pub fn new() -> Self { + todo!("Utwórz pusty AlertService") + } + + pub fn register(&mut self, notifier: Box) { + todo!("Dodaj notifier do listy") + } + + pub fn broadcast(&self, msg: &str) -> Vec { + todo!("Wywołaj format_message(msg) na każdym notifierze i zbierz wyniki") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn encapsulates_bank_account_balance() { + let mut acc = BankAccount::new(100); + acc.deposit(50); + assert_eq!(acc.balance(), 150); + assert!(acc.withdraw(40)); + assert_eq!(acc.balance(), 110); + assert!(!acc.withdraw(500)); + assert_eq!(acc.balance(), 110); + } + + #[test] + fn broadcasts_via_dynamic_dispatch() { + let mut service = AlertService::new(); + service.register(Box::new(EmailNotifier { + address: String::from("dev@example.com"), + })); + service.register(Box::new(SmsNotifier { + phone: String::from("+48123456789"), + })); + + let sent = service.broadcast("Disk 90% full"); + assert_eq!(sent, vec!["[email] Disk 90% full", "[sms] Disk 90% full"]); + } +} diff --git a/exercises/01-core/09-design-patterns/Cargo.toml b/exercises/01-core/09-design-patterns/Cargo.toml new file mode 100644 index 0000000..2b7e8ca --- /dev/null +++ b/exercises/01-core/09-design-patterns/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "core09-design-patterns" +version = "0.1.0" +edition = "2021" diff --git a/exercises/01-core/09-design-patterns/README.md b/exercises/01-core/09-design-patterns/README.md new file mode 100644 index 0000000..5b34f2e --- /dev/null +++ b/exercises/01-core/09-design-patterns/README.md @@ -0,0 +1,18 @@ +# 09 — Idiomatyczne Wzorce Projektowe w Ruście + +Zamiast kopiować 1:1 wzorce z Javy/C++, Rust promuje wzorce wykorzystujące system typów i ownership: +* **Newtype** — osobny typ dla identyfikatorów (zapobiega pomyleniu `UserId` z `OrderId`). +* **Builder** — bezpieczna konstrukcja obiektów z wieloma opcjami. +* **Typestate** — stany obiektu wymuszane na etapie kompilacji (`Draft` -> `Published`). +* **Strategy** — wstrzykiwanie zachowania przez trait. + +## Zadania (`src/lib.rs`) +1. `UserId(u64)` i `OrderId(u64)` — wzorzec Newtype. +2. `HttpRequestBuilder` — wzorzec Builder z metodami łańcuchowymi (`method`, `header`, `build`). +3. `Document` -> `publish()` -> `Document` — wzorzec Typestate (`PhantomData`). +4. `DiscountStrategy` + `PercentageDiscount` + `apply_discount` — wzorzec Strategy. + +## Uruchomienie testów +```bash +make test PKG=core09-design-patterns +``` diff --git a/exercises/01-core/09-design-patterns/src/lib.rs b/exercises/01-core/09-design-patterns/src/lib.rs new file mode 100644 index 0000000..a16f143 --- /dev/null +++ b/exercises/01-core/09-design-patterns/src/lib.rs @@ -0,0 +1,132 @@ +#![allow(unused_variables, dead_code, unused_mut)] + +use std::marker::PhantomData; + +// --- 1. Newtype --- +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct UserId(pub u64); + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct OrderId(pub u64); + +pub fn format_audit_entry(user: UserId, order: OrderId) -> String { + todo!("Zwróć \"user: order:\"") +} + +// --- 2. Builder --- +#[derive(Debug, PartialEq)] +pub struct HttpRequest { + pub url: String, + pub method: String, + pub timeout_ms: u64, +} + +pub struct HttpRequestBuilder { + url: String, + method: String, + timeout_ms: u64, +} + +impl HttpRequestBuilder { + pub fn new(url: impl Into) -> Self { + todo!("Utwórz builder z domyślną metodą \"GET\" i timeout_ms = 3000") + } + + pub fn method(mut self, method: impl Into) -> Self { + todo!("Ustaw method i zwróć self") + } + + pub fn timeout_ms(mut self, timeout_ms: u64) -> Self { + todo!("Ustaw timeout_ms i zwróć self") + } + + pub fn build(self) -> HttpRequest { + todo!("Zbuduj HttpRequest") + } +} + +// --- 3. Typestate --- +pub struct Draft; +pub struct Published; + +pub struct Document { + title: String, + _state: PhantomData, +} + +impl Document { + pub fn new(title: impl Into) -> Self { + todo!("Utwórz dokument w stanie Draft") + } + + pub fn publish(self) -> Document { + todo!("Przejdź ze stanu Draft do Published") + } +} + +impl Document { + pub fn title(&self) -> &str { + &self.title + } +} + +// --- 4. Strategy --- +pub trait DiscountStrategy { + fn discount(&self, price_cents: u64) -> u64; +} + +pub struct PercentageDiscount { + pub percent: u64, +} + +impl DiscountStrategy for PercentageDiscount { + fn discount(&self, price_cents: u64) -> u64 { + todo!("Oblicz rabat: price_cents * self.percent / 100") + } +} + +pub fn final_price(price_cents: u64, strategy: &dyn DiscountStrategy) -> u64 { + todo!("Zwróć cenę po rabacie (saturating_sub)") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn newtype_formats_audit_entry() { + assert_eq!( + format_audit_entry(UserId(7), OrderId(42)), + "user:7 order:42" + ); + } + + #[test] + fn builder_constructs_request() { + let req = HttpRequestBuilder::new("https://example.com") + .method("POST") + .timeout_ms(5000) + .build(); + assert_eq!( + req, + HttpRequest { + url: String::from("https://example.com"), + method: String::from("POST"), + timeout_ms: 5000, + } + ); + } + + #[test] + fn typestate_transitions_draft_to_published() { + let draft = Document::new("Rust Patterns"); + let published = draft.publish(); + assert_eq!(published.title(), "Rust Patterns"); + } + + #[test] + fn strategy_calculates_discounted_price() { + let strategy = PercentageDiscount { percent: 20 }; + assert_eq!(final_price(1000, &strategy), 800); + } +} diff --git a/exercises/01-core/10-crud-repository/Cargo.toml b/exercises/01-core/10-crud-repository/Cargo.toml new file mode 100644 index 0000000..22777c3 --- /dev/null +++ b/exercises/01-core/10-crud-repository/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "core10-crud-repository" +version = "0.1.0" +edition = "2021" diff --git a/exercises/01-core/10-crud-repository/README.md b/exercises/01-core/10-crud-repository/README.md new file mode 100644 index 0000000..3e4db61 --- /dev/null +++ b/exercises/01-core/10-crud-repository/README.md @@ -0,0 +1,20 @@ +# 10 — CRUD w pamięci (In-Memory Repository) + +## Zakres +* Operacje **Create, Read, Update, Delete** na strukturze domenowej `Task` +* Walidacja wejścia (pusty tytuł -> `RepoError::InvalidTitle`) +* Zarządzanie stanem i auto-inkrementacją ID w `BTreeMap` (deterministyczna kolejność) + +## Zadania (`src/lib.rs`) +Zaimplementuj `TaskStore`: +1. `create(&mut self, title: impl Into) -> Result` +2. `get(&self, id: u64) -> Option<&Task>` +3. `list(&self) -> Vec<&Task>` +4. `update_title(&mut self, id: u64, title: impl Into) -> Result` +5. `mark_done(&mut self, id: u64) -> Result` +6. `delete(&mut self, id: u64) -> Result` + +## Uruchomienie testów +```bash +make test PKG=core10-crud-repository +``` diff --git a/exercises/01-core/10-crud-repository/src/lib.rs b/exercises/01-core/10-crud-repository/src/lib.rs new file mode 100644 index 0000000..eb38807 --- /dev/null +++ b/exercises/01-core/10-crud-repository/src/lib.rs @@ -0,0 +1,85 @@ +#![allow(unused_variables, dead_code)] + +use std::collections::BTreeMap; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Task { + pub id: u64, + pub title: String, + pub done: bool, +} + +#[derive(Debug, PartialEq, Eq)] +pub enum RepoError { + InvalidTitle, + NotFound(u64), +} + +#[derive(Default)] +pub struct TaskStore { + next_id: u64, + tasks: BTreeMap, +} + +impl TaskStore { + pub fn new() -> Self { + Self { + next_id: 1, + tasks: BTreeMap::new(), + } + } + + pub fn create(&mut self, title: impl Into) -> Result { + todo!("Odrzuć pusty/samych-spacji tytuł (InvalidTitle), zapisz i zwróć Task") + } + + pub fn get(&self, id: u64) -> Option<&Task> { + todo!("Zwróć referencję do zadania po id") + } + + pub fn list(&self) -> Vec<&Task> { + todo!("Zwróć wszystkie zadania posortowane po id") + } + + pub fn update_title(&mut self, id: u64, title: impl Into) -> Result { + todo!("Zwaliduj tytuł, zaktualizuj istniejące zadanie lub zwróć NotFound(id)") + } + + pub fn mark_done(&mut self, id: u64) -> Result { + todo!("Ustaw done = true lub zwróć NotFound(id)") + } + + pub fn delete(&mut self, id: u64) -> Result { + todo!("Usuń i zwróć zadanie lub NotFound(id)") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn full_crud_lifecycle() { + let mut store = TaskStore::new(); + + assert_eq!(store.create(" "), Err(RepoError::InvalidTitle)); + + let t1 = store.create("Learn Rust").unwrap(); + let t2 = store.create("Build CLI").unwrap(); + assert_eq!(t1.id, 1); + assert_eq!(t2.id, 2); + assert_eq!(store.list().len(), 2); + + let updated = store.update_title(1, "Master Rust").unwrap(); + assert_eq!(updated.title, "Master Rust"); + + let done = store.mark_done(1).unwrap(); + assert!(done.done); + assert!(store.get(1).unwrap().done); + + let removed = store.delete(2).unwrap(); + assert_eq!(removed.id, 2); + assert_eq!(store.delete(2), Err(RepoError::NotFound(2))); + assert_eq!(store.list().len(), 1); + } +} diff --git a/exercises/03-structs-enums/Cargo.toml b/exercises/02-engineering-2026/01-ai-code-audit/Cargo.toml similarity index 60% rename from exercises/03-structs-enums/Cargo.toml rename to exercises/02-engineering-2026/01-ai-code-audit/Cargo.toml index d508871..233ea10 100644 --- a/exercises/03-structs-enums/Cargo.toml +++ b/exercises/02-engineering-2026/01-ai-code-audit/Cargo.toml @@ -1,4 +1,4 @@ [package] -name = "ex03-structs-enums" +name = "eng01-ai-code-audit" version = "0.1.0" edition = "2021" diff --git a/exercises/02-engineering-2026/01-ai-code-audit/README.md b/exercises/02-engineering-2026/01-ai-code-audit/README.md new file mode 100644 index 0000000..46590dd --- /dev/null +++ b/exercises/02-engineering-2026/01-ai-code-audit/README.md @@ -0,0 +1,19 @@ +# 01 — Audyt i Refaktoryzacja Kodu AI (AI-Era Drill) + +W 2026 roku jedną z najważniejszych umiejętności inżyniera jest **krytyczne czytanie i naprawianie kodu wygenerowanego przez AI**. + +W `src/lib.rs` znajdziesz kod, który "wygląda dobrze na pierwszy rzut oka", ale zawiera typowe błędy AI: +* ukryte `.unwrap()` powodujące panikę na niepoprawnych danych, +* niepotrzebne `.clone()` i przyjmowanie `String` zamiast `&str`, +* błędną obsługę przypadków brzegowych (dzielenie przez zero, pusta kolekcja, niepoprawny format). + +## Twoje zadanie +Przeprowadź audyt i refaktoryzację funkcji w `src/lib.rs` tak, aby: +1. Żadna funkcja **nie panikowała** (`unwrap` / `expect` / indeksowanie `[0]` bez sprawdzenia). +2. Wszystkie testy (w tym testy negatywne i brzegowe) przechodziły. +3. `make clippy` nie zgłaszał żadnych ostrzeżeń po usunięciu `#![allow(...)]`. + +## Uruchomienie testów +```bash +make test PKG=eng01-ai-code-audit +``` diff --git a/exercises/02-engineering-2026/01-ai-code-audit/src/lib.rs b/exercises/02-engineering-2026/01-ai-code-audit/src/lib.rs new file mode 100644 index 0000000..72460bc --- /dev/null +++ b/exercises/02-engineering-2026/01-ai-code-audit/src/lib.rs @@ -0,0 +1,51 @@ +#![allow(unused_variables, dead_code, clippy::all)] + +/// Celowo wadliwy kod w stylu "szybkiego draftu z AI". +/// Audytuj i napraw poniższe funkcje tak, aby nie panikowały i przeszły testy! + +pub fn parse_port(raw: &str) -> Result { + // BUG: panikuje na złym wejściu i akceptuje port 0! + let port: u16 = raw.trim().parse().unwrap(); + Ok(port) +} + +pub fn average(values: &[f64]) -> Option { + // BUG: dzieli przez 0.0 (zwraca NaN zamiast None dla pustego wycinka) + let sum: f64 = values.iter().sum(); + Some(sum / values.len() as f64) +} + +pub fn extract_bearer_token(auth_header: &str) -> Option<&str> { + // BUG: panikuje gdy brak spacji, nie sprawdza prefiksu "Bearer ", przepuszcza pusty token! + let parts: Vec<&str> = auth_header.split(' ').collect(); + Some(parts[1]) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rejects_invalid_and_zero_ports() { + assert_eq!(parse_port("8080"), Ok(8080)); + assert_eq!(parse_port(" 443 "), Ok(443)); + assert!(parse_port("0").is_err()); + assert!(parse_port("99999").is_err()); + assert!(parse_port("not-a-port").is_err()); + } + + #[test] + fn handles_empty_slice_without_nan() { + assert_eq!(average(&[]), None); + assert_eq!(average(&[10.0, 20.0]), Some(15.0)); + } + + #[test] + fn safely_parses_bearer_header() { + assert_eq!(extract_bearer_token("Bearer secret123"), Some("secret123")); + assert_eq!(extract_bearer_token("Bearer "), None); + assert_eq!(extract_bearer_token("Basic abc"), None); + assert_eq!(extract_bearer_token("MalformedHeader"), None); + assert_eq!(extract_bearer_token(""), None); + } +} diff --git a/exercises/04-collections-errors/Cargo.toml b/exercises/02-engineering-2026/02-type-driven-design/Cargo.toml similarity index 56% rename from exercises/04-collections-errors/Cargo.toml rename to exercises/02-engineering-2026/02-type-driven-design/Cargo.toml index ce3e8ab..d51727d 100644 --- a/exercises/04-collections-errors/Cargo.toml +++ b/exercises/02-engineering-2026/02-type-driven-design/Cargo.toml @@ -1,4 +1,4 @@ [package] -name = "ex04-collections-errors" +name = "eng02-type-driven-design" version = "0.1.0" edition = "2021" diff --git a/exercises/02-engineering-2026/02-type-driven-design/README.md b/exercises/02-engineering-2026/02-type-driven-design/README.md new file mode 100644 index 0000000..08eef90 --- /dev/null +++ b/exercises/02-engineering-2026/02-type-driven-design/README.md @@ -0,0 +1,12 @@ +# 02 — Type-Driven Design ("Make Illegal States Unrepresentable") + +W erze AI **system typów Rusta jest Twoją najskuteczniejszą specyfikacją**. Zamiast pisać w komentarzu „email musi być poprawny” lub „nie dodawaj PLN do EUR”, wymuś to typami. + +## Zadania (`src/lib.rs`) +1. `Email::parse(raw: &str) -> Result` — konstrukcja możliwa wyłącznie przez walidujący konstruktor (pole wewnętrzne prywatne). +2. `Money::checked_add(self, other: Money) -> Result` — bezpieczne dodawanie kwot w groszach/centach z kontrolą waluty. + +## Uruchomienie testów +```bash +make test PKG=eng02-type-driven-design +``` diff --git a/exercises/02-engineering-2026/02-type-driven-design/src/lib.rs b/exercises/02-engineering-2026/02-type-driven-design/src/lib.rs new file mode 100644 index 0000000..6e269f4 --- /dev/null +++ b/exercises/02-engineering-2026/02-type-driven-design/src/lib.rs @@ -0,0 +1,92 @@ +#![allow(unused_variables, dead_code)] + +#[derive(Debug, PartialEq, Eq)] +pub enum ValidationError { + InvalidEmail, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Email(String); + +impl Email { + pub fn parse(raw: &str) -> Result { + todo!( + "Odrzuć spacje, brak '@' lub pustą część przed/po '@'; zapisz znormalizowany lowercase" + ) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Currency { + Pln, + Eur, + Usd, +} + +#[derive(Debug, PartialEq, Eq)] +pub struct CurrencyMismatch; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Money { + pub cents: i64, + pub currency: Currency, +} + +impl Money { + pub fn checked_add(self, other: Money) -> Result { + todo!("Dodaj kwoty tylko jeśli waluty są identyczne; użyj checked_add lub zwróć Err") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn validates_email_at_boundary() { + let email = Email::parse("User@Example.COM").unwrap(); + assert_eq!(email.as_str(), "user@example.com"); + assert_eq!( + Email::parse("no-at-sign"), + Err(ValidationError::InvalidEmail) + ); + assert_eq!( + Email::parse("@example.com"), + Err(ValidationError::InvalidEmail) + ); + assert_eq!(Email::parse("user@"), Err(ValidationError::InvalidEmail)); + assert_eq!( + Email::parse("a b@c.com"), + Err(ValidationError::InvalidEmail) + ); + } + + #[test] + fn prevents_mismatched_currency_addition() { + let a = Money { + cents: 500, + currency: Currency::Pln, + }; + let b = Money { + cents: 250, + currency: Currency::Pln, + }; + let eur = Money { + cents: 100, + currency: Currency::Eur, + }; + + assert_eq!( + a.checked_add(b), + Ok(Money { + cents: 750, + currency: Currency::Pln + }) + ); + assert_eq!(a.checked_add(eur), Err(CurrencyMismatch)); + } +} diff --git a/exercises/02-engineering-2026/03-cross-platform/Cargo.toml b/exercises/02-engineering-2026/03-cross-platform/Cargo.toml new file mode 100644 index 0000000..b267907 --- /dev/null +++ b/exercises/02-engineering-2026/03-cross-platform/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "eng03-cross-platform" +version = "0.1.0" +edition = "2021" diff --git a/exercises/02-engineering-2026/03-cross-platform/README.md b/exercises/02-engineering-2026/03-cross-platform/README.md new file mode 100644 index 0000000..c1165c4 --- /dev/null +++ b/exercises/02-engineering-2026/03-cross-platform/README.md @@ -0,0 +1,16 @@ +# 03 — Programowanie Cross-Platform (Linux, Windows, macOS) + +## Zakres +* Abstrakcje ścieżek `Path` i `PathBuf` (nigdy nie sklejaj ścieżek przez `format!("{}/{}", ...)`!) +* Kompilacja warunkowa: `#[cfg(target_os = "linux")]`, `#[cfg(target_os = "macos")]`, `#[cfg(target_os = "windows")]` +* Bezpieczna obsługa zmiennych środowiskowych (wstrzykiwanie źródła zamiast globalnego stanu w testach) + +## Zadania (`src/lib.rs`) +1. `config_file_path(base_dir: &Path, app_name: &str) -> PathBuf` — zbuduj przenośną ścieżkę `//config.toml` używając `Path::join`. +2. `current_os_label() -> &'static str` — użyj `#[cfg(target_os = "...")]`, aby zwrócić `"linux"`, `"macos"`, `"windows"` lub `"other"`. +3. `has_extension(path: &Path, expected: &str) -> bool` — porównaj rozszerzenie pliku bez uwzględniania wielkości liter (ważne na Windows/macOS). + +## Uruchomienie testów +```bash +make test PKG=eng03-cross-platform +``` diff --git a/exercises/02-engineering-2026/03-cross-platform/src/lib.rs b/exercises/02-engineering-2026/03-cross-platform/src/lib.rs new file mode 100644 index 0000000..a17fe4a --- /dev/null +++ b/exercises/02-engineering-2026/03-cross-platform/src/lib.rs @@ -0,0 +1,40 @@ +#![allow(unused_variables, dead_code)] + +use std::path::{Path, PathBuf}; + +pub fn config_file_path(base_dir: &Path, app_name: &str) -> PathBuf { + todo!("Użyj base_dir.join(app_name).join(\"config.toml\")") +} + +pub fn current_os_label() -> &'static str { + todo!("Użyj #[cfg(target_os = \"...\")] dla linux, macos, windows oraz fallback other") +} + +pub fn has_extension(path: &Path, expected: &str) -> bool { + todo!("Porównaj path.extension() z expected bez wrażliwości na wielkość liter") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn builds_portable_config_path() { + let base = Path::new("home").join("user"); + let expected = base.join("myapp").join("config.toml"); + assert_eq!(config_file_path(&base, "myapp"), expected); + } + + #[test] + fn detects_known_os_label() { + let label = current_os_label(); + assert!(matches!(label, "linux" | "macos" | "windows" | "other")); + } + + #[test] + fn checks_extensions_case_insensitively() { + assert!(has_extension(Path::new("notes.MD"), "md")); + assert!(has_extension(Path::new("archive.tar.gz"), "gz")); + assert!(!has_extension(Path::new("README"), "md")); + } +} diff --git a/exercises/02-engineering-2026/04-best-practices/Cargo.toml b/exercises/02-engineering-2026/04-best-practices/Cargo.toml new file mode 100644 index 0000000..9b3414e --- /dev/null +++ b/exercises/02-engineering-2026/04-best-practices/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "eng04-best-practices" +version = "0.1.0" +edition = "2021" diff --git a/exercises/02-engineering-2026/04-best-practices/README.md b/exercises/02-engineering-2026/04-best-practices/README.md new file mode 100644 index 0000000..f510723 --- /dev/null +++ b/exercises/02-engineering-2026/04-best-practices/README.md @@ -0,0 +1,16 @@ +# 04 — Dobre Praktyki w Ruście (Errors, Display, From, Doctests) + +## Zakres +* Implementacja standardowych traitów `fmt::Display` i `std::error::Error` (fundament tego, co generuje `thiserror`) +* Konwersja błędów przez `From` dla czystego operatora `?` +* Dokumentacja publicznego API i **doctesty** (testy wewnątrz komentarzy `///`) + +## Zadania (`src/lib.rs`) +1. Zaimplementuj `fmt::Display` i `std::error::Error` dla `ConfigError`. +2. Zaimplementuj `From` dla `ConfigError`. +3. Zaimplementuj `parse_timeout_secs(raw: &str) -> Result` (odrzuca puste wejście jako `Missing`, błędy parsowania przez `?`, a wartości `0` lub `> 300` jako `OutOfRange(u64)`). + +## Uruchomienie testów +```bash +make test PKG=eng04-best-practices +``` diff --git a/exercises/02-engineering-2026/04-best-practices/src/lib.rs b/exercises/02-engineering-2026/04-best-practices/src/lib.rs new file mode 100644 index 0000000..4270a21 --- /dev/null +++ b/exercises/02-engineering-2026/04-best-practices/src/lib.rs @@ -0,0 +1,50 @@ +#![allow(unused_variables, dead_code)] + +use std::error::Error; +use std::fmt; +use std::num::ParseIntError; + +#[derive(Debug, PartialEq, Eq)] +pub enum ConfigError { + Missing, + InvalidNumber(String), + OutOfRange(u64), +} + +impl fmt::Display for ConfigError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + todo!("Sformatuj czytelny komunikat błędu dla każdego wariantu ConfigError") + } +} + +impl Error for ConfigError {} + +impl From for ConfigError { + fn from(err: ParseIntError) -> Self { + todo!("Zamień ParseIntError na ConfigError::InvalidNumber(err.to_string())") + } +} + +pub fn parse_timeout_secs(raw: &str) -> Result { + todo!("Trim -> Missing jeśli pusty -> parse::()? -> OutOfRange jeśli 0 lub > 300") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn validates_timeout_range_and_formatting() { + assert_eq!(parse_timeout_secs("30"), Ok(30)); + assert_eq!(parse_timeout_secs(" "), Err(ConfigError::Missing)); + assert_eq!(parse_timeout_secs("0"), Err(ConfigError::OutOfRange(0))); + assert_eq!(parse_timeout_secs("301"), Err(ConfigError::OutOfRange(301))); + assert!(matches!( + parse_timeout_secs("abc"), + Err(ConfigError::InvalidNumber(_)) + )); + + let msg = ConfigError::Missing.to_string(); + assert!(!msg.is_empty()); + } +} diff --git a/exercises/03-ecosystems/01-cli-clap/Cargo.toml b/exercises/03-ecosystems/01-cli-clap/Cargo.toml new file mode 100644 index 0000000..d4b1585 --- /dev/null +++ b/exercises/03-ecosystems/01-cli-clap/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "eco01-cli-clap" +version = "0.1.0" +edition = "2021" + +[dependencies] +clap = { version = "4", features = ["derive"] } diff --git a/exercises/03-ecosystems/01-cli-clap/README.md b/exercises/03-ecosystems/01-cli-clap/README.md new file mode 100644 index 0000000..5109b00 --- /dev/null +++ b/exercises/03-ecosystems/01-cli-clap/README.md @@ -0,0 +1,18 @@ +# 01 — Parsowanie argumentów CLI z `clap` + +`clap` (Command Line Argument Parser) to absolutny standard w ekosystemie Rusta do budowy narzędzi CLI. + +## Zakres +* Deklaratywne makra `#[derive(Parser)]` i `#[derive(Subcommand)]` +* Flagi (`--verbose` / `-v`), opcje z wartościami domyślnymi, argumenty pozycyjne i podkomendy (`add`, `list`, `done`) +* Testowanie parsera bez uruchamiania procesu: `Cli::try_parse_from(...)` + +## Zadania (`src/lib.rs`) +1. Uzupełnij atrybuty `clap` w strukturze `Cli` i enumie `Command` (np. `#[arg(short, long)]`, `#[command(subcommand)]`). +2. Zaimplementuj `parse_cli(args: &[&str]) -> Result` używając `Cli::try_parse_from(args)`. +3. Zaimplementuj `describe_command(cli: &Cli) -> String`, aby zamienić sparsowaną komendę na czytelny opis (w prawdziwym CLI byłoby tu wywołanie logiki biznesowej). + +## Uruchomienie testów +```bash +make test PKG=eco01-cli-clap +``` diff --git a/exercises/03-ecosystems/01-cli-clap/src/lib.rs b/exercises/03-ecosystems/01-cli-clap/src/lib.rs new file mode 100644 index 0000000..e7ab201 --- /dev/null +++ b/exercises/03-ecosystems/01-cli-clap/src/lib.rs @@ -0,0 +1,78 @@ +#![allow(unused_variables, dead_code)] + +use clap::{Parser, Subcommand}; + +#[derive(Debug, Parser, PartialEq, Eq)] +#[command(name = "todoctl", about = "Mini CLI do nauki clap")] +pub struct Cli { + #[arg(short, long, default_value_t = false)] + pub verbose: bool, + + #[command(subcommand)] + pub command: Command, +} + +#[derive(Debug, Subcommand, PartialEq, Eq)] +pub enum Command { + /// Dodaj nowe zadanie + Add { + /// Tytuł zadania + title: String, + + /// Priorytet (1-5) + #[arg(short, long, default_value_t = 3)] + priority: u8, + }, + /// Wyświetl listę zadań + List { + /// Pokaż również ukończone + #[arg(long, default_value_t = false)] + all: bool, + }, + /// Oznacz zadanie jako ukończone + Done { id: u64 }, +} + +pub fn parse_cli(args: &[&str]) -> Result { + todo!("Użyj Cli::try_parse_from(args)") +} + +pub fn describe_command(cli: &Cli) -> String { + todo!( + "Zwróć: Add -> \"add::p<priority>\", List -> \"list:all=<bool>\", Done -> \"done:<id>\"" + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_add_with_defaults_and_flags() { + let cli = parse_cli(&["todoctl", "-v", "add", "Learn clap"]).unwrap(); + assert!(cli.verbose); + assert_eq!( + cli.command, + Command::Add { + title: String::from("Learn clap"), + priority: 3 + } + ); + assert_eq!(describe_command(&cli), "add:Learn clap:p3"); + } + + #[test] + fn parses_list_and_done_subcommands() { + let list_cli = parse_cli(&["todoctl", "list", "--all"]).unwrap(); + assert_eq!(describe_command(&list_cli), "list:all=true"); + + let done_cli = parse_cli(&["todoctl", "done", "42"]).unwrap(); + assert_eq!(describe_command(&done_cli), "done:42"); + } + + #[test] + fn rejects_invalid_arguments() { + assert!(parse_cli(&["todoctl", "done", "not-a-number"]).is_err()); + assert!(parse_cli(&["todoctl", "unknown"]).is_err()); + } +} diff --git a/exercises/03-ecosystems/02-web-backend-axum/Cargo.toml b/exercises/03-ecosystems/02-web-backend-axum/Cargo.toml new file mode 100644 index 0000000..f3297a9 --- /dev/null +++ b/exercises/03-ecosystems/02-web-backend-axum/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "eco02-web-backend-axum" +version = "0.1.0" +edition = "2021" + +[dependencies] +axum = "0.8" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +tokio = { version = "1", features = ["macros", "rt-multi-thread"] } + +[dev-dependencies] +http-body-util = "0.1" +tower = { version = "0.5", features = ["util"] } diff --git a/exercises/03-ecosystems/02-web-backend-axum/README.md b/exercises/03-ecosystems/02-web-backend-axum/README.md new file mode 100644 index 0000000..3fab586 --- /dev/null +++ b/exercises/03-ecosystems/02-web-backend-axum/README.md @@ -0,0 +1,18 @@ +# 02 — Web Backend z `axum` + `tokio` + `serde` + +`axum` (oparty na `tokio` i `tower`) to najpopularniejszy nowoczesny framework backendowy w Ruście. + +## Zakres +* Routing HTTP (`Router::new().route(...)`) +* Serializacja/deserializacja JSON (`axum::Json`, `serde::Serialize`, `serde::Deserialize`) +* Kody statusu HTTP (`StatusCode`) i testowanie routera w pamięci bez otwierania portów (`tower::ServiceExt::oneshot`) + +## Zadania (`src/lib.rs`) +Zbuduj router w `build_router()`: +1. `GET /health` -> zwraca `200 OK` i JSON `{"status": "ok"}`. +2. `POST /echo` -> przyjmuje JSON `EchoRequest { message: String }`; jeśli `message.trim().is_empty()`, zwraca `400 BAD_REQUEST`, inaczej `200 OK` z `EchoResponse { echoed: message, len }`. + +## Uruchomienie testów +```bash +make test PKG=eco02-web-backend-axum +``` diff --git a/exercises/03-ecosystems/02-web-backend-axum/src/lib.rs b/exercises/03-ecosystems/02-web-backend-axum/src/lib.rs new file mode 100644 index 0000000..dd4853a --- /dev/null +++ b/exercises/03-ecosystems/02-web-backend-axum/src/lib.rs @@ -0,0 +1,110 @@ +#![allow(unused_variables, dead_code)] + +use axum::{ + http::StatusCode, + routing::{get, post}, + Json, Router, +}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] +pub struct HealthResponse { + pub status: String, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct EchoRequest { + pub message: String, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] +pub struct EchoResponse { + pub echoed: String, + pub len: usize, +} + +async fn health_handler() -> Json<HealthResponse> { + todo!("Zwróć Json(HealthResponse {{ status: \"ok\".into() }})") +} + +async fn echo_handler(Json(payload): Json<EchoRequest>) -> Result<Json<EchoResponse>, StatusCode> { + todo!("Odrzuć pusty message jako Err(StatusCode::BAD_REQUEST), inaczej zwróć EchoResponse") +} + +pub fn build_router() -> Router { + Router::new() + .route("/health", get(health_handler)) + .route("/echo", post(echo_handler)) +} + +#[cfg(test)] +mod tests { + use super::*; + use axum::{body::Body, http::Request}; + use http_body_util::BodyExt; + use tower::ServiceExt; + + #[tokio::test] + async fn health_endpoint_returns_ok_json() { + let app = build_router(); + let response = app + .oneshot( + Request::builder() + .uri("/health") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::OK); + let bytes = response.into_body().collect().await.unwrap().to_bytes(); + let body: HealthResponse = serde_json::from_slice(&bytes).unwrap(); + assert_eq!( + body, + HealthResponse { + status: String::from("ok") + } + ); + } + + #[tokio::test] + async fn echo_endpoint_validates_and_echoes() { + let app = build_router(); + let ok_resp = app + .clone() + .oneshot( + Request::builder() + .method("POST") + .uri("/echo") + .header("content-type", "application/json") + .body(Body::from(r#"{"message":"rust"}"#)) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(ok_resp.status(), StatusCode::OK); + let bytes = ok_resp.into_body().collect().await.unwrap().to_bytes(); + let body: EchoResponse = serde_json::from_slice(&bytes).unwrap(); + assert_eq!( + body, + EchoResponse { + echoed: String::from("rust"), + len: 4 + } + ); + + let bad_resp = app + .oneshot( + Request::builder() + .method("POST") + .uri("/echo") + .header("content-type", "application/json") + .body(Body::from(r#"{"message":" "}"#)) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(bad_resp.status(), StatusCode::BAD_REQUEST); + } +} diff --git a/exercises/03-ecosystems/03-shared-core-ffi/Cargo.toml b/exercises/03-ecosystems/03-shared-core-ffi/Cargo.toml new file mode 100644 index 0000000..9c12d17 --- /dev/null +++ b/exercises/03-ecosystems/03-shared-core-ffi/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "eco03-shared-core-ffi" +version = "0.1.0" +edition = "2021" + +[dependencies] +serde = { version = "1", features = ["derive"] } +thiserror = "2" diff --git a/exercises/03-ecosystems/03-shared-core-ffi/README.md b/exercises/03-ecosystems/03-shared-core-ffi/README.md new file mode 100644 index 0000000..81db133 --- /dev/null +++ b/exercises/03-ecosystems/03-shared-core-ffi/README.md @@ -0,0 +1,17 @@ +# 03 — Wspólny Rdzeń pod Mobile (iOS/Android UniFFI) i Desktop (Tauri) + +W projektach mobilnych (Swift/Kotlin) oraz desktopowych (Tauri v2) w Ruście pisze się **wspólny, niezależny od platformy rdzeń logiki**, a następnie wystawia go przez cienką granicę FFI/IPC (`UniFFI`, `tauri::command`). + +## Kluczowe zasady projektowania granicy FFI/IPC +* Płaskie, serializowalne DTO (`String`, `u64`, `Vec<T>`, `Option<T>`) — bez referencji z lifetime'ami `'a` w publicznym API. +* Jawne, serializowalne błędy (`thiserror::Error` + `Serialize`) — **zero `panic!` przez granicę FFI** (panika przez FFI to Undefined Behavior w C/Swift/Kotlin). +* Zero typów zależnych od systemu operacyjnego (`std::os::unix`) na granicy API. + +## Zadania (`src/lib.rs`) +1. Zaimplementuj `validate_and_create_note(input: CreateNoteDto) -> Result<NoteDto, CoreError>` (walidacja pustego tytułu, generowanie prostego sluga lowercase z `-` zamiast spacji). +2. Wykorzystaj `thiserror::Error` w `CoreError` dla czytelnych komunikatów błędów. + +## Uruchomienie testów +```bash +make test PKG=eco03-shared-core-ffi +``` diff --git a/exercises/03-ecosystems/03-shared-core-ffi/src/lib.rs b/exercises/03-ecosystems/03-shared-core-ffi/src/lib.rs new file mode 100644 index 0000000..8164de2 --- /dev/null +++ b/exercises/03-ecosystems/03-shared-core-ffi/src/lib.rs @@ -0,0 +1,66 @@ +#![allow(unused_variables, dead_code)] + +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct CreateNoteDto { + pub title: String, + pub body: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct NoteDto { + pub slug: String, + pub title: String, + pub word_count: u32, +} + +#[derive(Debug, Error, Serialize, Deserialize, PartialEq, Eq)] +pub enum CoreError { + #[error("note title cannot be empty")] + EmptyTitle, + #[error("note body exceeds maximum length of {max} characters")] + BodyTooLong { max: usize }, +} + +pub fn validate_and_create_note(input: CreateNoteDto) -> Result<NoteDto, CoreError> { + todo!( + "Odrzuć pusty title (EmptyTitle), body > 500 znaków (BodyTooLong {{ max: 500 }}), zbuduj slug (lowercase, spacje -> '-') i policz word_count" + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn builds_ffi_friendly_note_dto() { + let dto = CreateNoteDto { + title: String::from(" Hello Rust Mobile "), + body: String::from("Shared core works on iOS and Android"), + }; + let note = validate_and_create_note(dto).unwrap(); + assert_eq!(note.slug, "hello-rust-mobile"); + assert_eq!(note.title, "Hello Rust Mobile"); + assert_eq!(note.word_count, 7); + } + + #[test] + fn returns_typed_errors_instead_of_panicking() { + let empty = CreateNoteDto { + title: String::from(" "), + body: String::from("ok"), + }; + assert_eq!(validate_and_create_note(empty), Err(CoreError::EmptyTitle)); + + let huge = CreateNoteDto { + title: String::from("Valid"), + body: "a".repeat(501), + }; + assert_eq!( + validate_and_create_note(huge), + Err(CoreError::BodyTooLong { max: 500 }) + ); + } +} diff --git a/exercises/03-ecosystems/04-wasm-logic/Cargo.toml b/exercises/03-ecosystems/04-wasm-logic/Cargo.toml new file mode 100644 index 0000000..0d1cc17 --- /dev/null +++ b/exercises/03-ecosystems/04-wasm-logic/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "eco04-wasm-logic" +version = "0.1.0" +edition = "2021" + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = "1" diff --git a/exercises/03-ecosystems/04-wasm-logic/README.md b/exercises/03-ecosystems/04-wasm-logic/README.md new file mode 100644 index 0000000..94d520b --- /dev/null +++ b/exercises/03-ecosystems/04-wasm-logic/README.md @@ -0,0 +1,13 @@ +# 04 — Logika pod WebAssembly (Frontend / Przeglądarka) + +Na froncie Rust najczęściej pełni rolę **szybkiego, deterministycznego modułu obliczeniowego (WASM)** wywoływanego z TypeScriptu (np. parsery, walidatory, wyszukiwarki, edytory), wymieniającego dane przez JSON lub binarne bufory. + +Moduł testujesz normalnie natywnie (`make test PKG=eco04-wasm-logic`), a w docelowej aplikacji webowej wystarczy dodać atrybut `#[wasm_bindgen]` i skompilować pod target `wasm32-unknown-unknown`. + +## Zadania (`src/lib.rs`) +1. `analyze_text_json(input_json: &str) -> Result<String, String>` — zdeserializuj `TextInput { text: String }`, policz liczbę znaków (`chars().count()`), słów i linii, a wynik zwróć jako zserializowany JSON `TextStats`. + +## Uruchomienie testów +```bash +make test PKG=eco04-wasm-logic +``` diff --git a/exercises/03-ecosystems/04-wasm-logic/src/lib.rs b/exercises/03-ecosystems/04-wasm-logic/src/lib.rs new file mode 100644 index 0000000..bf357fa --- /dev/null +++ b/exercises/03-ecosystems/04-wasm-logic/src/lib.rs @@ -0,0 +1,44 @@ +#![allow(unused_variables, dead_code)] + +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Deserialize)] +pub struct TextInput { + pub text: String, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] +pub struct TextStats { + pub chars: usize, + pub words: usize, + pub lines: usize, +} + +pub fn analyze_text_json(input_json: &str) -> Result<String, String> { + todo!("Deserializuj TextInput z JSON, policz chars/words/lines i zserializuj TextStats do JSON") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn processes_json_boundary_for_js_interop() { + let raw = r#"{"text":"Rust\nin browser"}"#; + let out_json = analyze_text_json(raw).unwrap(); + let stats: TextStats = serde_json::from_str(&out_json).unwrap(); + assert_eq!( + stats, + TextStats { + chars: 15, + words: 3, + lines: 2 + } + ); + } + + #[test] + fn returns_error_on_invalid_json() { + assert!(analyze_text_json("{invalid").is_err()); + } +} diff --git a/exercises/05-generics-traits/README.md b/exercises/05-generics-traits/README.md deleted file mode 100644 index 5a41a37..0000000 --- a/exercises/05-generics-traits/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# 05 — Generyki, Traity i Lifetimes - -## Zakres -* Funkcje i typy generyczne (`<T: PartialOrd>`) -* Definiowanie i implementowanie traitów (`trait Summary`) -* Podstawowe adnotacje czasu życia (`'a`) - -## Zadania (`src/lib.rs`) -1. `largest<T: PartialOrd>(items: &[T]) -> Option<&T>` — zwróć referencję do największego elementu w wycinku (lub `None` dla pustego wycinka). -2. Zaimplementuj trait `Summary` dla struktury `Article`. -3. `longest<'a>(x: &'a str, y: &'a str) -> &'a str` — zwróć dłuższy z dwóch napisów (gdy równe, zwróć `x`). - -## Uruchomienie testów -```bash -make test PKG=ex05-generics-traits -``` diff --git a/notes/01-rust-ecosystem-2026.md b/notes/01-rust-ecosystem-2026.md new file mode 100644 index 0000000..66217da --- /dev/null +++ b/notes/01-rust-ecosystem-2026.md @@ -0,0 +1,56 @@ +# Ekosystem Rusta i najważniejsze biblioteki (2026) + +Praktyczna mapa narzędzi i crate'ów — co wybrać do konkretnego zastosowania i kiedy **nie** warto sięgać po Rusta. + +--- + +## 1. Najważniejsze biblioteki uniwersalne (fundament każdego projektu) + +| Obszar | Standardowy crate | Do czego służy | +| :--- | :--- | :--- | +| **Serializacja / JSON / TOML** | `serde`, `serde_json`, `toml` | De facto standard serializacji struktur w Ruście (`#[derive(Serialize, Deserialize)]`). | +| **CLI (argumenty i podkomendy)** | `clap` (z feature `derive`) | Parsowanie flag, opcji, podkomend, automatyczny `--help` i walidacja. | +| **Obsługa błędów (biblioteki)** | `thiserror` | Generowanie `Display` i `std::error::Error` dla typowanych enumów błędów. | +| **Obsługa błędów (aplikacje/CLI)** | `anyhow` / `eyre` | Wygodne propagowanie dowolnych błędów z kontekstem (`.context("...")`) w binarkach. | +| **Async runtime** | `tokio` | Standardowy runtime asynchroniczny (`async`/`await`, sieci, timery, zadania w tle). | +| **Logowanie i telemetria** | `tracing`, `tracing-subscriber` | Strukturalne logi (JSON), spany, integracja z OpenTelemetry. | +| **Klient HTTP** | `reqwest` | Wykonywanie zapytań HTTP (async/blocking, JSON, TLS). | +| **Czas i daty** | `chrono` lub `jiff` / `time` | Operacje na datach, strefach czasowych i formatowaniu ISO-8601. | +| **Testy i property-based** | `proptest`, `insta`, `wiremock` | Testy generatywne, snapshot testing i mockowanie zewnętrznych API HTTP. | + +--- + +## 2. Platformy i Frameworki + +### Linux / Windows / macOS (CLI, TUI, Daemony, Desktop) +* **CLI:** `clap` + `anyhow` + `indicatif` (paski postępu). +* **TUI (aplikacje terminalowe):** `ratatui` + `crossterm` (działa identycznie na Linux, macOS i Windows). +* **Desktop GUI:** + * **Tauri v2** — backend/logika w Ruście, lekki frontend w HTML/CSS/TS (natywny WebView systemu, małe binarki). + * **iced** / **egui** / **Slint** — natywne GUI w czystym Ruście (gdy nie chcesz warstwy webowej). + +### Web — Backend +* **`axum`** — obecny lider (od twórców `tokio`, świetna ergonomia, oparty o `tower`). +* **`actix-web`** — bardzo dojrzały i ekstremalnie szybki, popularny w dużych systemach. +* **Bazy danych:** + * **`sqlx`** — asynchroniczny SQL ze sprawdzaniem zapytań w czasie kompilacji (PostgreSQL, SQLite, MySQL). + * **`sea-orm`** / **`diesel`** — gdy preferujesz pełny ORM. + +### Web — Frontend (WebAssembly / WASM) +* **`wasm-bindgen` + `wasm-pack`** — kompilacja logiki Rusta do WASM wywoływanego z TypeScriptu/JS (najczęstsze i najbardziej pragmatyczne użycie: parsery, wyszukiwarki, kryptografia, silniki edytorów). +* **`Leptos`** / **`Dioxus`** — full-stack / frontendowe frameworki w czystym Ruście (reaktywne sygnały w stylu SolidJS). Dobre do eksperymentów i aplikacji typu dashboard, ale w typowych projektach biznesowych nadal częściej wygrywa TS/React + ewentualny moduł WASM w Ruście. + +### Mobile — iOS i Android +W praktyce w Ruście rzadko pisze się warstwę UI dla iOS/Androida. Dominują dwa modele: +1. **Shared Core + `UniFFI` (Mozilla):** wspólna logika biznesowa, synchronizacja, baza lokalna (SQLite) i kryptografia w jednym crate'cie Rusta, z którego `UniFFI` generuje natywne bindingi dla **Swift (iOS)** i **Kotlin (Android)**. +2. **Tauri v2 Mobile:** jedna aplikacja z rdzeniem w Ruście i wspólnym UI webowym na Desktop + iOS + Android. + +--- + +## 3. Kiedy NIE wybierać Rusta? (Świadomość architektoniczna 2026) + +Rust jest świetny tam, gdzie liczą się **wydajność, niskie zużycie pamięci, brak GC, niezawodność, pojedyncza binarka CLI lub bezpieczeństwo współbieżności**. +Nie jest najlepszym wyborem, gdy: +* potrzebujesz jednorazowego skryptu do analizy CSV/danych (Python będzie szybszy w iteracji), +* budujesz prosty panel administracyjny lub typowy frontend webowy (TypeScript + standardowy ekosystem webowy), +* zespół potrzebuje natychmiastowego prototypu bez czasu na walkę z borrow checkerem i długim czasem kompilacji ciężkich zależności. diff --git a/notes/README.md b/notes/README.md index e96538a..addd25e 100644 --- a/notes/README.md +++ b/notes/README.md @@ -3,3 +3,4 @@ Miejsce na własne notatki, podsumowania rozdziałów i najczęstsze błędy kompilatora. * [00 — Ściągawka Rust & Cargo](00-cheatsheet.md) +* [01 — Ekosystem Rusta i najważniejsze biblioteki (2026)](01-rust-ecosystem-2026.md)