blog.craton.devhomeblogabout

First post


Here’s a look at how syntax highlighting renders for a couple of languages.

Swift

A small async network client using structured concurrency:

import Foundation

struct Post: Codable, Identifiable {
    let id: Int
    let title: String
    let body: String
    let userId: Int
}

actor APIClient {
    private let session: URLSession
    private let baseURL: URL

    init(baseURL: URL, session: URLSession = .shared) {
        self.baseURL = baseURL
        self.session = session
    }

    func fetchPosts() async throws -> [Post] {
        let url = baseURL.appendingPathComponent("/posts")
        let (data, response) = try await session.data(from: url)

        guard let http = response as? HTTPURLResponse,
              (200...299).contains(http.statusCode) else {
            throw URLError(.badServerResponse)
        }

        return try JSONDecoder().decode([Post].self, from: data)
    }
}

@main
struct App {
    static func main() async {
        let client = APIClient(
            baseURL: URL(string: "https://jsonplaceholder.typicode.com")!
        )

        do {
            let posts = try await client.fetchPosts()
            for post in posts.prefix(5) {
                print("[\(post.id)] \(post.title)")
            }
        } catch {
            print("Error: \(error.localizedDescription)")
        }
    }
}

Rust

A concurrent web scraper using tokio and reqwest:

use std::collections::HashMap;
use tokio::sync::Mutex;
use std::sync::Arc;

#[derive(Debug, Clone)]
struct PageResult {
    url: String,
    status: u16,
    content_length: Option<u64>,
}

async fn fetch_page(client: &reqwest::Client, url: &str) -> Result<PageResult, reqwest::Error> {
    let response = client.get(url).send().await?;
    let status = response.status().as_u16();
    let content_length = response.content_length();

    Ok(PageResult {
        url: url.to_string(),
        status,
        content_length,
    })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let urls = vec![
        "https://www.rust-lang.org",
        "https://docs.rs",
        "https://crates.io",
        "https://blog.rust-lang.org",
    ];

    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(10))
        .build()?;

    let results: Arc<Mutex<HashMap<String, PageResult>>> =
        Arc::new(Mutex::new(HashMap::new()));

    let mut handles = vec![];

    for url in &urls {
        let client = client.clone();
        let results = Arc::clone(&results);
        let url = url.to_string();

        let handle = tokio::spawn(async move {
            match fetch_page(&client, &url).await {
                Ok(result) => {
                    let mut map = results.lock().await;
                    map.insert(url, result);
                }
                Err(e) => eprintln!("Failed to fetch {}: {}", url, e),
            }
        });

        handles.push(handle);
    }

    for handle in handles {
        handle.await?;
    }

    let results = results.lock().await;
    for (url, result) in results.iter() {
        println!(
            "{} => {} ({} bytes)",
            url,
            result.status,
            result.content_length.unwrap_or(0)
        );
    }

    Ok(())
}

Both languages show off nicely with Catppuccin Macchiato — keywords, types, strings, and function calls each get distinct colors matching the NeoVim experience.