<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ed Yu on Medium]]></title>
        <description><![CDATA[Stories by Ed Yu on Medium]]></description>
        <link>https://medium.com/@edlyuu?source=rss-931a37f1b662------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*uHxJiBXw3u3TM4Cr.</url>
            <title>Stories by Ed Yu on Medium</title>
            <link>https://medium.com/@edlyuu?source=rss-931a37f1b662------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 17:40:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@edlyuu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Zig Erasure Coding — WTF is Zig Comptime 2 (Part 1)]]></title>
            <link>https://medium.com/@edlyuu/zig-erasure-coding-wtf-is-zig-comptime-2-part-1-2df6da0a9d51?source=rss-931a37f1b662------2</link>
            <guid isPermaLink="false">https://medium.com/p/2df6da0a9d51</guid>
            <category><![CDATA[zig]]></category>
            <category><![CDATA[ziglang]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[erasure-coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ed Yu]]></dc:creator>
            <pubDate>Thu, 25 Jan 2024 04:03:46 GMT</pubDate>
            <atom:updated>2024-01-25T04:03:46.656Z</atom:updated>
            <content:encoded><![CDATA[<h3>Zig Erasure Coding — WTF is Zig Comptime 2 (Part 1)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*CFsB3fFJtyTzdVhCe7Q3cw.png" /></figure><p>The power and complexity of <strong>Comptime</strong> in Zig</p><p>Ed Yu (<a href="https://github.com/edyu">@edyu</a> on Github and <a href="https://twitter.com/edyu">@edyu</a> on Twitter) January.17.2024</p><h3>Introduction</h3><p><a href="https://ziglang.org/"><strong>Zig</strong></a> is a modern systems programming language and although it claims to a be a <strong>better C</strong>, many people who initially didn’t need systems programming were attracted to it due to the simplicity of its syntax compared to alternatives such as <strong>C++</strong> or <strong>Rust</strong>.</p><p>However, due to the power of the language, some of the syntaxes are not obvious for those first coming into the language. I was actually one such person.</p><p>Today we will explore a unique aspect of metaprogramming in <strong>Zig</strong> that sets it apart from other similarly low-level languages — comptime.</p><p>I’ve already written an <a href="https://zig.news/edyu/wtf-is-zig-comptime-and-inline-257b">earlier article</a> on comptime but today I want to explore an example using a simplified version of <a href="https://github.com/edyu/zig-erasure">erasure coding</a> that I&#39;ve implemented using <strong>Zig</strong> with extensive use of comptime.</p><p>Due to the length of the code example, I’ll explain the code in a series of articles and eventually even compare it to an <a href="https://odin-lang.org/">Odin</a> implementation.</p><h3>WTF is Comptime</h3><p>I gave an overview of <strong>Zig</strong> comptime in <a href="https://zig.news/edyu/wtf-is-zig-comptime-and-inline-257b">WTF Zig Comptime</a>. In short, comptime is a way to designate either a variable or a piece of code such as a block or a function as something to be run at compile time as opposed to runtime.</p><p>The first benefit of running a these comptime code at comptime is so that the results of comptime are essentially constants that can be used directly by the compiled program. As a result, comptime do not use runtime resources for these any results.</p><p>One example is the same factorial code I showed in <a href="https://zig.news/edyu/wtf-is-zig-comptime-and-inline-257b">WTF Zig Comptime</a>. In such a case, even if I pass in a large number <em>n</em>, which takes a long time to calculate at comptime, during runtime it&#39;s just another constant.</p><p>By using a comptime variable, I still have the flexibility to change the number anytime and just recompile the program to recalculate the correct result.</p><pre>pub fn factorial(comptime n: u8) comptime_int {<br>    var r = 1; // no need to write it as comptime var r = 1<br>    for (1..(n + 1)) |i| {<br>        r *= i;<br>    }<br>    return r;<br>}<br><br>const v = comptime factorial(120);</pre><p>The other benefit is actually due to necessity of metaprogramming. One of the primary reasons to use metaprogramming is to allow for different behaviors for different types.</p><p>Because you have to know precisely how much memory to allocate at compile time, <strong>Zig</strong> types must be complete at compile type. What it means is that if you want to a <em>type function</em> (once again, see <a href="https://zig.news/edyu/wtf-is-zig-comptime-and-inline-257b">WTF Zig Comptime</a>) to create different types based on some variable you pass, that variable must be comptime.</p><p>One example is say you want to create a matrix type and that a matrix type of <em>3 x 3</em> should be completely separate from a matrix type of <em>4 x 4</em> in that you cannot simply treat them in the same way. However, you do want to use the same <em>type function</em> to create both matrices, then you must declare the <em>n</em> in <em>n x n</em> matrix as a comptime variable that you pass in.</p><pre>    // a square matrix is a matrix where number_of_rows == number_of_cols<br>    pub fn SquareMatrix(comptime n: comptime_int) type {<br>        return struct {<br>            allocator: std.mem.Allocator,<br>            comptime numRows: u8 = n, <br>            comptime numCols: u8 = n, <br>            const Self = @This();<br> <br>            pub fn init(allocator: std.mem.Allocator) Self {<br>                return .{<br>                    .allocator = allocator,<br>                }<br>            }<br>            // other methods<br>        }<br>    }</pre><h3>WTF is Erasure Coding</h3><p>Now, with the introduction out of the way, let’s talk about Erasure Coding.</p><p><a href="https://en.wikipedia.org/wiki/Erasure_code">Erasure Coding</a> is a way to split up your data in multiple pieces (shards) so that if you lose one or more of the pieces, you can still retrieve the original data. If you think this sounds like duplication or replication, or even RAID, then you are somewhat correct. The difference is that in a simple replication (or RAID 1), you make complete copies of the data so that if you make 2 copies of the data, you have a total of 3 copies (including the original copy) and that as long as you don’t lose all 3 copies, you can get the data back. In a more complex RAID setup such as RAID 5, data is split across (stripe) multiple disks and then additional parity blocks are added to tolerate disk loss. However, in the case of RAID 5, you can tolerate 1 disk loss, whereas RAID 6 can tolerate up to 2 disk failures.</p><p>In <a href="https://en.wikipedia.org/wiki/Erasure_code">Erasure Coding</a>, you transform the data while you split the data so that the copies are not necessarily the same. You still need a minimum number of copies to reconstruct the original data and as long as you don’t lose more than such minimal number, you can reconstruct the data.</p><p>We typically describe <a href="https://en.wikipedia.org/wiki/Erasure_code">Erasure Coding</a> with 2 numbers of N and K where N is the total number of shards, and K is the minimum number of shards you need in order to reconstruct the data. For instance, in a (5, 3) Erasure Coding, N is 5 and K is 3, you need 3 of the 5 shards in order to reconstruct the data. In other words, you can tolerate the loss of up to (N — K) = 2 shards.</p><p>What makes <a href="https://en.wikipedia.org/wiki/Erasure_code">Erasure Coding</a> better than a simple replication is that you save more disk spaces by using Erasure Coding compared to simple replication.</p><p>In a quick test, using a file of 680 bytes, if I make 2 additional copies, the total storage needed is 680 <em>3 = 2040 bytes. If instead I use my </em><strong><em>Zig</em></strong><em> </em><a href="https://github.com/edyu/zig-erasure"><em>Erasure Coding</em></a><em>, I need 5 copies of 240 bytes each which means the total storage needed is 240 </em>5 = 1020 bytes. The total saving in storage comparing the two is (2040–1020) / 2040 = 50%.</p><p>Of course the storage saving is not free as there is extra computation involved both in encoding (splitting the original data to shards) and decoding (reconstruct the data from shards).</p><h3>Erasure Code Example</h3><p>The example <a href="https://github.com/edyu/zig-erasure">Erasure Coding</a> is based upon <a href="https://towardsdatascience.com/erasure-coding-for-the-masses-2c23c74bf87e">Erasure Coding For The Masses</a> by <a href="https://vishesh-khemani.medium.com/">Dr. Vishesh Khemani</a>.</p><p>The method described is not the most efficient <a href="https://en.wikipedia.org/wiki/Erasure_code">Erasure Coding</a> but it’s easy to understand and I really liked how <a href="https://vishesh-khemani.medium.com/">Dr. Vishesh Khemani</a> used simple <a href="https://en.wikipedia.org/wiki/Finite_field_arithmetic">finite field arithmetic</a> to describe <a href="https://en.wikipedia.org/wiki/Erasure_code">Erasure Coding</a>. <a href="https://en.wikipedia.org/wiki/Finite_field_arithmetic">finite field arithmetic</a> to describe <a href="https://en.wikipedia.org/wiki/Erasure_code">Erasure Coding</a>.</p><h3>Finite (Binary) Field Arithmetic</h3><p>If you are mathmetically inclined, you are certainly welcome to read the <a href="https://en.wikipedia.org/wiki/Finite_field_arithmetic">Wikipedia article</a> or in particular <a href="https://www.doc.ic.ac.uk/~mrh/330tutor/ch04s04.html">binary fields</a>. I’m not but I’ll try my best to give a simple explanation of <a href="https://www.doc.ic.ac.uk/~mrh/330tutor/ch04s04.html">binary fields</a> from a programmer’s perspective.</p><p>When you have a <a href="https://en.wikipedia.org/wiki/Finite_field_arithmetic">finite field</a>, you are basically doing <a href="https://en.wikipedia.org/wiki/Modular_arithmetic">modular maths</a>, which basically means that you have to take the modulo of the modulus (usually 1 more than then largest allowed number). For example, for a finite field of 3, you only have [0, 1, 2] as valid numbers, the <strong>modulus</strong> is 3 (1 more than the largest number which is 2). So if you add 1 and 2 together, you normally would get 3 without <a href="https://en.wikipedia.org/wiki/Modular_arithmetic">modular arithmetic</a> but because it&#39;s <a href="https://en.wikipedia.org/wiki/Modular_arithmetic">modulo maths</a>, you have to modulo 3 which is 3 mod 3 = 0. For us programmers, this is very similar to how a <a href="https://en.wikipedia.org/wiki/Circular_buffer">ring buffer</a> works.</p><p>In the case of <a href="https://www.doc.ic.ac.uk/~mrh/330tutor/ch04s04.html">binary fields</a>, the maths is even easier as you only have [0, 1] as valid numbers and addition is really just XOR because <em>1 + 1 = 2 mod 2 = 0 = 1 XOR 1</em>. What&#39;s even cooler is that because <em>-1 = 1 mod 2</em> (try going counter-clockwise on your <a href="https://en.wikipedia.org/wiki/Circular_buffer">ring buffer</a>), we can do subtraction just as we do addition because <em>n - 1 = n + (-1) = n + 1</em>.</p><h3>Code: matrix.zig</h3><p>Ok, that’s probably too much maths already. Let’s go back to the <a href="https://github.com/edyu/wtf-zig-erasure">code example</a>.</p><p>The <a href="https://github.com/edyu/wtf-zig-erasure/matrix.zig">first code</a> I want to describe is an implementation of <em>m x n</em> matrix where <em>m</em> is the number of rows and <em>n</em> is the number of columns.</p><p>I decided to use <em>type function</em> to return the matrix type because I wanted to make sure the compiler can enforce that a <em>3 x 2</em> matrix is different from a <em>2 x 3</em> matrix.</p><p>The way to do so is to pass in both <em>m</em> and <em>n</em> as comptime variables to the <em>type function</em>.</p><pre>pub fn Matrix(comptime m: comptime_int, comptime n: comptime_int) type {<br>    return struct {<br>        allocator: std.mem.Allocator = undefined,<br>        mdata: std.ArrayList(u8) = undefined,<br>        mtype: DataOrder = undefined,<br>        comptime numRows: u8 = m,<br>        comptime numCols: u8 = n,<br>        const Self = @This();<br>        // followed by type methods<br>    }<br>}</pre><p>Do note that I ended up saving <em>m</em> and <em>n</em> as fields inside the Matrix(m, n) type as numRows and numCols. <strong>Zig</strong> doesn&#39;t require you to only access fields as methods and by exposing them as fields, I can use mat.numRow and mat.numCols directly if mat is a Matrix(m, n). I do have to designate both numRows and numCols as comptime in order to store <em>m</em> and <em>n</em>.</p><p>The code should be fairly straightforward but I do want to explain why I have an enum called DataOrder. The internal data format is an array using ArrayList called mdata. Typically, you can store a 2D matrix as 1D vector (or ArrayList in <strong>Zig</strong>) either in row-major or column-major order. The original reason to have DataOrder is so that I can have the flexibility to store the matrix data in either order and then transpose is really just changing the mtype from one to the other.</p><p>In the end, not only I ended up not needing such flexibiltiy, but it made my code much more complicated. I kept it there mostly as a reminder to myself to not do <a href="https://wiki.c2.com/?PrematureOptimization">premature optimization</a>.</p><pre>Premature Optimization is the root of all evil<br>                            -- Donald Knuth</pre><p>One artifact of such <em>complication</em> is that getSlice() returns a vector based on whether the matrix is stored internally in row-major or colume-major. The burden is on the caller to keep track of of the DataOrder because the caller is the one that initialized the matrix. Of course, getRow() and getCol() are exposed and preferred.</p><pre>// return eithers a row or a column based on matrix data order<br>// use getRow() or getCol() if you want row/col regardless of data order<br>pub fn getSlice(self: *const Self, rc: usize) []u8 {<br>    switch (self.mtype) {<br>        .row =&gt; {<br>            std.debug.assert(rc &lt; m);<br>            const i = rc * n;<br>            return self.mdata.items[i .. i + n];<br>        },<br>        .col =&gt; {<br>            std.debug.assert(rc &lt; n);<br>            const i = rc * m;<br>            return self.mdata.items[i .. i + m];<br>        },<br>    }<br>}</pre><p>The reverse setSlice() has similar logic and in the end, I&#39;m not sure whether the <em>optimization</em> is ever needed. Once again, it&#39;s probably better to not go through such complication and just expose setRow() and setCol() instead.</p><pre>fn setSlice(self: *Self, rc: usize, new_rc: []const u8) void {<br>    switch (self.mtype) {<br>        .row =&gt; {<br>            std.debug.assert(rc &lt; m and new_rc.len &gt;= n);<br>            const i = rc * n;<br>            self.mdata.replaceRange(i, n, new_rc[0..n]) catch return;<br>        },<br>        .col =&gt; {<br>            std.debug.assert(rc &lt; n and new_rc.len &gt;= m);<br>            const i = rc * m;<br>            self.mdata.replaceRange(i, m, new_rc[0..m]) catch return;<br>        },<br>    }<br>}</pre><h3>Code: finite_field.zig</h3><p>Finally, we can look at the <a href="https://github.com/edyu/wtf-zig-erasure/finite_field.zig">code</a> for <a href="https://www.doc.ic.ac.uk/~mrh/330tutor/ch04s04.html">binary fields</a>. The <a href="https://github.com/edyu/wtf-zig-erasure/finite_field.zig">finite_field.zig</a> exposes the n of finite field p^n^ as n using comptime: Because we only care about <a href="https://www.doc.ic.ac.uk/~mrh/330tutor/ch04s04.html">binary finite fields</a>, p is always 2 and doesn&#39;t needed to specifically passed in.</p><pre>pub fn BinaryFiniteField(comptime n: comptime_int) type {<br>    return struct {<br>        exp: u8 = undefined,<br>        order: u8 = undefined,<br>        divisor: u8 = undefined,<br>        // more code<br>    }<br>}</pre><p>The init() method mostly initializes the 3 numbers needed later. The exp is just the n passed in. Note that because of the use case and my lack of advanced mathematics knowledge, I only care about n &gt;= 1 and n &lt;= 7. This also made it easier for calculating the order because u8 is enough to left shift 1 based on the n. The divisor are primes that are results of using 2 as x in the comments. Leave in the comments if you know the maths and want to explain to other readers why that&#39;s the case.</p><pre>pub fn init() ValueError!Self {<br>    var d: u8 = undefined;<br>    // Irreducible polynomial for mod multiplication<br>    d = switch (n) {<br>        1 =&gt; 3, // 1 + x ? undef  shift(0b11)=2<br>        2 =&gt; 7, // 1 + x + x^2    shift(0b111)=3<br>        3 =&gt; 11, // 1 + x + x^3   shift(0b1011)=4<br>        4 =&gt; 19, // 1 + x + x^4   shift(0b10011)=5<br>        5 =&gt; 37, // 1 + x^2 + x^5 shift(0b100101)=6<br>        6 =&gt; 67, // 1 + x + x^6   shift(0b1000011)=7<br>        7 =&gt; 131, // 1 + x + x^7  shift(0b10000011)=8<br>        else =&gt; return ValueError.InvalidExponentError,<br>    };<br>   return .{<br>        .exp = @intCast(n),<br>        .divisor = d,<br>        .order = @as(u8, 1) &lt;&lt; @intCast(n),<br>    };<br>}</pre><p>The number order is the 1 + the maximum allowed number in the fields. For example, if <em>n</em> is 3, the field cannot contain any number greater than 10.</p><pre>pub fn validated(self: *const Self, a: usize) ValueError!u8 {<br>    if (a &lt; self.order) {<br>        return @intCast(a);<br>    } else {<br>        return ValueError.InvalidNumberError;<br>    }<br>}</pre><h3>Addition and Subtraction</h3><p>Recall that for <a href="https://www.doc.ic.ac.uk/~mrh/330tutor/ch04s04.html">binary fields</a>, addition is just exclusive OR.</p><pre>pub fn add(self: *const Self, a: usize, b: usize) ValueError!u8 {<br>    return try self.validated((try self.validated(a)) ^ (try self.validated(b)));<br>}</pre><p>Also, negation is simply the number itself and subtraction is just addition of the negation.</p><pre>pub fn neg(self: *const Self, a: usize) ValueError!u8 {<br>    return try self.validated(a);<br>}<br><br>pub fn sub(self: *const Self, a: usize, b: usize) ValueError!u8 {<br>    return try self.add(a, try self.neg(b));<br>}</pre><h3>Multiplication</h3><p>Multiplication is probably the most complicated of all the methods except in the case of <em>n</em> is 1.</p><pre>pub fn mul(self: *const Self, a: usize, b: usize) ValueError!u8 {<br>    if (self.exp == 1) {<br>        return self.validated(try self.validated(a) * try self.validated(b));<br>    }<br>    // n &gt; 1<br>    const x = try self.validated(a);<br>    const y = try self.validated(b);<br>    var result: u16 = 0;<br>    for (0..8) |i| {<br>        const j = 7 - i;<br>        if (((y &gt;&gt; @intCast(j)) &amp; 1) == 1) {<br>           result ^= @as(u16, x) &lt;&lt; @intCast(j);<br>        }<br>    }<br>    while (result &gt;= self.order) {<br>        // count how many binary digits result has<br>        var j = countBits(result);<br>        j -= self.exp + 1;<br>        result ^= @as(u16, self.divisor) &lt;&lt; @intCast(j);<br>    }<br>    return try self.validated(result);<br>}</pre><p>It requires a function to count the number of binary digits of a number. There is probably a much better way to figure this out in <strong>Zig</strong> but since I don’t know, I just implemented a naive solution. Leave a comment if you know a better way.</p><pre>fn countBits(num: usize) u8 {<br>    var v = num;<br>    var c: u8 = 0;<br>    while (v != 0) {<br>        v &gt;&gt;= 1;<br>        c += 1;<br>    }<br>    return c;<br>}</pre><h3>Division</h3><p>Division is simply the multiplication of the inverse.</p><pre>pub fn div(self: *const Self, a: usize, b: usize) ValueError!u8 {<br>    return try self.mul(a, try self.invert(b));<br>}</pre><p>However, finding the inverse of a number is more complicated than negation. We do have to check whether the number is 0 first, hence no inverse. We then find the inverse using brute force by trying every number within the order to see whether the result is 1 because b is the inverse of a if and only if a * b == 1. Once again, if you have a better way, leave a comment.</p><pre>pub fn invert(self: *const Self, a: usize) ValueError!u8 {<br>    if (try self.validated(a) == 0) {<br>        return ValueError.NoInverseError;<br>    }<br>    for (0..self.order) |b| {<br>        if (try self.mul(a, b) == 1) {<br>            return try self.validated(b);<br>        }<br>    }<br>    return ValueError.NoInverseError;<br>}</pre><h3>Matrix Representation</h3><p>The final 3 methods are used to find the <em>n x n</em> matrix representation for a number in the field. This is also the primary reason why we had to implement a <a href="https://github.com/edyu/wtf-zig-erasure/matrix.zig">matrix</a>. The main idea is to separate the number into its basis based on the polynormials mentioned in the comments of init().</p><pre>fn setCol(m: *mat.Matrix(n, n), c: usize, a: u8) void {<br>    for (0..n) |r| {<br>        const v = (a &gt;&gt; @intCast(r)) &amp; 1;<br>        m.set(r, c, v);<br>    }<br>}<br><br>fn setAllCols(self: *const Self, m: *mat.Matrix(n, n), a: usize) !void {<br>    var basis: u8 = 1;<br>    for (0..n) |c| {<br>        const p = try self.mul(a, basis);<br>        basis &lt;&lt;= 1;<br>        setCol(m, c, p);<br>    }<br>}<br><br>// n x n binary matrix representation<br>pub fn toMatrix(self: *const Self, allocator: std.mem.Allocator, a: usize) !mat.Matrix(n, n) {<br>    var m = try mat.Matrix(n, n).init(allocator, mat.DataOrder.row);<br>    try self.setAllCols(&amp;m, a);<br>    return m;<br>}</pre><h3>Bonus</h3><p>By adding a function called format to <a href="https://github.com/edyu/wtf-zig-erasure/matrix.zig">matrix.zig</a>, it&#39;s much easier to print out the matrix in debugging calls such as std.debug.print because <strong>Zig</strong> would implicitly check whether such method exists for the struct and use it to format the output. As such I can just call std.debug.print(&quot;{}&quot;, mat) if mat is of type Matrix(m, n).</p><pre>pub fn format(self: *const Self, comptime _: []const u8, _: std.fmt.FormatOptions, stream: anytype) !void {<br>    switch (self.mtype) {<br>        .row =&gt; {<br>            try stream.print(&quot;\n{d}x{d} row -&gt;\n&quot;, .{ m, n });<br>            for (0..m) |r| {<br>                for (0..n) |c| {<br>                    try stream.print(&quot;{d} &quot;, .{self.get(r, c)});<br>                }<br>                try stream.print(&quot;\n&quot;, .{});<br>            }<br>        },<br>        .col =&gt; {<br>            try stream.print(&quot;\n{d}x{d} col -&gt;\n&quot;, .{ m, n });<br>            for (0..n) |c| {<br>                for (0..m) |r| {<br>                    try stream.print(&quot;{d} &quot;, .{self.get(r, c)});<br>                }<br>                try stream.print(&quot;\n&quot;, .{});<br>            }<br>        },<br>    }<br>}</pre><h3>The End</h3><p>You can read my part 1 at <a href="https://zig.news/edyu/wtf-is-zig-comptime-and-inline-257b">WTF Zig Comptime</a>.</p><p>The inspiration of the code is from <a href="https://towardsdatascience.com/erasure-coding-for-the-masses-2c23c74bf87e">Erasure Coding For The Masses</a>.</p><p>You can find the code for the article <a href="https://github.com/edyu/wtf-zig-erasure">here</a>.</p><p>The full erasure coding code is <a href="https://github.com/edyu/zig-erasure">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*XNLPWMRj8X4DXezSVuup0g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2df6da0a9d51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zig Zap — WTF is ⚡Zap⚡]]></title>
            <link>https://medium.com/@edlyuu/zig-zap-wtf-is-zap-8b34a8d892f3?source=rss-931a37f1b662------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b34a8d892f3</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[web-server]]></category>
            <category><![CDATA[zig]]></category>
            <category><![CDATA[ziglang]]></category>
            <dc:creator><![CDATA[Ed Yu]]></dc:creator>
            <pubDate>Thu, 25 Jan 2024 03:43:59 GMT</pubDate>
            <atom:updated>2024-01-29T18:15:38.045Z</atom:updated>
            <content:encoded><![CDATA[<h3>Zig Zap — WTF is ⚡Zap⚡</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*CFsB3fFJtyTzdVhCe7Q3cw.png" /></figure><p>The power of ⚡<strong>Zap</strong>⚡ for Zig</p><p>Ed Yu (<a href="https://github.com/edyu">@edyu</a> on Github and <a href="https://twitter.com/edyu">@edyu</a> on Twitter) January.23.2024</p><h3>Introduction</h3><p><a href="https://ziglang.org/"><strong>Zig</strong></a> is a modern systems programming language and although it claims to a be a <strong>better C</strong>, many people who initially didn’t need systems programming were attracted to it due to the simplicity of its syntax compared to alternatives such as <strong>C++</strong> or <strong>Rust</strong>.</p><p>However, due to the power of the language, some of the syntaxes are not obvious for those first coming into the language. I was actually one such person.</p><p>Today we will explore an awesome <strong>Zig</strong> project called ⚡<a href="https://github.com/zigzap/zap"><strong>Zap</strong></a>⚡. From a high level, <a href="https://github.com/zigzap/zap"><strong>Zap</strong></a> is web-server. However, it’s not a web-server fully implemented in <strong>Zig</strong>. It’s a wrapper on top of a <strong>C</strong> web-server (library) called <a href="https://facil.io/">facil.io</a>.</p><h3>Why Zap</h3><p>There are many reasons I like <a href="https://github.com/zigzap/zap"><strong>Zap</strong></a> but I’ll list the top 3:</p><ol><li><a href="https://github.com/zigzap/zap"><strong>Zap</strong></a> is designed by <a href="https://github.com/renerocksai">Rene</a>, who’s probably one of the most practical engineers I know.</li><li><a href="https://github.com/zigzap/zap"><strong>Zap</strong></a> is extremely fast.</li><li><a href="https://github.com/zigzap/zap"><strong>Zap</strong></a> is very simple.</li></ol><p>Let me explain each of these reasons:</p><p><a href="https://github.com/renerocksai">Rene</a> originally started <a href="https://github.com/zigzap/zap"><strong>Zap</strong></a> for his own use at work so it was designed to make his work easier. He made many decisions along the way and I believe he made many correct decisions.</p><p>He will not implement something just because every other webserver has it nor would he implement something in the same way that other web-servers implemented the feature.</p><p><a href="https://github.com/zigzap/zap"><strong>Zap</strong></a> is extremely fast because <a href="https://facil.io/">facil.io</a> is extremely fast. You can check out the full benchmark <a href="https://github.com/zigzap/zap/blob/master/blazingly-fast.md">here</a>.</p><p>Of course, a benchmark doesn’t tell the full story and can be easily manipulated but it at least shows that bottleneck is definitely not in <a href="https://github.com/zigzap/zap"><strong>Zap</strong></a> or <strong>Zig</strong> itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*iiePusg3eKcCEizJ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*t1CRguLc_19WJTp2.png" /></figure><p><a href="https://github.com/zigzap/zap"><strong>Zap</strong></a> is simple because <a href="https://github.com/renerocksai">Rene</a> didn’t implement anything he didn’t need and when he did need a feature, he tried to implement it in a straightforward manner. His code is a pleasure to read and I can honestly say that he was probably the primary reason I was able to learn <strong>Zig</strong>.</p><p><a href="https://github.com/zig"><strong>Zap</strong></a> also has one of the best <a href="https://github.com/zigzap/zap/tree/master/examples">examples</a> of any projects on github. Just by looking at the <a href="https://github.com/zigzap/zap/tree/master/examples">example</a>, you should be able to get up to speed quickly.</p><h3>Why Not Zap</h3><p>Of course, <a href="https://github.com/zigzap/zap"><strong>Zap</strong></a> is not for everyone and here are three reasons why you may not want to use it:</p><ol><li>If you have <a href="https://en.wikipedia.org/wiki/Not_invented_here">NIH Syndrome</a>, <a href="https://github.com/zigzap/zap"><strong>Zap</strong></a> is <strong>NOT</strong> implemented in <strong>Zig</strong>.</li><li>If you are on Windows or you need <a href="https://en.wikipedia.org/wiki/HTTP/2">HTTP/2</a> or <a href="https://en.wikipedia.org/wiki/HTTP/3">HTTP/3</a> because <a href="https://facil.io/">facil.io</a> only implemented HTTP/1.0 and HTTP/1.1.</li><li>You need to write a lot of code even for simple things in <a href="https://github.com/zigzap/zap"><strong>Zap</strong></a> compared to most other web frameworks because <a href="https://github.com/zigzap/zap"><strong>Zap</strong></a> is a web-server not a web framework.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*lkj_webrLzfcVrqT.gif" /></figure><p>For any new language, there is a tendency for early adopters of that language to reimplement everything in the new shiny language. Even if the language is not new anymore, there will still be plenty of people creating a new <em>framework</em> in that language.</p><p>This is certainly not the case for <a href="https://github.com/zigzap/zap"><strong>Zap</strong></a> because every feature that is exposed is used by <a href="https://github.com/renerocksai">Rene</a> himself.</p><p>He also made it very clear that <a href="https://github.com/zigzap/zap"><strong>Zap</strong></a> will not reimplement everything in <a href="https://facil.io/">facil.io</a> using <strong>Zig</strong>. <a href="https://github.com/renerocksai">Rene</a> also tries to minimize any changes to the upstream <a href="https://github.com/boazsegev/facil.io">facil.io</a>. Unfortunately, it also means that <a href="https://github.com/zigzap/zap"><strong>Zap</strong></a> won’t run on Windows.</p><p>Lastly, understand that even the simplest language and simplest wrapper would introduce artifacts that complicate usage due to impedence mismatch.</p><p>For example, to get a parameter that was passed in the URL, you have to do the following in <a href="https://github.com/zigzap/zap"><strong>Zap</strong></a>:</p><pre>if (r.getParamStr(allocator, &quot;my-param&quot;, false)) |maybe_str| {<br>    if (maybe_str) |*s| {<br>        defer s.deinit();<br>        std.log.info(&quot;Param my-param = {s}&quot;, .{s.str});<br>    } else {<br>        std.log.info(&quot;Param my-param not found!&quot;, .{});<br>    }<br>}</pre><p>There is also no authentication (other than basic HTTP authentication), authorization (other than HTTP Bearer authorization), or database built-in so you’ll end up writing a lot of code to implement these yourself.</p><p>In some private tests I’ve done myself, you end up writing about 5 times as much code in <strong>Zig</strong> and <a href="https://github.com/zigzap/zap"><strong>Zap</strong></a> than if you use something like <strong>Python</strong> <a href="https://fastapi.tiangolo.com/"><strong>FastAPI</strong></a>, or even comparing to another extremely young web-framework such as <strong>Julia</strong> <a href="https://ndortega/Oxygen.jl"><strong>Oxygen.jl</strong></a>. So whether that’s worth the trade-off is up to you.</p><p>Fortunately, as more people start using <a href="https://github.com/zigzap/zap"><strong>Zap</strong></a>, more features are being added. For example, <a href="https://github.com/zigzap/zap"><strong>Zap</strong></a> recently finally has <em>TLS</em> added. The built-in <a href="https://mustache.github.io/"><strong>Mustache</strong></a> template engine is also recently improved as well.</p><h3>Zig 0.11 vs master (0.12)</h3><p>By default, <a href="https://github.com/zigzap/zap"><strong>Zap</strong></a> is on <strong>Zig</strong> <a href="https://ziglang.org/download/0.11.0/release-notes.html">0.11</a> so if you can, please use that instead.</p><p>However, <strong>Zig</strong> by default exposes <em>master</em>, which is currently pre-release <a href="https://ziglang.org/download/">0.12.0</a>, which would not build the <a href="https://github.com/zigzap/zap"><strong>Zap</strong></a> project properly.</p><h3>Build using Zig 0.11</h3><p>You don’t necessarily need to build <a href="https://github.com/zigzap/zap"><strong>Zap</strong></a> although it would make referring to the <a href="https://github.com/zigzap/zap/tree/master/examples">examples</a> and the source code easier.</p><p>To build <a href="https://github.com/zigzap/zap"><strong>Zap</strong></a>, you need to do the following:</p><pre>1. git clone git@github.com:zigzap/zap.git<br>2. cd zap<br>3. zig build</pre><p>If you want to build all the examples:</p><pre>zig build all</pre><p>If you only need to build a specific example such as hello:</p><pre>zig build hello</pre><h3>Zig master (0.12)</h3><p>To build <a href="https://github.com/zigzap/zap"><strong>Zap</strong></a> on <strong>Zig</strong> master, you need to do the following:</p><pre>1. git clone git@github.com:zigzap/zap.git<br>2. cd zap<br>3. git switch zig-0.12.0<br>4. zig build</pre><p>The other steps are the same as 0.11.</p><h3>Setup for Zig 0.11</h3><p>For your <strong>Zap</strong> project, you need to have the following in your build.zig.zon:</p><pre>.{<br>    .name = &quot;wtf-zig-zap&quot;,<br>    .version = &quot;0.0.1&quot;,<br>    .dependencies = .{<br>        // zap v0.5.0<br>        .zap = .{<br>            .url = &quot;https://github.com/zigzap/zap/archive/refs/tags/v0.5.0.tar.gz&quot;,<br>            .hash = &quot;1220aabff84ad1d800f5657d6a49cb90dab3799765811ada27faf527be45dd315a4d&quot;,<br>        }<br>    }<br>}</pre><p>For build.zig, you need the following:</p><pre>const exe = b.addExecutable(.{<br>    .name = &quot;wtf-zig-zap&quot;,<br>    // In this case the main source file is merely a path, however, in more<br>    // complicated build scripts, this could be a generated file.<br>    .root_source_file = .{ .path = &quot;src/main.zig&quot; },<br>    .target = target,<br>    .optimize = optimize,<br>});<br><br>const zap = b.dependency(&quot;zap&quot;, .{<br>    .target = target,<br>    .optimize = optimize,<br>});<br>exe.addModule(&quot;zap&quot;, zap.module(&quot;zap&quot;));<br>exe.linkLibrary(zap.artifact(&quot;facil.io&quot;));</pre><h3>Setup for Zig master (0.12)</h3><p>Because all official <a href="https://github.com/zigzap/zap"><strong>Zap</strong></a> releases are based on <strong>Zig</strong> <a href="https://ziglang.org/download/0.11.0/release-notes.html">0.11</a>, for <strong>Zig</strong> master, you’ll need to either build your own package or use a package I built.</p><pre>.{<br>    .name = &quot;wtf-zig-zap&quot;,<br>    .version = &quot;0.0.1&quot;,<br>    // note the extra paths field for zig 0.12<br>    .paths = .{&quot;.&quot;},<br>    .dependencies = .{<br>        // zap v0.4.0<br>        .zap = .{<br>            // note this is a package built from my forked repository<br>            .url = &quot;https://github.com/edyu/zap/archive/refs/tags/v0.4.0.tar.gz&quot;,<br>            // the hash is also different<br>            .hash = &quot;12203e381b737b077759d3c63a1752fe79bb35dd50d1122a329a3f7b4504156d5595&quot;,<br>        }<br>    }<br>}</pre><p>The build.zig has some more changes due to <strong>Zig</strong> 0.12:</p><pre>const exe = b.addExecutable(.{<br>    .name = &quot;wtf-zig-zap&quot;,<br>    .root_source_file = .{ .path = &quot;src/main.zig&quot; },<br>    .target = target,<br>    .optimize = optimize,<br>});<br><br>const zap = b.dependency(&quot;zap&quot;, .{<br>    .target = target,<br>    .optimize = optimize,<br>});<br>exe.root_module.addImport(&quot;zap&quot;, zap.module(&quot;zap&quot;));<br>exe.linkLibrary(zap.artifact(&quot;facil.io&quot;));</pre><h3>Hello World</h3><p>This is basically the same example as hello in the official <a href="https://github.com/zigzap/zap/tree/master/examples">examples</a>:</p><p>The main entry to your code is the callback on_request which you specify in zap.HttpListener.init().</p><p>In this example, there are on_request_verbose and on_request_minimal to illustrate how you get the path and query from the zap.Request:</p><p>You start the server by using calling zap.start.</p><p>The workers (.workers) do not share memory so if you store states in your <a href="https://github.com/zigzap/zap"><strong>Zap</strong></a> server in memory, you&#39;ll have multiple copies of the states. Therefore, I recommend to start with .workers = 1 until you know what that means or that you make your server state-free and only use a shared database for states.</p><p>For threads, you use .threads; you can have more than 1 and note that if all the threads hang, your server will hang as well.</p><pre>const std = @import(&quot;std&quot;);<br>const zap = @import(&quot;zap&quot;);<br><br>fn on_request_verbose(r: zap.Request) void {<br>    if (r.path) |the_path| {<br>        std.debug.print(&quot;PATH: {s}\n&quot;, .{the_path});<br>    }<br>    if (r.query) |the_query| {<br>        std.debug.print(&quot;QUERY: {s}\n&quot;, .{the_query});<br>    }<br>    r.sendBody(&quot;&lt;html&gt;&lt;body&gt;&lt;h1&gt;Hello from ZAP!!!&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;&quot;) catch return;<br>}<br><br>fn on_request_minimal(r: zap.Request) void {<br>    r.sendBody(&quot;&lt;html&gt;&lt;body&gt;&lt;h1&gt;Hello from ZAP!!!&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;&quot;) catch return;<br>}<br><br>pub fn main() !void {<br>    var listener = zap.HttpListener.init(.{<br>        .port = 3000,<br>        // .on_request = on_request_minimal,<br>        .on_request = on_request_verbose,<br>        .log = true,<br>        .max_clients = 100000,<br>    });<br>    try listener.listen();<br>    std.debug.print(&quot;Listening on 0.0.0.0:3000\n&quot;, .{});<br>    // start worker threads<br>    zap.start(.{<br>        // if all threads hang, your server will hang<br>        .threads = 2,<br>        // workers share memory so do not share states if you have multiple workers<br>        .workers = 1,<br>    });<br>}</pre><p>To run this:</p><pre>zig build run</pre><p>You can now go to localhost:3000 on your browser to see your server in action!</p><h3>Static Files</h3><p>You can specify a folder for static files with .public_folder, which will be served by the server directly.</p><pre>const std = @import(&quot;std&quot;);<br>const zap = @import(&quot;zap&quot;);<br><br>fn on_request(r: zap.Request) void {<br>    r.setStatus(.not_found);<br>    r.sendBody(&quot;&lt;html&gt;&lt;body&gt;&lt;h1&gt;404 - File not found&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;&quot;) catch return;<br>}<br><br>pub fn main() !void {<br>    var listener = zap.HttpListener.init(.{<br>        .port = 3000,<br>        .on_request = on_request,<br>        .log = true,<br>        .public_folder = &quot;public&quot;,<br>        .max_clients = 100000,<br>    });<br>    try listener.listen();<br>    std.debug.print(&quot;Listening on 0.0.0.0:3000\n&quot;, .{});<br>    // start worker threads<br>    zap.start(.{<br>        // if all threads hang, your server will hang<br>        .threads = 2,<br>        // workers share memory so do not share states if you have multiple workers<br>        .workers = 1,<br>    });<br>}</pre><p>If you put a file such as zap.png in the public directory, you can access the file with localhost:3000/zap.png.</p><h3>Bonus</h3><p>This is not specific to <a href="https://github.com/zigzap/zap"><strong>Zap</strong></a> but I found that it’s invaluable to keep track of memory leaks during development.</p><p><strong>Zig</strong> makes it very easy to keeping track of memory leaks. Just wrap your server code as follows:</p><pre>pub fn main() !void {<br>    var gpa = std.heap.GeneralPurposeAllocator(.{<br>        .thread_safe = true,<br>    }){};<br>    {<br>        // use this allocator for all your memory allocation<br>        var allocator = gpa.allocator();<br>        var listener = zap.HttpListener.init(.{<br>            .port = 3000,<br>            .on_request = on_request,<br>            .log = true,<br>            .public_folder = &quot;public&quot;,<br>            .max_clients = 100000,<br>        });<br>        try listener.listen();<br>        std.debug.print(&quot;Listening on 0.0.0.0:3000\n&quot;, .{});<br>        // start worker threads<br>        zap.start(.{<br>            // if all threads hang, your server will hang<br>            .threads = 2,<br>            // workers share memory so do not share states if you have multiple workers<br>            .workers = 1,<br>        });<br>    }<br>    // all defers should have run by now<br>    std.debug.print(&quot;\n\nSTOPPED!\n\n&quot;, .{});<br>    // we&#39;ll arrive here after zap.stop()<br>    const leaked = gpa.detectLeaks();<br>    std.debug.print(&quot;Leaks detected: {}\n&quot;, .{leaked});<br>}</pre><p>Now, whenever you Ctrl-C out of your server, it will report whether you have memory leaks in your application.</p><h3>Until Next Time</h3><p>Once again, I recommend reading the <a href="https://github.com/zigzap/zap/tree/master/examples">examples</a> because there is pretty much an example of everything to get you started such as sending a file, using a template engine, and basic routing.</p><p>As I wrote earlier, there is no modern authentication built-in so if you want to use <a href="https://en.wikipedia.org/wiki/HTTP_cookie">cookies</a> for authentication and/or <a href="https://en.wikipedia.org/wiki/OAuth">OAuth</a>, you need to implement it yourself. I’ll likely follow up next time with an <a href="https://en.wikipedia.org/wiki/OAuth">oauth</a> implementation in <a href="https://github.com/zigzap/zap"><strong>Zap</strong></a>.</p><h3>The End</h3><p>You can find the code for the article <a href="https://github.com/edyu/wtf-zig-zap">here</a>.</p><p><strong>Zap</strong> is <a href="https://github.com/zigzap/zap">here</a> and the patched <strong>facil.io</strong> is <a href="https://github.com/zigzap/facil.io">here</a>.</p><p><strong>Facil.io</strong> is <a href="https://facil.io/">here</a> and the code is <a href="https://github.com/boazsegev/facil.io">here</a>.</p><p>The examples are <a href="https://github.com/zigzap/zap/tree/master/examples">here</a>.</p><p>The <a href="https://github.com/zigzap/zap"><strong>Zap</strong></a><strong> </strong>discord is<strong> </strong><a href="https://discord.gg/CWEQxEHF">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*XNLPWMRj8X4DXezSVuup0g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b34a8d892f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zig Package Manager 2 — WTF is Build.Zig.Zon and Build.Zig (0.11.0 Update)]]></title>
            <link>https://medium.com/@edlyuu/zig-package-manager-2-wtf-is-build-zig-zon-and-build-zig-0-11-0-update-5bc46e830fc1?source=rss-931a37f1b662------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bc46e830fc1</guid>
            <category><![CDATA[zig]]></category>
            <category><![CDATA[ziglang]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[build]]></category>
            <category><![CDATA[package-manager]]></category>
            <dc:creator><![CDATA[Ed Yu]]></dc:creator>
            <pubDate>Thu, 19 Oct 2023 03:10:19 GMT</pubDate>
            <atom:updated>2023-10-19T22:18:09.812Z</atom:updated>
            <content:encoded><![CDATA[<h3>Zig Package Manager 2 — WTF is Build.Zig.Zon and Build.Zig (0.11.0 Update)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*UXqEpvQsWrXfJYuwPQR87g.png" /></figure><p>The power hack and complexity of <strong>Package Manager</strong> in Zig 0.11.0</p><p>Ed Yu (<a href="https://github.com/edyu">@edyu</a> on Github and <a href="https://twitter.com/edyu">@edyu</a> on Twitter) Oct.18.2023</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Zi6kS-LHbNeKepJMqynuKQ.png" /></figure><h3>Introduction</h3><p><a href="https://ziglang.org/"><strong>Zig</strong></a> is a modern system programming language and although it claims to a be a <strong>better C</strong>, many people who initially didn’t need system programming were attracted to it due to the simplicity of its syntax compared to alternatives such as <strong>C++</strong> or <strong>Rust</strong>.</p><p>However, due to the power of the language, some of the syntaxes are not obvious for those first coming into the language. I was actually one such person.</p><p>Several months ago, when I first tried out the new <strong>Zig</strong> package manager, it was before <strong>Zig</strong> <a href="https://github.com/ziglang/zig/releases/tag/0.11.0">0.11.0</a> was officially released. Not only was the language unstable, but also the package manager itself was subject to a lot of stability issues especially with TLS. I had to hack together a system that worked for my need, and I documented my journey in <a href="https://zig.news/edyu/zig-package-manager-wtf-is-zon-558e">Zig Package Manager — WTF is Zon</a>.</p><p>Since then I’ve had discussion of the <strong>Zig</strong> <em>package manager</em> with <a href="https://github.com/andrewrk">Andrew</a> and various others through the <a href="https://discord.com/servers/zig-programming-language-605571803288698900">Zig Discord</a>, <a href="https://ziggit.dev/">Ziggit</a>, and even opened up a <a href="https://github.com/ziglang/zig/issues/16172">Github issue</a>.</p><p>Now that <strong>Zig</strong> has released <a href="https://github.com/ziglang/zig/releases/tag/0.11.0">0.11.0</a> in August 2023, and many of the stability problems were resolved so I want to revisit my hack to see whether I can do a better <em>hack</em>.</p><p>A special shoutout to my friend <a href="https://github.com/inkryption">InKryption</a>, who was tremendously helpful in my understanding of the <em>package manager</em>. I wouldn’t be able to come up with this better hack without his help.</p><h3>Disclaimer</h3><p>As I mentioned in my <a href="https://zig.news/edyu/zig-package-manager-wtf-is-zon-558e">previous article</a>, I changed my typical subtitle of <em>power and complexity</em> to <em>hack and complexity</em> because not only was <strong>Zig</strong> <a href="https://github.com/ziglang/zig/releases/tag/0.11.0">0.11.0</a> (which first introduced the package manager) not released yet but also I had to do a pretty ugly <a href="https://zig.news/edyu/zig-package-manager-wtf-is-zon-558e#provide-a-package">hack</a> to make it work.</p><p>I just want to reiterate my stance on <strong>Zig</strong> and the <em>package manager</em>. I’m not writing this to discourage you from using it but to set the right expectation and hopefully help you in case you encounter similar issues.</p><p><strong>Zig</strong> along with its package manager is being constantly improved and I’m looking forward to the <a href="https://github.com/ziglang/zig/milestone/23">0.12.0</a> release.</p><p>Today, I’ll introduce a better hack than what I had to do in June, 2023 and ideally I can retire my hack after the <a href="https://github.com/ziglang/zig/milestone/23">0.12.0</a> release.</p><p>I’ll most likely write a follow-up article once <strong>Zig</strong> <a href="https://github.com/ziglang/zig/milestone/23">0.12.0</a> is released (hopefully) by the end of the year.</p><p>I will not reiterate concepts introduced in <a href="https://zig.news/edyu/zig-package-manager-wtf-is-zon-558e">Part 1</a>, so please read that first if you find this article confusing.</p><h3>Package (Manager) vs Binary Library</h3><p>One of my previous misunderstandings of the package manager was that I was using a <strong>Zig</strong> package as a library.</p><p>Let’s reuse the same example of C -&gt; B -&gt; A from <a href="https://zig.news/edyu/zig-package-manager-wtf-is-zon-558e">Part 1</a> in that our <em>program C</em> depended on <em>package B</em>, which in turn depended on <em>package A</em>.</p><p>The way I was building the <em>program C</em> and <em>packages B and A</em> was that I was basically <em>copying</em> over everything <em>package A</em> produced to <em>package B</em> and then <em>copied</em> over both what <em>package B</em> produced and <em>package A</em> produced to <em>program C</em> as part of the build process. The thing that was produced is called an <em>artifact</em> in <strong>Zig</strong> package manager.</p><p>That was not the correct way to use a package manager because one of the benefits of a package manager is that you only need to concern yourself with the packages you depended on directly without needing to care about the additional packages those direct packages depended on themselves.</p><p>In the example of C -&gt; B -&gt; A, <em>program C</em> should only know/care about <em>package B</em> and not needing to care at all that <em>package B</em> needed <em>package A</em> internally because the package manager should have taken care of the transitive dependencies.</p><p>In other words, package manager should have good enough encapsulation for packages so that the users need not care about packages not directly required by the main (their own) programs.</p><p>As an example, despite many of the dependency problems, <em>npm</em> does a good job (probably too good a job) of encapsulation.</p><p>It’s so good that sometimes when you add 1 package, you might be surprised when <em>npm</em> automatically pulls down hundreds of packages because it would recursively download all depenencies.</p><p>However, such clean encapsulation is not always possible when we are building native programs in <strong>Zig</strong> especially when shared libraries are involved.</p><h3>Artifact vs Module</h3><p>In addition to <em>artifacts</em>, the <strong>Zig</strong> package manager also has the concept of a <em>module</em> but it is mainly referring to <strong>Zig</strong> source code and is primary used so that your program can import the <strong>Zig</strong> package as a library.</p><p>A module is equivalent to a <strong>Zig</strong> library (source code) exposed by the package manager. A <em>module</em> is not useful when the binary library you depend on is not written in <strong>Zig</strong>.</p><p>When building your program, you need access to the <em>artifact</em> produced by the dependency in order to access the specific items produced by such dependency.</p><p>To summarize, if your package is written in <strong>Zig</strong>, then you can access the <strong>Zig</strong> code in such package as a <em>module</em> and you can access either the shared libarary, static library, or the executable produced by such package as <em>artifacts</em>. However, if your package is not written in <strong>Zig</strong>, then you need to do some additional work to expose the code/library as a <em>module</em> and expose the resulting items as part of the <em>artifact</em>.</p><p>The main problem I had to deal with was that the <strong>Zig</strong> package manager resolved around the idea of an <em>artifact</em> which requires a <em>Compile</em> step that is involved with either a compilation and/or linking step. As stated earlier, an <em>artifact</em> is the stuff that was produced as part of the <em>build</em> process. Where this falls apart is when we need to package together items that do not require a <em>build</em> (<em>Compile</em>) step.</p><p>Hence, the existing <em>artifact</em> conceptualization doesn’t work well with when we have to deal with a package composed of an existing binary library such as a shared library that doesn’t require any additional compilation or linking. Note that this can be the case even if you have the source code because you may not want to compile the source code yourself if the project releases binary packages as part of its releases.</p><h3>The Problem</h3><p>I’ll reintroduce the problem mentioned in <a href="https://zig.news/edyu/zig-package-manager-wtf-is-zon-558e">Part 1</a>.</p><p>The scenario is quite common in projects that uses packages written in a different language from the main project:</p><p>A: You often would need the shared or static library from the package written in another language compiled for your environment (such as <strong>Linux</strong>). B: You would also need to write a wrapper for such library in your native language. C: You then would write your program calling the functions provided by the wrapper <em>B</em>.</p><p>Our concrete example has 3 packages <em>A</em>, <em>B</em>, and <em>C</em>. Our program <em>my-wtf-project</em> is in <em>package C</em>, which needs to use <a href="https://duckdb.org/">DuckDb</a> for its database needs.</p><p>The project C will use the <strong>Zig</strong> layer provided by <em>package B</em>, which in turn will need the actual <a href="https://duckdb.org/">DuckDb</a> implementation provided by <em>package A</em>.</p><p>For our my-wtf-project, our main program will call the <strong>Zig</strong> library provided by <a href="https://github.com/beachglasslabs/zig-duckdb">zig-duckdb</a>. The <a href="https://github.com/beachglasslabs/zig-duckdb">zig-duckdb</a> is just a <strong>Zig</strong> wrapper of <a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a> that provides the dynamic library of <a href="https://github.com/duckdb/duckdb/releases/tag/v0.9.1">release 0.9.1</a> of <a href="https://duckdb.org/">DuckDb</a>.</p><p>To use the C -&gt; B -&gt; A example in the earlier section, <em>program C</em> is our project my-wtf-project, <em>package B</em> is <a href="https://github.com/beachglasslabs/zig-duckdb">zig-duckdb</a>, and <em>project A</em> is <a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a>.</p><p>Note that <em>package B</em> used to be called duckdb.zig but it has since been renamed to <a href="https://github.com/beachglasslabs/zig-duckdb">zig-duckdb</a>.</p><h3>The Hack in Part 1</h3><p>There are two hacks I had to do for the build.zig of <em>package A</em>(<a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a>), <em>package B</em>(<a href="https://github.com/beachglasslabs/zig-duckdb">zig-duckdb</a>), and <em>program C</em>(<em>my-wtf-project</em>):</p><ol><li>In the build.zig of <a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a>, I had to create an <em>artifact</em> even if the libduckdb.so is a shared library that doesn&#39;t need additional compilation/linking by creating a new static library that is linked to libduckdb.so just so I can use the <em>artifact</em> in <a href="https://github.com/beachglasslabs/zig-duckdb">zig-duckdb</a>.</li><li>I had to use Build.installHeader to install both the duckdb.h and the libduckdb.so in all the build.zig to copy over these 2 files to zig-out/include and zig-out/lib respectively.</li></ol><h3>The New Hack</h3><p>I’m still calling this a hack because as stated, a <em>module</em> is mainly used to refer to <strong>Zig</strong> source code that can be used as a library to be imported by your program. Just like how a shared library is not meant to be installed via calls to install header files, a <em>module</em> is meant to be used to refer to individual <em>artifacts</em> in a package. However, this is exactly what I had to do.</p><p>I believe this is better than how I was using Build.installHeader and Build.installLibraryHeader to install <em>artifacts</em> produced by dependencies.</p><p>A big benefit of using the <em>module</em> to refer to <em>non-Zig-produced</em> <em>artifacts</em> is that we do not need to <em>copy</em> over <em>artifacts</em> from the dependencies anymore.</p><h3>A: <a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a></h3><p>The <a href="https://github.com/duckdb/duckdb">duckdb</a> was written in <strong>c++</strong> and the libduckdb-linux-amd64 release from <a href="https://github.com/duckdb/duckdb">duckdb</a> only provided 3 files: duckdb.h, duckdb.hpp, and libduckdb.so.</p><p>I unzipped the package and placed duckdb.h under the include directory and libduckdb.so under the lib directory.</p><h3>build.zig.zon of A: <a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a></h3><p>Because <a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a> has no dependencies, the <em>zon</em> file is extremely simple.</p><p>It just lists the name and the version. I’ve intentionally been using the actual version number of the underlying <a href="https://duckdb.org/">DuckDb</a>.</p><pre>// build.zig.zon<br>// there are no dependencies<br>.{<br>    // note that we don&#39;t have to call this libduckdb<br>    .name = &quot;duckdb&quot;,<br>    .version = &quot;0.9.1&quot;,<br>}</pre><h3>build.zig of A: <a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a></h3><p>This is the first big change from <a href="https://github.com/beachglasslabs/libduckdb/blob/57bb5689984c598494b40b91d79cdbe8ed102279/build.zig">Part 1</a>. We are not building anymore fake artifact. We are only introducing some <em>modules</em> so that any package depending on this package can reference these items using the various <em>module</em> names. This is still a <strong>hack</strong> because technically these items are <em>artifacts</em> not <em>modules</em> but at least we don’t have to compile a shared library that doesn’t need to be compiled.</p><pre>pub fn build(b: *std.Build) !void {<br>    _ = b.addModule(&quot;libduckdb.lib&quot;, .{ .source_file = .{ .path = b.pathFromRoot(&quot;lib&quot;) } });<br>    _ = b.addModule(&quot;libduckdb.include&quot;, .{ .source_file = .{ .path = b.pathFromRoot(&quot;include&quot;) } });<br>    _ = b.addModule(&quot;duckdb.h&quot;, .{ .source_file = .{ .path = b.pathFromRoot(&quot;include/duckdb.h&quot;) } });<br>    _ = b.addModule(&quot;libduckdb.so&quot;, .{ .source_file = .{ .path = b.pathFromRoot(&quot;lib/libduckdb.so&quot;) } });<br>}</pre><p>This will make more sense in the next sections.</p><h3>B: <a href="https://github.com/beachglasslabs/zig-duckdb">zig-duckdb</a></h3><p>The <a href="https://github.com/beachglasslabs/zig-duckdb">zig-duckdb</a> is still a minimal <strong>Zig</strong> wrapper to <a href="https://duckdb.org/">DuckDb</a>. It suits my needs for now and the only changes added since last time are the ability to query for boolean and optional values.</p><p>The big change is that we no longer need to install libduckdb.so or duckdb.h from <a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a>.</p><h3>build.zig.zon of B: <a href="https://github.com/beachglasslabs/zig-duckdb">zig-duckdb</a></h3><p>We do have a dependency now as we need to refer to a release of A: <a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a>.</p><pre>// build.zig.zon<br>// Now we depend on a release of A: libduckdb<br>.{<br>    .name = &quot;duck&quot;,<br>    .version = &quot;0.0.5&quot;,<br>    .dependencies = .{<br>        // this is the name you want to use in the build.zig to reference this dependency<br>        // note that we didn&#39;t have to call this libduckdb or even duckdb<br>        .duckdb = .{<br>            .url = &quot;https://github.com/beachglasslabs/libduckdb/archive/refs/tags/v0.9.1.3.tar.gz&quot;,<br>            .hash = &quot;1220e182337ada061ebf86df2a73bda40e605561554f9dfebd6d1cd486a86c964e09&quot;,<br>        },<br>    },<br>}</pre><h3>build.zig of B: <a href="https://github.com/beachglasslabs/zig-duckdb">zig-duckdb</a></h3><p>Note that we no longer <em>install</em> libduckdb.so or duckdb.h as part of the build process we previous had to do in <a href="https://github.com/beachglasslabs/zig-duckdb/blob/8aab6c6029cb8d9e0492f3135f892f10cbd1e3bf/build.zig">Part 1</a>.</p><p>We do have to call addModule multiple times to expose not only the library libduck.a (the <em>artifact</em> of this package) itself but also <em>re-export</em> the modules provided by <a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a>.</p><p>Note how we now call duck_dep.builder.pathFromRoot(duck_dep.module(&quot;libduckdb.include&quot;).source_file.path to access the include directory and duck_dep.builder.pathFromRoot(duck_dep.module(&quot;libduckdb.lib&quot;).source_file.path) to access the lib directory.</p><p>You can think of this as equivalent of reaching inside of <a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a> to access these items and therefore we don’t have to copy these items into our output directory anymore as we previously had to do with lib.installLibraryHeaders(duck_dep.artifact(&quot;duckdb&quot;)).</p><pre>pub fn build(b: *std.Build) !void {<br>    const target = b.standardTargetOptions(.{});<br>    const optimize = b.standardOptimizeOption(.{});<br>    const duck_dep = b.dependency(&quot;duckdb&quot;, .{});<br>    // this is our main wrapper file<br>    _ = b.addModule(&quot;duck&quot;, .{<br>        .source_file = .{ .path = &quot;src/main.zig&quot; },<br>    });<br>    // (re-)add modules from libduckdb<br>    _ = b.addModule(&quot;libduckdb.include&quot;, .{<br>        .source_file = .{ .path = duck_dep.builder.pathFromRoot(<br>            duck_dep.module(&quot;libduckdb.include&quot;).source_file.path,<br>        ) },<br>    });<br>    _ = b.addModule(&quot;libduckdb.lib&quot;, .{<br>        .source_file = .{ .path = duck_dep.builder.pathFromRoot(<br>            duck_dep.module(&quot;libduckdb.lib&quot;).source_file.path,<br>        ) },<br>    });<br>    _ = b.addModule(&quot;duckdb.h&quot;, .{<br>        .source_file = .{ .path = duck_dep.builder.pathFromRoot(<br>            duck_dep.module(&quot;duckdb.h&quot;).source_file.path,<br>        ) },<br>    });<br>    _ = b.addModule(&quot;libduckdb.so&quot;, .{<br>        .source_file = .{ .path = duck_dep.builder.pathFromRoot(<br>            duck_dep.module(&quot;libduckdb.so&quot;).source_file.path,<br>        ) },<br>    });<br>    const lib = b.addStaticLibrary(.{<br>        .name = &quot;duck&quot;,<br>        // In this case the main source file is merely a path, however, in more<br>        // complicated build scripts, this could be a generated file.<br>        .root_source_file = .{ .path = &quot;src/main.zig&quot; },<br>        .target = target,<br>        .optimize = optimize,<br>    });<br>    lib.addLibraryPath(.{ .path = duck_dep.builder.pathFromRoot(<br>        duck_dep.module(&quot;libduckdb.lib&quot;).source_file.path,<br>    ) });<br>    lib.addIncludePath(.{ .path = duck_dep.builder.pathFromRoot(<br>        duck_dep.module(&quot;libduckdb.include&quot;).source_file.path,<br>    ) });<br>    lib.linkSystemLibraryName(&quot;duckdb&quot;);<br>    b.installArtifact(lib);<br>}</pre><p>Note that if you really want to install libduckdb.so for example, you can do so with the following call:</p><pre>_ = b.installLibFile(duck_dep.builder.pathFromRoot(<br>    duck_dep.module(&quot;libduckdb.so&quot;).source_file.path,<br>    ), &quot;libduckdb.so&quot;);</pre><p>If you look into the project, you will see that I introduced a new file called test.zig that was meant to test the new boolean and optional values.</p><p>In order to run the test, I’ve added a new <em>test</em> step in build.zig:</p><pre>const unit_tests = b.addTest(.{<br>        .root_source_file = .{ .path = &quot;src/test.zig&quot; },<br>        .target = target,<br>        .optimize = optimize,<br>    });<br>    unit_tests.step.dependOn(b.getInstallStep());<br>    unit_tests.linkLibC();<br>    // note how I use modules to access these directories<br>    unit_tests.addLibraryPath(.{ .path = duck_dep.builder.pathFromRoot(<br>        duck_dep.module(&quot;libduckdb.lib&quot;).source_file.path,<br>    ) });<br>    unit_tests.addIncludePath(.{ .path = duck_dep.builder.pathFromRoot(<br>        duck_dep.module(&quot;libduckdb.include&quot;).source_file.path,<br>    ) });<br>    unit_tests.linkSystemLibraryName(&quot;duckdb&quot;);<br>    const run_unit_tests = b.addRunArtifact(unit_tests);<br>    run_unit_tests.setEnvironmentVariable(&quot;LD_LIBRARY_PATH&quot;, duck_dep.builder.pathFromRoot(<br>        duck_dep.module(&quot;libduckdb.lib&quot;).source_file.path,<br>    ));<br>    const test_step = b.step(&quot;test&quot;, &quot;Run unit tests&quot;);<br>    test_step.dependOn(&amp;run_unit_tests.step);</pre><p>Once again, you can see that’s why I’ve exposed the lib and include directories of <a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a> via <em>module</em>. I can now call addIncludePath and addLibraryPath by referencing their modules.</p><p>Note the call to setEnvironmentVariable because -L is only useful for <em>linking</em> not for running the test/program. Hence you need to point to libduckdb.so using LD_LIBRARY_PATH and once again by accessing the location of the shared library inside the <a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a> package.</p><h3>C: my-wtf-project</h3><p>Now to create the executable for our project, we need to link to the packages A <a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a> and B <a href="https://github.com/beachglasslabs/zig-duckdb">zig-duckdb</a>.</p><h3>build.zig.zon of C: my-wtf-project</h3><p>Our only dependency is the release of B: <a href="https://github.com/beachglasslabs/zig-duckdb">zig-duckdb</a>.</p><pre>// build.zig.zon<br>// Now we depend on a release of B: zig-duckdb<br>.{<br>    // this is the name of our own project<br>    .name = &quot;my-wtf-project&quot;,<br>    // this is the version of our own project<br>    .version = &quot;0.0.2&quot;,<br>    .dependencies = .{<br>        // we depend on the duck package described in B<br>        .duck = .{<br>            .url = &quot;https://github.com/beachglasslabs/zig-duckdb/archive/refs/tags/v0.0.5.tar.gz&quot;,<br>            .hash = &quot;1220fe38df4d196b7aeca68ee6de3f7b36f1424196466038000f7485113cf704f478&quot;,<br>        },<br>    },<br>}</pre><h3>build.zig of C: my-wtf-project</h3><p>This is somewhat similar to the build.zig of B (<a href="https://github.com/beachglasslabs/zig-duckdb">zig-duckdb</a>).</p><p>Note once again that we do not need to call installLibraryHeaders to install the libduckdb.so and duckdb.h anymore.</p><p>I’ve also added setEnvironmentVariable to set LD_LIBRARY_PATH for running the test program.</p><pre>pub fn build(b: *std.Build) !void {<br>    const target = b.standardTargetOptions(.{});<br>    const optimize = b.standardOptimizeOption(.{});<br>    const exe = b.addExecutable(.{<br>        .name = &quot;my-wtf-project&quot;,<br>        .root_source_file = .{ .path = &quot;testzon.zig&quot; },<br>        .target = target,<br>        .optimize = optimize,<br>    });<br>    const duck = b.dependency(&quot;duck&quot;, .{<br>        .target = target,<br>        .optimize = optimize,<br>    });<br>    exe.addModule(&quot;duck&quot;, duck.module(&quot;duck&quot;));<br>    exe.linkLibrary(duck.artifact(&quot;duck&quot;));<br>    exe.addIncludePath(.{ .path = duck.builder.pathFromRoot(<br>        duck.module(&quot;libduckdb.include&quot;).source_file.path,<br>    ) });<br>    exe.addLibraryPath(.{ .path = duck.builder.pathFromRoot(<br>        duck.module(&quot;libduckdb.lib&quot;).source_file.path,<br>    ) });<br>    //  You&#39;ll get segmentation fault if you don&#39;t link with libC<br>    exe.linkLibC();<br>    exe.linkSystemLibraryName(&quot;duckdb&quot;);<br>    b.installArtifact(exe);<br>    const run_cmd = b.addRunArtifact(exe);<br>    run_cmd.step.dependOn(b.getInstallStep());<br>    // you must set the LD_LIBRARY_PATH to find libduckdb.so<br>    run_cmd.setEnvironmentVariable(&quot;LD_LIBRARY_PATH&quot;, duck.builder.pathFromRoot(<br>        duck.module(&quot;libduckdb.lib&quot;).source_file.path,<br>    ));<br>    const run_step = b.step(&quot;run&quot;, &quot;Run the test&quot;);<br>    run_step.dependOn(&amp;run_cmd.step);<br>}</pre><h3>Running the executable</h3><p>You can now just call zig build run to run the test program because we already set LD_LIBRARY_PATH using setEnvironmentVariable in our build.zig.</p><pre>I  ~/w/z/wtf-zig-zon-2 6m 10.7s ❱ zig build run<br>info: duckdb: opened in-memory db<br>info: duckdb: db connected<br>debug: duckdb: query sql select * from pragma_version();<br>Database version is v0.9.1<br><br>STOPPED!<br>Leaks detected: false<br> I  ~/w/z/wtf-zig-zon-2 4.1s ❱</pre><h3>Bonus: Package Cache</h3><p>When I mentioned reaching inside the package, what happens behind the scene is that the package is in ~/.cache/zig so all these magic with <em>module</em> is really specifying the path to the particular packages under ~/.cache/zig.</p><p>You can see more clearly what’s going on if you add --verbose to your zig build or zig build commands.</p><pre>I  ~/w/z/wtf-zig-zon-2 4.1s ❱ zig build run --verbose<br>/snap/zig/8241/zig build-lib /home/ed/.cache/zig/p/1220fe38df4d196b7aeca68ee6de3f7b36f1424196466038000f7485113cf704f478/src/main.zig -lduckdb --cache-dir /home/ed/ws/zig/wtf-zig-zon-2/zig-cache --global-cache-dir /home/ed/.cache/zig --name duck -static -target native-native -mcpu znver3-mwaitx-pku+shstk-wbnoinvd -I /home/ed/.cache/zig/p/1220e182337ada061ebf86df2a73bda40e605561554f9dfebd6d1cd486a86c964e09/include -L /home/ed/.cache/zig/p/1220e182337ada061ebf86df2a73bda40e605561554f9dfebd6d1cd486a86c964e09/lib --listen=-<br>/snap/zig/8241/zig build-exe /home/ed/ws/zig/wtf-zig-zon-2/testzon.zig /home/ed/ws/zig/wtf-zig-zon-2/zig-cache/o/b893f00994b9c79eab2c150de991b233/libduck.a -lduckdb -lduckdb -lc --cache-dir /home/ed/ws/zig/wtf-zig-zon-2/zig-cache --global-cache-dir /home/ed/.cache/zig --name my-wtf-project --mod duck::/home/ed/.cache/zig/p/1220fe38df4d196b7aeca68ee6de3f7b36f1424196466038000f7485113cf704f478/src/main.zig --deps duck -I /home/ed/.cache/zig/p/1220e182337ada061ebf86df2a73bda40e605561554f9dfebd6d1cd486a86c964e09/include -L /home/ed/.cache/zig/p/1220e182337ada061ebf86df2a73bda40e605561554f9dfebd6d1cd486a86c964e09/lib --listen=-<br>LD_LIBRARY_PATH=/home/ed/.cache/zig/p/1220e182337ada061ebf86df2a73bda40e605561554f9dfebd6d1cd486a86c964e09/lib /home/ed/ws/zig/wtf-zig-zon-2/zig-out/bin/my-wtf-project<br>info: duckdb: opened in-memory db<br>info: duckdb: db connected<br>debug: duckdb: query sql select * from pragma_version();<br>Database version is v0.9.1<br><br>STOPPED!<br>Leaks detected: false<br> I  ~/w/z/wtf-zig-zon-2 ❱</pre><h3>The End</h3><p>Part 1 is <a href="https://zig.news/edyu/zig-package-manager-wtf-is-zon-558e">here</a>.</p><p>You can find the code <a href="https://github.com/edyu/wtf-zig-zon-2">here</a>.</p><p>Here are the code for <a href="https://github.com/beachglasslabs/zig-duckdb">zig-duckdb</a> and <a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a>.</p><p>Special thanks to <a href="https://github.com/inkryption">@InKryption</a> for helping out on the new hack for the <strong>Zig</strong> package manager!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/168/1*hzqdBBi4_vWBoLKBps-3iA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bc46e830fc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zig Comptime — WTF is Zig Comptime (and Inline)]]></title>
            <link>https://medium.com/@edlyuu/zig-comptime-wtf-is-zig-comptime-and-inline-e6ea40e0cb41?source=rss-931a37f1b662------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6ea40e0cb41</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[zig]]></category>
            <category><![CDATA[ziglang]]></category>
            <category><![CDATA[compilers]]></category>
            <dc:creator><![CDATA[Ed Yu]]></dc:creator>
            <pubDate>Thu, 24 Aug 2023 01:42:06 GMT</pubDate>
            <atom:updated>2023-09-04T19:29:04.339Z</atom:updated>
            <content:encoded><![CDATA[<h3>Zig Comptime — WTF is Comptime (and Inline)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*CFsB3fFJtyTzdVhCe7Q3cw.png" /></figure><p>The power and complexity of <strong>Comptime</strong> and <strong>Inline</strong> in Zig</p><p>Ed Yu (<a href="https://github.com/edyu">@edyu</a> on Github and <a href="https://twitter.com/edyu">@edyu</a> on Twitter)</p><p>August.23.2023</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Zi6kS-LHbNeKepJMqynuKQ.png" /></figure><h3>Introduction</h3><p><a href="https://ziglang.org/"><strong>Zig</strong></a> is a modern systems programming language and although it claims to a be a <strong>better C</strong>, many people who initially didn’t need systems programming were attracted to it due to the simplicity of its syntax compared to alternatives such as <strong>C++</strong> or <strong>Rust</strong>.</p><p>However, due to the power of the language, some of the syntaxes are not obvious for those first coming into the language. I was actually one such person.</p><p>Today we will explore a unique aspect of metaprogramming in <strong>Zig</strong> in its comptime and inline keywords. I&#39;ve always known comptime is special in <strong>Zig</strong> but I never used it extensively until recently when I was implementing <a href="https://github.com/beachglasslabs/eraser">erasure coding</a>. Although the new implementation removed much of the comptime used in the project, I believe it&#39;s illuminating to explain my learning journey in comptime (and inline) while implementing the initial mostly comptime <a href="https://github.com/beachglasslabs/eraser/tree/405a6809c387eb83de279b2f9f9fb15e5e37ee18">version</a> of that project because it allowed me certainly to gain a better grasp both in the power and the restriction of comptime.</p><h3>WTF is Comptime</h3><p>If you start learning about <strong>Zig</strong>, you’ll certainly encounter the comptime keywords, and you&#39;ll notice it&#39;s sprinkled in many places.</p><p>For example, in the signature for ArrayList, you&#39;ll notice it&#39;s written as pub fn ArrayList(comptime T: type) type. You know that when you create an ArrayList, you do need to pass in a type such as var list = std.ArrayList(u8).init(allocator);.</p><p>You’d most likely take a mental note that when you declare a type as a function parameter, you need to declare that type as <em>comptime</em>. And for many use cases, that’s all you need to know about comptime and go your merry way.</p><p><a href="https://kristoff.it/">Loris Cro</a> wrote <a href="https://kristoff.it/blog/what-is-zig-comptime/">“What is Zig’s Comptime?”</a> in 2019 and you are welcome to read through that first.</p><p>So, what exactly is comptime? If we look at it literally, the <em>comp</em> part of comptime stands for <strong>compile</strong> so comptime really means <strong>compile time</strong>. The keyword comptime is a label that you can apply to a variable to say that the variable can only be changed during comptime so that after the program is compiled and during <em>runtime</em> (when running the program), that variable is essentially const.</p><p>That was a mouthful so why would you make a variable comptime? It would allow you to create <a href="https://en.wikipedia.org/wiki/Macro_(computer_science">macros</a>) because macros are <strong>compile time</strong>. And note that one of the reasons that <a href="https://github.com/andrewrk">Andrew</a> created <strong>Zig</strong> initially is to remove macros from the <strong>C</strong> so comptime is the answer to the <strong>C</strong> macro use case. I know the previous sentences are somewhat contradictory so what I mean really is that comptime was invented to allow the use cases of macros by using comptime instead.</p><p>Now the question is what is a macro? One way to think about it is that macros are substitutions that happen during <strong>compile time</strong> as part of a <em>preprocessor</em>. A <em>preprocessor</em> is a step before the regular compilation (although it happens normally as part of compilation).</p><p>In <strong>C</strong>, for example, you often use macros to define a constant such as this:</p><pre>// a constant<br>#define MY_CONST 5</pre><p>And after you define the constant, you can then use such constant anywhere in your code. The preprocessor would <em>substitute</em> everywhere the macro is used with the value that was defined (in this case 5).</p><pre>printf(&quot;The constant is %d&quot;, MY_CONST);</pre><p>In <strong>Zig</strong>, you can just say:</p><pre>const MY_CONST = 5;<br><br>std.debug.print(&quot;The constant is {d}&quot;, .{MY_CONST});</pre><p>This is not very useful but often people define more complex macros such as the following:</p><pre>// square a number<br>// you need the () around x because you might call square(4 + 2)<br>#define square(x) ((x) * (x))<br>// find the minimum of 2 numbers<br>#define min(a, b) (((a) &lt; (b)) ? (a) : (b))</pre><h3>WTF is Inline</h3><p>So why would those <strong>C</strong> macros be useful? Why can’t we just define these as regular functions?</p><p>Often people use macros instead of functions because they want to optimize the code by not incurring the overhead of calling a function.</p><p>In this case, <strong>Zig</strong> introduced an inline keyword so that you can do the following:</p><pre>// note that this will overflow<br>// but I left it in this form intentionally<br>// to mimic the simplicity of the C macro<br>pub inline fn square(x: i32) i32 {<br>    return x * x;<br>}<br><br>pub inline fn min(a: i32, b: i32) i32 {<br>    return if (a &lt; b) a else b;<br>}<br><br>test &quot;square&quot; {<br>    try std.testing.expectEqual(9, square(3));<br>    try std.testing.expectEqual(25, square(3 + 2));<br>}<br><br>test &quot;min&quot; {<br>    try std.testing.expectEqual(min(2, 3), 2);<br>    try std.testing.expectEqual(min(3, 3), 3);<br>    try std.testing.expectEqual(min(-1, -3), -3);<br>}</pre><p>As you can see, by using inline, <strong>Zig</strong> would effectively <em>inline</em> (substitute) the function calls in code without incurring the overhead of a function call.</p><h3>WTF is Comptime_Int</h3><p>As you can see from our test code, that we are using constants or just numbers, so we can actually rewrite the functions by introducing a new type as comptime_int. By denoting the type as comptime_int, the compiler would automatically figure out what&#39;s the best type to use because the inputs to the functions are known at <strong>compile time</strong> or comptime. Note that you have to add the comptime keyword in front of the variable names in the argument. You do not need to denote the return type as comptime however.</p><pre>pub fn squareComptime(comptime x: comptime_int) comptime_int {<br>    return x * x;<br>}<br><br>pub inline fn minComptime(comptime a: comptime_int, comptime b: comptime_int) comptime_int {<br>    return if (a &lt; b) a else b;<br>}<br><br>test &quot;squareComptime&quot; {<br>    try std.testing.expectEqual(9, squareComptime(3));<br>    try std.testing.expectEqual(25, squareComptime(3 + 2));<br>}<br><br>test &quot;minComptime&quot; {<br>    try std.testing.expectEqual(minComptime(0, 0), 0);<br>    try std.testing.expectEqual(minComptime(30000000, 30000000000), 30000000);<br>    try std.testing.expectEqual(minComptime(-10, -3), -10);<br>}</pre><p>Note that I marked squareComptime as a regular function but denoted minComptime as an inline function. In other words, inline and comptime are not exclusive to each other. You don&#39;t have to have both even if both are used at <strong>compile time</strong>.</p><h3>Why Not Comptime Everything</h3><p>When I first started using comptime, I realized two problems:</p><ol><li>comptime in some way <em>pollutes</em> the code it touches. What I mean is that once you comptime something, everything it uses would also need to be comptime. I&#39;ll show a more complex example later.</li><li>The other problem is that as soon as you need to start using a <em>runtime</em> value such as passing in a commmand-line argument, you’ll encounter errors while compiling your code.</li></ol><p>Let me illustrate the problem 2 here. Say I want to pass in numbers during <em>runtime</em> by passing in the number on the command-line (same problem from a file, or from user input), you will have a hard time calling the squareComptime and minComptime versions.</p><p>My friend [InKryption] put it succinctly in a quote: “comptime exists in a sort of pure realm where I/O doesn’t exist.”</p><p>If you try to pass in a command-line argument to the function:</p><pre>pub fn main() !void {<br>    var gpa = std.heap.GeneralPurposeAllocator(.{}){};<br>    defer _ = gpa.deinit();<br>    const allocator = gpa.allocator();<br>    const args = try std.process.argsAlloc(allocator);<br>    defer std.process.argsFree(allocator, args);<br>    var x = try std.fmt.parseInt(i32, args[1], 10);<br>    var y = squareComptime(x);<br>    std.debug.print(&quot;square = {d}\n&quot;, .{y});<br>}</pre><p>And then run the program:</p><pre>&gt; zig run main.zig -- 1337</pre><p>You’ll encounter the following error:</p><pre>error: unable to resolve comptime value<br>var y = squareComptime(x);</pre><p>In other words, once you make your function comptime by making a parameter comptime, you cannot pass non-comptime parameters such as a command-line argument.</p><p>On the other hand, if all your parameters of a function are comptime, you can make a variable that takes in the return value of the function comptime.</p><pre>test &quot;comptime&quot; {<br>    comptime var y = squareComptime(1337);<br>    // you can now pass y to anything that requires comptime<br>    comptime var z = minComptime(y, 7331);<br>    try std.testing.expectEqual(z, 1337);<br>}</pre><p>The only way to <em>fix</em> problem 2 is to make your functions non-comptime.</p><pre>// while we are at it, might as well fix the overflow problem<br>pub inline fn squareNoOverflow(x: i32) u64 {<br>    return @intCast(std.math.mulWide(i32, x, x));<br>}<br><br>pub fn main() !void {<br>    var gpa = std.heap.GeneralPurposeAllocator(.{}){};<br>    defer _ = gpa.deinit();<br>    const allocator = gpa.allocator();<br>    const args = try std.process.argsAlloc(allocator);<br>    defer std.process.argsFree(allocator, args);<br>    var x = try std.fmt.parseInt(i32, args[1], 10);<br>    var y = squareNoOverflow(x);<br>    std.debug.print(&quot;square = {d}\n&quot;, .{y});<br>}</pre><p>Now run it with a command-line argument:</p><pre>&gt; zig run main.zig -- 1337<br>square = 1787569</pre><h3>Unrolling Loops with Inline</h3><p>I’ve already mentioned one common use of inline by prefixing the function declaration with the keyword inline to <em>inline</em> the function for efficiency reasons. The even more common use than <em>inlining</em> a function with inline is to <em>unroll</em> a loop by prefixing a for loop with inline.</p><p>For example, say I need to calculate the factorial of a number. We know that that factorial of a number n is written as n! and it means n * (n - 1) * (n - 2)...1. In other words, 2! is 2 * 1 = 2, 3! is 3 * 2 * 1 = 6, 4! is 4 * 3 * 2 * 1 = 24, and so on. For the special cases of 1! and 0!, they are both 1.</p><p>Although factorial are often written as a recursive function, it’s also fairly easy and efficient to just use a for loop.</p><p>Let’s write a comptime version:</p><pre>pub fn factorial(comptime n: u8) comptime_int {<br>    var r = 1; // no need to write it as comptime var r = 1<br>    for (1..(n + 1)) |i| {<br>        r *= i;<br>    }<br>    return r;<br>}</pre><p>When you prefix a for loop with the inline, you are effectively <a href="https://en.wikipedia.org/wiki/Loop_unrolling"><em>unrolling</em></a> the loop so that each iteration of the loop is executed sequentially without branching. This is usually done also for efficiency reasons.</p><p>When you inline the loop, the loop can still do <em>runtime</em> stuff but the loop branching and the iteration variables are now comptime.</p><pre>pub fn factorial(comptime n: u8) comptime_int {<br>    var r = 1; // no need to write it as comptime var r = 1<br>    inline for (1..(n + 1)) |i| {<br>        r *= i;<br>    }<br>    return r;<br>}</pre><h3>WTF is Type Function</h3><p>The real power of comptime lies in something called a <em>type function</em>. Earlier when I showed the signature of ArrayList, it&#39;s actually a <em>type function</em>. A <em>type function</em> is simply a function that returns a type.</p><p>Let’s see the ArrayList <em>type function</em> again:</p><pre>pub fn ArrayList(comptime T: type) type {<br>    return ArrayListAligned(T, null);<br>}</pre><p>As you can see because the <em>type function</em> returns a type, the function name is usually capitalized by convention as if it’s a type. Effectively you can use <em>type function</em> anywhere a type is usually required such as type annotation, function arguments, and even return types. However, take note that <em>type function</em> name by itself is not a type, because it’s a function, you need to actually supply it with the parameters it needs. For example, ArrayList is not a type, but ArrayList(u8) is a type because the ArrayList <em>type function</em> requires a type as its parameter specified as comptime T: type.</p><p>For example, say I need to implement a function that allows me to calculate the combinatorics of m choose n. From your high-school maths, you know that (m choose n) is equal to m! / (n! * (m-n)!). In other words, if you have 3 items and you want to get all the combinations of 2 items from those 3 times, you can use such function to calculate how many unique combinations you&#39;d get. So for (3 choose 2), you have 3! / (2! * 1!) = (6 / 2) = 3.</p><p>You can use the following function to do the maths:</p><pre>pub fn numChosen(comptime m: u8, comptime n: u8) comptime_int {<br>    return factorial(m) / (factorial(n) * factorial(m - n));<br>}</pre><p>If you want to get all the actual permutations of such combinatorics, you need to have some way of grouping the permutations together, and for (3 choose 2) or the 6 permutations, you need to have a group of 6 items where each item is a combination of 2 indices. For example, say you have (0, 1, 2) as in the input, you want to get back an array of [6][2]u8, which is an array of 6 items where each of the item is an array of 2 u8s.</p><p>The reason why we use array instead of an ArrayList is to not only be able to find the permutations in comptime but also we don&#39;t have to deal with allocators.</p><p>In order to make this work, we need to have a <em>type function</em> that would simplify the return type of our function.</p><pre>pub fn ChosenType(comptime m: u8, comptime n: u8) type {<br>    comptime var t = numChosen(m, n);<br>    return [t][n]u8;<br>}</pre><p>As you can see, this function calls the previously defined numChosen to calculate the number of items in the return array type. The return type of the <em>type function</em> is a type.</p><p>Now for the final implementation of the choose function that returns all the permutations.</p><pre>pub fn choose(comptime l: []const u8, comptime k: u8) ChosenType(l.len, k) {<br>    std.debug.assert(l.len &gt;= k);<br>    std.debug.assert(k &gt; 0);<br>    var ret: ChosenType(l.len, k) = std.mem.zeroes(ChosenType(l.len, k));<br>    if (k == 1) {<br>        inline for (0..l.len) |i| {<br>            ret[i] = [k]u8{l[i]};<br>        }<br>        return ret;<br>    }<br>    comptime var c = choose(l[1..], k - 1);<br>    comptime var i = 0;<br>    inline for (0..(l.len - 1)) |m| {<br>        inline for (0..c.len) |n| {<br>            if (l[m] &lt; c[n][0]) {<br>                ret[i][0] = l[m];<br>                inline for (0..c[n].len) |j| {<br>                    ret[i][j + 1] = c[n][j];<br>                }<br>                i += 1;<br>            }<br>        }<br>    }<br>    return ret;<br>}</pre><h3>Dependency Order of Comptime Arguments and Return Type</h3><p>You function doesn’t have to make all the arguments comptime unless you need to use the function in comptime such as a <em>type function</em>.</p><p>There is however an order of comptime variable dependency. What I mean is that if you have 2 comptime parameters, then the latter parameter can depend on the earlier comptime parameter. This is true regardless of the number of parameters in the function, and the return type of the function can depend on the values of the comptime variables defined in the parameters of the function.</p><p>In the choose function, the return type ChosenType(m, n) depends on both of the 2 parameters in function arguments. In this particular function, it actually depends on the length of the first comptime slice and the number passed in as the 2nd argument.</p><p>A more complex example is in used my code where although I didn’t need to pass in the comptime z parameter, I had to because I need that parameter to determine both what matrix to allow multiplying to and the result matrix. In other words, when you multiple an m x n (self) matrix with an n x z (other) matrix, you know the type must be an m x z (return type) matrix. However, because I cannot specify the parameter of the (other) matrix without knowing both values of n and z from some other parameter except when it&#39;s already passed in in the argument, I have to take in an extra z parameter.</p><pre>pub fn multiply(self: *Self, comptime z: comptime_int, other: BinaryFieldMatrix(n, z, b)) !BinaryFieldMatrix(m, z, b)</pre><p>In this particular function declaration, BinaryFieldMatrix is a <em>type function</em> as well.</p><p>This is actually one of the manifestation of the problem 1 I mentioned earlier in the section <strong>WTF is Comptime_Int</strong>.</p><p>I originally made Matrix a <em>type function</em> that takes in comptime values, and that made both BinaryFiniteField and BinaryFieldMatrix <em>type functions</em>, which in turn made my ErasureCoder also a <em>type function</em>, and everything depended on comptime values to initialize which worked great when I was testing the code.</p><p>However, when I started running the code by specifying command-line arguments I realized that I cannot pass in any command-line arguments to construct the ErasureCoder because command-line arguments cannot be forced into comptime even if I prepend the variable name with comptime.</p><p>Now I’m going to end with the platitude of “great power comes with great responsibility”. Use your comptime wisely, my friend!</p><h3>Bonus</h3><p>The keyword comptime in fact can be put in front of any expression such as a loop, or a block, or even a function.</p><p>When you do so, you are effectively making that expression comptime.</p><p>For example, when you call the factorial function, you can prepend comptime to the function call and then the function would be run at comptime and it would not take any run-time resource to calculate the factorial. So it doesn&#39;t matter whether it&#39;s 5! or 10!, at <em>run time</em>, it&#39;s really just a constant that was calculated at <strong>compile time</strong>.</p><pre>pub fn main() !void {<br>    const z = comptime factorial(50);<br>    std.debug.print(&quot;10! = {d}\n&quot;, .{z});<br>}</pre><pre>&gt; zig run main.zig<br>10! = 3628800</pre><h3>The End</h3><p>You can read <a href="https://kristoff.it/">Loris Cro</a>’s blog <a href="https://kristoff.it/blog/what-is-zig-comptime/">“What is Zig’s Comptime?”</a>.</p><p>You can find the code <a href="https://github.com/edyu/wtf-zig-comptime">here</a> and the older code that mostly uses comptime is <a href="https://github.com/beachglasslabs/eraser/tree/405a6809c387eb83de279b2f9f9fb15e5e37ee18">here</a>.</p><p>Special thanks to <a href="https://github.com/inkryption">InKryption</a> for helping out on <strong>comptime</strong> questions!</p><p>The erasure coding project I mentioned earlier is <a href="https://github.com/beachglasslabs/eraser">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*XNLPWMRj8X4DXezSVuup0g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6ea40e0cb41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zig C/C++ Compiler — WTF is Zig C++]]></title>
            <link>https://medium.com/@edlyuu/zig-c-c-compiler-wtf-is-zig-c-790d9ad8d85b?source=rss-931a37f1b662------2</link>
            <guid isPermaLink="false">https://medium.com/p/790d9ad8d85b</guid>
            <category><![CDATA[ziglang]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[zig]]></category>
            <dc:creator><![CDATA[Ed Yu]]></dc:creator>
            <pubDate>Thu, 20 Jul 2023 22:15:52 GMT</pubDate>
            <atom:updated>2023-07-31T22:15:11.120Z</atom:updated>
            <content:encoded><![CDATA[<h3>Zig C/C++ Compiler — WTF is Zig C++</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*CFsB3fFJtyTzdVhCe7Q3cw.png" /></figure><p>The power and complexity of <strong>Zig C/C++ Compiler</strong> in Zig</p><p>Ed Yu (<a href="https://github.com/edyu">@edyu</a> on Github and <a href="https://twitter.com/edyu">@edyu</a> on Twitter) Jul.20.2023</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Zi6kS-LHbNeKepJMqynuKQ.png" /></figure><h3>Introduction</h3><p><a href="https://ziglang.org/"><strong>Zig</strong></a> is a modern systems programming language and although it claims to a be a <strong>better C</strong>, many people who initially didn’t need systems programming were attracted to it due to the simplicity of its syntax compared to alternatives such as <strong>C++</strong> or <strong>Rust</strong>.</p><p>However, due to the power of the language, some of the syntaxes are not obvious for those first coming into the language. I was actually one such person.</p><p>Today we will explore Zig as a <strong>C/C++</strong> programmer and see how the <strong>Zig</strong> compiler can be used as a <strong>C/C++</strong> compiler. The idea of the post came from a <a href="https://www.youtube.com/watch?v=-XLSyaJ6m3o">talk</a> I gave to the <a href="https://www.meetup.com/cpp-bay-area/"><em>Bay Area C++ Group</em></a>. Because the <a href="https://www.youtube.com/watch?v=-XLSyaJ6m3o">talk</a> was presented to a mostly <strong>C++</strong> group that may have never heard of <strong>Zig</strong>, the deck was ridiculously long. In response, the purpose of this blog is to only focus on using <strong>Zig</strong> as a <strong>C/C++</strong> toolchain rather than as a language.</p><h3>Zig Toolchain</h3><p>If you go to the <a href="https://ziglang.org/"><strong>Zig</strong> website</a>, you’ll see the following quote:</p><blockquote><em>Zig is a general-purpose programming language and toolchain for maintaining robust, optimal and reusable software.</em></blockquote><p>What I found interesting when I first read it was that it added the words <em>and toolchain</em>.</p><p>And if you go further down as on the page, you’ll see a particular section focused on <strong>C/C++ </strong>:</p><blockquote><em>Incrementally improve your C/C++/Zig codebase.</em></blockquote><blockquote><em>* Use Zig as a zero-dependency, drop-in C/C++ compiler that supports cross-compilation out-of-the-box.</em></blockquote><blockquote><em>* Leverage zig build to create a consistent development environment across all platforms.</em></blockquote><blockquote><em>* Add a Zig compilation unit to C/C++ projects; cross-language LTO is enabled by default.</em></blockquote><p>For those who don’t know (and I had to look it up myself), <em>LTO</em> stands for <em>Link-Time Optimization</em>.</p><p>To summarize, <strong>Zig</strong> can be used as a <strong>C/C++</strong> compiler that has great cross-compilation support and is optimized by default.</p><h3>Zig as a C Compiler</h3><p>Let’s start with a simple <strong>C</strong> program — <a href="https://www.programiz.com/c-programming/examples/print-sentence"><em>Hello World</em></a>:</p><pre>#include &lt;stdio.h&gt;<br>int main() {<br>  // printf() displays the string inside quotation<br>  printf(&quot;Hello, World!\n&quot;);<br>  return 0;<br>}</pre><p>Let’s compile it using the <strong>Zig</strong> toolchain by calling zig cc:</p><pre>zig cc hello.c -o &quot;hello-c&quot;<br>./hello-c</pre><p>It works!</p><h3>Zig as a C++ Compiler</h3><p>Now Let’s do the same with a <strong>C++</strong> program — <a href="https://www.programiz.com/cpp-programming/examples/print-sentence"><em>Hello World</em></a></p><pre>// Your First C++ Program<br><br>#include &lt;iostream&gt;<br><br>int main() {<br>  std::cout &lt;&lt; &quot;Hello World!&quot;;<br>  return 0;<br>}</pre><p>Similar to zig cc, <strong>Zig</strong> can compile <strong>C++</strong> programs by calling zig c++:</p><pre>zig c++ hello.cpp -o &quot;hello-cpp&quot;<br>./hello-cpp</pre><p>It works too!</p><h3>Zig as a C Cross-Compiler</h3><p>If you specify a -target, you can cross compile to any target that <strong>Zig</strong> supports. For example, because I develop on <em>Ubuntu</em> on a <em>Windows</em> laptop using <em>WSL</em>, it&#39;s easy for me to test the <em>Windows</em> cross compilation.</p><p>In my <em>WSL</em>, I can do the following:</p><pre>zig cc hello.c -o &quot;hello-c.exe&quot; -target x86_64-windows</pre><p>I then copy over the file to <em>Windows</em> from my <em>WSL</em>:</p><pre>cp hello-c.exe /mnt/c/Users/edlyu/Downloads/</pre><p>Finally, I can run the program on my <em>Windows Terminal</em>:</p><pre>cd Downloads<br>.\hello-c.exe</pre><h3>Zig as a C++ Cross-Compiler</h3><p>For <strong>C++</strong>, the only difference is replacing zig cc with zig c++</p><pre>zig c++ hello.cpp -o &quot;hello-cpp.exe&quot; -target x86_64-windows</pre><p>Copy over the file to <em>Windows</em>:</p><pre>cp hello-cpp.exe /mnt/c/Users/edlyu/Downloads/</pre><p>Run the program:</p><pre>cd Downloads<br>.\hello-cpp.exe</pre><h3>Zig Cross-Compilation</h3><p>The <strong>Zig Toolchain</strong> is used at Uber for compiling and cross-compiling the <strong>Go</strong> monorepo. The initial motivation was to support the <em>arm64</em> hardware.</p><p>Motiejus Jakštys wrote a great article on how the <strong>Zig</strong> toolchain is used in Uber at this <a href="https://www.uber.com/blog/bootstrapping-ubers-infrastructure-on-arm64-with-zig/">blog post</a> and his <a href="https://www.youtube.com/watch?v=SCj2J3HcEfc">talk</a>. He had another update earlier this year, but it hasn’t been updated yet.</p><p>One of the reasons why <strong>Zig</strong> is so suitable for cross-compilation is because it bundles <em>libC</em> in source form so not only can one <strong>Zig</strong> toolchain used for cross-compilation for many targets but also the toolchain size is very small.</p><p>As of writing, <strong>Zig</strong> supports about 40+ <em>OS</em> and <em>ABI</em> targets, and 60+ <em>arch</em> targets. In addition, if you need <em>libC</em> support, there are also about 60 target architectures that bundles <em>libC</em>.</p><p>You can see all the targets yourself by running zig targets.</p><h3>Zig Toolchain Example</h3><p>As an example, I wanted to compile something slightly more complicated than <em>Hello World</em>, so I decided to compile <a href="https://github.com/grpc/grpc"><em>gRPC</em></a> which is mostly written in <strong>C++</strong> using the <strong>Zig</strong> toolchain.</p><p>The <em>gRPC</em> example is moderately complicated because it has 20+ dependencies that are built together.</p><p>One of the complications I encountered was that <em>gRPC</em> uses <a href="https://bazel.build/"><em>Bazel</em></a> or <a href="https://cmake.org/"><em>CMake</em></a>. I decided to use <em>CMake</em> for this example.</p><p>What I found is that if you decide to use <strong>Zig</strong> toolchain to build a <strong>C++</strong> library you’ll need to build both the library and the code that uses the library with the <strong>Zig</strong> toolchain. In other words, you cannot build the <strong>C++</strong> library first and then only use the <strong>Zig</strong> toolchain for the code that uses the library.</p><p>On my <em>WSL</em>, I was able to build the main <em>gRPC</em> library using the following commands:</p><pre>CC=&quot;zig cc -mcrc32&quot; CXX=&quot;zig c++ -mcrc32&quot; cmake \ <br>  -DgRPC_INSTALL=ON \<br>  -DgRPC_BUILD_TESTS=OFF \ <br>  -DOPENSSL_NO_ASM=ON \<br>  -DCMAKE_INSTALL_PREFIX=/home/edyu/.env \<br>  ../..<br><br>make -j 4<br>make</pre><p>Make sure you replace CMAKE_INSTALL_PREFIX with where you&#39;d prefer to install the <em>gRPC</em> library locally.</p><p>I had to include -mcrc32 and set -DOPENSSL_NO_ASM=ON to make it work on my <em>WSL</em> whereas if I didn&#39;t use the <em>Zig</em> toolchain, I didn&#39;t need to.</p><p>After the <em>gRPC</em> library itself was built and installed, I then run the following commands to build the examples:</p><pre>CC=&quot;zig cc&quot; CXX=&quot;zig c++&quot; cmake -DCMAKE_PREFIX_PATH=/home/edyu/.env ../..<br>make -j 4</pre><p>Make sure you replace CMAKE_PREFIX_PATH with the same location you set in CMAKE_INSTALL_PREFIX earlier.</p><p>For me, on my <em>WSL</em> I was able to build the <em>gRPC</em> library, compile against the library, and the compiled programs worked.</p><h3>Importing C++ Library using Build.Zig</h3><p>For those of you who are not familiar with <em>build.zig</em>, you can read my previous <a href="https://medium.com/@edlyuu/zig-package-manager-wtf-is-zon-df5ecbafcc54">blog post</a>.</p><p>Basically, <em>build.zig</em> allows you to describe the build process using <em>Zig</em> code itself instead of resorting to something like a <em>Makefile</em>. The benefit is so that a <strong>Zig</strong> programmer doesn’t need to context-switch to another file format or build language such as <em>Makefile</em>.</p><p>Here is a more complex example of <a href="https://github.com/kimmolinna/duckdb-zig-build/blob/master/build.zig">build.zig</a> file used to build <a href="https://duckdb.org/">DuckDB</a>, another <strong>C++</strong> library.</p><p>We now talk about exporting your <strong>C++</strong> library to <strong>Zig</strong> code.</p><p>Let’s write a simple <em>Hello World</em> library in C++ and call it using <em>Zig</em>. The following example is based upon a <a href="https://stackoverflow.com/questions/73467232/how-to-incorporate-the-c-standard-library-into-a-zig-program"><em>StackOverflow</em> answer</a>.</p><p>Because there is no default binding in <strong>C++</strong> in <strong>Zig</strong>, we’ll have to write our own binding.</p><p>In the following example, our function is directly defined inside the binding function but in a more realistic example, you’ll write binding functions that call your library functions after importing them just like how std::cout is imported via &lt;iostream&gt;.</p><pre>#include &lt;iostream&gt;<br><br>extern &quot;C&quot; void helloWorld(void) {<br>  std::cout &lt;&lt; &quot;Hello world!&quot;;<br>}</pre><p>Note that we are converting our <strong>C++</strong> function to <strong>C</strong> convention.</p><p>We also need the header file and because <strong>Zig</strong> has much better support for <strong>C</strong>, we need the <strong>C</strong> header file:</p><pre>void helloWorld(void);</pre><p>And finally, we need to call our <strong>C/C++</strong> function:</p><pre>const std = @import(&quot;std&quot;);<br>const cpp = @cImport({<br>    @cInclude(&quot;hello.h&quot;);<br>});<br><br>pub fn main() !void {<br>    cpp.helloWorld();<br>}</pre><p>Now, let’s first define the build process in our build.zig:</p><pre>const std = @import(&quot;std&quot;);<br><br>pub fn build(b: *std.Build) void {<br>    const target = b.standardTargetOptions(.{});<br>    const optimize = b.standardOptimizeOption(.{});<br>    const exe = b.addExecutable(.{<br>        .name = &quot;helloworld&quot;,<br>        .root_source_file = .{ .path = &quot;src/main.zig&quot; },<br>        .target = target,<br>        .optimize = optimize,<br>    });<br>    // link with the standard library libcpp<br>    exe.linkLibCpp();<br>    exe.addIncludePath(&quot;src&quot;);<br>    exe.addCSourceFile(&quot;src/hello.cpp&quot;, &amp;.{});<br>    b.installArtifact(exe);<br>}</pre><p>Build and run the program:</p><pre>zig build<br>./zig-out/bin/helloworld</pre><p>Viola, it worked!</p><h3>Package Manager</h3><p>The previous <strong>C++</strong> library build.zig example is extremely simple in that everything is defined in one file.</p><p>In general, in best practice, you’ll likely separate your <strong>C++</strong> library and binding from the code that calls the library. In fact, you may even write a wrapper in <strong>Zig</strong> and separate that from the main code.</p><p>For that to work, you’ll need to utilize the new <em>Package Manager</em>. You can read about how to do so in my previous <a href="https://medium.com/@edlyuu/zig-package-manager-wtf-is-zon-df5ecbafcc54">blog post</a>.</p><h3>Bonus</h3><p>Instead of zig cc, you can also build a <strong>C</strong> program and link to <em>libC</em> with the following command:</p><pre>zig build-exe hello.c --library c<br>./hello</pre><p>You can do the same for <strong>C++</strong>; instead of calling zig c++:</p><pre>zig build-exe hello.cpp --library c++<br>./hello</pre><p>Run the command zig libc to see where the native <em>libC</em> files.</p><p>There is also a zig translate-c that can be useful if you are converting your <strong>C</strong> code to <strong>Zig</strong> but it&#39;s fairly complex due to the number of options it gives you.</p><h3>The End</h3><p>You can also read the <a href="https://andrewkelley.me/post/zig-cc-powerful-drop-in-replacement-gcc-clang.html">blog post</a> about using zig cc by Andrew Kelley himself.</p><p>You can find the code <a href="https://github.com/edyu/wtf-zig-cpp">here</a>.</p><p>Special thanks to <a href="https://github.com/kassane">Matheus França</a> for helping out on <strong>C++</strong> build question!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*XNLPWMRj8X4DXezSVuup0g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=790d9ad8d85b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zig Package Manager — WTF is Zon]]></title>
            <link>https://medium.com/@edlyuu/zig-package-manager-wtf-is-zon-df5ecbafcc54?source=rss-931a37f1b662------2</link>
            <guid isPermaLink="false">https://medium.com/p/df5ecbafcc54</guid>
            <category><![CDATA[ziglang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[package-management]]></category>
            <category><![CDATA[zig]]></category>
            <category><![CDATA[programming-languages]]></category>
            <dc:creator><![CDATA[Ed Yu]]></dc:creator>
            <pubDate>Tue, 27 Jun 2023 19:35:27 GMT</pubDate>
            <atom:updated>2023-07-12T16:56:43.436Z</atom:updated>
            <content:encoded><![CDATA[<h3>Zig Package Manager — WTF is Zon</h3><p>The ̶p̶o̶w̶e̶r̶ hack and complexity of <strong>Package Manager</strong> in Zig</p><p>Ed Yu (<a href="https://github.com/edyu">@edyu</a> on Github and <a href="https://twitter.com/edyu">@edyu</a> on Twitter) Jun.27.2023</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Zi6kS-LHbNeKepJMqynuKQ.png" /></figure><h3>Introduction</h3><p><a href="https://ziglang.org/"><strong>Zig</strong></a> is a modern systems programming language and although it claims to a be a <strong>better C</strong>, many people who initially didn’t need systems programming were attracted to it due to the simplicity of its syntax compared to alternatives such as <strong>C++</strong> or <strong>Rust</strong>.</p><p>However, due to the power of the language, some of the syntaxes are not obvious for those first coming into the language. I was actually one such person.</p><p>Today we will take a break from the language itself to talk about one of the most important new features that was introduced recently in <strong>Zig</strong> — the package manager. I’ve read somewhere that all modern languages need to have package manager built in. Although I don’t share the same opinion, it’s indicative of how important a good package manager is for the underlying language. For example, <strong>Javascript</strong> has npm, <a href="https://www.haskell.org/"><strong>Haskell</strong></a> has <a href="https://haskell.org/cabal/">cabal</a>, and <strong>Rust</strong> has <a href="https://doc.rust-lang.com/cargo/">cargo</a>.</p><h3>Disclaimer</h3><p>There is a reason why I changed my typical subtitle of <em>power and complexity</em> to <em>hack and complexity</em> for this particular article because unfortunately the <strong>Zig</strong> package manager is currently only on the <em>master</em> branch (or edge) and its a work-in-progress until 0.11 is released. As for the <strong>hack</strong> part, it will make sense after you read through the part of <a href="#provide_a_package">Provide a Package</a>.</p><p>The state of the release 0.11 as of June 2023 is in flux so you will encounter many bugs and problems along the way. I&#39;m not writing this to discourage you from using it but to set the right expectation, so you don&#39;t throw away the <em>baby</em> (<strong>Zig</strong>) with the <em>bath water</em> (package manager).</p><p><strong>Zig</strong> along with its package manager is being constantly improved, and honestly, it’s already very useful and usable even in the current state (despite the frustrations along with one of the <strong>hackiest</strong> things I’ve done, which I will describe later in the article).</p><p>When you run zig build, you may see several failures (such as segmentation fault) when it&#39;s pulling down packages before it will succeed after several more tries. Although there is indication it&#39;s because of <em>TLS</em> but I don&#39;t want to give out wrong information that I haven&#39;t investigated myself.</p><pre>~/w/z/my-wtf-project main• ❱ zig build<br>fish: Job 1, &#39;zig build&#39; terminated by signal SIGSEGV (Address boundary error)<br>~/w/z/my-wtf-project main• 3.8s | 139 ❱ zig build<br>fish: Job 1, &#39;zig build&#39; terminated by signal SIGSEGV (Address boundary error)<br>~/w/z/my-wtf-project main• 1.2s | 139 ❱ zig build<br>fish: Job 1, &#39;zig build&#39; terminated by signal SIGSEGV (Address boundary error)<br>~/w/z/my-wtf-project main• 1.2s | 139 ❱ zig build<br>fish: Job 1, &#39;zig build&#39; terminated by signal SIGSEGV (Address boundary error)<br>~/w/z/my-wtf-project main• 3s | 139 ❱ zig build<br>~/w/z/my-wtf-project main• 38s ❱ ls</pre><h3>Package Manager</h3><p>So what’s the purpose of the package manager? For a developer, the package manager is used to use other people’s code easily. For example, say you need to use a new library, it’s much easier to use the underlying <em>package manager</em> to add (either download and/or link to the library) the library and then somehow configure something in your project to <em>magically</em> link to the library for you to use it in your code.</p><h3>Zig Package Manager(s)</h3><p><strong>Zig</strong> had some other package managers in the past but now we have a built-in <em>official</em> package manager as part of version 0.11 (not released yet as of July, 2023).</p><p>Interestingly, there are no additional commands to remember as the package manager is built into the language. <strong>Zig</strong> also does not have a global repository or a website that hosts the global repository such as <a href="https://npmjs.com/">npmjs</a> does for <em>JavaScript</em> or <a href="https://crates.io/">crates.io</a> for <strong>Rust</strong>.</p><p>So really, the <strong>Zig</strong> package manager is just same old zig build that you need to build your project anyways. There is nothing new you really need to use the package manager.</p><p>There is however a new file-type with the extension .zon and a new file called build.zig.zon. zon stands for <strong>Zig</strong> Object Notation similar to how json stands for <strong>JavaScript</strong> Object Notation. It&#39;s mainly a way to describe hierarchical relationship such as dependencies needed in the project.</p><p>In order to use a <strong>Zig</strong> package using the package manager, you’ll need to do 3 things:</p><ol><li>Add your dependencies in build.zig.zon</li><li>Incorporate your dependencies to your build process in build.zig</li><li>Import your dependencies in your code using @import</li></ol><h3>build.zig.zon</h3><p>If you open up a zon file such as the following, you&#39;ll notice, it looks like a json file such as the typical package.json somewhat.</p><pre>// because zon file is really just a zig struct<br>// comments are really done in the same way using 2 forward slashes<br>.{<br>    // the name of your project<br>    .name = &quot;my-wtf-project&quot;,<br>    // the version of your project<br>    .version = &quot;0.0.1&quot;,<br><br>    // the actual packages you need as dependencies of your project <br>    .dependencies = .{<br>        // the name of the package<br>        .zap = .{<br>            // the url to the release of the module<br>            .url = &quot;https://github.com/zigzap/zap/archive/refs/tags/v0.1.7-pre.tar.gz&quot;,<br>            // the hash of the module, this is not the checksum of the tarball<br>            .hash = &quot;1220002d24d73672fe8b1e39717c0671598acc8ec27b8af2e1caf623a4fd0ce0d1bd&quot;,<br>        },<br>    }<br>}</pre><p>There are several things of note here in the code above:</p><ol><li>The <em>object</em> looking curly braces are actually <em>anonymous</em> structs, if you don&#39;t know what structs are, you can think them as like an object. I briefly talked about structs in my previous article: <a href="https://zig.news/edyu/zig-unionenum-wtf-is-switchunionenum-2e02">Zig Union(Enum)</a>.</li><li>The . in front of the curly braces are important as it denotes the struct as an <em>anonymous</em> struct. “For the purpose of <em>zon</em>, you can think of <em>anonymous</em> <em>struct</em> as a similar data format to <em>json</em>, but instead using <strong>Zig</strong>&#39;s struct literal syntax.&quot; -- <a href="https://github.com/inkryption">@InKryption</a>.</li><li>3. The . in front of field names are also important because it conforms to the expected structure. In this particular struct, there is an expectation of three top level fields of name, version, and dependencies respectively.</li></ol><h3>dependencies</h3><p>To use a package that’s been prepared for the new Zig package manager, you just need to list it in the dependencies section.</p><p>In the previous example, I showed how to add <a href="https://github.com/zigzap/zap"><em>Zap</em></a>, a webserver, to your project by listing both the url of the release and the hash.</p><p>The url is fairly easy to find as you can normally find it on <a href="https://github.com/zigzap/zap/releases">GitHub</a> directly.</p><p>However, the hash is difficult to find out because it&#39;s not just the md5sum, sha1sum, or even sha256sum of the tarball listed in url. The hash does use <em>sha256</em> but it&#39;s not a direct hash of the tarball so it&#39;s not easily calculated by the user of the package.</p><p>Luckily the easiest way I found is just to put any hash there initially and then zig build will complain and give you the correct hash. I know it&#39;s not ideal until all package author follows what <a href="https://github.com/zigzap/zap"><em>Zap</em></a> does by listing the hash in the <a href="https://github.com/zigzap/zap/releases">release notes</a> or the README.</p><p>The dependencies section showing 2 packages:</p><pre>.dependencies = .{<br>        .zap = .{<br>            .url = &quot;https://github.com/zigzap/zap/archive/refs/tags/v0.1.7-pre.tar.gz&quot;,<br>            .hash = &quot;1220002d24d73672fe8b1e39717c0671598acc8ec27b8af2e1caf623a4fd0ce0d1bd&quot;,<br>        },<br>        .duck = .{<br>            .url = &quot;https://github.com/beachglasslabs/duckdb.zig/archive/refs/tags/v0.0.1.tar.gz&quot;,<br>            .hash = &quot;12207c44a5bc996bb969915a5091ca9b70e5bb0f9806827f2e3dd210c946e346a05e&quot;,<br>        }<br>    }</pre><p>Once you add your dependencies, zig buid would pull down your dependent packages as part of your project.</p><p>But you may need to add the package in your build step as well. <strong>Zig</strong> is different in many languages that it minimizes a runtime so often you’ll need to build and link your dependencies in your project.</p><h3>Module</h3><p>In order to use the library exposed as a dependency, you have to expose the module of the dependency and add the module to the compile step.</p><p>You can think of a module as the code that are exported by the library so that the caller of the package can import the library into the source code.</p><p>In the next section, the code adds a module using a call to addModule(). The first argument is the name you want to use in your code so you can import the module. The second argument is where the code is located within the module in the dependency. In other words, you are aliasing a namespace (the 2nd argument) to a new name (1st argument).</p><h3>build.zig</h3><p>Here is an example of the build.zig illustrating how to add the module duck in your project so that you can subsequently use the library by importing const duck = @import(&quot;duck&quot;);:</p><pre>const std = @import(&quot;std&quot;);<br><br>pub fn build(b: *std.Build) !void {<br>    // these are boiler plate code until you know what you are doing<br>    // and you need to add additional options<br>    const target = b.standardTargetOptions(.{});<br>    const optimize = b.standardOptimizeOption(.{});<br>    // this is your own program<br>    const exe = b.addExecutable(.{<br>        // the name of your project<br>        .name = &quot;my-wtf-project&quot;,<br>        // your main function<br>        .root_source_file = .{ .path = &quot;testzon.zig&quot; },<br>        // references the ones you declared above<br>        .target = target,<br>        .optimize = optimize,<br>    });<br><br>    // using duck as a dependency<br>    const duck = b.dependency(&quot;duck&quot;, .{<br>        .target = target,<br>        .optimize = optimize,<br>    });<br>    // duck has exported itself as duck <br>    // now you are re-exporting duck<br>    // as a module in your project with the name duck<br>    exe.addModule(&quot;duck&quot;, duck.module(&quot;duck&quot;));<br>    // you need to link to the output of the build process<br>    // that was done by the duck package<br>    // in this case, duck is outputting a library<br>    // to which your project need to link as well<br>    exe.linkLibrary(duck.artifact(&quot;duck&quot;));<br>    // now install your own executable after it&#39;s built correctly<br>    b.installArtifact(exe);<br>}</pre><p>What the code snippet above does is that it first declares your project as an executable and then pulls in duck as a dependency.</p><p>The build.zig in the duck project already <em>exported</em> itself as the module duck but you are adding it again as a module with the same name duck.</p><p>The linkLibrary call is the actual call to link to the output (<strong>Zig</strong> calls it artifact) of the duck module.</p><h3>@import</h3><p>Now you have everything setup in your build, you need to use the new package in your code.</p><p>All you need to do is to use the @import builtin to import your new library just like how you normally import the standard library @import(std).</p><pre>const std = @import(&quot;std&quot;);<br>const DuckDb = @import(&quot;duck&quot;);<br><br>pub fn main() !void {<br>    // setup database<br>    var duck = try DuckDb.init(null);<br>    defer duck.deinit();<br>}</pre><h3>Provide a Package</h3><p>Ok, this is for those who would like to understand how the <strong>Zig</strong> package manager works as a library/package provider.</p><p>To better illustrate things, I’ll use a new package <a href="https://github.com/beachglasslabs/duckdb.zig">duckdb.zig</a> that I wrote.</p><p><a href="https://duckdb.org/">DuckDb</a> is a column-based SQL database so think it as basically a column-based <a href="https://www.sqlite.org/index.html">SQLite</a>. I will split the project into 3 packages A, B, and C. Basically the idea is that our project will be C that is the actual project that uses <em>DuckDb</em>. The project C will then use the <strong>Zig</strong> layer provided by package B, which in turn will need the actual <em>DuckDb</em> libraries in package A.</p><p>So in our case, we have the project <em>my-wtf-project</em>, which will call the <strong>Zig</strong> library provided by <a href="https://github.com/beachglasslabs/duckdb.zig">duckdb.zig</a>. The <a href="https://github.com/beachglasslabs/duckdb.zig">duckdb.zig</a> is really a wrapper of <a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a> that provides the dynamic library of <a href="https://github.com/duckdb/duckdb/releases/tag/v0.8.1">release 0.8.1</a> of <a href="https://duckdb.org/">DuckDb</a>. To use the A, B, C in the previous paragraph, C is our project <em>my-wtf-project</em>, B is <a href="https://github.com/beachglasslabs/duckdb.zig">duckdb.zig</a>, and A is <a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a>.</p><p>Note: I will talk about the actual process of making a wrapper library in a future article.</p><h3>A: <a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a></h3><p>The <em>duckdb</em> is written in c++ and the libduckdb-linux-amd64 release from <em>duckdb</em> only provided 3 files: duckdb.h, duckdb.hpp, and libduckdb.so.</p><p>I unzipped the package and placed duckdb.h under include directory and libduckdb.so under lib directory.</p><p>Here are the first 3 hacks needed:</p><ol><li>You don’t need to build anything, but the package manager expects to see a build.zig file in the package so you must provide one.</li><li>Because you provided a build.zig, you need to provide some build artifact even if it&#39;s not needed.</li><li>The most important part and the <strong>hackiest</strong> part is that you need to use the constructs used for header files to install the library.</li></ol><h3>build.zig.zon of A: <a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a>.</h3><p>This is probably the simplest build.zig.zon as you don&#39;t need any dependencies.</p><p>This should remind people of a very simple .cabal, cargo.toml, or package.json file.</p><pre>// build.zig.zon<br>// there are no dependencies<br>// eventually, may want to list duckdb itself as a dependency<br>.{<br>    .name = &quot;duckdb&quot;,<br>    .version = &quot;0.8.1&quot;,<br>}</pre><h3>Artifact</h3><p>You’ll see the word artifact used often in the build process. One way to grasp artifact is to think it as the output of the build. If you are building a shared library, the .so file is the artifact; a static library, the .a file is the artifact; and for an executable, the actual execuable is the artifact.</p><p>When you have the artifact in the code (build.zig), you can then use the artifact <em>object</em> to pass in to other function calls that can <em>extract</em> parts of the artifact based on their individual need. For example, installLibraryHeaders() would take in the artifact <em>object</em> and install any header files installed as part of the artifact.</p><p>In fact, this is something we will and we have to take advantage of in order to make our ̶h̶a̶c̶k̶ build work.</p><p>In the code below, the executable .name = &quot;my-wtf-project tells the build that <em>my-wtf-project</em> is the name of the artifact and the executable is the actual artifact.</p><pre>pub fn build(b: *std.Build) !void {<br>    const target = b.standardTargetOptions(.{});<br>    const optimize = b.standardOptimizeOption(.{});<br><br>    const exe = b.addExecutable(.{<br>        .name = &quot;my-wtf-project&quot;,<br>        .root_source_file = .{ .path = &quot;testzon.zig&quot; },<br>        .target = target,<br>        .optimize = optimize,<br>    });<br>    // see how exe is now referred as artifact<br>    b.installArtifact(exe);<br>}</pre><h3>build.zig of A: <a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a>.</h3><p>We are essentially building something we don’t really need but we definitely need the installHeader calls because this is how we <em>install</em> the 2 files we need in our artifact: include/duckdb.h and lib/libduckdb.so.</p><p>Note that we are building a library without specifying a source code anywhere. We however do need to at least link to something. In this case, we need to link to the libduckdb.so even though we don&#39;t need any symbols from it because the build process needs either a source file or a library to link to.</p><p>Yes, we are using the installHeader to install a dynamic library because there is no alternative.</p><p>We can use installLibFile to install the lib/libduckdb.so but as you&#39;ll see in package B, it won&#39;t work without using installHeader.</p><p>The call to installHeader requires a source and destination arguments but the destination argument assumes relative path of the target header directory. Therefore, we need to use ../lib/libduckdb.so in order to install libduckdb.so under lib directory instead of the default include.</p><p>The final call to installArtifact is the one that will be utilized by B to grab the 2 files needed as described next. It will in this case, create an artifact libduckdb.a that we don&#39;t really need. For us, the artifact contains 3 things, the duckdb.h, libduckdb.so, and libduckdb.a. We only need the first two and libduckdb.a really is a side-effect of the artifact that we can toss away later in B.</p><p>You can say we only need the bath water, not the baby. (Sorry for the bad jokes but I can’t help myself. :blush: )</p><pre>const std = @import(&quot;std&quot;);<br><br>pub fn build(b: *std.Build) !void {<br>    const target = b.standardTargetOptions(.{});<br>    const optimize = b.standardOptimizeOption(.{});<br><br>    var libduckdb_module = b.createModule(.{<br>        .source_file = .{<br>            .path = &quot;lib/libduckdb.so&quot;<br>        }<br>    });<br><br>    try b.modules.put(b.dupe(&quot;libduckdb&quot;), libduckdb_module);<br><br>    // We don&#39;t need this static library<br>    // but a build process is required<br>    // in order to use the artifact<br>    // the artifact is named by the .name field<br>    // in this case it&#39;s called &#39;duckdb&#39;<br>    // notice there is no reference to a source file<br>    const lib = b.addStaticLibrary(.{<br>        .name = &quot;duckdb&quot;,<br>        .target = target,<br>        .optimize = optimize,<br>    });<br><br>    // point to the library path<br>    lib.addIncludePath(&quot;include&quot;);<br>    // point to the library path so we can find the system library<br>    // we need this to find the libduckdb.so<br>    lib.addLibraryPath(&quot;lib&quot;);<br>    // this means to link to libduckdb.so in the lib directory<br>    // the call will prepend &#39;lib&#39; and append &#39;.so&#39;<br>    lib.linkSystemLibraryName(&quot;duckdb&quot;);<br><br>    // HACK XXX hope zig fixes it<br>    // installHeader assumes include target directory<br>    // so we need to use &#39;..&#39; to go to the parent directory<br>    lib.installHeader(&quot;lib/libduckdb.so&quot;, &quot;../lib/libduckdb.so&quot;);<br>    lib.installHeader(&quot;include/duckdb.h&quot;, &quot;duckdb.h&quot;);<br><br>    b.installArtifact(lib);<br>}</pre><h3>B: <a href="https://github.com/beachglasslabs/duckdb.zig">duckdb.zig</a></h3><p>The <a href="https://github.com/beachglasslabs/duckdb.zig">duckdb.zig</a> is a minimal (for now) <strong>Zig</strong> wrapper to <em>duckdb</em>. The idea is so that any <strong>Zig</strong> project depending on it doesn’t have to deal with the <strong>C/C++</strong> API just the <strong>Zig</strong> equivalent.</p><p>We still need to perpetuate the <strong>hack</strong> by making sure libduckdb.so is part of the output artifact of <a href="https://github.com/beachglasslabs/duckdb.zig">duckdb.zig</a> as well.</p><h3>build.zig.zon of B: <a href="https://github.com/beachglasslabs/duckdb.zig">duckdb.zig</a></h3><p>We do have a dependency now as we need to refer to a release of A: <a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a>.</p><pre>// build.zig.zon<br>// Now we depend on a release of A: libduckdb<br>.{<br>    // name of the package<br>    .name = &quot;duck&quot;,<br>    // now we can version it to anything<br>    // as it&#39;s just the version of the zig wrapper<br>    .version = &quot;0.0.1&quot;,<br><br>    .dependencies = .{<br>        // point to the name defined in libduckdb&#39;s build.zig.zon<br>        .duckdb = .{<br>            // the github release<br>            .url = &quot;https://github.com/beachglasslabs/libduckdb/archive/refs/tags/v0.8.1.tar.gz&quot;,<br>            .hash = &quot;1220f2fd60e07231291a44683a9297c1b42ed9adc9c681594ee21e0db06231bf4e07&quot;,<br>        }<br>    }<br>}</pre><h3>build.zig of B: <a href="https://github.com/beachglasslabs/duckdb.zig">duckdb.zig</a></h3><p>We now need to refer to the libduckdb (A) package using the name duckdb by making a call to Build.dependency(&quot;duckdb).</p><p>We then name our module duck and add the module to Build with such name so that the build process can get the module by name if needed.</p><p>Our own artifact is now named duck by calling Build.addStaticLibrary() with .name = &quot;duck&quot; in the <em>anonymous</em> struct.</p><p>Although we call linkLibrary(duck_dep.artifact(&quot;duckdb&quot;)), the empty library created in libduckdb A doesn&#39;t actually resolve anything symbols because all the symbols are really in the dynamic library libduckdb.so.</p><p>The most important part of the ̶h̶a̶c̶k̶ build is to call to installLibraryHeaders() because we want to once again include the output of the libduckdb artifact in our own artifact so that anything that depends on duckdb.zig would have access to both the duckdb.h and libduckdb.so from A.</p><pre>const std = @import(&quot;std&quot;);<br><br>pub fn build(b: *std.Build) !void {<br>    const target = b.standardTargetOptions(.{});<br>    const optimize = b.standardOptimizeOption(.{});<br>    // we need to refer to the dependency in build.zig.zon<br>    const duck_dep = b.dependency(&quot;duckdb&quot;, .{<br>        .target = target,<br>        .optimize = optimize,<br>    });<br>    // we are creating our own module here<br>    var duck_module = b.createModule(.{<br>        .source_file = .{ .path = &quot;src/main.zig&quot; },<br>    });<br>    // we name the module duck which will be used later<br>    try b.modules.put(b.dupe(&quot;duck&quot;), duck_module);<br>    // we are building a static library<br>    const lib = b.addStaticLibrary(.{<br>        // the output will be libduck.a<br>        .name = &quot;duck&quot;,<br>        // the code to our wrapper library<br>        .root_source_file = .{ .path = &quot;src/main.zig&quot; },<br>        .target = target,<br>        .optimize = optimize,<br>    });<br>    // we link to the empty library in libduckdb<br>    // package that doesn&#39;t resolve any symbols<br>    // as these symbols are defined in libduckdb.so<br>    lib.linkLibrary(duck_dep.artifact(&quot;duckdb&quot;));<br>    // we must use this hack again<br>    // to make sure include/duckdb.h and lib/libduckdb.so<br>    // are installed<br>    lib.installLibraryHeaders(duck_dep.artifact(&quot;duckdb&quot;));<br>    // run the install to install the output artifact<br>    b.installArtifact(lib);<br>}</pre><h3>C: my-wtf-project</h3><p>Now to create the executable for our project, we need to link to the packages A <a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a> and B <a href="https://github.com/beachglasslabs/duckdb.zig">duckdb.zig</a>.</p><h3>build.zig.zon of C: my-wtf-project</h3><p>Our only dependency is the release of B: <a href="https://github.com/beachglasslabs/duckdb.zig">duckdb.zig</a>.</p><p>Notice that we do not need to refer to A (<a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a>) at all because B hides that from us.</p><pre>// build.zig.zon<br>// Now we depend on a release of B: duckdb.zig<br>.{<br>    // this is the name of our own project<br>    .name = &quot;my-wtf-project&quot;,<br>    // this is the version of our own project<br>    .version = &quot;0.0.1&quot;,<br><br>   .dependencies = .{<br>        // we depend on the duck package described in B<br>        .duck = .{<br>            .url = &quot;https://github.com/beachglasslabs/duckdb.zig/archive/refs/tags/v0.0.1.tar.gz&quot;,<br>            .hash = &quot;12207c44a5bc996bb969915a5091ca9b70e5bb0f9806827f2e3dd210c946e346a05e&quot;,<br>        },<br>    },<br>}</pre><h3>build.zig of C: my-wtf-project</h3><p>This is somewhat similar to the build.zig of B (<a href="https://github.com/beachglasslabs/duckdb.zig">duckdb.zig</a>).</p><p>Although we never referred to A (<a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a>) at all in build.zig.zon, we do need to refer to the artifact of &quot;duck&quot; and install libduckdb.so from A (<a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a>) using the same ̶h̶a̶c̶k̶ call installLibraryHeaders(duck.artifact(&quot;duck&quot;)). However, We now refer to the library header as part of the artifact of B (<a href="https://github.com/beachglasslabs/duckdb.zig">duckdb.zig</a>), not that of A (<a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a>).</p><p>We also have to link to the library provided by B (<a href="https://github.com/beachglasslabs/duckdb.zig">duckdb.zig</a>) because it actually includes the <strong>Zig</strong> wrapper functions we need in our code by calling linkLibrary(duck.artifact(&quot;duck&quot;)).</p><p>If you look at the code below, you’ll notice a curious use of std.fmt.allocPrint() that refers to something called Build.install_prefix. It&#39;s just a fancy way to refer to the output directory what typically defaults to zig-out. The reason is that our executable do need to find the symbols exposed by the dynamic library from A (<a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a>) for the linking process.</p><p>We basically tell the build that to add zig-out/lib to find the libraries needed for linking and then link to libduckdb.so by calling linkSystemLibraryName(&quot;duckdb&quot;).</p><p>Due to the latest change in <strong>Zig</strong>, we also now need to tell the build that libduckdb.so requires the libC by calling linkLibC.</p><p>Afterwards, we just install the executable by calling ‘Build.installArtifact()’, which would install the executable to zig-out/bin just like how <strong>Zig</strong> normally does. Note that our artifact for our project is called &quot;my-wtf-project&quot; because we put that name in .name during our call to Build.addExecutable.</p><pre>const std = @import(&quot;std&quot;);<br><br>pub fn build(b: *std.Build) !void {<br>    const target = b.standardTargetOptions(.{});<br>    const optimize = b.standardOptimizeOption(.{});<br>    const exe = b.addExecutable(.{<br>        // the name of our project artifact (executable)<br>        .name = &quot;my-wtf-project&quot;,<br>        // we point to our project code<br>        .root_source_file = .{ .path = &quot;testzon.zig&quot; },<br>        .target = target,<br>        .optimize = optimize,<br>    });<br><br>    // we depends on duckdb.zig artifact<br>    // this is the name in build.zig.zon<br>    const duck = b.dependency(&quot;duck&quot;, .{<br>        .target = target,<br>        .optimize = optimize,<br>    });<br>    exe.installLibraryHeaders(duck.artifact(&quot;duck&quot;));<br>    exe.addModule(&quot;duck&quot;, duck.module(&quot;duck&quot;));<br>    exe.linkLibrary(duck.artifact(&quot;duck&quot;));<br><br>    // install_prefix by default is &quot;zig-out&quot;<br>    const path = try std.fmt.allocPrint(b.allocator, &quot;{s}/lib&quot;, .{b.install_prefix});<br>    defer b.allocator.free(path);<br>    // we need to somehow refer to the location of the libduckdb.so<br>    exe.addLibraryPath(path);<br>    exe.linkSystemLibraryName(&quot;duckdb&quot;);<br>    // libduckdb requires libC<br>    exe.linkLibC();<br>    // This declares intent for the executable to be installed into the<br>    // standard location when the user invokes the &quot;install&quot; step (the default<br>    // step when running `zig build`).<br>    b.installArtifact(exe);<br>}</pre><h3>Running the executable</h3><p>Note that in order to run our executable, we need to tell it where to find libduckdb.so.</p><p>The easiest way I found is to invoke our exectable like LID_LIBRARY_PATH=zig-out/lib my-wtf-project.</p><pre>~/w/z/wtf-zig-zon master• ❱ LD_LIBRARY_PATH=zig-out/lib zig-out/bin/my-wtf-project<br>duckdb: opened in-memory db<br>duckdb: db connected<br>duckdb: query sql select * from pragma_version();<br>Database version is v0.8.1<br><br>STOPPED!<br>Leaks detected: false</pre><h3>Bonus: Cache</h3><p>When the <strong>Zig</strong> package manager pulls down the packages, it saves them under .cache/zig. What it means is that once you have pulled down a package, you don&#39;t need network to pull down the same package again. However, there are times where the <strong>Zig</strong> package manager doesn&#39;t update/work properly, you&#39;ll need to delete the cache specific to your package and tell <strong>Zig</strong> to re-download the package.</p><p>The following command will remove all the packages from your cache:</p><pre>rm -rf ~/.cache/zig/*</pre><h3>The End</h3><p>You can find the code <a href="https://github.com/edyu/wtf-zig-zon">here</a>.</p><p>Here are the code for <a href="https://github.com/beachglasslabs/duckdb.zig">duckdb.zig</a> and <a href="https://github.com/beachglasslabs/libduckdb">libduckdb</a>.</p><p>Special thanks to <a href="https://github.com/inkryption">@InKryption</a> for helping out on package manager questions!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*CFsB3fFJtyTzdVhCe7Q3cw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df5ecbafcc54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zig Union(Enum) — WTF is switch(union(enum))]]></title>
            <link>https://medium.com/@edlyuu/zig-union-enum-wtf-is-switch-union-enum-9345659d557f?source=rss-931a37f1b662------2</link>
            <guid isPermaLink="false">https://medium.com/p/9345659d557f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[zig]]></category>
            <category><![CDATA[ziglang]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[system-programming]]></category>
            <dc:creator><![CDATA[Ed Yu]]></dc:creator>
            <pubDate>Fri, 16 Jun 2023 23:01:46 GMT</pubDate>
            <atom:updated>2023-09-24T02:41:23.690Z</atom:updated>
            <content:encoded><![CDATA[<h3>Zig Union(Enum) — WTF is switch(union(enum))</h3><p>The power and complexity of <strong>Union(Enum)</strong> in Zig</p><p>Ed Yu (<a href="https://github.com/edyu">@edyu</a> on Github and <a href="https://twitter.com/edyu">@edyu</a> on Twitter) Jun.13.2023</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Ny8_EsyraQ04KR2qpiz9aQ.png" /></figure><h3>Introduction</h3><p><a href="https://ziglang.org/"><strong>Zig</strong></a> is a modern system programming language and although it claims to a be a <strong>better C</strong>, many people who initially didn’t need system programming were attracted to it due to the simplicity of its syntax compared to alternatives such as <strong>C++</strong> or <strong>Rust</strong>.</p><p>However, due to the power of the language, some of the syntax are not obvious for those first coming into the language. I was actually one such person.</p><p>One of my favorite languages is <a href="https://www.haskell.org/"><strong>Haskell</strong></a> and if you ever thought that you prefer a typed language you owe it to yourself to learn <strong>Haskell</strong> at least once so you can appreciate how many other languages “borrowed” their type systems from it. I can promise you that you’ll come out a better programmer.</p><h3>ADT</h3><p>One of the most widely used features and the underlying foundation of the <strong>Haskell</strong> type system is the <em>ADT</em> or <a href="https://wiki.haskell.org/Algebraic_data_type"><em>Algebraic Data Types</em></a> (not to be confused with <a href="https://wiki.haskell.org/Abstract_data_type"><em>Abstract Data Types</em></a>). You can look up the difference on <a href="https://stackoverflow.com/questions/42833270/what-is-the-difference-between-abstract-data-types-and-algebraic-data-types">StackOverflow</a>.</p><p>However, for us programmers, you can just think of <em>Abstract Data Types</em> as either a <em>struct</em> or a simple <em>class</em> (simple as in not nested).</p><p>For <em>ADT</em> or <em>Algebraic Data Types</em>, we need to have access to <em>union</em> for those that has experienced it before in languages that provide such construct such as <strong>C</strong> or in our case <strong>Zig</strong>.</p><p><strong>Note</strong>: In order for <em>ADT</em> to be called <em>Algebraic</em>, it needs to support both <em>sum</em> and <em>product</em>. <em>Sum</em> means that the type needs to support A or B but not both together, whereas <em>product</em> means the type needs to support A and B together.</p><h3>Why do we care?</h3><p>The main reason for <em>ADT</em> to exist is so that you can express the concept of a type that can be in multiple states or forms. In other words, you can say that an object of that type can be either this or that, or something else.</p><p>For example, for a typical tree structure, you can say a tree node is either a leaf or a node that contains either other nodes or a leaf.</p><p>Another example would be that for a linked list, you can say that the list is formed recursively by a node that <em>points</em> to either another node or by the end of the list.</p><p>However, to show how we can use <em>ADT</em> in <strong>Zig</strong>, we have to explain some other concepts first.</p><h3>Zig Struct</h3><p>The foundation of data types in <strong>Zig</strong> is the <em>struct</em>. In fact, it’s pretty much everywhere in <strong>Zig</strong>.</p><p>The <em>struct</em> in <strong>Zig</strong> is probably the closest thing to a <em>class</em> in most object-oriented programming languages.</p><p>Here is the basic idea:</p><pre>// if you want to try yourself, you must import `std`<br>const std = @import(&quot;std&quot;);<br><br>// let&#39;s construct a binary tree node<br>const BinaryTree = struct {<br>    // a binary tree has a left subtree and a right subtree<br>    left: ?*BinaryTree,<br>    // for simplicity, let&#39;s just say we have an unsigned 32-bit integer value<br>    value: u32,<br>    right: ?*BinaryTree,<br>};<br><br>const tree = BinaryTree{ .left = null, .value = 42, .right = null };</pre><p>There are several things of note here in the code above:</p><ol><li>If you are not familiar with ?, you are welcome to look over <a href="https://zig.news/edyu/zig-if-wtf-is-bool-48hh">Zig If - WTF</a>. It basically means that the variable can either have a value of the type after ? or if it doesn&#39;t then it will take on a value of null.</li><li>We are referring to the <em>BinaryTree</em> type inside the <em>BinaryTree</em> type definition as a tree is a recursive structure.</li><li>However, you must use the * to denote that <em>left</em> and <em>right</em> are pointers to another <em>BinaryTree</em> struct. If you leave out the pointer then the compiler will complain because then the size of <em>BinaryTree</em> is dynamic as it can grow to be arbitrarily big as we add more sub-trees.</li></ol><p>The following code will show a slightly more complex tree structure. Note that we have to use &amp; in order to get the pointer of the <em>BinaryTree</em> struct.</p><pre>var left = BinaryTree{ .left = null, .value = 21, .right = null };<br>    var far_right = BinaryTree{ .left = null, .value = 168, .right = null };<br>    var right = BinaryTree{ .left = null, .value = 84, .right = &amp;far_right };<br><br>const tree2 = BinaryTree{ .left = &amp;left, .value = 42, .right = &amp;right };</pre><h3>Zig Enum</h3><p>Sometimes, a <em>struct</em> is an overkill if you just want to have a set of possible values for a variable to take and restrict the variable to take only a value from the set. Usually, we would use <em>enum</em> for such a use case.</p><pre>// sorry if I left our your favorite pet<br>const Pet = enum { Dog, Cat, Fish, Iguana, Platypus };<br><br>const fav: Pet = .Cat;<br><br>// Each of the value of an enum is called a tag<br>std.debug.print(&quot;Ed&#39;s favorite pet is {s}.\n&quot;, .{@tagName(Pet.Cat)});<br><br>// you can specify what type and what value the enum takes<br>const Binary = enum(u1) { Zero = 0, One = 1 };<br><br>std.debug.print(&quot;There are {d}{d} types of people in this world, those understand binary and those who don&#39;t.\n&quot;, .{<br>    @intFromEnum(Binary.One),<br>    @intFromEnum(Binary.Zero)<br>});</pre><h3>Switch on Enum</h3><p>One of the most convenient constructs for an <em>enum</em> is the <em>switch</em> expression. In <strong>Haskell</strong>, the reason <em>ADT</em> is so useful is the ability to pattern match on the <em>switch</em> expression. In fact, <strong>Haskell</strong>, function definition is basically a super-charged switch statement.</p><p>So how do we use <em>switch</em> statement in <strong>Zig</strong>?</p><pre>const fav: Pet = .Cat;<br><br>std.debug.print(&quot;{s} is &quot;, .{@tagName(fav)});<br>switch (fav) {<br>    .Dog =&gt; std.debug.print(&quot;needy!\n&quot;, .{}),<br>    .Cat =&gt; std.debug.print(&quot;perfect!\n&quot;, .{}),<br>    .Fish =&gt; std.debug.print(&quot;so much work!\n&quot;, .{}),<br>    .Iguana =&gt; std.debug.print(&quot;not tasty!\n&quot;, .{}),<br>    else =&gt; std.debug.print(&quot;legal?\n&quot;, .{}),<br>}<br><br>const score = switch (fav) {<br>    .Dog =&gt; 50,<br>    .Cat =&gt; 100,<br>    .Fish =&gt; 25,<br>    .Iguana =&gt; 15,<br>    else =&gt; 75,<br>};</pre><h3>Union</h3><p>In <em>C</em> and in <em>Zig</em>, <em>union</em> is similar to <em>struct</em>, except that instead of the structure having all the fields, only one of the fields of the <em>union</em> is active. For those familiar with <em>C</em> union, please be aware that <em>Zig</em> union cannot be used to reinterpret memory. So in other words, you cannot use one field of the <em>union</em> to <strong>cast</strong> the value defined by another field type.</p><pre>const Value = union {<br>    int: i32,<br>    float: f64,<br>    string: []const u8,<br>};<br><br>var value = Value{ .int = 42 };<br>// you can&#39;t do this<br>var fval = value.float;<br>std.debug.print(&quot;{d}\n&quot;, .{fval});<br><br>// you can&#39;t do this, either<br>var bval = value.string;<br>std.debug.print(&quot;{c}\n&quot;, .{bval[0]});</pre><h3>Switch on Union</h3><p>Well, you cannot use <em>switch</em> on <em>union</em>; at least not on simple <em>union</em>.</p><pre>// won&#39;t compile<br>switch (value) {<br>    .int =&gt; std.debug.print(&quot;value is int={d}\n&quot;, .{value.int}),<br>    .float =&gt; std.debug.print(&quot;value is float={d}\n&quot;, .{value.float}),<br>    .string =&gt; std.debug.print(&quot;value is string={s}!\n&quot;, .{value.string}),<br>}</pre><h3>Union(Enum) is Tagged Union</h3><p>The error message on the previous example will actual say: note: consider &#39;union(enum)&#39; here.</p><p>The <strong>Zig</strong> nomenclature for union(enum) is actually called tagged <em>union</em>. As we mentioned earlier, the individual fields of an <em>enum</em> are called tags.</p><p>Tagged <em>union</em> was created so that they can be used in <em>switch</em> expressions.</p><pre>// first define the tags<br>const ValueType = enum {<br>    int,<br>    float,<br>    string,<br>    unknown,<br>};<br><br>// not too different from simple union<br>const Value = union(ValueType) {<br>    int: i32,<br>    float: f64,<br>    string: []const u8,<br>    unknown: void,<br>};<br><br>// just like the simple union<br>var value = Value{ .float = 42.21 };<br><br>switch (value) {<br>    .int =&gt; std.debug.print(&quot;value is int={d}\n&quot;, .{value.int}),<br>    .float =&gt; std.debug.print(&quot;value is float={d}\n&quot;, .{value.float}),<br>    .string =&gt; std.debug.print(&quot;value is string={s}\n&quot;, .{value.string}),<br>    else =&gt; std.debug.print(&quot;value is unknown!\n&quot;, .{}),<br>}</pre><h3>Capture Tagged Union Value</h3><p>You can use the capture in the <em>switch</em> expression if you need to access the value.</p><pre>switch (value) {<br>    .int =&gt; |v| std.debug.print(&quot;value is int={d}\n&quot;, .{v}),<br>    .float =&gt; |v| std.debug.print(&quot;value is float={d}\n&quot;, .{v}),<br>    .string =&gt; |v| std.debug.print(&quot;value is string={s}\n&quot;, .{v}),<br>    else =&gt; std.debug.print(&quot;value is unknown!\n&quot;, .{}),<br>}</pre><h3>Modify Tagged Union</h3><p>If you need to modify the value, you have to use convert the value to a pointer in the capture using *.</p><pre>switch (value) {<br>    .int =&gt; |*v| v.* += 1,<br>    .float =&gt; |*v| v.* ^= 2,<br>    .string =&gt; |*v| v.* = &quot;I&#39;m not Ed&quot;,<br>    else =&gt; std.debug.print(&quot;value is unknown!\n&quot;, .{}),<br>}</pre><h3>Tagged Union as ADT</h3><p>We now have everything we need to implement <strong>Zig</strong> version of <em>ADT</em>. What makes <em>ADT</em> useful is that not only it will tell you the state but also the context of the state.</p><p>Using <strong>Zig</strong> for instance, the active tag in a union will tell you the state, and if the <em>tag</em> is a type that has a value, then the value is the context.</p><pre>// this example is fairly involved, please see the full code on github<br>// You can find the code at https://github.com/edyu/wtf-zig-adt/blob/master/testadt.zig<br>const NodeType = enum {<br>    tip,<br>    node,<br>};<br><br>const Tip = struct {};<br><br>const Node = struct {<br>    left: *const Tree,<br>    value: u32,<br>    right: *const Tree,<br>};<br><br>const Tree = union(NodeType) {<br>    tip: Tip,<br>    node: *const Node,<br>}<br><br>const leaf = Tip{};<br><br>// this is meant to reimplement the binary tree example on https://wiki.haskell.org/Algebraic_data_type<br>// if you call tree.toString(), it will print out:<br>// Node (Node (Node (Tip 1 Tip) 3 Node (Tip 4 Tip)) 5 Node (Tip 7 Tip))<br>const tree = Tree{ .node = &amp;Node{<br>    .left = &amp;Tree{ .node = &amp;Node{<br>        .left = &amp;Tree{ .node = &amp;Node{<br>            .left = &amp;Tree{ .tip = leaf },<br>            .value = 1,<br>            .right = &amp;Tree{ .tip = leaf } } },<br>        .value = 3,<br>        .right = &amp;Tree{ .node = &amp;Node{<br>            .left = &amp;Tree{ .tip = leaf },<br>            .value = 4,<br>            .right = &amp;Tree{ .tip = leaf } } } } },<br>    .value = 5,<br>    .right = &amp;Tree{ .node = &amp;Node{<br>        .left = &amp;Tree{ .tip = leaf },<br>        .value = 7,<br>        .right = &amp;Tree{ .tip = leaf } } } } };<br>// see the full example on github</pre><h3>Bonus</h3><p>In <strong>Zig</strong>, there is also something called <em>non-exhaustive enum</em>.</p><p><em>Non-exhaustive enum</em> must be defined with an integer tag type in the (). You then put _ as the last tag in the <em>enum</em> definition.</p><p>Instead of else, you can use _ to ensure you handled all the cases in the <em>switch</em> expression.</p><pre>const Eds = enum(u8) {<br>    Ed,<br>    Edward,<br>    Edmond,<br>    Eduardo,<br>    Edwin,<br>    Eddy,<br>    Eddie,<br>    _,<br>};<br><br>const ed = Eds.Ed;<br><br>std.debug.print(&quot;All your code are belong to &quot;, .{});<br>switch (ed) {<br>    // Zig switch uses , not | for multiple options<br>    .Ed, .Edward =&gt; std.debug.print(&quot;{s}!\n&quot;, .{@tagName(ed)}),<br>    // can use capture<br>    .Edmond, .Eduardo, .Edwin, .Eddy, .Eddie =&gt; |name| std.debug.print(&quot;this {s}!\n&quot;, .{@tagName(name)}),<br>    // else works but look at the code below for _ vs else<br>    else =&gt; std.debug.print(&quot;us\n&quot;, .{}),<br>}<br><br>// obviously no such enum predefined<br>const not_ed = @as(Eds, @enumFromInt(241));<br>std.debug.print(&quot;All your base are belong to &quot;, .{});<br>switch (not_ed) {<br>    .Ed, .Edward =&gt; std.debug.print(&quot;{s}!\n&quot;, .{@tagName(ed)}),<br>    .Edmond, .Eduardo, .Edwin, .Eddy, .Eddie =&gt; |name| std.debug.print(&quot;this {s}!\n&quot;, .{@tagName(name)}),<br>    // _ will force you to handle all defined cases<br>    // if any of the previous .Ed, .Edward ... .Eddie is missing, this won&#39;t compile<br>    // for example, if you forgot .Edurdo<br>    // and wrote: .Edmond, .Eduardo, .Edwin, .Eddy, .Eddie =&gt; ...<br>    // the code won&#39;t compile<br>    _ =&gt; std.debug.print(&quot;us\n&quot;, .{}),<br>}</pre><p>Btw, you can add functions to <em>enum</em>, <em>union</em>, <em>union(enum)</em> just like you can in <em>struct</em>. You can see examples of that in the code below.</p><h3>The End</h3><p>You can find the code <a href="https://github.com/edyu/wtf-zig-adt/blob/master/testadt.zig">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*cRSFQUdoz0FY09EdcprfEQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9345659d557f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zig If — WTF is !?bool]]></title>
            <link>https://medium.com/@edlyuu/zig-if-wtf-is-bool-79001f71f9be?source=rss-931a37f1b662------2</link>
            <guid isPermaLink="false">https://medium.com/p/79001f71f9be</guid>
            <category><![CDATA[zig]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ed Yu]]></dc:creator>
            <pubDate>Wed, 07 Jun 2023 09:29:38 GMT</pubDate>
            <atom:updated>2023-07-12T16:57:47.926Z</atom:updated>
            <content:encoded><![CDATA[<h3>Zig If — WTF is !?bool</h3><p>The power and complexity of <strong>if</strong> in Zig</p><figure><img alt="zig logo" src="https://cdn-images-1.medium.com/max/400/1*Zi6kS-LHbNeKepJMqynuKQ.png" /></figure><p>Jun.06.2023</p><p>by Ed Yu (find me <a href="https://github.com/edyu">@edyu</a> on Github and <a href="https://twitter.com/edyu">@edyu</a> on Twitter)</p><h3>Introduction</h3><p><a href="https://ziglang.org/"><strong>Zig</strong></a> is a modern systems programming language and although it claims to a be a <strong>better C</strong>, many people who initially didn’t need systems programming were attracted to it due to the simplicity of its syntax compared to alternatives such as <strong>C++</strong> or <strong>Rust</strong>.</p><p>However, due to the power of the language, some of the syntaxes are not obvious for those first coming into the language. I was actually one such person.</p><p>When I was thrown into <strong>Zig</strong> (by choice) for my current project, I didn’t think twice but as my code becomes more complex, I started to be confused in the simplest programming construct — <em>if</em> statement.</p><p>The reason is that <strong>Zig</strong> happens to overload the simple <em>if</em> statement for many of the new concepts that underly <strong>Zig</strong>’s power. Today we’ll explore the <em>if</em> statement in <strong>Zig</strong> and by the end hopefully you’ll have a better grasp of the language.</p><h3>Basic if statement</h3><p>The main reason for <em>if</em> statements to exist in any programming language is to allow conditional processing of conditional expression so that if some condition is true, do this or else do something else.</p><p>Here is the basic idea:</p><pre>// if you want to try yourself, you must import `std`<br>const std = @import(&quot;std&quot;);<br><br>if (true) {<br>    std.debug.print(&quot;hello Ed\n&quot;, .{});<br>} else {<br>    std.debug.print(&quot;hello world\n&quot;, .{});<br>}</pre><p>So the above code will always print <strong>“hello Ed”</strong> because the condition is true. The following code will always print <strong>“hello world”</strong> because the condition is false.</p><pre>if (false) {<br>    std.debug.print(&quot;hello Ed\n&quot;, .{});<br>} else {<br>    std.debug.print(&quot;hello world\n&quot;, .{});<br>}</pre><p>Of course that’s not very useful so let’s do a string comparison in our function</p><pre>// note that strings in Zig is []const u8 which means an array o<br>fn dudeIsEd(name: []const u8) bool {<br>    // remember zig is like C, so you can’t just do name == “Ed”<br>    if (std.mem.eql(u8, name, &quot;Ed&quot;)) {<br>        return true;<br>    } else {<br>        return false;<br>    }<br>}<br><br>// we can now call the function as a boolean expression<br>fn sayHello(name: []const u8) void {<br>    if (dudeIsEd(name)) {<br>        std.debug.print(&quot;hello {s}\n&quot;, .{name});<br>    } else {<br>        std.debug.print(&quot;hello world!\n&quot;, .{});<br>    }<br>}</pre><p>Because dudeIsEd will return a boolean, then you can use the function in any if statement as the condition.</p><h3>Error-handling if statement</h3><p>Ok, let’s now introduce error in the function. One of the coolest part of <strong>Zig</strong> is how it handles errors. Errors are just regular return type mostly. The <em>if</em> statement is overloaded for error handling. The main difference is that now you can <strong>capture</strong> the error using<em> |err|</em> in the <em>else</em> expression.</p><pre>const Error = error { WrongPerson };<br><br>// you have to declare your function will return error by using ! in front of<br>// the return type which actually signals that your function will return an<br>// error union (union of error with your actual return type)<br>fn dudeIsEdOrError(name: []const u8) !void {<br>    if (std.jjkmem.eql(u8, name, &quot;Ed&quot;)) {<br>        std.debug.print(&quot;hello {s}\n&quot;, .{name});<br>    } else {<br>        return Error.WrongPerson;<br>    }<br>}<br><br>// handle the error just like regular boolean<br>fn sayHelloError(name: []const u8) void {<br>    // notice that dudeIsEdOrError doesn&#39;t return boolean<br>    if (dudeIsEdOrError(name)) {<br>        std.debug.print(&quot;good seeing you {s} again\n&quot;, .{name});<br>    } else |err| {<br>        std.debug.print(&quot;got error: {}!\n&quot;, .{err});<br>        std.debug.print(&quot;hello world!\n&quot;, .{});<br>    }<br>}<br><br>// if you want to ignore the error, use _ in the capture<br>fn sayHelloIgnoreError(name: []const u8) void {<br>    if (dudeIsEdOrError(name)) {<br>        std.debug.print(&quot;good seeing you {s} again\n&quot;, .{name});<br>    } else |_| {<br>        std.debug.print(&quot;hello world!\n&quot;, .{});<br>    }<br>}</pre><h3>Mixing boolean with error-handling if statement</h3><p>So, how do you mix boolean and error together in an <em>if</em> statement?</p><p>You can use capture the boolean in the <em>if</em> expression as as you were capturing the error in the <em>else</em> expression.</p><pre>fn dudeIsEdishOrError(name: []const u8) !bool {<br>    if (std.mem.eql(u8, name, &quot;Ed&quot;)) {<br>        std.debug.print(&quot;hello {s}\n&quot;, .{name});<br>        return true;<br>    } else if (std.mem.eql(u8, name, &quot;Edward&quot;)) {<br>        std.debug.print(&quot;hello again {s}\n&quot;, .{name});<br>        return false;<br>    } else {<br>        return Error.WrongPerson;<br>    }<br>}<br><br>fn sayHelloEdish(name: []const u8) void {<br>    // notice that dudeIsEdOrError doesn&#39;t return boolean<br>    if (dudeIsEdishOrError(name)) |ed| {<br>        std.debug.print(&quot;ed? {}\n&quot;, .{ed});<br>        if (ed) {<br>            std.debug.print(&quot;good seeing you {s}\n&quot;, .{name});<br>        } else {<br>            std.debug.print(&quot;good seeing you again {s}\n&quot;, .{name});<br>        }<br>    } else |err| {<br>        std.debug.print(&quot;got error: {}!\n&quot;, .{err});<br>        std.debug.print(&quot;hello world!\n&quot;, .{});<br>    }<br>}</pre><h3>Optional if statement</h3><p>Another cool thing that <strong>Zig</strong> introduced is optional. Optional is similar to how many other languages handles the idea of maybe. If optional is used in the return type it designates that a function may or may not return a value. For many languages optional is similar to how a variable can either have a value or be <em>null</em>. <strong>Zig</strong> made it so that you have to explicitly declare a variable optional before you can assign <em>null</em> to a variable. The way to designate something optional is to use the question mark <em>?</em>.</p><p>Interestingly, <strong>Zig</strong> decided to overload <em>if</em> statement once again to handle optional. To determine whether you have a value or not in the <em>if</em> statement, you have to use capture again but this time you use it in the <em>if</em> expression instead of the <em>else</em> expression to unwrap the optional value.</p><pre>fn dudeIsMaybeEd(name: []const u8) ?bool {<br>    if (std.mem.eql(u8, name, &quot;Ed&quot;)) {<br>        return true;<br>    } else if (std.mem.eql(u8, name, &quot;Edward&quot;)) {<br>        return false;<br>    } else {<br>        return null;<br>    }<br>}<br><br>fn sayHelloMaybeEd(name: []const u8) void {<br>    // this if expression is to check whether you have a value or null<br>    if (dudeIsMaybeEd(name)) |ed| {<br>        if (ed) {<br>            std.debug.print(&quot;hello {s}\n&quot;, .{name});<br>        } else {<br>            std.debug.print(&quot;hello again {s}\n&quot;, .{name});<br>        }<br>    } else { // when you get null<br>        std.debug.print(&quot;hello world!\n&quot;, .{});<br>    }<br>}</pre><h3>Optional if statement with error-handling</h3><p>So now you have boolean, optional, and error that can all be handled by <em>if </em>statements, what if you have all three?</p><p>How would you parse that?</p><p>Assuming you have the following function:</p><pre>// Ed or Edward are ok but definitely not Eddie, anyone else don&#39;t care<br>fn dudeIsMaybeEdOrError(name: []const u8) !?bool {<br>    if (std.mem.eql(u8, name, &quot;Ed&quot;)) {<br>        return true;<br>    } else if (std.mem.eql(u8, name, &quot;Edward&quot;)) {<br>        return false;<br>    } else if (std.mem.eql(u8, name, &quot;Eddie&quot;)) {<br>        return Error.WrongPerson;<br>    } else {<br>        return null;<br>    }<br>}</pre><p>You’ll have to unwrap !?bool from left to right in that you first use <em>if</em> statement to unwrap the <em>!</em> error conditional by handling the error condition in the <em>else</em> expression. Then, you also use the <em>if</em> expression to unwrap the the optional <em>?</em> conditional. Finally, you then use another <em>if</em> statement to unwrap the <em>bool</em> conditional.</p><pre>fn sayHelloMaybeEdOrError(name: []const u8) void {<br>    if (dudeIsMaybeEdOrError(name)) |maybe_ed| {<br>        if (maybe_ed) |ed| {<br>            std.debug.print(&quot;ed? {}\n&quot;, .{ed});<br>            if (ed) {<br>                std.debug.print(&quot;hello {s}\n&quot;, .{name});<br>            } else {<br>                std.debug.print(&quot;hello again {s}\n&quot;, .{name});<br>            }<br>        } else {<br>            std.debug.print(&quot;goodbye {s}\n&quot;, .{name});<br>        }<br>    } else |err| {<br>        std.debug.print(&quot;got error: {}!\n&quot;, .{err});<br>        std.debug.print(&quot;hello world!\n&quot;, .{});<br>    }<br>}</pre><h3>Bonus</h3><p>I lied; well, what I meant is that <em>if</em> can also be an <strong>expression</strong> not just a<strong> statement </strong>so that you can assign the return value of <em>if</em> expression to a variable. It’s functionally similar to ternary <em>?:</em> expression in many languages such as <strong>C</strong>. However, <em>if </em>expression has many restrictions compared to the <em>if</em> statement so use it only as a shorthand equivalent to ternary <em>?:</em>.</p><pre>// greeting will be &quot;hello&quot;<br>const greeting = if (dudeIsEd(&quot;Ed&quot;)) &quot;hello&quot; else &quot;goodbye&quot;;</pre><p>Also, there is also catch and orelse to deal with error and optional respectively for simple cases where you don&#39;t have to unwrap the value using <em>if</em> statements.</p><pre>const is_ed = dudeIsMaybeEd(&quot;Ed&quot;) orelse false;<br>const not_ed = dudeIsEdishOrError(&quot;Not Ed&quot;) catch false;</pre><h3>The End</h3><p>You can find the code <a href="https://github.com/edyu/wtf-zig-if/blob/master/testif.zig">here</a>.</p><figure><img alt="ziguana the zig mascot" src="https://cdn-images-1.medium.com/max/288/1*cRSFQUdoz0FY09EdcprfEQ.png" /></figure><p>Special thanks to Rene <a href="https://github.com/renerocksai">@renerocksai</a> for helping out on my <strong>Zig</strong> questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79001f71f9be" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>