feat: reorganize workbook into 3 tracks (core, engineering-2026, ecosystems)

This commit is contained in:
soda64 committed 2026-11-30 22:30:53 +01:00
1 parent 82677455b2
commit 2e002b6176
64 files changed
+2295 -196

No files matched your search

-18
View File
@@ -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
```
-53
View File
@@ -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");
}
}
@@ -1,4 +1,4 @@
[package]
name = "ex01-basics"
name = "core01-basics"
version = "0.1.0"
edition = "2021"
+20
View File
@@ -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
```
+77
View File
@@ -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");
}
}
@@ -1,4 +1,4 @@
[package]
name = "ex02-ownership"
name = "core02-ownership"
version = "0.1.0"
edition = "2021"
@@ -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
```
File renamed without changes.
@@ -1,4 +1,4 @@
[package]
name = "ex05-generics-traits"
name = "core03-structs-enums"
version = "0.1.0"
edition = "2021"
@@ -3,14 +3,14 @@
## Zakres
* Definiowanie `struct` oraz metod w blokach `impl`
* `enum` z danymi (*algebraic data types*)
* `match`, `Option<T>`, `Result<T, E>`
* `match`, `Option<T>`
## 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<f64>` — zwróć `None` przy dzieleniu przez `0.0`, w przeciwnym razie `Some(a / b)`.
3. `safe_divide(a: f64, b: f64) -> Option<f64>` — `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
```
@@ -0,0 +1,4 @@
[package]
name = "core04-collections-errors"
version = "0.1.0"
edition = "2021"
@@ -6,11 +6,11 @@
* Własne typy błędów (`enum`)
## Zadania (`src/lib.rs`)
1. `word_counts(text: &str) -> HashMap<String, usize>` — policz wystąpienia słów (case-insensitive, po podziale po białych znakach).
2. `parse_positive_i32(input: &str) -> Result<i32, ParsePositiveError>` — sparsuj tekst do `i32` i odrzuć wartości `<= 0` odpowiednim wariantem błędu.
3. `sum_parsed_positives(inputs: &[&str]) -> Result<i32, ParsePositiveError>` — zsumuj listę tekstów, propagując pierwszy napotkany błąd przez `?`.
1. `word_counts(text: &str) -> HashMap<String, usize>` — policz wystąpienia słów (case-insensitive).
2. `parse_positive_i32(input: &str) -> Result<i32, ParsePositiveError>` — sparsuj tekst do `i32` i odrzuć wartości `<= 0`.
3. `sum_parsed_positives(inputs: &[&str]) -> Result<i32, ParsePositiveError>` — 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
```
@@ -0,0 +1,4 @@
[package]
name = "core05-generics-traits"
version = "0.1.0"
edition = "2021"
@@ -0,0 +1,16 @@
# 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>` — 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
```
@@ -0,0 +1,4 @@
[package]
name = "core06-iterators-closures"
version = "0.1.0"
edition = "2021"
@@ -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<F>(items: &[i32], predicate: F) -> Vec<i32>` — odfiltruj elementy spełniające `predicate` i pomnóż każdy przez 2.
3. `non_empty_trimmed(lines: &[&str]) -> Vec<String>` — przytnij białe znaki (`trim`) i odrzuć puste linie.
## Uruchomienie testów
```bash
make test PKG=core06-iterators-closures
```
@@ -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<F>(items: &[i32], predicate: F) -> Vec<i32>
where
F: Fn(i32) -> bool,
{
todo!("Odfiltruj items przez predicate i pomnóż każdy przez 2")
}
pub fn non_empty_trimmed(lines: &[&str]) -> Vec<String> {
todo!("Przytnij białe znaki i zwróć tylko niepuste linie jako Vec<String>")
}
#[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"]);
}
}
@@ -0,0 +1,4 @@
[package]
name = "core07-data-structures"
version = "0.1.0"
edition = "2021"
@@ -0,0 +1,16 @@
# 07 — Struktury Danych (Data Structures)
## Zakres
* Własny stos generyczny `Stack<T>` na bazie `Vec<T>`
* Kolejka `Queue<T>` na bazie `VecDeque<T>`
* Jednokierunkowa lista łączona `LinkedList<T>` z użyciem `Option<Box<Node<T>>>` (świetny trening dla `Option::take()` i ownershipu na stercie)
## Zadania (`src/lib.rs`)
1. Zaimplementuj `Stack<T>`: `new`, `push`, `pop`, `peek`, `is_empty`.
2. Zaimplementuj `Queue<T>`: `new`, `enqueue`, `dequeue`, `len`.
3. Zaimplementuj `LinkedList<T>`: `new`, `push_front`, `pop_front`.
## Uruchomienie testów
```bash
make test PKG=core07-data-structures
```
@@ -0,0 +1,122 @@
#![allow(unused_variables, dead_code)]
use std::collections::VecDeque;
#[derive(Debug, Default)]
pub struct Stack<T> {
items: Vec<T>,
}
impl<T> Stack<T> {
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<T> {
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<T> {
items: VecDeque<T>,
}
impl<T> Queue<T> {
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<T> {
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<T> {
value: T,
next: Option<Box<Node<T>>>,
}
#[derive(Default)]
pub struct LinkedList<T> {
head: Option<Box<Node<T>>>,
}
impl<T> LinkedList<T> {
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<T> {
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);
}
}
@@ -0,0 +1,4 @@
[package]
name = "core08-oop-composition"
version = "0.1.0"
edition = "2021"
@@ -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<dyn Trait>`).
## 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<Box<dyn Notifier>>`: metoda `broadcast(&self, msg: &str) -> Vec<String>`.
## Uruchomienie testów
```bash
make test PKG=core08-oop-composition
```
@@ -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<Box<dyn Notifier>>,
}
impl AlertService {
pub fn new() -> Self {
todo!("Utwórz pusty AlertService")
}
pub fn register(&mut self, notifier: Box<dyn Notifier>) {
todo!("Dodaj notifier do listy")
}
pub fn broadcast(&self, msg: &str) -> Vec<String> {
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"]);
}
}
@@ -0,0 +1,4 @@
[package]
name = "core09-design-patterns"
version = "0.1.0"
edition = "2021"
@@ -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<Draft>` -> `publish()` -> `Document<Published>` — wzorzec Typestate (`PhantomData`).
4. `DiscountStrategy` + `PercentageDiscount` + `apply_discount` — wzorzec Strategy.
## Uruchomienie testów
```bash
make test PKG=core09-design-patterns
```
@@ -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:<id> order:<id>\"")
}
// --- 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<String>) -> Self {
todo!("Utwórz builder z domyślną metodą \"GET\" i timeout_ms = 3000")
}
pub fn method(mut self, method: impl Into<String>) -> 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<State> {
title: String,
_state: PhantomData<State>,
}
impl Document<Draft> {
pub fn new(title: impl Into<String>) -> Self {
todo!("Utwórz dokument w stanie Draft")
}
pub fn publish(self) -> Document<Published> {
todo!("Przejdź ze stanu Draft do Published")
}
}
impl Document<Published> {
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);
}
}
@@ -0,0 +1,4 @@
[package]
name = "core10-crud-repository"
version = "0.1.0"
edition = "2021"
@@ -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<u64, Task>` (deterministyczna kolejność)
## Zadania (`src/lib.rs`)
Zaimplementuj `TaskStore`:
1. `create(&mut self, title: impl Into<String>) -> Result<Task, RepoError>`
2. `get(&self, id: u64) -> Option<&Task>`
3. `list(&self) -> Vec<&Task>`
4. `update_title(&mut self, id: u64, title: impl Into<String>) -> Result<Task, RepoError>`
5. `mark_done(&mut self, id: u64) -> Result<Task, RepoError>`
6. `delete(&mut self, id: u64) -> Result<Task, RepoError>`
## Uruchomienie testów
```bash
make test PKG=core10-crud-repository
```
@@ -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<u64, Task>,
}
impl TaskStore {
pub fn new() -> Self {
Self {
next_id: 1,
tasks: BTreeMap::new(),
}
}
pub fn create(&mut self, title: impl Into<String>) -> Result<Task, RepoError> {
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<String>) -> Result<Task, RepoError> {
todo!("Zwaliduj tytuł, zaktualizuj istniejące zadanie lub zwróć NotFound(id)")
}
pub fn mark_done(&mut self, id: u64) -> Result<Task, RepoError> {
todo!("Ustaw done = true lub zwróć NotFound(id)")
}
pub fn delete(&mut self, id: u64) -> Result<Task, RepoError> {
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);
}
}
@@ -1,4 +1,4 @@
[package]
name = "ex03-structs-enums"
name = "eng01-ai-code-audit"
version = "0.1.0"
edition = "2021"
@@ -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
```
@@ -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<u16, String> {
// 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<f64> {
// 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);
}
}
@@ -1,4 +1,4 @@
[package]
name = "ex04-collections-errors"
name = "eng02-type-driven-design"
version = "0.1.0"
edition = "2021"
@@ -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<Email, ValidationError>` — konstrukcja możliwa wyłącznie przez walidujący konstruktor (pole wewnętrzne prywatne).
2. `Money::checked_add(self, other: Money) -> Result<Money, CurrencyMismatch>` — bezpieczne dodawanie kwot w groszach/centach z kontrolą waluty.
## Uruchomienie testów
```bash
make test PKG=eng02-type-driven-design
```
@@ -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<Self, ValidationError> {
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<Money, CurrencyMismatch> {
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));
}
}
@@ -0,0 +1,4 @@
[package]
name = "eng03-cross-platform"
version = "0.1.0"
edition = "2021"
@@ -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ę `<base_dir>/<app_name>/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
```
@@ -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"));
}
}
@@ -0,0 +1,4 @@
[package]
name = "eng04-best-practices"
version = "0.1.0"
edition = "2021"
@@ -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<E>` 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<ParseIntError>` dla `ConfigError`.
3. Zaimplementuj `parse_timeout_secs(raw: &str) -> Result<u64, ConfigError>` (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
```
@@ -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<ParseIntError> for ConfigError {
fn from(err: ParseIntError) -> Self {
todo!("Zamień ParseIntError na ConfigError::InvalidNumber(err.to_string())")
}
}
pub fn parse_timeout_secs(raw: &str) -> Result<u64, ConfigError> {
todo!("Trim -> Missing jeśli pusty -> parse::<u64>()? -> 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());
}
}
@@ -0,0 +1,7 @@
[package]
name = "eco01-cli-clap"
version = "0.1.0"
edition = "2021"
[dependencies]
clap = { version = "4", features = ["derive"] }
@@ -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<Cli, clap::Error>` 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
```
@@ -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<Cli, clap::Error> {
todo!("Użyj Cli::try_parse_from(args)")
}
pub fn describe_command(cli: &Cli) -> String {
todo!(
"Zwróć: Add -> \"add:<title>: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());
}
}
@@ -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"] }
@@ -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
```
@@ -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);
}
}
@@ -0,0 +1,8 @@
[package]
name = "eco03-shared-core-ffi"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = { version = "1", features = ["derive"] }
thiserror = "2"
@@ -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
```
@@ -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 })
);
}
}
@@ -0,0 +1,8 @@
[package]
name = "eco04-wasm-logic"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
@@ -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
```
@@ -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());
}
}
-16
View File
@@ -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
```