← Back to posts

Code-heavy test post

A post with a lot of code in several languages, for measuring server-side highlighting.

rust

use std::collections::HashMap;
use std::fmt;
#[derive(Debug, Clone, PartialEq)]
pub enum Token {
    Number(f64),
    Ident(String),
    Op(char),
    LParen,
    RParen,
}
pub struct Lexer<'a> {
    chars: std::iter::Peekable<std::str::Chars<'a>>,
}
impl<'a> Lexer<'a> {
    pub fn new(src: &'a str) -> Self {
        Self { chars: src.chars().peekable() }
    }
    fn number(&mut self, first: char) -> Token {
        let mut s = String::from(first);
        while let Some(&c) = self.chars.peek() {
            if c.is_ascii_digit() || c == '.' {
                s.push(c);
                self.chars.next();
            } else {
                break;
            }
        }
        Token::Number(s.parse().unwrap_or(0.0))
    }
    fn ident(&mut self, first: char) -> Token {
        let mut s = String::from(first);
        while let Some(&c) = self.chars.peek() {
            if c.is_alphanumeric() || c == '_' {
                s.push(c);
                self.chars.next();
            } else {
                break;
            }
        }
        Token::Ident(s)
    }
}
impl<'a> Iterator for Lexer<'a> {
    type Item = Token;
    fn next(&mut self) -> Option<Token> {
        loop {
            let c = self.chars.next()?;
            return Some(match c {
                ' ' | '	' | '
' => continue,
                '0'..='9' => self.number(c),
                'a'..='z' | 'A'..='Z' | '_' => self.ident(c),
                '(' => Token::LParen,
                ')' => Token::RParen,
                '+' | '-' | '*' | '/' | '^' => Token::Op(c),
                other => panic!("unexpected {other:?}"),
            });
        }
    }
}
impl fmt::Display for Token {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Token::Number(n) => write!(f, "{n}"),
            Token::Ident(s) => write!(f, "{s}"),
            Token::Op(c) => write!(f, "{c}"),
            Token::LParen => write!(f, "("),
            Token::RParen => write!(f, ")"),
        }
    }
}
fn main() {
    let env: HashMap<&str, f64> = [("pi", 3.14159), ("e", 2.71828)].into();
    for tok in Lexer::new("pi * (e + 2.5) ^ 2") {
        println!("{tok}");
    }
    println!("{:?}", env.get("pi"));
}

go

package main
import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"sync"
	"time"
)
type Item struct {
	ID        int64     `json:"id"`
	Name      string    `json:"name"`
	CreatedAt time.Time `json:"created_at"`
}
type Store struct {
	mu    sync.RWMutex
	items map[int64]Item
	next  int64
}
func NewStore() *Store {
	return &Store{items: make(map[int64]Item), next: 1}
}
func (s *Store) Add(name string) Item {
	s.mu.Lock()
	defer s.mu.Unlock()
	it := Item{ID: s.next, Name: name, CreatedAt: time.Now()}
	s.items[it.ID] = it
	s.next++
	return it
}
func (s *Store) Get(id int64) (Item, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	it, ok := s.items[id]
	if !ok {
		return Item{}, errors.New("not found")
	}
	return it, nil
}
func (s *Store) handleItems(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case http.MethodPost:
		var body struct{ Name string }
		if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		json.NewEncoder(w).Encode(s.Add(body.Name))
	default:
		s.mu.RLock()
		defer s.mu.RUnlock()
		json.NewEncoder(w).Encode(s.items)
	}
}
func main() {
	store := NewStore()
	mux := http.NewServeMux()
	mux.HandleFunc("/items", store.handleItems)
	srv := &http.Server{Addr: ":8080", Handler: mux}
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()
	go func() {
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Fatal(err)
		}
	}()
	<-ctx.Done()
	shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	fmt.Println("shutting down")
	_ = srv.Shutdown(shutdownCtx)
}

python

from __future__ import annotations
import asyncio
import dataclasses
import json
import re
from collections import Counter, defaultdict
from pathlib import Path
from typing import Iterable, Iterator
WORD_RE = re.compile(r"[a-zA-Z']+")
@dataclasses.dataclass(frozen=True)
class Document:
    path: Path
    text: str
    @property
    def words(self) -> Iterator[str]:
        for match in WORD_RE.finditer(self.text):
            yield match.group(0).lower()
class Index:
    """A tiny inverted index over a set of documents."""
    def __init__(self) -> None:
        self._postings: dict[str, set[Path]] = defaultdict(set)
        self._freq: Counter[str] = Counter()
    def add(self, doc: Document) -> None:
        for word in doc.words:
            self._postings[word].add(doc.path)
            self._freq[word] += 1
    def search(self, query: str) -> list[Path]:
        terms = [t.lower() for t in WORD_RE.findall(query)]
        if not terms:
            return []
        hits = set.intersection(*(self._postings.get(t, set()) for t in terms))
        return sorted(hits)
    def top(self, n: int = 10) -> list[tuple[str, int]]:
        return self._freq.most_common(n)
    def dump(self, path: Path) -> None:
        payload = {w: sorted(str(p) for p in ps) for w, ps in self._postings.items()}
        path.write_text(json.dumps(payload, indent=2))
async def read_all(paths: Iterable[Path]) -> list[Document]:
    async def read(p: Path) -> Document:
        return Document(p, await asyncio.to_thread(p.read_text, errors="ignore"))
    return await asyncio.gather(*(read(p) for p in paths))
async def main(root: Path) -> None:
    docs = await read_all(root.rglob("*.md"))
    index = Index()
    for doc in docs:
        index.add(doc)
    for word, count in index.top():
        print(f"{word:>15}  {count}")
    print(index.search("rust blog"))
if __name__ == "__main__":
    asyncio.run(main(Path(".")))

javascript

const state = new Map();
const listeners = new Set();
export function createStore(reducer, initial) {
  let current = initial;
  const subscribers = [];
  return {
    getState: () => current,
    dispatch(action) {
      current = reducer(current, action);
      subscribers.forEach((fn) => fn(current));
      return action;
    },
    subscribe(fn) {
      subscribers.push(fn);
      return () => subscribers.splice(subscribers.indexOf(fn), 1);
    },
  };
}
function reducer(state = { todos: [], filter: "all" }, action) {
  switch (action.type) {
    case "add":
      return { ...state, todos: [...state.todos, { id: Date.now(), text: action.text, done: false }] };
    case "toggle":
      return {
        ...state,
        todos: state.todos.map((t) => (t.id === action.id ? { ...t, done: !t.done } : t)),
      };
    case "filter":
      return { ...state, filter: action.filter };
    default:
      return state;
  }
}
const store = createStore(reducer);
store.subscribe((s) => {
  const visible = s.todos.filter((t) =>
    s.filter === "all" ? true : s.filter === "done" ? t.done : !t.done
  );
  document.querySelector("#list").innerHTML = visible
    .map((t) => `<li class="${t.done ? "done" : ""}" data-id="${t.id}">${t.text}</li>`)
    .join("");
});
document.querySelector("#form").addEventListener("submit", (e) => {
  e.preventDefault();
  const input = e.target.elements.text;
  if (input.value.trim()) store.dispatch({ type: "add", text: input.value.trim() });
  input.value = "";
});
document.querySelector("#list").addEventListener("click", (e) => {
  const li = e.target.closest("li");
  if (li) store.dispatch({ type: "toggle", id: Number(li.dataset.id) });
});
async function load() {
  try {
    const res = await fetch("/api/todos");
    if (!res.ok) throw new Error(res.statusText);
    for (const todo of await res.json()) store.dispatch({ type: "add", text: todo.text });
  } catch (err) {
    console.error("load failed", err);
  }
}
load();

sql

CREATE TABLE posts (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT NOT NULL,
    slug TEXT NOT NULL UNIQUE,
    content TEXT NOT NULL DEFAULT '',
    status TEXT NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'published')),
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    published_at TEXT
);
CREATE INDEX idx_posts_status_published_at ON posts (status, published_at);
WITH monthly AS (
    SELECT strftime('%Y-%m', published_at) AS month, COUNT(*) AS n
    FROM posts
    WHERE status = 'published'
    GROUP BY month
),
ranked AS (
    SELECT month, n, RANK() OVER (ORDER BY n DESC) AS rnk
    FROM monthly
)
SELECT month, n
FROM ranked
WHERE rnk <= 5
ORDER BY month;
UPDATE posts
SET status = 'published', published_at = datetime('now')
WHERE slug = 'hello-world' AND status = 'draft';
SELECT p.title, GROUP_CONCAT(t.name, ', ') AS tags
FROM posts p
LEFT JOIN post_tags pt ON pt.post_id = p.id
LEFT JOIN tags t ON t.id = pt.tag_id
GROUP BY p.id
HAVING COUNT(t.id) > 0
ORDER BY p.published_at DESC
LIMIT 20;

bash

#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
OUT="${1:-$ROOT/dist}"
VERSION="$(git -C "$ROOT" describe --tags --always)"
log() { printf '[%s] %s
' "$(date +%H:%M:%S)" "$*" >&2; }
build() {
  local target="$1"
  log "building $target"
  cargo build --release --target "$target" --quiet
  install -d "$OUT/$target"
  cp "target/$target/release/rust-blog" "$OUT/$target/"
  strip "$OUT/$target/rust-blog" 2>/dev/null || true
}
for target in x86_64-unknown-linux-musl aarch64-unknown-linux-musl; do
  if rustup target list --installed | grep -q "$target"; then
    build "$target"
  else
    log "skipping $target (not installed)"
  fi
done
tar -C "$OUT" -czf "$OUT/rust-blog-$VERSION.tar.gz" .
sha256sum "$OUT/rust-blog-$VERSION.tar.gz" | tee "$OUT/SHA256SUMS"
log "done: $OUT/rust-blog-$VERSION.tar.gz"

c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
    char *key;
    int value;
    struct node *next;
} node_t;
#define BUCKETS 64
static unsigned hash(const char *s) {
    unsigned h = 5381;
    for (; *s; s++) h = h * 33 + (unsigned char)*s;
    return h % BUCKETS;
}
typedef struct { node_t *buckets[BUCKETS]; } map_t;
static void map_put(map_t *m, const char *key, int value) {
    unsigned b = hash(key);
    for (node_t *n = m->buckets[b]; n; n = n->next) {
        if (strcmp(n->key, key) == 0) { n->value = value; return; }
    }
    node_t *n = malloc(sizeof *n);
    n->key = strdup(key);
    n->value = value;
    n->next = m->buckets[b];
    m->buckets[b] = n;
}
static int map_get(const map_t *m, const char *key, int *out) {
    for (node_t *n = m->buckets[hash(key)]; n; n = n->next) {
        if (strcmp(n->key, key) == 0) { *out = n->value; return 1; }
    }
    return 0;
}
static void map_free(map_t *m) {
    for (int i = 0; i < BUCKETS; i++) {
        node_t *n = m->buckets[i];
        while (n) { node_t *next = n->next; free(n->key); free(n); n = next; }
    }
}
int main(void) {
    map_t m = {0};
    map_put(&m, "alpha", 1);
    map_put(&m, "beta", 2);
    int v;
    if (map_get(&m, "beta", &v)) printf("beta = %d
", v);
    map_free(&m);
    return 0;
}

html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Plain page</title>
  <style>
    body { max-width: 65ch; margin: 1em auto; font: 1em/1.5 sans-serif; }
    nav a + a::before { content: "C6"; margin: 0 .5em; }
  </style>
</head>
<body>
  <nav><a href="/">Home</a><a href="/w/">Writings</a><a href="/quotes/">Quotes</a></nav>
  <main>
    <h1>Hello</h1>
    <p>A paragraph with <a href="#">a link</a> and <code>inline code</code>.</p>
    <figure>
      <img src="/media/photo.jpg" alt="A photo" loading="lazy">
      <figcaption>Caption</figcaption>
    </figure>
  </main>
  <script type="module">
    import { createStore } from "/store.js";
    console.log(createStore((s) => s, {}).getState());
  </script>
</body>
</html>