<?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"><channel><title><![CDATA[Eagle Blog]]></title><description><![CDATA[Practical engineering guides on Rust, Flutter/Dart, ESP32, and systems performance, with runnable code examples and production debugging notes.]]></description><link>https://eagleblog.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/6b116cf964228a2ca4464c97/053a811c-087c-44eb-9d09-714c3dea1d14.png</url><title>Eagle Blog</title><link>https://eagleblog.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Fri, 04 Dec 2026 21:56:41 GMT</lastBuildDate><atom:link href="https://eagleblog.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[SIMD in Rust: From the 10-Minute GTA Online Loading Bug to 4 Ways to Vectorize Code]]></title><description><![CDATA[How a single CPU instruction crunches 16–64 bytes at once, why GTA Online stalled on JSON, and 4 ways to use SIMD in Rust.]]></description><link>https://eagleblog.hashnode.dev/rust-simd-and-gta</link><guid isPermaLink="true">https://eagleblog.hashnode.dev/rust-simd-and-gta</guid><category><![CDATA[Rust]]></category><category><![CDATA[performance]]></category><category><![CDATA[optimization]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[simd]]></category><dc:creator><![CDATA[Eagle]]></dc:creator><pubDate>Thu, 03 Dec 2026 14:27:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b116cf964228a2ca4464c97/22b69480-aa24-40b1-9be7-1750f9627ff8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>How a single CPU instruction can crunch 16–64 bytes at once, why the infamous GTA Online loading bug is a great reminder of what bad parsing costs, and four ways to use SIMD in Rust.</p>
</blockquote>
<p>In this post I will walk through the basics of vector processing (SIMD), look at real-world examples like <code>simdjson</code>, and cover the four ways you can work with SIMD in Rust.</p>
<blockquote>
<p><strong>Companion Code Repository:</strong> Runnable examples covering auto-vectorization, <code>std::arch</code>, <code>wide</code>, <code>pulp</code>, <code>std::simd</code>, and a benchmark are open-sourced on GitHub: <a href="https://github.com/eaglebk/rust-simd-examples">github.com/eaglebk/rust-simd-examples</a>.</p>
</blockquote>
<hr />
<h2>What GTA Online Has to Do With It</h2>
<p>Before diving into CPU instructions, let's recall the story of an enthusiast named <code>t0st</code> who fixed a long-standing GTA Online bug in 2021 that kept players staring at loading screens for 5–10 minutes.</p>
<p>Rockstar's mistake happened during JSON parsing. While reading a 10 MB JSON file, C's <code>sscanf</code> kept calling <code>strlen</code> on every single step to recompute the remaining string length. A routine operation ended up burning CPU cycles on redundant work.</p>
<p>Rockstar confirmed the root cause and awarded the researcher a $10,000 bounty (you can read the full story on <a href="https://arstechnica.com/gaming/2021/03/developers-to-update-gta-online-to-address-poor-load-times-after-community-fix/">Ars Technica</a>).</p>
<p>I bring this up for a reason: it shows how a poorly implemented low-level operation can bottleneck an entire application.</p>
<hr />
<h2>Speeding Up JSON: The <code>simdjson</code> Approach</h2>
<p>When JSON parsing performance comes up, <a href="https://github.com/simdjson/simdjson">simdjson</a> (by Daniel Lemire and Geoff Langdale) is hard to ignore.</p>
<p>At first glance, JSON looks like a poor fit for vectorization. Standard sequential parsing depends on preceding characters: you have to track quotes, <code>\</code> escapes, and nested objects.</p>
<p>The <code>simdjson</code> authors split the work into two stages:</p>
<ol>
<li><strong>Structural indexing with SIMD.</strong> Vector instructions scan large chunks of text in parallel, locate structural characters, find string boundaries, and handle escape sequences.</li>
<li><strong>Document parsing.</strong> The second stage builds the actual structure using the already indexed positions.</li>
</ol>
<p>As a result, <code>simdjson</code> parses JSON at several gigabytes per second, outperforming many traditional parsers and even some binary format implementations.</p>
<hr />
<h2>What SIMD Is and How It Works</h2>
<p>To see where that speedup comes from, let's drop down to machine instructions.</p>
<p>A machine instruction is a basic command a CPU executes directly: add two numbers, compare values, or load data from memory into a register.</p>
<p>For a long time, most code relied on <strong>scalar operations</strong> that handle one value at a time, such as the classic <code>ADD EAX, EBX</code> instruction adding two 32-bit integers. Over time, CPUs gained instruction set extensions: <strong>SSE</strong>, <strong>AVX</strong>, <strong>AVX2</strong>, <strong>AVX-512</strong> on x86, and <strong>NEON</strong> on ARM. These brought vector instructions to everyday processors.</p>
<p><strong>SIMD</strong> stands for <em>Single Instruction, Multiple Data</em>.</p>
<p>With SIMD, the CPU operates on multiple values in parallel. Instead of comparing bytes one by one, it can compare 16, 32, or 64 bytes in a single vector instruction.</p>
<p>The exact element count depends on register width and element size:</p>
<ul>
<li><strong>128-bit</strong> holds 16 bytes (or four 32-bit <code>f32</code> floats);</li>
<li><strong>256-bit</strong> holds 32 bytes (or eight <code>f32</code> floats);</li>
<li><strong>512-bit</strong> holds 64 bytes (or sixteen <code>f32</code> floats).</li>
</ul>
<h3>How It Looks on the Hardware</h3>
<p>The idea is straightforward: instead of loading a single number into a register, the CPU loads an entire vector. A 128-bit SSE register fits four <code>f32</code> values, and one vector instruction adds all four pairs at once.</p>
<p>This is not four scalar additions bundled together as syntax sugar. It is <strong>one vector instruction</strong> running on dedicated vector registers and SIMD execution units inside a single core, with no extra threads or cores required.</p>
<p>Of course, SIMD pairs well with multithreading. Multithreading spreads work across multiple CPU cores, while SIMD speeds up uniform operations inside each core. They complement each other rather than competing.</p>
<hr />
<h2>Where to Look for SIMD Opportunities</h2>
<p>Spotting vectorization candidates in existing code is fairly straightforward. Whenever you see loops like this (pseudocode):</p>
<pre><code class="language-text">for (byte in bytes) { ... }
for (item in array) { ... }
for (char in string) { ... }
</code></pre>
<p>it is worth taking a closer look. Loops where each iteration handles independent elements are prime targets: adding two arrays, applying a filter, or scanning byte sequences.</p>
<p>Conceptually, processing one element per step turns into processing a whole chunk:</p>
<pre><code class="language-text">for (8 elements in array) { ... }
</code></pre>
<p>Not every loop can be vectorized, though:</p>
<ul>
<li><strong>Loop-carried dependencies.</strong> If an iteration depends on the previous iteration's result, vectorization may be impossible or counterproductive.</li>
<li><strong>Small datasets.</strong> SIMD shines on hundreds of thousands or millions of elements. On tiny slices, setup overhead can wipe out any gain.</li>
<li><strong>Memory bottlenecks.</strong> If the program spends most of its time waiting on RAM, faster arithmetic will barely move the needle.</li>
</ul>
<p>Always verify SIMD changes with benchmarks (for example with <code>criterion</code>, covered in <a href="https://eagle2000.space/en/rust/crate-of-the-day-criterion/">Crate of the Day: Criterion</a>, and in the <a href="https://github.com/eaglebk/rust-simd-examples">examples repository</a>). Today, vector instructions are everywhere: image and audio processing, digital signal processing (DSP), matrix math, cryptography, and runtimes like Node.js and Bun (see the <a href="https://github.com/simdjson/simdjson#real-world-usage">simdjson real-world usage list</a>).</p>
<hr />
<h2>Working With SIMD in Rust: 4 Approaches</h2>
<p>Since I mostly write Rust, let's look at four ways to use SIMD in the language (though the same ideas apply to C/C++, Go, or Zig).</p>
<h3>1. Auto-vectorization</h3>
<p>The simplest path: we write a plain idiomatic Rust loop, and LLVM tries to turn it into SIMD instructions in release builds.</p>
<p>There is no guarantee it will happen, though. It depends on the target CPU, compiler flags, and whether the optimizer can prove there are no aliasing or dependency issues. You can check the generated assembly to see what LLVM actually emitted.</p>
<h3>2. Direct Intrinsics (<code>std::arch</code>)</h3>
<p>When you want full control, Rust's <code>std::arch</code> module exposes SSE, AVX2, AVX-512, and ARM NEON intrinsics directly.</p>
<p>On <code>x86_64</code>, for instance, you can load four <code>f32</code> values with <code>_mm_loadu_ps</code> and add them in one shot with <code>_mm_add_ps</code>. The <code>u</code> suffix stands for <em>unaligned</em> (loading without requiring strict vector boundary alignment).</p>
<p>The upside is exact control over the instructions emitted into the binary. The downside is <code>unsafe</code> code, handling CPU architectures explicitly, and dealing with any leftover tail elements that do not fill a full vector.</p>
<p><strong>Scalar loop (1 element per step):</strong></p>
<pre><code class="language-rust">fn add_scalar(a: &amp;[f32; 4], b: &amp;[f32; 4], out: &amp;mut [f32; 4]) {
    for i in 0..4 {
        out[i] = a[i] + b[i];
    }
}
</code></pre>
<p><strong>Explicit SIMD (4×</strong> <code>f32</code> <strong>in one op):</strong></p>
<pre><code class="language-rust">#[cfg(target_arch = "x86_64")]
unsafe fn add_sse(a: &amp;[f32; 4], b: &amp;[f32; 4], out: &amp;mut [f32; 4]) {
    use std::arch::x86_64::{_mm_add_ps, _mm_loadu_ps, _mm_storeu_ps};
    let va = _mm_loadu_ps(a.as_ptr());
    let vb = _mm_loadu_ps(b.as_ptr());
    let sum = _mm_add_ps(va, vb);
    _mm_storeu_ps(out.as_mut_ptr(), sum);
}
</code></pre>
<ul>
<li><strong>Loading:</strong> <code>_mm_loadu_ps</code> loads 128 bits (4 × <code>f32</code>) into XMM registers at once.</li>
<li><strong>Addition:</strong> One SSE vector instruction (<code>_mm_add_ps</code>) sums all 4 pairs in parallel.</li>
<li><strong>Storing:</strong> <code>_mm_storeu_ps</code> writes the resulting 128-bit vector back to memory in one step without strict alignment requirements.</li>
</ul>
<h3>3. Portable SIMD (<code>std::simd</code>)</h3>
<p>To avoid tying your code to a single CPU architecture, Rust is developing <code>std::simd</code>. Instead of <code>_mm_add_ps</code>, you work with a portable <code>Simd::&lt;f32, 4&gt;</code> vector type and a regular <code>+</code> operator, letting the compiler pick the right instructions for the target.</p>
<p>One catch: <code>std::simd</code> is still experimental and requires nightly Rust with <code>#![feature(portable_simd)]</code>.</p>
<h3>4. Ready-Made SIMD Crates</h3>
<p>If you want to skip low-level intrinsics and <code>unsafe</code> on stable Rust, the ecosystem has solid crates:</p>
<ul>
<li><a href="https://github.com/Lokathor/wide">wide</a> — portable vector types with standard arithmetic;</li>
<li><a href="https://github.com/sarah-quinones/pulp">pulp</a> — cross-architecture SIMD abstraction with runtime dispatch;</li>
<li><a href="https://github.com/AdamNiederer/faster">faster</a> — a crate for ergonomic iterator vectorization.</li>
</ul>
<hr />
<h2>Useful Links</h2>
<ul>
<li><a href="https://arstechnica.com/gaming/2021/03/developers-to-update-gta-online-to-address-poor-load-times-after-community-fix/">GTA Online: the JSON parsing fix story</a></li>
<li><a href="https://github.com/simdjson/simdjson">simdjson on GitHub</a></li>
<li><a href="https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html">Intel Intrinsics Guide</a></li>
<li><a href="https://developer.arm.com/architectures/instruction-sets/intrinsics/">ARM NEON Intrinsics</a></li>
<li><a href="https://doc.rust-lang.org/stable/std/arch/">Rust <code>std::arch</code> docs</a></li>
<li><a href="https://doc.rust-lang.org/nightly/std/simd/">Portable SIMD (<code>std::simd</code>) docs</a></li>
</ul>
<hr />
<p><em>Originally published on</em> <a href="https://eagle2000.space/en/rust/rust-simd-and-gta/"><em>EagleBlog</em></a><em>, where you can also run the interactive Rust Playground slides and take the quiz. Which approach do you reach for in production — relying on LLVM auto-vectorization, crates like</em> <code>wide</code> <em>/</em> <code>pulp</code><em>, or dropping down to</em> <code>std::arch</code><em>?</em></p>
]]></content:encoded></item><item><title><![CDATA[Why My 202 Accepted Endpoint Still Timed Out After 8 Seconds (and How tokio::spawn Fixed It)]]></title><description><![CDATA[My Axum endpoint returned 202 Accepted, yet Flutter crashed with TimeoutException after 8s. Offloading SMTP to tokio::spawn cut latency to 15ms.]]></description><link>https://eagleblog.hashnode.dev/http-202-async-email-timeout</link><guid isPermaLink="true">https://eagleblog.hashnode.dev/http-202-async-email-timeout</guid><category><![CDATA[Rust]]></category><category><![CDATA[backend]]></category><category><![CDATA[debugging]]></category><category><![CDATA[api]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Eagle]]></dc:creator><pubDate>Thu, 03 Dec 2026 14:25:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b116cf964228a2ca4464c97/0df73b5c-2b9c-4e90-aef6-4f0272b71cd4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>Short breakdown of a non-obvious production bug I hit myself — and why returning <code>202 Accepted</code> while still <code>await</code>ing SMTP defeats the whole point of async.</p>
</blockquote>
<p>Today's topic is the deceptive <code>202 Accepted</code> status code and why sending an email over SMTP must never block an HTTP response.</p>
<hr />
<h2>What it looked like</h2>
<p>A user in the Flutter app enters their email and taps "Get code". Eight seconds later the screen shows an error:</p>
<pre><code class="language-text">TimeoutException after 0:00:08: Future not completed
</code></pre>
<p>A couple of seconds later, the email with the code <strong>arrives in their inbox</strong>. So the server did everything right, yet the client assumed the server was dead and never navigated to the code-entry screen.</p>
<hr />
<h2>What was happening on the server</h2>
<p>My <code>POST /v1/members/magic</code> endpoint honestly returned <code>202 Accepted</code>, but inside the handler there was a plain <code>await</code>:</p>
<pre><code class="language-rust">repo::insert_code(&amp;st.db, Uuid::new_v4(), member.id, &amp;hash(&amp;code), expires).await?;
mailer.send_code(&amp;email, &amp;code).await?; // &lt;-- Waiting for the full SMTP send right here!
Ok(())
</code></pre>
<p>While I tested locally with a console mailer (which just printed the code to stdout), it took <code>0.1 ms</code>.</p>
<p>Once a real direct MX sender in Rust (<code>mail-send</code>) came into play, a single <code>send_code()</code> call turned into a chain of network round-trips: an MX DNS lookup, TCP connection on port 25, TLS handshake, and message transfer until the remote mail server replies.</p>
<p>All of that took <strong>3 to 10 seconds</strong>, and with ISP throttling and network slowdowns, external TCP/TLS handshakes to mail servers stall even longer. Meanwhile, the mobile client had a hard <strong>8-second</strong> timeout.</p>
<blockquote>
<p><strong>Note:</strong> HTTP <strong>202 Accepted</strong> means the server has accepted the request for processing, not that the work is already finished when the response is sent. Waiting for an external SMTP server before replying defeats the purpose of <code>202</code>.</p>
</blockquote>
<hr />
<h2>The fix: an honest 202 Accepted via <code>tokio::spawn</code></h2>
<p>The code is already persisted in the database, so the client doesn't need to wait until a mail server on the other side of the internet replies <code>250 OK</code>. Offloading the send to the background is enough:</p>
<pre><code class="language-rust">repo::insert_code(&amp;st.db, Uuid::new_v4(), member.id, &amp;hash(&amp;code), expires).await?;

if matches!(mailer, Mailer::Console | Mailer::Capture(_)) {
    // In dev and unit tests, await directly here without tokio::spawn
    mailer.send_code(&amp;email, &amp;code).await?;
} else {
    let mailer = mailer.clone();
    let email_bg = email.clone();
    tokio::spawn(async move {
        if let Err(e) = mailer.send_code(&amp;email_bg, &amp;code).await {
            tracing::error!(error = %e, to = %email_bg, "failed to send magic code");
        }
    });
}
</code></pre>
<p>Now the response goes back to the client in <strong>~15 ms</strong> instead of 8+ seconds.</p>
<blockquote>
<p><strong>Tip:</strong> Errors from a spawned <code>tokio::spawn</code> task never reach the HTTP handler, so log them explicitly inside the <code>async move</code> block (for example with <code>tracing::error!</code>). Otherwise SMTP failures will happen silently.</p>
</blockquote>
<hr />
<h2>Three important details to avoid stepping on a new rake</h2>
<ol>
<li><strong>Don't break unit tests.</strong> When tests use a mock mailer (<code>Mailer::Capture</code>), the test immediately checks that the email was saved in the mock's in-memory buffer (e.g., an internal <code>Vec</code>) right after calling the handler. Moving the mock into <code>tokio::spawn</code> as well would make tests flaky due to a race condition, so keep a direct <code>.await</code> for mock and console mailers.</li>
<li><strong>Set timeouts inside the background task.</strong> If the recipient's primary MX server doesn't respond, an untimed <code>connect()</code> can hang for a minute on every attempt. I wrap <code>connect</code> (10s) and <code>send</code> (15s) in <code>tokio::time::timeout</code>.</li>
<li><strong>Spam protection is already in place.</strong> Saving the code in the DB (and checking the 60-second cooldown) happens <strong>before</strong> <code>tokio::spawn</code>, so a repeated tap from the user won't trigger a second email.</li>
</ol>
<blockquote>
<p><strong>Trade-off:</strong> There is one catch with a bare <code>tokio::spawn</code>: if the server restarts abruptly or runs out of memory, the in-flight background task may not finish even though the client already got <code>202</code>. If guaranteed delivery across restarts matters, store outgoing emails in a database outbox table instead.</p>
</blockquote>
<p><strong>Docs:</strong> <a href="https://docs.rs/tokio/latest/tokio/task/fn.spawn.html">tokio::spawn</a></p>
<hr />
<p><em>Originally published on</em> <a href="https://eagle2000.space/en/rust/http-202-async-email-timeout/"><em>EagleBlog</em></a><em>. How do you handle background email or webhook delivery in Rust services — bare</em> <code>tokio::spawn</code> <em>with timeouts, or a full DB outbox / job queue?</em></p>
]]></content:encoded></item><item><title><![CDATA[File Modes, Builder Pattern, and Path / PathBuf in Rust]]></title><description><![CDATA[A practical guide to files and paths in Rust: File::options(), POSIX flags, Path vs PathBuf, and ergonomic APIs with impl AsRef<Path>.]]></description><link>https://eagleblog.hashnode.dev/rust-files-tempfile-and-docs</link><guid isPermaLink="true">https://eagleblog.hashnode.dev/rust-files-tempfile-and-docs</guid><category><![CDATA[Rust]]></category><dc:creator><![CDATA[Eagle]]></dc:creator><pubDate>Thu, 03 Dec 2026 13:59:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b116cf964228a2ca4464c97/889f594e-80b2-46b2-ad58-bccbeb8e6134.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>A practical guide to configuring OS file descriptors with <code>File::options()</code>, avoiding TOCTOU bugs, and designing zero-allocation APIs with <code>impl AsRef&lt;Path&gt;</code>.</p>
</blockquote>
<p>Almost every CLI tool, web service, or database eventually hits disk I/O. In Rust, the filesystem API is designed to avoid redundant allocations and prevent accidental descriptor bugs.</p>
<p>In this guide, I'll walk through two core topics for filesystem work:</p>
<ol>
<li>Configuring OS file descriptors with the <strong>Builder</strong> pattern in <code>File::options()</code> and how those methods map to POSIX flags.</li>
<li>The <code>Path</code> <strong>vs</strong> <code>PathBuf</code> pair, unsized types (<code>DST</code>), and designing ergonomic public APIs with <code>impl AsRef&lt;Path&gt;</code>.</li>
</ol>
<hr />
<h2>1. File Descriptors and the Builder Pattern in <code>File::options()</code></h2>
<h3>What Is a File Descriptor?</h3>
<p>When a program opens a file, network socket, or pipe, the operating system does not hand over raw disk access. Instead, it creates an entry in the process's open-file table and returns a small integer (like <code>3</code> or <code>4</code>) called a <strong>file descriptor</strong> (<code>fd</code>). Every process starts with three standard descriptors already open: <code>0</code> for <code>stdin</code>, <code>1</code> for <code>stdout</code>, and <code>2</code> for <code>stderr</code>.</p>
<p>On Windows, the equivalent kernel identifier is a <code>HANDLE</code>. Rust's <code>std::fs::File</code> wraps this OS handle and automatically closes it when the <code>File</code> goes out of scope (via <code>Drop</code>), preventing descriptor leaks.</p>
<h4>How to Inspect File Descriptors in the Terminal</h4>
<p><strong>Linux and macOS: listing open file descriptors</strong></p>
<p>On Linux, a process's open descriptors appear as symlinks inside <code>/proc/&lt;PID&gt;/fd</code>. You can bind a test file to descriptor <code>3</code> directly in your shell and inspect the table:</p>
<pre><code class="language-bash"># 1. Attach test.log to file descriptor 3
exec 3&gt; test.log

# 2. List open descriptors for the current shell ($$ is its PID)
ls -la /proc/$$/fd
# Linux output: 0 -&gt; /dev/pts/0, 1 -&gt; /dev/pts/0, 2 -&gt; /dev/pts/0, 3 -&gt; /tmp/test.log

# On macOS (no /proc), use lsof instead:
lsof -p $$

# 3. Close descriptor 3 and remove the test file
exec 3&gt;&amp;- &amp;&amp; rm test.log
</code></pre>
<p><strong>Windows: inspecting open HANDLEs</strong></p>
<p>Windows does not expose <code>/proc</code>, so you can inspect open <code>HANDLE</code>s in two ways:</p>
<ol>
<li><strong>Built-in Resource Monitor:</strong> run <code>resmon.exe</code> from PowerShell or <code>Win + R</code>, open the <strong>CPU</strong> tab, and check <strong>Associated Handles</strong> to see every file handle held by a process.</li>
<li><strong>In PowerShell / CMD</strong> using Microsoft Sysinternals <code>handle.exe</code>:</li>
</ol>
<pre><code class="language-powershell"># Show all open handles for notepad.exe
handle.exe -p notepad.exe
</code></pre>
<h3>Mapping to POSIX System Calls</h3>
<p>At the OS level, Unix/POSIX and Windows require access bitmasks when opening a file via <code>open(2)</code> or <code>CreateFileW</code>.</p>
<blockquote>
<p><strong>What is POSIX?</strong> It is a family of standards for Unix-like operating systems (such as Linux, macOS, and FreeBSD) that defines common system calls and constants for files, processes, and sockets. Windows uses its own native API (<code>CreateFileW</code>), and Rust's standard library automatically translates <code>File::options()</code> into the right OS-specific flags for each platform.</p>
</blockquote>
<p>In POSIX, these flags are represented as constants:</p>
<ul>
<li><code>O_RDONLY</code> - open for reading only.</li>
<li><code>O_WRONLY | O_CREAT</code> - open for writing, creating the file if it does not exist.</li>
<li><code>O_APPEND</code> - append all writes strictly to the end of the file.</li>
<li><code>O_EXCL</code> - fail if the file already exists (atomic creation guarantee).</li>
<li><code>O_TRUNC</code> - truncate the file size to 0 upon opening.</li>
</ul>
<p>Rust's <code>File::open(path)</code> and <code>File::create(path)</code> provide common presets for these flags. Whenever you need a custom combination (for example, opening a file for both reading and appending without truncating), use <code>std::fs::OpenOptions</code> or <code>File::options()</code>.</p>
<p>Quick cheat sheet:</p>
<ul>
<li><strong>Read-only:</strong> <code>File::open(path)</code></li>
<li><strong>Create or truncate to zero (</strong><code>O_TRUNC</code><strong>):</strong> <code>File::create(path)</code></li>
<li><strong>Create if missing and append:</strong> <code>File::options().create(true).append(true).open(path)</code></li>
</ul>
<h3>Applying the Builder Pattern</h3>
<p><code>File::options()</code> returns a configuration builder using the <strong>Builder pattern</strong> (covered in detail in <a href="https://eagle2000.space/en/rust/rust-builder/">The Builder Pattern in Rust</a>):</p>
<pre><code class="language-rust">use std::fs::File;

let mut file = File::options()
    .read(true)        // Enables read mode
    .write(true)       // Combined with .read(true), maps to O_RDWR
    .create(true)      // Creates the file if missing (O_CREAT)
    .append(true)      // Moves the write cursor to the end (O_APPEND)
    .open("app.log")?;
</code></pre>
<p>Each method updates the builder's internal state and returns <code>&amp;mut Self</code>, while the final <code>.open()</code> call executes the OS syscall.</p>
<blockquote>
<p><strong>How do you create a file without overwriting an existing one?</strong> If you first check <code>if !path.exists()</code> and then call <code>File::create()</code>, another process can create a file with the same name in between those two steps, and your code will silently overwrite it (a TOCTOU race condition: Time-of-Check to Time-of-Use). Use <code>.create_new(true)</code> instead: the OS performs the existence check and file creation as a single atomic step, returning <code>AlreadyExists</code> if the file is already there (which maps to <code>O_CREAT | O_EXCL</code> on POSIX).</p>
</blockquote>
<h3>Common Pitfalls with Descriptors and <code>File::options()</code></h3>
<ul>
<li><strong>Writing to a read-only file (</strong><code>os error 9</code><strong>):</strong> if you open a file with <code>File::open("app.log")</code> and try to <code>writeln!</code> to it, Unix/Linux fails with <code>Bad file descriptor (os error 9)</code> (on Windows, <code>os error 5</code>, Access Denied) because that descriptor lacks write permissions.</li>
<li><strong>Calling</strong> <code>.create(true)</code> <strong>without</strong> <code>.append</code> <strong>or</strong> <code>.truncate</code> <strong>(</strong><code>os error 22</code><strong>):</strong> <code>File::options().create(true).open("app.log")</code> compiles fine, but returns <code>InvalidInput</code> ("Invalid argument") at runtime. The OS needs to know whether to append (<code>.append(true)</code>) or truncate (<code>.truncate(true)</code>/<code>false</code>). Running <code>cargo clippy</code> catches this immediately with <em>file opened with</em> <code>create</code><em>, but</em> <code>truncate</code> <em>behavior not defined</em>.</li>
<li><strong>Simple one-liners:</strong> when you do not need custom flags or a long-lived handle, <code>std::fs::read_to_string(path)</code> and <code>std::fs::write(path, data)</code> are much shorter.</li>
</ul>
<hr />
<h2>2. Path Types Anatomy: <code>Path</code> vs <code>PathBuf</code> and <code>impl AsRef&lt;Path&gt;</code></h2>
<h3>A Strict Analogy with String Types</h3>
<p>Filesystem paths in Rust follow the exact same design as string types (<code>&amp;str</code> and <code>String</code>):</p>
<table>
<thead>
<tr>
<th>Concept</th>
<th>Borrowed Unsized Slice</th>
<th>Owned Heap Buffer</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Text Data</strong></td>
<td><code>&amp;str</code></td>
<td><code>String</code></td>
</tr>
<tr>
<td><strong>OS Native Strings</strong></td>
<td><code>&amp;OsStr</code></td>
<td><code>OsString</code></td>
</tr>
<tr>
<td><strong>Filesystem Paths</strong></td>
<td><code>&amp;Path</code></td>
<td><code>PathBuf</code></td>
</tr>
</tbody></table>
<h3>Why Is <code>Path</code> an Unsized Type (DST)?</h3>
<p>Most Rust types have a fixed size known at compile time (a <code>u64</code> is always 8 bytes). <strong>DSTs (Dynamically Sized Types)</strong>, such as <code>str</code>, <code>[T]</code>, and <code>Path</code> (a thin wrapper around <code>OsStr</code>), do not: the byte length of a path like <code>"/var/log/app.log"</code> is only known at runtime.</p>
<p>Because the compiler cannot reserve an unknown number of bytes on the stack, you can never create a bare <code>let p: Path;</code> variable. Instead, <code>Path</code> always lives behind a reference or smart pointer like <code>&amp;Path</code> or <code>Box&lt;Path&gt;</code>. Under the hood, <code>&amp;Path</code> is a fat pointer that carries both the memory address and the byte length of the path.</p>
<p>In contrast, <code>PathBuf</code> owns a growable byte buffer on the heap and lets you mutate paths safely at runtime:</p>
<pre><code class="language-rust">use std::path::PathBuf;

let mut path = PathBuf::from("/var/log");
path.push("eagleblog");       // Inserts the OS separator ('/' on Unix, '\' on Windows)
path.push("telemetry.log");
path.set_extension("json");   // Changes extension to /var/log/eagleblog/telemetry.json
</code></pre>
<h3>Ergonomic APIs with <code>impl AsRef&lt;Path&gt;</code></h3>
<p>When designing a library or service module, taking concrete types like <code>fn save_data(path: &amp;PathBuf)</code> or <code>fn save_data(path: &amp;str)</code> is a common API mistake: callers either have to allocate a <code>PathBuf::from(...)</code> unnecessarily, or cannot pass an existing <code>PathBuf</code> directly.</p>
<p>The idiomatic solution is accepting <code>impl AsRef&lt;Path&gt;</code>:</p>
<p><strong>Before — Rigid API (</strong><code>&amp;PathBuf</code><strong>):</strong></p>
<pre><code class="language-rust">use std::path::PathBuf;
use std::fs;

pub fn read_file_content(path: &amp;PathBuf) -&gt; std::io::Result&lt;String&gt; {
    fs::read_to_string(path)
}

fn main() {
    // Callers are forced to allocate a PathBuf:
    let _ = read_file_content(&amp;PathBuf::from("config.toml"));
}
</code></pre>
<p><strong>After — Ergonomic API (</strong><code>impl AsRef&lt;Path&gt;</code><strong>, 0 extra allocations):</strong></p>
<pre><code class="language-rust">use std::path::Path;
use std::fs;

pub fn read_file_content(path: impl AsRef&lt;Path&gt;) -&gt; std::io::Result&lt;String&gt; {
    fs::read_to_string(path.as_ref())
}

fn main() {
    // Works with any path-like type without conversions:
    let _ = read_file_content("config.toml");
    let _ = read_file_content(&amp;PathBuf::from("config.toml"));
}
</code></pre>
<ul>
<li><strong>Signature:</strong> Instead of locking callers to a heap buffer (<code>path: &amp;PathBuf</code>), accept any type that cheaply converts to <code>&amp;Path</code> (<code>path: impl AsRef&lt;Path&gt;</code>).</li>
<li><strong>String literal call:</strong> A string literal <code>&amp;str</code> implements <code>AsRef&lt;Path&gt;</code> directly, avoiding a heap allocation (<code>"config.toml"</code> instead of <code>&amp;PathBuf::from("config.toml")</code>).</li>
</ul>
<h3>Three Practical Tips for <code>impl AsRef&lt;Path&gt;</code> and <code>Path</code></h3>
<ol>
<li><strong>Watch out for moves:</strong> because <code>path: impl AsRef&lt;Path&gt;</code> is passed by value, calling <code>fs::exists(path)</code> moves <code>path</code>, so a subsequent <code>fs::read_to_string(path)</code> will not compile. Pass <code>&amp;path</code> instead, or bind <code>let path = path.as_ref();</code> at the top of the function.</li>
<li><strong>Storing in structs and printing:</strong> to store the path inside a struct, convert it into an owned <code>PathBuf</code> with <code>PathBuf::from(path.as_ref())</code> (or <code>.to_path_buf()</code>). When printing a <code>&amp;Path</code>, call <code>.display()</code> because <code>Path</code> does not implement <code>Display</code> (OS paths are not guaranteed to be valid UTF-8).</li>
<li><strong>Prefer</strong> <code>std::fs::exists</code> <strong>(Rust 1.81+):</strong> <code>path.exists()</code> silently returns <code>false</code> on permission errors, whereas <code>std::fs::exists(&amp;path)?</code> returns <code>io::Result&lt;bool&gt;</code> and surfaces real I/O failures.</li>
</ol>
<hr />
<h2>Further Reading</h2>
<p>Most of these patterns come from John Arundel's book “The Secrets of Rust: Tools”. Chapter 5, “Files” (pages 89–114), walks through file descriptors, <code>File::options()</code>, <code>Path</code>, <code>PathBuf</code>, and <code>AsRef&lt;Path&gt;</code> using the <code>logbook</code> CLI project.</p>
<hr />
<p><em>Originally published on</em> <a href="https://eagle2000.space/en/rust/rust-files-tempfile-and-docs/"><em>EagleBlog</em></a><em>, where you can also run the interactive Rust Playground slides and take the quiz.</em></p>
]]></content:encoded></item><item><title><![CDATA[Rust Article Roadmap: From Ownership and Traits to Files and Tokio]]></title><description><![CDATA[Structured map of all Rust guides on EagleBlog: core syntax, ownership and lifetimes, traits, iterators, file I/O, BufReader, SIMD, and crates.]]></description><link>https://eagleblog.hashnode.dev/rust-roadmap</link><guid isPermaLink="true">https://eagleblog.hashnode.dev/rust-roadmap</guid><category><![CDATA[Rust]]></category><dc:creator><![CDATA[Eagle]]></dc:creator><pubDate>Thu, 03 Dec 2026 13:57:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b116cf964228a2ca4464c97/c30da2ee-a062-45fa-967c-cded016b6ad8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Once the Rust posts here passed a couple dozen entries, reading them in reverse chronological order stopped making sense. I put together this map to group the English guides in a practical learning order — from core syntax and memory rules to traits, file I/O, and performance.</p>
<p>Most posts include runnable Rust Playground slides and a short quiz at the end on <a href="https://eagle2000.space/en/rust/rust-roadmap/">EagleBlog</a>.</p>
<h2>1. Core Types and Control Flow</h2>
<ul>
<li><a href="https://eagle2000.space/en/rust/rust-conditionals/">Conditionals and Branching in Rust</a></li>
<li><a href="https://eagle2000.space/en/rust/rust-enums/">Enums in Rust: From Syntax to Pattern Matching</a></li>
<li><a href="https://eagle2000.space/en/rust/rust-pattern-matching-deep-dive/">Pattern Matching Deep Dive: Destructuring and Guards</a></li>
</ul>
<h2>2. Memory, Lifetimes, and Smart Pointers</h2>
<ul>
<li><a href="https://eagle2000.space/en/rust/rust-raii-box-deref/">Memory Management in Rust: RAII, <code>Box&lt;T&gt;</code>, and Deref Coercion</a></li>
<li><a href="https://eagle2000.space/en/rust/rust-lifetimes-deep-dive/">Lifetimes Deep Dive: Elision, HRTB, and Variance</a></li>
<li><a href="https://eagle2000.space/en/rust/rust-interior-mutability/">Interior Mutability: <code>Cell</code> and <code>RefCell</code></a></li>
</ul>
<h2>3. Traits, Closures, and Collections</h2>
<ul>
<li><a href="https://eagle2000.space/en/rust/rust-traits/">Traits and Static Polymorphism</a></li>
<li><a href="https://eagle2000.space/en/rust/rust-dyn-traits/">Trait Objects (<code>dyn Trait</code>) and Dynamic Polymorphism</a></li>
<li><a href="https://eagle2000.space/en/rust/rust-advanced-traits/">Advanced Traits: Associated Types and Supertraits</a></li>
<li><a href="https://eagle2000.space/en/rust/rust-closures/">Closures in Rust: Functions with Captured State</a></li>
<li><a href="https://eagle2000.space/en/rust/rust-iterators-deep-dive/">Iterators Deep Dive: Lazy Processing Without Extra Allocations</a></li>
<li><a href="https://eagle2000.space/en/rust/rust-collections-overview/">Choosing <code>std::collections</code>: <code>BTreeMap</code>, <code>VecDeque</code>, <code>BinaryHeap</code></a></li>
</ul>
<h2>4. Files, I/O, and Performance</h2>
<ul>
<li><a href="https://eagle2000.space/en/rust/rust-files-tempfile-and-docs/">File Modes, <code>File::options()</code>, and <code>Path</code> / <code>PathBuf</code> in Rust</a></li>
<li><a href="https://eagle2000.space/en/rust/rust-bufreader/">BufReader in Rust: Speeding Up File I/O</a></li>
<li><a href="https://eagle2000.space/en/rust/rust-io-bufread-and-errors/">Fast I/O in Rust: Buffering, Tests, and Error Handling</a></li>
<li><a href="https://eagle2000.space/en/rust/rust-simd-and-gta/">SIMD in Practice (and What GTA Has to Do with It)</a></li>
<li><a href="https://eagle2000.space/en/rust/http-202-async-email-timeout/">Production Pitfall: <code>202 Accepted</code> and a 9-Second Client Timeout</a></li>
<li>Crates of the Day: <a href="https://eagle2000.space/en/rust/crate-of-the-day-rayon/">Rayon (Data Parallelism in One Line)</a> and <a href="https://eagle2000.space/en/rust/crate-of-the-day-strum/">Strum (Enum Iteration and Conversion)</a></li>
</ul>
]]></content:encoded></item></channel></rss>