Deep Dive: egui/eframe for instant UIs — why Immediate Mode fits system languages, State management with Rust's ownership, Layout & Style, Custom painting, and when Retained Mode is the better choice.
Deep dive: atomic operations, memory orderings, and CAS loops — tools without locks but with sharper contracts. When atomics shine and when the mutex stays.
This module ties your knowledge together into a real project: a Static Site Generator (SSG). An SSG turns text files into HTML pages — that's how countless blogs and documentation sites (e.g. many Rust crates) work.
Your mini SSG should:
This connects Modules 6 (Collections), 7 (Errors), 8 (Traits/Generics), 10 (Closures/Iterators), 15 (Testing), 16 (Workspace & cargo), 18 (I/O), and 19 (Macros).
Why this project?
An SSG is fully runnable in the browser sandbox: it works on text in memory (String → blocks → HTML) instead of files or the network. So you can try every step directly — and still understand the filesystem version as a real CLI at the end.
Check: What is the core task of a static site generator?
Answer: Convert text into HTML pages
An SSG takes text (e.g. Markdown-like) and produces HTML pages from it — no server at runtime, hence 'static'.
⚠ Common mistake: Skipping the intermediate model and gluing raw input text straight into the HTML template means you can neither validate structure nor escape deliberately — and every new element (lists, code blocks) worms through the entire output. Splitting
parseandrenderisn't bureaucracy: it keeps the two halves independently testable.
Takeaways:
The heart is our data model: a Block enum that describes the building
blocks of a page. The parser fills it, the renderer reads it — both only hang
off this type:
#[derive(Debug, PartialEq, Clone)]
pub enum Block {
Heading(u32, String), // level (1,2,3...) and text
Paragraph(String),
}
Heading(u32, String) is a struct variant with two fields: the heading
level and the text. PartialEq and Debug come from derive — important for
tests (assert_eq!) and error messages.
Enum as a shared interface
Parser and renderer communicate only through the Block type. As long as
both know the same type, you can test and extend them independently. A cleanly
chosen data model is half the architecture — a lesson from Module 5 (Enums) and
8 (Traits).
Check: Why is PartialEq important on our Block enum?
Answer: So assert_eq! can compare blocks in tests
PartialEq enables equality comparisons, which assert_eq! needs in tests to compare expected with actual blocks.
⚠ Common mistake: Without
#[derive(PartialEq, Debug)],assert_eq!onBlockvalues doesn't compile — the compiler reports E0369 ("binary operation==cannot be applied to typeBlock"), and even a plain==has no failure output withoutDebug. Both traits aren't in the derive list for decoration.
Takeaways:
Our parser reads the text line by line and builds blocks:
# → heading (count of # = level)pub fn parse(text: &str) -> Vec<Block> {
let mut blocks = Vec::new();
let mut para = Vec::new();
for line in text.lines() {
if line.starts_with('#') {
if !para.is_empty() {
blocks.push(Block::Paragraph(para.join(" ")));
para.clear();
}
let level = line.chars().take_while(|&c| c == '#').count() as u32;
let content = line
.chars()
.skip(level as usize)
.collect::<String>()
.trim()
.to_string();
blocks.push(Block::Heading(level, content));
} else if line.trim().is_empty() {
if !para.is_empty() {
blocks.push(Block::Paragraph(para.join(" ")));
para.clear();
}
} else {
para.push(line.trim().to_string());
}
}
if !para.is_empty() {
blocks.push(Block::Paragraph(para.join(" ")));
}
blocks
}
// → parse("# Title\n\ntext") yields [Heading(1, "Title"), Paragraph("text")]
A paragraph spanning multiple lines is joined with join(" ") into one
Paragraph.
The state pattern in the parser
The parser holds a small state (para) while walking the lines. At
structure changes (heading, blank line) it "flushes" the state into the output.
This pattern — holding state, releasing it at boundaries — recurs in almost
every parser.
Check: What happens when the parser hits an empty line?
Answer: It closes the running paragraph into a block
An empty line marks the end of a paragraph: the collected text is stored as a Paragraph block and the state is flushed.
⚠ Common mistake: Forget to push the leftover
paraintoblocksafter the loop and you silently lose the last paragraph — precisely when the text doesn't end with a blank line. The bug stays hidden because almost every test input politely ends with\n\n.
Takeaways:
The renderer does the opposite of the parser: it translates Blocks into HTML
strings:
pub fn render_block(block: &Block) -> String {
match block {
Block::Heading(level, text) => format!("<h{level}>{}</h{level}>", escape(text)),
Block::Paragraph(text) => format!("<p>{}</p>", escape(text)),
}
}
// → render_block(&Block::Paragraph("a & b")) yields "<p>a & b</p>"
User text must never land unchanged in HTML — otherwise a <script>
injection ("XSS") is possible. We replace the dangerous characters:
pub fn escape(s: &str) -> String {
s.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
}
// → escape("<script>&") yields "<script>&"
So <script>& becomes <script>& — harmless visible text in the
browser.
Trust boundaries: user input != HTML
Every place foreign text flows into output is a trust boundary. Escaping belongs in the renderer, before HTML is built — not at the caller, and not optional. This is not a nice-to-have but the basis of safe output.
Check: Why do we escape HTML special characters?
Answer: To neutralize injections like <script>
Writing raw user HTML into the output allows script injection (XSS). Escaping turns foreign text into harmless, visible text.
⚠ Common mistake: Replace
&last and you escape twice: the entities you already emitted for the angle brackets contain an&themselves, which the final replace turns into&again — the browser then literally shows the text "<" instead of a bracket. That's why the&replace comes first inescape.
Takeaways:
A real HTML page needs <!DOCTYPE html>, <head>, <title>, and <body>.
Our render_page function builds the complete document:
pub fn render_page(title: &str, blocks: &[Block]) -> String {
let body: String = blocks
.iter()
.map(render_block)
.collect::<Vec<_>>()
.join("\n");
format!(
"<!DOCTYPE html>\n<html>\n<head><meta charset=\"utf-8\">\
\n<title>{}</title></head>\n<body>\n{}\n</body>\n</html>\n",
escape(title),
body
)
}
blocks.iter().map(render_block) converts every block to HTML (map),
collects the result (collect), and joins the pieces with \n (join) — a
showcase of the iterator tools from Module 10.
Instead of only returning strings, we use the Write trait (Module 18) — so we
can write into a Vec<u8>, files, or even network streams:
use std::io::Write;
pub fn build_to_writer<W: Write>(
w: &mut W,
title: &str,
blocks: &[Block],
) -> std::io::Result<()> {
let html = render_page(title, blocks);
w.write_all(html.as_bytes())
}
<W: Write> is a generic parameter: the function accepts any writer that
implements the Write trait.
Generic over Write = maximum reuse
Thanks to W: Write our builder isn't tied to concrete outputs: in the sandbox
test we write into a Vec<u8>, in the CLI version into a file via
std::fs::File — both implement Write. One interface, many targets (Modules
8, 18).
Check: What does the generic parameter W: Write enable?
Answer: The same function writes into Vec, file, or stream
Any type implementing Write (Vec<u8>, File, Stream) is allowed as a target — one function, many output channels.
⚠ Common mistake:
writemay write fewer bytes than requested and only tells you through its return value — swappingwrite_allforwriteand ignoring the returned length silently truncates the HTML output.write_allloops internally until everything is really out.
Takeaways:
Our generator lives in a library (src/lib.rs) — clean, reusable logic.
The entry point (binary) is a thin CLI that reads files and writes HTML:
// src/main.rs (Binary) — just the entry
use std::fs;
use minissg::{parse, render_page};
fn main() -> std::io::Result<()> {
let src = fs::read_to_string("index.md")?;
let blocks = parse(&src);
let html = render_page("My page", &blocks);
fs::write("index.html", html)?;
Ok(())
}
In Cargo.toml the binary is just a file that uses the library as a path
dependency (workspace concept from Module 16):
[package]
name = "minissg"
[dependencies]
minissg-lib = { path = "lib" }
Thin binary, fat library
All the testing and maintenance weight lives in the library — parsing, rendering, and layout are there. The binary is deliberately thin: it just wires file → parse → render → file. Thanks to the split you can unit-test the logic without starting a CLI.
Check: Why does the logic live in a library instead of the binary?
Answer: So it's unit-testable and reusable
Logic in the library is isolated-testable and reusable; the binary stays a thin entry point. That eases testing and maintenance.
⚠ Common mistake: Cargo translates hyphens in crate names to underscores: the dependency
minissg-libbecomesminissg_libin code. Writinguse minissg-lib::parse;fails at parse time — the compiler suggests the underscore spelling; theCargo.tomlkeeps the hyphen, theusepath never does.
Takeaways:
A project is only done when it's securable. Our three key tests cover parser, security, and output:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_headings_and_paragraphs() {
let blocks = parse("# Title\n\na paragraph.\nand more.");
assert_eq!(
blocks,
vec![
Block::Heading(1, "Title".to_string()),
Block::Paragraph("a paragraph. and more.".to_string()),
]
);
}
#[test]
fn escapes_html() {
assert_eq!(escape("<script>&"), "<script>&");
}
#[test]
fn renders_writer_output() {
let mut buf = Vec::new();
let blocks = parse("# Hi");
build_to_writer(&mut buf, "Page", &blocks).unwrap();
let html = String::from_utf8(buf).unwrap();
assert!(html.contains("<h1>Hi</h1>"));
assert!(html.contains("<title>Page</title>"));
}
}
Each test secures a property: sensible parsing, safe output, correct writer path. These three together catch the most common regressions.
What makes a good capstone?
A capstone joins many modules into a tested, working whole — not a pile of endless features. Whoever masters parsing, rendering, layout, workspace, and tests here has traversed this course's Rust path: from basics to safe, reusable program architecture.
Rust in the real world: AI tools and systems programming
Rust is not just a teaching language — it powers current AI tools and systems projects:
Your capstone is a complete static site generator: parsing, rendering, I/O, tests. The same skills — safe systems programming, error handling, performant I/O — make Rust the language of choice for AI infrastructure.
Check: What purpose does the escapes_html test serve?
Answer: It secures the safety property of the output
The test checks that special characters become harmless HTML entities — i.e. the safety property against XSS vulnerabilities.
Scenario: The marketing site
⚠ Common mistake:
assert_eq!(block, Block::Heading(1, "Title"))doesn't compile — E0308 ("mismatched types"): the enum field wants aString, but"Title"is a&str. Append.to_string()as in the test above instead of mixing&strliterals intoStringfields.
Takeaways:
Course navigation: ← Module 21 · All 27 modules · Module 23 →