brain

tamnd's digital brain — notes, problems, research

43815 notes

Hello, Zig

The first program in Zig is small.

zigbook
`@compileError`

@compileError stops compilation with a custom error message.

zigbook
`@panic`

@panic stops the program immediately with a message.

zigbook
Appendix I. Zig Coding Style Guide

Zig code should be explicit, simple, and easy to inspect. The goal is not cleverness. The goal is code that another programmer can read, verify, and maintain.

zigbook
Contributing to Zig

Contributing to Zig means helping the language, compiler, standard library, documentation, tests, or tooling improve.

zigbook
Build a Programming Language Lexer

A lexer is the first stage of many programming language tools.

zigbook
Handling Platform Differences

A cross-platform Zig program should not pretend that every operating system behaves the same way. Windows, Linux, macOS, WebAssembly, and embedded targets have different...

zigbook
Writing a Compiler in Zig

A compiler translates one form of code into another form.

zigbook
Benchmark the Right Thing

Benchmarking means measuring how fast code runs.

zigbook
Writing a TCP Server

A TCP server is a program that waits for clients to connect.

zigbook
Event Loops

An event loop is code that waits for events, then runs the right piece of work for each event.

zigbook
ABI Compatibility

ABI means Application Binary Interface.

zigbook
Memory Debugging

Memory debugging means finding mistakes in how a program uses memory.

zigbook
Running Tests

Zig has built-in support for tests.

zigbook
Time and Timers

Programs often need to work with time.

zigbook
`@floatCast`

@floatCast converts one floating-point value to another floating-point type.

zigbook
Appendix H. Useful Open Source Zig Projects

This appendix lists useful Zig projects to read after you know the basics.

zigbook
Open Issues and RFCs

A programming language is never only its syntax.

zigbook
Build a Small Database

A database stores data so it can be saved, searched, updated, and loaded again later.

zigbook
Portable APIs

A portable API is an interface that works across more than one platform.

zigbook
Writing a Virtual Machine

A virtual machine is a program that runs another program.

zigbook
Why Branch Prediction Exists

Branch prediction is a CPU optimization.

zigbook
Network Protocols

A network protocol is a rulebook for how programs talk over a network.

zigbook
Await and Suspension

await means: wait until an asynchronous operation has finished, then continue with its result.

zigbook
Exporting Zig to C

Zig can call C, but C can also call Zig.

zigbook
Using GDB and LLDB

GDB and LLDB are debuggers.

zigbook
Release Modes

Zig can build the same program in different optimization modes.

zigbook
Parsing Numbers and Text

Parsing means turning text into data.

zigbook
Why Trees Matter

A tree is a collection made of nodes.

zigbook
Building Allocation-Friendly APIs

An allocation-friendly API makes memory behavior clear to the caller.

zigbook
`@truncate`

@truncate converts an integer to a smaller integer type by keeping only the low bits.

zigbook
Appendix G. C Interop Reference

Zig is designed to work closely with C. You can call C from Zig, call Zig from C, compile C code with Zig, and link Zig programs against existing C libraries.

zigbook
LLVM Integration

LLVM is a compiler infrastructure project.

zigbook
Build a Memory Allocator

A memory allocator is code that gives memory to the rest of a program.

zigbook
Cross-Target Debugging

Cross-target debugging means debugging a program built for a different machine, operating system, or CPU architecture than the one you are sitting at.

zigbook
Writing a Parser

A parser reads text and turns it into structure.

zigbook
Small Values Are Fine to Copy

Copying data is sometimes necessary, but unnecessary copying is one of the easiest ways to waste time and memory.

zigbook
Endianness

Endianness means the order used to store the bytes of a multi-byte value.

zigbook
Async Functions

Async code lets a program start an operation now and receive the result later.

zigbook
Building Mixed Zig and C Projects

A mixed Zig and C project contains source files from both languages.

zigbook
Assertions

An assertion is a check that must be true while the program runs.

zigbook
Static and Dynamic Linking

Linking is the step where the compiler connects your program with the code it depends on.

zigbook
Formatting and Printing

Formatting means turning values into text.

zigbook
The Core Idea

A ring buffer is a fixed-size queue that reuses its storage.

zigbook
Lifetime Management

Memory lifetime means:

zigbook
`@intCast`

@intCast converts one integer value to another integer type.

zigbook
When Not to Use `comptime`

comptime is one of Zig’s strongest features, but it should not be used everywhere.

zigbook
Appendix F. Build Modes Reference

When Zig compiles a program, it can build the program in different modes.

zigbook
Code Generation

Code generation is the compiler stage that turns analyzed program meaning into target code.

zigbook
Build a Thread Pool

A thread pool is a group of worker threads that wait for jobs.

zigbook
ARM and Embedded Targets

ARM is a CPU architecture family used in phones, tablets, laptops, routers, Raspberry Pi boards, microcontrollers, servers, and many embedded devices. When you write Zig for...

zigbook
Writing a Game Engine Core

A game engine core is the small central layer that runs the game.

zigbook
Why Allocations Cost Time

Allocations are one of the most common causes of slow programs.

zigbook
Binary File Formats

A binary file format stores data as bytes with a specific structure.

zigbook
Condition Variables

A condition variable lets one thread sleep until another thread says that something has changed.

zigbook
Linking C Libraries

Importing a C header lets Zig understand a C API. Linking gives the final program the actual compiled code.

zigbook
Stack Traces

A stack trace shows how your program reached a failure.

zigbook
Cross Compilation

Cross compilation means building a program for a different machine than the one you are using.

zigbook
Directories and Paths

A file lives inside a directory.

zigbook
Why Bit Sets Matter

A bit set is a compact collection of yes-or-no values.

zigbook
Memory Leak Detection

A memory leak happens when a program allocates memory and then loses the ability to free it.

zigbook
`@memcpy`

@memcpy copies bytes from one memory region to another.

zigbook
Metaprogramming Patterns

Metaprogramming means writing code that helps create, inspect, or specialize other code.

zigbook
Volatile and Atomic Memory

Most memory in Zig is ordinary memory.

zigbook
LeetCode 1084: Sales Analysis III

A clear explanation of finding products sold only in the first quarter of 2019 using GROUP BY with date range conditions.

leetcodedatabase
LeetCode 1081: Smallest Subsequence of Distinct Characters

A clear explanation of finding the lexicographically smallest subsequence with all distinct characters using a greedy stack approach.

leetcodestringstackgreedymonotonic-stack
LeetCode 1066: Campus Bikes II

A clear explanation of finding the minimum total Manhattan distance to assign bikes to workers using bitmask dynamic programming.

leetcodearraydynamic-programmingbit-manipulationbitmask
LeetCode 1071: Greatest Common Divisor of Strings

A clear explanation of finding the longest string that divides both strings using the GCD of their lengths.

leetcodemathstring
LeetCode 1030: Matrix Cells in Distance Order

A clear explanation of sorting matrix cells by Chebyshev distance from a given center cell using BFS.

leetcodearraymathsortingmatrix
LeetCode 1073: Adding Negative Numbers

A clear explanation of adding two non-positive integers represented as arrays of digits.

leetcodearraymathsimulation
LeetCode 1009: Complement of Base 10 Integer

A clear explanation of finding the complement of a number by XORing with a bitmask of the same bit length.

leetcodebit-manipulation
LeetCode 1097: Game Play Analysis V

A clear explanation of finding the fraction of players retained the day after their first login using self-join and window functions.

leetcodedatabase
LeetCode 1092: Shortest Common Supersequence

A clear explanation of finding the shortest string containing both input strings as subsequences using LCS dynamic programming.

leetcodestringdynamic-programming
LeetCode 1072: Flip Columns For Maximum Number of Equal Rows

A clear explanation of finding the maximum number of rows that can be made all-equal by flipping columns, using row pattern normalization.

leetcodearrayhash-tablematrix
LeetCode 1036: Escape a Large Maze

A clear explanation of determining if a source can reach a target in a very large grid with blocked cells using BFS with a cell count limit.

leetcodearrayhash-tablebreadth-first-search
LeetCode 1078: Occurrences After Bigram

A clear explanation of finding all words that follow a two-word sequence in a text string.

leetcodestring
LeetCode 1082: Sales Analysis I

A clear explanation of finding the best seller(s) by total price using GROUP BY, SUM, and a subquery for the maximum.

leetcodedatabase
LeetCode 1018: Binary Prefix Divisible By 5

A clear explanation of checking divisibility of binary prefixes by 5 using running remainder tracking.

leetcodearraybit-manipulation
LeetCode 1057: Campus Bikes

A clear explanation of greedily assigning bikes to workers based on Manhattan distance, prioritizing by distance then worker then bike index.

leetcodearraygreedysorting
LeetCode 1041: Robot Bounded In Circle

A clear explanation of determining if a robot stays in a bounded circle by checking position and direction after one instruction cycle.

leetcodemathstringsimulation
LeetCode 1038: Binary Search Tree to Greater Sum Tree

A clear explanation of converting a BST to a greater sum tree by accumulating values in reverse inorder traversal.

leetcodetreedepth-first-searchbinary-search-treebinary-tree
LeetCode 1014: Best Sightseeing Pair

A clear explanation of maximizing the sightseeing score by tracking the best left value seen so far in a single pass.

leetcodearraydynamic-programming
LeetCode 1034: Coloring A Border

A clear explanation of coloring the border of a connected component in a grid using BFS.

leetcodearraydepth-first-searchbreadth-first-searchmatrix
LeetCode 1020: Number of Enclaves

A clear explanation of counting land cells unreachable from the grid border using BFS from boundary land cells.

leetcodearraydepth-first-searchbreadth-first-searchunion-findmatrix
LeetCode 1029: Two City Scheduling

A clear explanation of minimizing total travel cost for two-city scheduling using a greedy refund approach after sending everyone to city A.

leetcodearraygreedysorting
LeetCode 1069: Product Sales Analysis II

A clear explanation of computing total quantity sold per product using GROUP BY and SUM aggregation.

leetcodedatabase
LeetCode 1002: Find Common Characters

A clear explanation of finding characters that appear in all words using minimum frequency counts.

leetcodearrayhash-tablestring
LeetCode 1017: Convert to Base -2

A clear explanation of converting a non-negative integer to its base negative-two representation.

leetcodemath
LeetCode 1099: Two Sum Less Than K

A clear explanation of finding the maximum sum of two numbers less than k using a two-pointer approach on a sorted array.

leetcodearraytwo-pointerssortingbinary-search
LeetCode 1080: Insufficient Nodes in Root to Leaf Paths

A clear explanation of pruning tree nodes where all root-to-leaf paths through them have sum less than a limit, using post-order DFS.

leetcodetreedepth-first-searchbinary-tree
LeetCode 1047: Remove All Adjacent Duplicates In String

A clear explanation of eliminating adjacent duplicate character pairs from a string using a stack.

leetcodestringstack
LeetCode 1050: Actors and Directors Who Cooperated At Least Three Times

A clear explanation of finding actor-director pairs with at least three collaborations using GROUP BY and HAVING.

leetcodedatabase
LeetCode 1096: Brace Expansion II

A clear explanation of generating all strings from a brace expansion expression using recursive parsing and set union/concatenation.

leetcodestringbacktrackingstack
LeetCode 1091: Shortest Path in Binary Matrix

A clear explanation of finding the shortest path from top-left to bottom-right in a binary matrix using BFS.

leetcodearraybreadth-first-searchmatrix
LeetCode 1003: Check If Word Is Valid After Substitutions

A clear explanation of validating a string by repeatedly removing 'abc' substrings using a stack.

leetcodestringstack
LeetCode 1058: Minimize Rounding Error to Meet Target

A clear explanation of minimizing total rounding error when rounding prices to meet a target sum using a greedy approach.

leetcodearraymathgreedysorting
LeetCode 1028: Recover a Tree From Preorder Traversal

A clear explanation of reconstructing a binary tree from a depth-encoded preorder traversal string using a stack.

leetcodestringtreedepth-first-searchbinary-tree
LeetCode 1056: Confusing Number

A clear explanation of checking if a number becomes a different valid number when rotated 180 degrees.

leetcodemath
LeetCode 1083: Sales Analysis II

A clear explanation of finding buyers who bought an iPhone but not an iPad using JOIN and NOT IN filtering.

leetcodedatabase
LeetCode 1089: Duplicate Zeros

A clear explanation of duplicating zeros in-place in an array without using extra space by working backwards.

leetcodearraytwo-pointers