Side A introduces a substantive architectural artifact (RouteContext wrapper plus a detailed migration plan for ItemId/routing) that guides real future refactoring work, even if incomplete. Side B is almost entirely mechanical rustfmt/tooling churn (reformatting durable/* examples and tests, toolchain pinning, vscode settings) with only a trivial CSS dedup and no functional improvement, offering little lasting design value beyond formatting consistency.
constitution · epochs · watch · epoch 3
c_7ec67b9cef2c (tommy-mor) vs c_9e1ff4fc0186 (tommy-mor)
download prompt · raw event · cmp_2e638f970b75d1
council reasoning
A adds lasting design value: a concrete RouteContext API (routing.rs + re-export) and a detailed ItemId migration plan that stages real architecture work. B is almost entirely rustfmt churn across examples/lib plus minor toolchain/VS Code pins and a one-line CSS merge, with negligible lasting product substance.
Side A introduces a new `RouteContext` abstraction (`server/src/html/routing.rs`) and exports it from `server/src/html/mod.rs`, creating a centralized API for scoped URL generation (`item_href`, `thread_url`, room/public handling) that supports an ongoing architectural refactor. It also adds a detailed migration plan (`plan.md`) documenting the intended replacement of `CanonicalItemUrl` with `ItemId` and the phased implementation strategy, whereas Side B is overwhelmingly workspace-wide formatting plus tooling configuration (`rust-toolchain.toml`, VS Code settings) with only a minor CSS rule merge and no substantial behavioral change.
sides
A — c_7ec67b9cef2c (tommy-mor)
message
[1c914c6e] stage set
diff preview
diff --git a/plan.md b/plan.md
new file mode 100644
index 0000000000000000000000000000000000000000..00d6867a1e0ed144a16a020ea037f685ce646c73
--- /dev/null
+++ b/plan.md
@@ -0,0 +1,155 @@
+# Plan: `ItemId` + `RouteContext` (identity vs hrefs)
+
+This document is for **the next agent** to continue the refactor without re-deriving context from chat. It supersedes ad-hoc notes: treat it as the checklist of record until the work lands and this file is deleted or trimmed.
+
+## Goal
+
+- **Identity** (what lives in the reducer graph, votes, indexes) becomes a **structural `ItemId` enum** in `slug-types`, not a canonical `String` / `CanonicalItemUrl` newtype.
+- **Presentation** (tilde / dash display, breadcrumbs) derives from `ItemId` via explicit methods, not string stripping.
+- **Routing** (browser `href`s for public vs room) goes through **`RouteContext`** (started in `server/src/html/routing.rs`) so Maud/handlers do not stitch `/r/…` vs `/~` ad hoc.
+
+**Non-goals for v1 of the migration:** backward-compatible JSONL or dual-read of old canonical strings in the event log (project has accepted breaking changes). If you reintroduce compat, document it here.
+
+## Current state (as of this plan)
+
+- **`CanonicalItemUrl`** (`types/src/paths.rs`): newtype around `String`; `parse` / `parent` / `display_path` / `tilde_tail` / etc. Reducer `ContentState`, `VoteData`, ranking, RPC, search, garden, breadcrumbs all use it or `String` keys derived from it.
+- **`ThreadNav`** (`server/src/html/forum/nav.rs`): encodes scope prefixes for threads and garden URLs; **`RouteContext`** now wraps `ThreadNav` (`server/src/html/routing.rs`, re-exported from `server/src/html/mod.rs`) but **most HTML still takes `&ThreadNav` directly** — migration incomplete.
+- **URL normalization** lives in `types/src/url_normalize.rs` + `canonicalize_item` / `finalize_external_identity_url` in `paths.rs` (YouTube, sorted query params, room path `room_route_segment` in `paths.rs`).
+- **Room HTTP paths** are `/r/{short}{slug}` (fused segment); wire **`room_id`** remains `short/slug` for RPC/events.
+
+## Target architecture
+
+### `ItemId` (types)
+
+Suggested shape (adjust after profiling `Ord` / `Hash` / serde size):
+
+```text
+ItemId::Root — tilde ontology root (today `SLUG_TILDE_ONTOLOGY_ROOT`)
+ItemId::Local { segments } — slug.social ~/… path as Vec<String> (lowercase segments, non-empty for non-root)
+ItemId::External { url: Url } — normalized `url::Url` (crate `url` already in `slug-types`)
+```
+
+**API surface (minimum):**
+
+- `ItemId::parse(&str) -> Option<ItemId>` — single entry from DSL / user input / legacy wire (internally may call `canonicalize_item` + structured split).
+- `ItemId::to_wire_url(&self) -> String` — only for **external** boundaries if needed (HTTP fetch, rare assertions); avoid using as the primary key once maps use `ItemId`.
+- `parent`, `display_path`, `tilde_tail` / `tilde_http_tail`, `tilde_segments`, `last_segment`, `normalized_storage` — port from `CanonicalItemUrl`.
+- **`Ord` + `Hash` + `Eq`** stable for `BTreeSet` / `HashMap` (see `write_actor` scope-rank snapshots).
+- **`Serialize` / `Deserialize`** — decide **tagged JSON** for any persisted or API-carried structs (e.g. `VoteData` in tests). If RPC must stay stringy for clients, use a **DTO layer** that converts `ItemId` ↔ wire at the boundary only.
+
+**Remove:** `CanonicalItemUrl` type and all `path_types::CanonicalItemUrl` / `slug_types::paths::CanonicalItemUrl` exports once call sites are migrated. **`Borrow<str>`** on the old newtype goes away; update `nav!` / any code that assumed map keys borrowed as `str`.
+
+### `RouteContext` (server HTML)
+
+- **File:** `server/src/html/routing.rs` — **`RouteContext(ThreadNav)`** with `item_href`, `item_href_raw`, `thread_url`, `garden_root_url`, `room_url`, `From`/`Into` `ThreadNav`.
+- **Direction:** new code and refactored Maud should take **`&RouteContext`** (or owned where appropriate) instead of `&ThreadNav` when building links. Long term, **`item_href(&ItemId)`** should not parse strings — it should pattern-match `ItemId` and append tilde tail or `/-/…` external tail using the same rules as today’s `ThreadNav::garden_item_url`.
+
+### Axum / garden routes
+
+- **No** single catch-all route (explicit decision): keep the existing router layout in `server/src/lib.rs`.
+- Room routes stay **`/r/:room_key/...`** with `room_key` fused; parsing via `slug_types::room_id_from_route_segment` / `room_route_segment` in `paths.rs`.
+
+## Phased execution (recommended order)
+
+### Phase 0 — Preconditions (quick)
+
+1. Read **`AGENTS.md`** (UI contract, durability matrix, `RpcCommand` vs `HtmlUiAction`).
+2. Run **`cargo test --workspace`** and **`./scripts/clj-test.sh`** on clean `main` before large diffs; repeat after each phase.
+
+### Phase 1 — `ItemId` in `slug-types` (no server yet)
+
+1. Add **`ItemId`** (new file e.g. `types/src/item_id.rs` **or** inline at bottom of `paths.rs` — see **Module cycle** below).
+2. Implement **`ItemId::parse`** using existing **`canonicalize_item`** + normalization; port **`CanonicalItemUrl`** methods to **`ItemId`** with tests ported from `paths.rs` `#[cfg(test)] mod tests`.
+3. **`GardenItemUrl::from_stored(&ItemId, room_wire)`** (and thread helpers) — build absolute hrefs from structure, not from re-parsing a canonical string.
+4. **`TildeHttpPathTail::to_item_id`** (rename from `to_canonical`) / **`tilde_http_path_to_item_id`**.
+5. **`TildeOntologyPath::from_stored(&ItemId)`**.
+6. Export **`ItemId`** from **`types/src/lib.rs`**; update **`server/src/path_types.rs`** re-exports.
+7. **Delete `CanonicalItemUrl`** and fix all **in-crate** references in `types` only until `cargo test` passes for `slug-types`.
+
+**Module cycle trap:** `item_id.rs` must not `use crate::paths::{...}` if `paths.rs` also imports `ItemId` for `GardenItemUrl` in the same module. **Fix one of:**
+
+- **A)** Put `ItemId` **inside `paths.rs`** below `canonicalize_item` / helpers (simplest, large file), or
+- **B)** Split **`canonicalize_item`** (+ dash host helpers + `finalize_external_identity_url`) into **`types/src/item_wire.rs`**, then `paths.rs` + `item_id.rs` both depend on `item_wire` only (cleaner, more files).
+
+### Phase 2 — Reducer + ranking (server core)
+
+1. **`server/src/reducer.rs`**: `ContentState` / `GroupState` / **`VoteData`** — replace **`CanonicalItemUrl`** with **`ItemId`** on all maps, sets, deques, vectors.
+2. **`apply_vote`**: normalize `a`/`b` via **`ItemId::parse`** or **`ItemId`**-aware logic (remove string round-trip).
+3. **`apply_ingest_to_content`**: **`dsl`** still yields strings for item titles in statements; normalize to **`ItemId`** at ingest boundary via **`ItemId::parse`** once per item.
+4. **`server/src/ranking.rs`**, **`server/src/scope_rank.rs`**, **`server/src/api/write_actor.rs`** (including **`BTreeSet`** ordering), **`server/src/api/validate.rs`**, **`server/src/api/helpers.rs`** — propagate **`ItemId`**.
+5. **`server/tests/basic.rs`** and any reducer tests constructing **`VoteData`** — use **`ItemId::parse(...).unwrap()`** or helpers.
+
+### Phase 3 — RPC + search + external resolver
+
+1. **`server/src/api/rpc.rs`**: rank/pair/matchup/search payloads; today many paths use **`GardenItemUrl::from_storage_str(item.as_str(), …)`** — switch to **`ItemId`** + **`GardenItemUrl::from_stored(&item_id, …)`** (or equivalent).
+2. **`server/src/html/search.rs`**: scoring uses item path strings — derive from **`ItemId::display_path`** / **`to_wire_url`** only at the scoring boundary if needed.
+3. **`server/src/external_resolver.rs`**: take **`&ItemId`** or **`ItemId::external_url()`** instead of **`&CanonicalItemUrl`**.
+
+### Phase 4 — HTML / Maud
+
+1. **`ThreadNav::garden_item_url`**: overload or replace with **`garden_item_href(&self, item: &ItemId)`** (no `CanonicalItemUrl::parse` inside).
+2. **`RouteContext`**: extend **`item_href(&ItemId)`**; migrate call sites from **`ThreadNav`** to **`RouteContext`** where only link-building is needed (keep **`ThreadNav`** where scope / auth helpers need the full struct).
+3. **`server/src/html/garden.rs`**, **`breadcrumb_path.rs`**, **`forum/*`**, **`editor.rs`**: replace **`CanonicalItemUrl`** with **`ItemId`**; breadcrumbs should walk **`ItemId::parent`** without string `rsplit`.
+4. **`types` JSON types** (`RankRow`, etc.): decide whether **`GardenItemUrl`** stays string for JSON or becomes a structured field; keep **one** wire format for the public API.
+
+### Phase 5 — Cleanup + docs
+
+1. Remove dead **`canonical_path`** / **`breadcrumb_path`** string logic if fully superseded.
+2. Update **`AGENTS.md`** if durability, `POST /ui`, or command surfaces change.
+3. Delete or shrink **`plan.md`** when done.
+
+## File / symbol checklist (non-exhaustive — grep-driven)
+
+Run periodically:
+
+```bash
+rg "CanonicalItemUrl" -g'*.rs'
+rg "path_types::CanonicalItemUrl" -g'*.rs'
+rg "tilde_http_path_to_canonical" -g'*.rs'
+```
+
+**High-touch files (from prior exploration):**
+
+| Area | Files |
+|------|--------|
+| Types | `types/src/paths.rs`, `types/src/lib.rs`, `types/src/url_normalize.rs`, (optional) `types/src/item_id.rs`, `types/src/item_wire.rs` |
+| Server re-exports | `server/src/path_types.rs`, `server/src/canonical_path.rs` |
+| Reducer / ingest | `server/src/reducer.rs`, `server/src/dsl.rs` (parse output types if changed) |
+| Ranking | `server/src/ranking.rs`, `server/src/scope_rank.rs` |
+| Writer / RPC | `server/src/api/write_actor.rs`, `server/src/api/rpc.rs`, `server/src/api/helpers.rs`, `server/src/api/validate.rs` |
+| HTML | `server/src/html/garden.rs`, `server/src/html/breadcrumb_path.rs`, `server/src/html/forum/nav.rs`, `server/src/html/routing.rs`, `server/src/html/search.rs`, `server/src/html/editor.rs`, `server/src/html/forum/ingest.rs`, … |
+| Tests | `server/tests/basic.rs`, `server/tests/integration.rs`, `types/src/paths.rs` tests, Clojure under `test/` if URLs/assertions mention canonical shapes |
+
+## Events / JSONL
+
+- **`Ingest`** events store **`raw` DSL** only — no change required for item identity inside the event.
+- If any future event type stores item ids as strings, migrate to **structured `ItemId` serde** or accept string only at the event boundary with immediate parse into **`ItemId`** on `apply_event`.
+
+## `nav!` macro (`server/src/paths.rs`)
+
+- Macros use **`keypath($key)`** with **`.clone()`** — **`ItemId`** must be **`Clone`** (already for enums). Remove any reliance on **`Borrow<str>`** for map keys.
+
+## Testing gate
+
+After each phase:
+
+```bash
+cargo test --workspace
+./scripts/clj-test.sh
+```
+
+## Risks / gotchas
+
+1. **`Ord` on `ItemId`**: must match prior **`CanonicalItemUrl`** / `String` ordering wherever **`BTreeSet`** is used (e.g. deterministic scope-rank snapshots in **`write_actor`**).
+2. **External `ItemId`**: **`Url`** equality / hashing — normalization is already centralized in **`url_normalize`**; ensure **`ItemId::parse`** always inserts normalized **`Url`** into **`External`**.
+3. **Fake parent URLs** in garden (e.g. **`https://.`** for external root ranking): find all **`parse("https://.")`** style hacks and express as **`ItemId`** or a dedicated sentinel.
+4. **Serde**: tests and any RPC clients that snapshot JSON may need expectation updates if **`VoteData`** shape changes.
+
+## Optional follow-ups (not blocking `ItemId`)
+
+- More **domain normalizers** in **`url_normalize.rs`** (e.g. `music.youtube.com`, Spotify, etc.).
+- **Room wire** vs **HTTP segment** helpers already in **`paths.rs`** (`ROOM_SHORT_ID_LEN`, `room_route_segment`, `room_id_from_route_segment`).
+
+---
+
+**End state criteria:** `rg CanonicalItemUrl` returns nothing; reducer maps use **`ItemId`**; HTML link generation for items goes through **`RouteContext` + `ItemId`**; tests and Kaocha green.
diff --git a/server/src/html/mod.rs b/server/src/html/mod.rs
index c3dccd03dc6da2a2f6f6fa828657e33a951884b
… preview truncated; 2,831 characters omittedB — c_9e1ff4fc0186 (tommy-mor)
message
[2a94401b] Run rustfmt workspace-wide and fix lint tooling. Pin rustfmt and clippy in rust-toolchain.toml after a broken component install, merge a duplicate vote-slider CSS rule, and add VS Code settings so rust-analyzer uses the project toolchain. Co-authored-by: Cursor <cursoragent@cursor.com>
diff preview
diff --git a/.vscode/settings.json b/.vscode/settings.json
new file mode 100644
index 0000000000000000000000000000000000000000..98ebd754a6d5a972550506c69c5a10c10e3210b6
--- /dev/null
+++ b/.vscode/settings.json
@@ -0,0 +1,8 @@
+{
+ "rust-analyzer.rustc.source": "discover",
+ "rust-analyzer.check.command": "check",
+ "rust-analyzer.procMacro.enable": true,
+ "rust-analyzer.cargo.extraEnv": {
+ "RUSTUP_TOOLCHAIN": "1.88.0"
+ }
+}
diff --git a/durable/examples/combined_example.rs b/durable/examples/combined_example.rs
index 626a6e1cf7e3c9c26f9f2edc58950d9bc31ec67e..6e9cb3210714d74c9a2cc0ed4f87e1b8d84788da 100644
--- a/durable/examples/combined_example.rs
+++ b/durable/examples/combined_example.rs
@@ -1,5 +1,5 @@
use durable::{Db, DurableMap, DurableVec};
-use serde::{Serialize, Deserialize};
+use serde::{Deserialize, Serialize};
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -28,36 +28,48 @@ fn get_timestamp() -> u64 {
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Open or create a database
let db = Db::open("chat_db")?;
-
+
// Create our collections
let mut users = DurableMap::<String, User>::new(&db, "users")?;
let mut messages = DurableVec::<Message>::new(&db, "messages")?;
let mut user_message_indices = DurableMap::<String, Vec<usize>>::new(&db, "user_messages")?;
-
+
// Create some users
- users.insert("alice".to_string(), User {
- username: "alice".to_string(),
- display_name: "Alice Smith".to_string(),
- message_count: 0,
- })?;
-
- users.insert("bob".to_string(), User {
- username: "bob".to_string(),
- display_name: "Bob Johnson".to_string(),
- message_count: 0,
- })?;
-
- users.insert("charlie".to_string(), User {
- username: "charlie".to_string(),
- display_name: "Charlie Brown".to_string(),
- message_count: 0,
- })?;
-
+ users.insert(
+ "alice".to_string(),
+ User {
+ username: "alice".to_string(),
+ display_name: "Alice Smith".to_string(),
+ message_count: 0,
+ },
+ )?;
+
+ users.insert(
+ "bob".to_string(),
+ User {
+ username: "bob".to_string(),
+ display_name: "Bob Johnson".to_string(),
+ message_count: 0,
+ },
+ )?;
+
+ users.insert(
+ "charlie".to_string(),
+ User {
+ username: "charlie".to_string(),
+ display_name: "Charlie Brown".to_string(),
+ message_count: 0,
+ },
+ )?;
+
// Helper to send a message
- let send_message = |from: &str, to: &str, content: &str,
+ let send_message = |from: &str,
+ to: &str,
+ content: &str,
messages: &mut DurableVec<Message>,
users: &mut DurableMap<String, User>,
- indices: &mut DurableMap<String, Vec<usize>>| -> Result<(), Box<dyn std::error::Error>> {
+ indices: &mut DurableMap<String, Vec<usize>>|
+ -> Result<(), Box<dyn std::error::Error>> {
// Create message
let msg_id = messages.len()? as u64;
let message = Message {
@@ -67,61 +79,93 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
content: content.to_string(),
timestamp: get_timestamp(),
};
-
+
// Store message
messages.push(message)?;
let msg_index = messages.len()? - 1;
-
+
// Update sender's message count
if let Some(mut sender) = users.get(&from.to_string())? {
sender.message_count += 1;
users.insert(from.to_string(), sender)?;
}
-
+
// Track message indices for recipient
let mut recipient_indices = indices.get(&to.to_string())?.unwrap_or_default();
recipient_indices.push(msg_index);
indices.insert(to.to_string(), recipient_indices)?;
-
+
Ok(())
};
-
+
// Send some messages
println!("💬 Chat Application Demo\n");
println!("Sending messages...");
-
- send_message("alice", "bob", "Hey Bob, how's the Durable library coming along?",
- &mut messages, &mut users, &mut user_message_indices)?;
-
- send_message("bob", "alice", "It's going great! We have DurableVec and DurableMap working!",
- &mut messages, &mut users, &mut user_message_indices)?;
-
- send_message("charlie", "alice", "That sounds awesome! Can I help with testing?",
- &mut messages, &mut users, &mut user_message_indices)?;
-
- send_message("alice", "charlie", "Absolutely! The more testing the better!",
- &mut messages, &mut users, &mut user_message_indices)?;
-
- send_message("bob", "charlie", "Check out the examples directory for usage patterns",
- &mut messages, &mut users, &mut user_message_indices)?;
-
+
+ send_message(
+ "alice",
+ "bob",
+ "Hey Bob, how's the Durable library coming along?",
+ &mut messages,
+ &mut users,
+ &mut user_message_indices,
+ )?;
+
+ send_message(
+ "bob",
+ "alice",
+ "It's going great! We have DurableVec and DurableMap working!",
+ &mut messages,
+ &mut users,
+ &mut user_message_indices,
+ )?;
+
+ send_message(
+ "charlie",
+ "alice",
+ "That sounds awesome! Can I help with testing?",
+ &mut messages,
+ &mut users,
+ &mut user_message_indices,
+ )?;
+
+ send_message(
+ "alice",
+ "charlie",
+ "Absolutely! The more testing the better!",
+ &mut messages,
+ &mut users,
+ &mut user_message_indices,
+ )?;
+
+ send_message(
+ "bob",
+ "charlie",
+ "Check out the examples directory for usage patterns",
+ &mut messages,
+ &mut users,
+ &mut user_message_indices,
+ )?;
+
// Display all users and their message counts
println!("\n👥 Users:");
let mut all_users = users.to_vec()?;
all_users.sort_by_key(|(username, _)| username.clone());
-
+
for (username, user) in all_users {
- println!(" {} ({}) - {} messages sent",
- user.display_name, username, user.message_count);
+ println!(
+ " {} ({}) - {} messages sent",
+ user.display_name, username, user.message_count
+ );
}
-
+
// Display all messages
println!("\n📨 All messages:");
for (i, msg) in messages.iter()?.enumerate() {
let msg = msg?;
println!(" [{}] {} → {}: {}", i, msg.from, msg.to, msg.content);
}
-
+
// Show inbox for each user
println!("\n📥 User inboxes:");
for item in users.iter() {
@@ -135,26 +179,26 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
}
}
}
-
+
// Statistics
println!("\n📊 Statistics:");
println!(" Total users: {}", users.len()?);
println!(" Total messages: {}", messages.len()?);
-
+
// Demonstrate persistence
println!("\n💾 Data has been persisted to disk!");
println!(" Database location: ./chat_db");
-
+
// Clean up
drop(messages);
drop(users);
drop(user_message_indices);
drop(db);
-
+
// Remove the database for this example
std::fs::remove_dir_all("chat_db").ok();
-
+
println!("\n✅ Example completed!");
-
+
Ok(())
-}
\ No newline at end of file
+}
diff --git a/durable/examples/map_example.rs b/durable/examples/map_example.rs
index 08b8f2c8826caf53c4c20b422a540c92f6624029..1d9c4a14b0f4cfe39ade84ebb1f1a14033e8ff1b 100644
--- a/durable/examples/map_example.rs
+++ b/durable/examples/map_example.rs
@@ -1,5 +1,5 @@
use durable::{Db, DurableMap};
-use serde::{Serialize, Deserialize};
+use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
struct UserProfile {
@@ -11,10 +11,10 @@ struct UserProfile {
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Open or create a database
let db = Db::open("example_db")?;
-
+
// Create a persistent map of user profiles
let mut users = DurableMap::<String, UserProfile>::new(&db, "users")?;
-
+
// Insert some users
// Using put() when we don't need the old value - more efficient!
users.put(
@@ -25,7 +25,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
score: 1500,
},
)?;
-
+
users.put(
"bob".to_string(),
UserProfile {
@@ -34,7 +34,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
score: 1200,
},
)?;
-
+
// Using insert() when we might need the old value
let old_charlie = users.insert(
"charlie".to_string(),
@@ -44,21 +44,24 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
score: 1800,
},
)?;
-
+
if old_charlie.is_some() {
println!("Replaced existing charlie entry");
}
-
+
println!("Total users: {}", users.len()?);
-
+
// Look up a specific user
if let Some(alice) = users.get(&"alice".to_string())? {
println!("\nAlice's profile: {:?}", alice);
}
-
+
// Check if a user exists
- println!("\nDoes 'david' exist? {}", users.contains_key(&"david".to_string())?);
-
+ println!(
+ "\nDoes 'david' exist? {}",
+ users.contains_key(&"david".to_string())?
+ );
+
// Update a user's score
if let Some(mut bob) = users.get(&"bob".to_string())? {
bob.score += 100;
@@ -66,34 +69,40 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
users.put("bob".to_string(), bob)?;
println!("Updated Bob's score!");
}
-
+
// Iterate over all users
println!("\nAll users (sorted by username):");
let mut all_users = users.to_vec()?;
all_users.sort_by_key(|(username, _)| username.clone());
-
+
for (username, profile) in all_users {
- println!(" {} ({}) - Score: {}", username, profile.email, profile.score);
+ println!(
+ " {} ({}) - Score: {}",
+ username, profile.email, profile.score
+ );
}
-
+
// Get just the usernames
let mut usernames = users.keys_vec()?;
usernames.sort();
println!("\nAll usernames: {:?}", usernames);
-
+
// Find the highest scoring user
let profiles = users.values_vec()?;
if let Some(top_user) = profiles.iter().max_by_key(|p| p.score) {
- println!("\nTop scorer: {} with {} points", top_user.name, top_user.score);
+ println!(
+ "\nTop scorer: {} with {} points",
+ top_user.name, top_user.score
+ );
}
-
+
// Remove a user
if let Some(removed) = users.remove(&"charlie".to_string())? {
println!("\nRemoved user: {}", removed.name);
println!("Users remaining: {}", users.len()?);
}
-
+
println!("\nData has been persisted to disk.");
-
+
Ok(())
-}
\ No newline at end of file
+}
diff --git a/durable/examples/nested_example.rs b/durable/examples/nested_example.rs
index 3b880f2c8b8ad2633d4b5fcf2016652216c9de8e..f16090cf6fb854ac7a1b00acfd31fbd12c25dbce 100644
--- a/durable/examples/nested_example.rs
+++ b/durable/examples/nested_example.rs
@@ -3,27 +3,31 @@ use durable::{Db, DurableMap, DurableVec};
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Open a database
let db = Db::open("nested_example_db")?;
-
+
// Create a map where each user has a list of posts
- let user_posts: DurableMap<String, DurableVec<String>> = DurableMap::new_nested(&db, "user_posts");
-
+ let user_posts: DurableMap<String, DurableVec<String>> =
+ DurableMap::new
… preview truncated; 96,900 characters omittedHardlinks — judgments / attempts / prompt
judgments
attempts
Prompt text is loaded only by the download route.