Reference

Programming languages

Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.

Scope and conventions

TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.

Libraries: data & formats

Structured and binary data: JSON and config formats, bytes, encodings, regular expressions, hashing and cryptography, compression, SQL databases, URLs and templates. Entries outside the standard library name what to install.

JSON: JSON, encoding/json, serde_json, nlohmann/json

C++

The C++ standard library has no JSON support. nlohmann/json is the most common choice: a header-only library where json behaves like a dynamic value (parse, dump, at, get<T>, iteration), with optional to_json and from_json functions for your own types. simdjson and Boost.JSON are alternatives when speed or Boost integration matters.

Complete program

Complete program.

Before you use this

Not in the standard library: nlohmann/json 3.11+ (header-only) from vcpkg, Conan, your system package manager or CMake FetchContent.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <nlohmann/json.hpp>
#include <print>
#include <string>
#include <vector>

using json = nlohmann::json;

int main() {
    json order = json::parse(R"({"id": 7, "items": ["bolt", "nut"]})"); // throws on bad JSON

    int id = order.at("id").get<int>(); // at() throws when the key is missing
    auto items = order.at("items").get<std::vector<std::string>>();
    std::println("{} {}", id, items.size());

    json out = {{"id", 8}, {"items", json::array()}};
    std::println("{}", out.dump()); // dump(2) pretty-prints
}

Most used: json::parse, j.at("key").get<T>(), j.dump(), j.contains, initializer-list construction, NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE for structs.

Config formats (TOML, YAML, XML, protobuf): yaml, encoding/xml, serde + toml, toml++

C++

The C++ standard library parses none of these formats. Common choices: toml++ (tomlplusplus, header-only, C++17) for TOML; yaml-cpp for YAML (libyaml is the C alternative); pugixml or tinyxml2 for XML DOM parsing, and libxml2 for validation and XPath-heavy work; protobuf (libprotobuf with protoc-generated classes) for Protocol Buffers. toml++ returns a toml::table you index like a map, with typed lookups that return std::optional instead of throwing.

Complete program

Complete program.

Before you use this

Not in the standard library: toml++ 3.x (header-only), for example brew install tomlplusplus, vcpkg install tomlplusplus or the single toml.hpp header from its releases.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <iostream>
#include <print>
#include <string>
#include <toml++/toml.hpp>

int main() {
    constexpr std::string_view text = R"(
name = "orders"
port = 8080 # comments are allowed
tags = ["api", "internal"]

[db]
url = "postgres://localhost/orders"
)";
    toml::table config;
    try {
        config = toml::parse(text);
    } catch (const toml::parse_error& error) { // carries the line and column
        std::println("invalid TOML: {}", error.description());
        return 1;
    }

    std::string_view name = config["name"].value_or(""); // default if missing or another type
    int port = config["port"].value_or(0);
    auto url = config["db"]["url"].value<std::string>(); // std::optional<std::string>
    std::println("{} {} {} {}", name, port + 1, config["tags"].as_array()->size(), url.value_or("?"));

    config.insert_or_assign("port", 9090);
    std::cout << config << '\n'; // writes TOML
}

Most used: toml::parse, toml::parse_file, table["key"].value_or(default), value<T>() returning std::optional, as_array, insert_or_assign, operator<< to write TOML, YAML::LoadFile, pugi::xml_document::load_string.

With exceptions disabled (TOML_EXCEPTIONS=0), toml::parse returns a toml::parse_result to test instead of throwing toml::parse_error.

value_or returns the default both when the key is missing and when it holds another type, so a quoted "8080" silently becomes 0 here; use value<T>() and check the optional when that matters.

Bytes & binary data: Uint8Array, encoding/binary, Vec<u8>, std::byte

C++

std::byte (<cstddef>) is the type for raw bytes, and std::span (C++20) is a non-owning view of a contiguous block, often std::span<const std::byte>. <bit> handles byte order and bit operations: std::endian, std::byteswap (C++23), std::bit_cast (reinterpret an object's bytes safely), popcount and rotl. std::vector<std::byte> or std::vector<unsigned char> hold owned buffers, and std::memcpy copies bytes.

Complete program

Complete program. Standard library: ships with your compiler, no install.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <bit>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <print>
#include <span>
#include <string>
#include <vector>

// Write a 32-bit value in big-endian order on any machine.
void put_u32_be(std::span<std::byte, 4> out, std::uint32_t value) {
    if constexpr (std::endian::native == std::endian::little) value = std::byteswap(value);
    std::memcpy(out.data(), &value, 4);
}

int main() {
    std::string text = "héllo";
    std::println("{} {:x}", text.size(), static_cast<unsigned char>(text[1]));

    std::vector<std::byte> header(8);
    put_u32_be(std::span(header).first<4>(), 0xcafebabe);
    for (std::byte b : header) std::print("{:02x} ", std::to_integer<int>(b));
    std::println("");

    float pi = 3.14f;
    auto bits = std::bit_cast<std::uint32_t>(pi); // reinterpret bytes safely (C++20)
    std::println("{:08x} {}", bits, std::popcount(bits));
}

Most used: std::byte, std::span, std::vector<std::byte>, std::endian::native, std::byteswap, std::bit_cast, std::to_integer, std::memcpy, std::as_bytes.

Base64, hex & CSV: Buffer, encoding/*, base64/hex/csv crates, OpenSSL

C++

The C++ standard library has no base64 or CSV support; hex is easy with std::format("{:02x}"). Projects usually take base64 from a library they already link, such as OpenSSL's EVP_EncodeBlock (shown here) or a small header like cppcodec. For CSV, rapidcsv and csv-parser handle quoting and headers.

Complete program

Complete program.

Before you use this

Base64 here uses OpenSSL (link with -lcrypto); the hex helper uses only the standard library.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <format>
#include <openssl/evp.h>
#include <print>
#include <string>
#include <string_view>

std::string to_base64(std::string_view raw) {
    std::string out(4 * ((raw.size() + 2) / 3), '\0');
    int size = EVP_EncodeBlock(reinterpret_cast<unsigned char*>(out.data()),
                               reinterpret_cast<const unsigned char*>(raw.data()),
                               static_cast<int>(raw.size()));
    out.resize(size);
    return out;
}

std::string to_hex(std::string_view raw) {
    std::string out;
    for (unsigned char byte : raw) out += std::format("{:02x}", byte);
    return out;
}

int main() {
    std::println("{} {}", to_base64("id=7&ok"), to_hex("id=7&ok"));
}

Most used: std::format("{:02x}", byte), OpenSSL EVP_EncodeBlock and EVP_DecodeBlock, cppcodec, rapidcsv::Document.

Regular expressions: RegExp, regexp, regex crate, <regex>

C++

<regex> provides std::regex with ECMAScript syntax by default: regex_match (whole string), regex_search (anywhere), sregex_iterator for every match and regex_replace. Raw string literals R"(...)" avoid double escaping. The standard implementations are known to be slow and can overflow the stack on long inputs, so performance-sensitive code uses RE2, PCRE2 or the compile-time CTRE library.

Complete program

Complete program. Standard library: ships with your compiler, no install.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <print>
#include <regex>
#include <string>

int main() {
    const std::string line = "order=7 total=40.50 status=paid";
    const std::regex field(R"((\w+)=([\w.]+))"); // ECMAScript grammar by default

    for (std::sregex_iterator it(line.begin(), line.end(), field), end; it != end; ++it)
        std::println("{} {}", (*it)[1].str(), (*it)[2].str());

    std::smatch match;
    if (std::regex_search(line, match, std::regex(R"(total=(\d+\.\d{2}))")))
        std::println("{}", match[1].str());
    std::println("{}", std::regex_replace(line, std::regex(R"(\d+)"), "#"));
}

Most used: std::regex, std::regex_search, std::regex_match, std::smatch, std::sregex_iterator, std::regex_replace, R"(...)" raw strings.

Hashing & cryptography: node:crypto, crypto/*, RustCrypto, OpenSSL

C++

The C++ standard library has no cryptography; std::hash is for hash tables only. OpenSSL (libcrypto) is the most widely deployed choice: EVP_Digest for SHA-256, HMAC for message authentication codes, RAND_bytes for secure random bytes, the EVP cipher API for AES-GCM and CRYPTO_memcmp for constant-time comparison. libsodium offers a smaller API that is harder to misuse, and Botan is a C++-native alternative.

Complete program

Complete program.

Before you use this

Not in the standard library: OpenSSL 3 (link with -lcrypto) from your system package manager, vcpkg or Conan.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <format>
#include <openssl/crypto.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/rand.h>
#include <print>
#include <string>

std::string to_hex(const unsigned char* data, unsigned int size) {
    std::string out;
    for (unsigned int i = 0; i < size; ++i) out += std::format("{:02x}", data[i]);
    return out;
}

int main() {
    const std::string message = "order:7";
    auto data = reinterpret_cast<const unsigned char*>(message.data());

    unsigned char digest[EVP_MAX_MD_SIZE];
    unsigned int digest_size = 0;
    EVP_Digest(data, message.size(), digest, &digest_size, EVP_sha256(), nullptr);
    std::println("{}", to_hex(digest, digest_size).substr(0, 16)); // checksums, cache keys

    unsigned char key[32];
    if (RAND_bytes(key, sizeof key) != 1) return 1; // a shared secret key

    unsigned char mac[EVP_MAX_MD_SIZE], check[EVP_MAX_MD_SIZE];
    unsigned int mac_size = 0, check_size = 0;
    HMAC(EVP_sha256(), key, sizeof key, data, message.size(), mac, &mac_size);
    HMAC(EVP_sha256(), key, sizeof key, data, message.size(), check, &check_size);
    std::println("{}", CRYPTO_memcmp(mac, check, mac_size) == 0); // constant time
}

Most used: EVP_Digest, EVP_sha256, HMAC, RAND_bytes, CRYPTO_memcmp, EVP_EncryptInit_ex2 with EVP_aes_256_gcm, EVP_MAC for MACs in OpenSSL 3, libsodium's crypto_generichash and crypto_pwhash.

Compression & archives: node:zlib, compress/* + archive/*, flate2, zlib

C++

There is no compression in the C++ standard library. zlib is the universal C library for the deflate, zlib and gzip formats: compress and uncompress for buffers, the z_stream API (deflateInit2, deflate, inflate) for streaming, and gzopen and gzread for .gz files. libarchive and libzip handle archives, and zstd and brotli have their own C libraries.

Complete program

Complete program.

Before you use this

Not in the standard library: zlib (link with -lz); it ships with most operating systems.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <print>
#include <string>
#include <vector>
#include <zlib.h>

int main() {
    std::string text;
    for (int i = 0; i < 1000; ++i) text += "order line\n";
    auto input = reinterpret_cast<const Bytef*>(text.data());

    uLongf packed_size = compressBound(text.size()); // worst-case output size
    std::vector<Bytef> packed(packed_size);
    if (compress(packed.data(), &packed_size, input, text.size()) != Z_OK) return 1;
    std::println("{} {}", text.size(), packed_size);

    std::string back(text.size(), '\0'); // the caller must know or store the size
    uLongf back_size = back.size();
    auto output = reinterpret_cast<Bytef*>(back.data());
    int status = uncompress(output, &back_size, packed.data(), packed_size);
    std::println("{} {}", status == Z_OK, back == text);
}

Most used: compressBound, compress, uncompress, deflateInit2 with windowBits 31 for gzip, inflate, gzopen, gzread, gzwrite.

SQL databases: node:sqlite, database/sql, rusqlite/sqlx, SQLite C API

C++

There is no database support in the C++ standard library. SQLite's C API is used directly (sqlite3_open, sqlite3_prepare_v2, sqlite3_bind_*, sqlite3_step, sqlite3_column_*, sqlite3_finalize), usually wrapped in small RAII classes or a library such as SQLiteCpp. PostgreSQL uses libpq or its C++ wrapper libpqxx. This example checks only the open call; real code checks every return code.

Complete program

Complete program.

Before you use this

Not in the standard library: SQLite 3 (link with -lsqlite3); it ships with macOS and most Linux distributions.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <print>
#include <sqlite3.h>

int main() {
    sqlite3* db = nullptr;
    if (sqlite3_open(":memory:", &db) != SQLITE_OK) return 1;
    sqlite3_exec(db, "CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE)",
                 nullptr, nullptr, nullptr);

    sqlite3_stmt* insert = nullptr;
    sqlite3_prepare_v2(db, "INSERT INTO items (name) VALUES (?)", -1, &insert, nullptr);
    for (const char* name : {"bolt", "nut"}) {
        sqlite3_bind_text(insert, 1, name, -1, SQLITE_TRANSIENT); // a bound value, not SQL text
        sqlite3_step(insert);
        sqlite3_reset(insert);
    }
    sqlite3_finalize(insert);

    sqlite3_stmt* query = nullptr;
    sqlite3_prepare_v2(db, "SELECT id, name FROM items WHERE name LIKE ?", -1, &query, nullptr);
    sqlite3_bind_text(query, 1, "b%", -1, SQLITE_STATIC);
    while (sqlite3_step(query) == SQLITE_ROW) {
        auto name = reinterpret_cast<const char*>(sqlite3_column_text(query, 1));
        std::println("{} {}", sqlite3_column_int(query, 0), name);
    }
    sqlite3_finalize(query);
    sqlite3_close(db);
}

Most used: sqlite3_open, sqlite3_prepare_v2, sqlite3_bind_text and sqlite3_bind_int, sqlite3_step, sqlite3_column_text, sqlite3_finalize, SQLiteCpp, libpqxx's pqxx::work.

URLs & query strings: URL, net/url, url crate, Boost.URL

C++

The C++ standard library has no URL type. Boost.URL (Boost 1.81+) parses and builds URLs following RFC 3986, with a params() view that encodes and decodes query parameters and resolve for relative references. ada, the parser Node.js uses, implements the WHATWG standard as a single file. HTTP libraries such as cpp-httplib include their own simpler helpers.

Complete program

Complete program.

Before you use this

Not in the standard library: Boost.URL (Boost 1.81+, link boost_url) or ada-url.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <boost/url.hpp>
#include <iostream>

namespace urls = boost::urls;

int main() {
    urls::url url = urls::parse_uri("https://shop.example/orders?status=paid&page=2#top").value();
    auto status = url.params().find("status");
    std::cout << url.host() << ' ' << url.path() << ' ' << (*status).value << '\n';

    url.params().set("q", "bolt & nut"); // encodes the value
    url.set_path("/orders/7");
    std::cout << url << '\n';

    urls::url resolved;
    auto base = urls::parse_uri("https://shop.example/api/").value();
    auto ref = urls::parse_relative_ref("items?id=7").value();
    urls::resolve(base, ref, resolved); // resolve a relative reference
    std::cout << resolved << '\n';
}

Most used: boost::urls::parse_uri, url.params().find/set/append, set_path, boost::urls::resolve, ada::parse, ada::url_search_params.

Text templates: template literals, text/template, minijinja, std::format

C++

The C++ standard library has no template engine; std::format with a loop covers simple output, and HTML needs manual escaping. inja (Jinja-style, built on nlohmann/json) and mustache-style libraries such as kainjow/mustache handle real template files, and the {fmt} library adds named arguments to format strings.

Complete program

Complete program. Standard library: ships with your compiler, no install.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <format>
#include <print>
#include <string>
#include <vector>

struct Item {
    std::string name;
    int qty;
};

std::string escape_html(const std::string& text) {
    std::string out;
    for (char c : text) {
        switch (c) {
        case '&': out += "&amp;"; break;
        case '<': out += "&lt;"; break;
        case '>': out += "&gt;"; break;
        case '"': out += "&quot;"; break;
        case '\'': out += "&#39;"; break;
        default: out += c;
        }
    }
    return out;
}

int main() {
    std::vector<Item> items{{"bolt <M8>", 3}};
    std::string rows;
    for (const auto& item : items)
        rows += std::format("  <li>{} × {}</li>\n", escape_html(item.name), item.qty);
    std::print("<h1>Order {}</h1>\n<ul>\n{}</ul>\n", 7, rows);
}

Most used: std::format and std::print in a loop, a small escape function, inja::render, kainjow::mustache, fmt::arg for named placeholders.