<?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 Rahul Singh on Medium]]></title>
        <description><![CDATA[Stories by Rahul Singh on Medium]]></description>
        <link>https://medium.com/@rahulsingh_88457?source=rss-5a893db7f56f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2dB8uAaw3D4zHSM6</url>
            <title>Stories by Rahul Singh on Medium</title>
            <link>https://medium.com/@rahulsingh_88457?source=rss-5a893db7f56f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:56:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rahulsingh_88457/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[Recursion and Stack Overflow]]></title>
            <link>https://medium.com/@rahulsingh_88457/recursion-and-stack-overflow-dc5c0b5f86f1?source=rss-5a893db7f56f------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc5c0b5f86f1</guid>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[stackoverflow]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Rahul Singh]]></dc:creator>
            <pubDate>Sun, 10 Dec 2023 10:45:34 GMT</pubDate>
            <atom:updated>2023-12-10T11:10:20.892Z</atom:updated>
            <content:encoded><![CDATA[<p>Recursion is an elegant programming technique. Definitely something that programmers should learn and be comfortable with understanding and applying. However, when not used judiciously, it can also lead to very unpleasant program crashes.</p><p>A couple of days ago, I was trying to solve one of the <a href="https://adventofcode.com/2023">Advent Of Code 2023</a> challenges (Part of 2 of Day 8 challenge, to be precise). I won’t go into the nature of the puzzle here, but eventually in my case the answer to the puzzle was going to be the LCM (Lowest Common Multiple) of these numbers: [12083, 18827, 19951, 17141, 22199, 16579]. This LCM happens to be 16,342,438,708,751 — a number in excess of 16 Trillion.<br>I was going to compute the LCM of those numbers by processing 2 of them at a time — compute the LCM of first and second numbers; compute the LCM of previous result and third number; compute the LCM of previous result and 4th number; and so on. The “previous result” tends to get pretty large in that computation chain, and in one of the runs the LCM of 4,540,827,649 and 17,141 had to be computed.</p><p>The mathematical property I was using to compute the LCM of any two numbers is:</p><pre>Num1 x Num2 = LCM(Num1,Num2) x GCD(Num1,Num2)</pre><p>So if the GCD (Greatest Common Divisor) of the two numbers can be computed, then LCM would be obtained by dividing the product of the numbers with the GCD (I didn’t have to worry about overflows since all the numbers could be comfortably handled with 64 bit integer type).</p><p>I did not remember the details of Euclidean’s algorithm for computing GCD of 2 numbers, and the first web search result I clicked on showed the algorithm’s version that is based on subtraction and uses recursion. For people who might be well versed with the Euclidean’s algorithm, let’s kindly ignore the foolishness of choosing the subtraction based GCD calculation for the purposes of the rest of this article, and let’s assume that that’s the best we can do. <br>So, I duly coded it up in Rust and my program crashed with its thread stack overflown.</p><pre>fn gcd_recursive(num1: usize, num2: usize) -&gt; usize {<br>    if num1 == 0 { return num2; }<br>    if num2 == 0 { return num1; }<br>    if num1==num2 { return num1; }<br><br>    if num1 &gt; num2 { return gcd_recursive(num1 - num2, num2); }<br>    else { return gcd_recursive(num1, num2 - num1); }<br>}<br><br><br>thread &#39;main&#39; has overflowed its stack</pre><p>When the difference between the two numbers is large (e.g. like in my example above when the inputs are 4,540,827,649 and 17,141), the subtraction based algorithm causes a large number of subtraction operations to be computed (since the number ‘num1-num2&#39; decreases very slowly. I think it caused more than 284,000 subtraction operations for the inputs above). So if each subtraction operation happens in its independent (recursive) function call, that results in a lot of function call frames getting stacked up on the program’s thread stack (there’s a diagram later to help visualize this). Thread stacks have some upper limits, and if those limits are breached, program crashes happen.</p><p>I changed the implementation to an iterative one from the recursive one. That did not reduce the number of subtraction operations, but it performed all those operation within the context if a single <em>gcd_recursive</em> function call, which got rid of the stack overflow issue. <br>This is the best approach to solve thread stack overflow problem due to uncontrolled recursion — just get rid of the recursion, which was very simple in my toy case, but is likely to be more interesting in other cases. Well, in my particular case, the best approach would have been to just look a bit more and find the improved division based version of the Euclidean algorithm, but you get the point :)</p><p>What though, if in certain real life circumstances, changing the code is either not trivial or not possible due to complexity or ownership constraints. Are their other mitigations one can investigate?<br>Let me walk through some more fun I had with this code, and hopefully it has something in it for you as well.</p><p>I started by trying to estimate the thread stack size of a simple Rust program on Windows.</p><pre>fn main() {<br>    let t = std::thread::spawn(|| {<br>      let num1: usize = 17,141;<br>      let num2: usize = 4,540,827,649;<br>      println!(&quot;gcd of {}, {}&quot;, num1, num2);<br>      let gcd = gcd_recursive(num1, num2, (&amp;num1 as *const usize));<br>      println!(&quot;         = {}&quot;, gcd);<br>    );<br><br>    _ = t.join().unwrap();<br>}<br><br>fn gcd_recursive(num1: usize, num2: usize, addr: *const u8) -&gt; usize {<br>    if num1 == 0 { return num2; }<br>    if num2 == 0 { return num1; }<br>    if num1==num2 { return num1; }<br><br>    let num1addr = &amp;num1 as *const usize as *const u8;<br>    println!(&quot;estimated stack size: {:?} &quot;, (addr as usize) - (num1addr as usize));<br>    if num1 &gt; num2 { return gcd_recursive(num1 - num2, num2, addr); }<br>    else { return gcd_recursive(num1, num2 - num1, addr); }<br>}</pre><p>This program crashed after printing an estimated stack size of 2 MiB. Following diagram illustrates the estimated stack size calculation in the above code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*5AH0KJwqMbOCgaxS4GLiZg.jpeg" /></figure><p>Essentially the <em>address </em>of the <em>num1 </em>variable in the <em>main </em>function’s stack frame is captured in the <em>addr </em>variable.<br>Then within each <em>gcd_recursive</em> call, the <em>address </em>of its local <em>num1 </em>variable is taken in the <em>num1addr</em> variable, and its difference from <em>addr</em> is estimated as the used stack size up-to that point. The value of the difference printed just before the crash, should be a rough estimate of the max thread stack size. The diagram above should illustrate the estimation to be roughly fine.</p><p>I noticed that operating system thread creation APIs (like <a href="https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createthread">CreateThread </a>function in Windows, <a href="https://man7.org/linux/man-pages/man3/pthread_create.3.html">pthread_create</a> in Linux and MacOS, and <a href="https://developer.android.com/reference/java/lang/Thread#Thread(java.lang.ThreadGroup,%20java.lang.Runnable,%20java.lang.String,%20long)">Thread ctor</a> in Android SDK) allow the specification of a <strong>Stack Size</strong>. <br>Since this seems like a common pattern supported by (probably) all operating systems, I guessed that Rust standard library might also support the specification of a desired stack size value. It turned out to be true, as illustrated in the following program, using <a href="https://doc.rust-lang.org/std/thread/struct.Builder.html">std::thread::Builder</a>:</p><pre>fn main() {<br>    let mut builder = std::thread::Builder::new();<br>    builder = builder.stack_size(96 * 1024 * 1024);<br><br>    let t = builder.spawn(|| {<br>        let num1: usize = 17,141;<br>        let num2: usize = 4,540,827,649;<br>        println!(&quot;gcd of {}, {}&quot;, num1, num2);<br>        let gcd = gcd_recursive(num1, num2, (&amp;num1 as *const usize));<br>        println!(&quot;         = {}&quot;, gcd);<br>    }).unwrap();<br><br>    _ = t.join().unwrap();<br>}<br><br>fn gcd_recursive(num1: usize, num2: usize, addr: *const usize) -&gt; usize {<br>    if num1 == 0 { return num2; }<br>    if num2 == 0 { return num1; }<br>    if num1==num2 { return num1; }<br><br>    println!(&quot;estimated stack size: {:?} &quot;, (addr as usize) - (num1addr as usize));<br>    if num1 &gt; num2 { return gcd_recursive(num1 - num2, num2, addr); }<br>    else { return gcd_recursive(num1, num2 - num1, addr); }<br>}</pre><p>For my particular inputs, they finally worked when I set the stack size to a whooping 96 MiB.</p><p>So, the generic mitigation arrived at above is to see if you can find a way to hook into the code that creates threads in your problematic program, and if you can figure out a way to supply a reasonable larger stack size value there (FWIW, 96 MiB is probably not a reasonable value. If some code is demanding that large a thread stack, its owners probably should be questioned to understand what really is going on).</p><p>What if it’s not possible to hook into the code that creates threads in your program. For example, if the code is executed on the threads of the ThreadPool provided by .NET’s CLR, is there something that can be done. Well, probably yes. <br>On Windows, the <a href="https://learn.microsoft.com/en-us/cpp/build/reference/stack-stack-allocations?view=msvc-170">stack</a> compiler option’s documentation indicates that the <a href="https://learn.microsoft.com/en-us/cpp/build/reference/editbin-reference?view=msvc-170">EDITBIN </a>tool can be used to edit default stack size inside an executable file. On Linux, it appears that ulimit can be used to set stack sizes on a shell that’d apply to its child processes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc5c0b5f86f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualizing I/O Completion Ports based Async I/O on Windows]]></title>
            <link>https://medium.com/@rahulsingh_88457/visualizing-i-o-completion-ports-based-async-i-o-on-windows-8773d51ac19f?source=rss-5a893db7f56f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8773d51ac19f</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[diagrams]]></category>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[windows]]></category>
            <dc:creator><![CDATA[Rahul Singh]]></dc:creator>
            <pubDate>Wed, 06 Dec 2023 09:51:00 GMT</pubDate>
            <atom:updated>2023-12-06T09:51:00.617Z</atom:updated>
            <content:encoded><![CDATA[<p>A few months ago, I had read about Windows’ Asynchronous I/O mechanisms in Jeffrey Richter’s excellent textbook <a href="https://www.amazon.com/Windows-via-Jeffrey-M-Richter/dp/0735624240/ref=sr_1_1?crid=2G72ND1HEG0CY&amp;keywords=windows+via+c%2B%2B&amp;qid=1701851050&amp;sprefix=windows+via+%2Caps%2C145&amp;sr=8-1&amp;ufe=app_do%3Aamzn1.fos.17d9e15d-4e43-4581-b373-0e5c1a776d5d">Windows via C/C++</a>. Internalizing how the concept of I/O Completion Ports (IOCP) facilitates asynchronous I/O was a very rewarding learning experience for me. Jeffrey’s book goes into detailed descriptions of the APIs involved, which is a highly recommended read. I’ll try to illustrate a high level overview of how IOCP based async I/O works through a few diagrams in this article.</p><p>To setup some context on what is meant by async I/O — essentially the thread that issues an I/O operation does not stay blocked for the operation to finish. It issues the I/O operation and moves on to execute other code. It’s responsibility is to set up appropriate data structures so that when eventually the underlying I/O finishes, ‘some thread’ has the opportunity to execute code that needs to be executed upon the completion of that operation. <br>As an example, let’s quickly discussed highly used webservers. They read requests from users (I/O operation), determine what to do with it (computation and potentially more I/O to do database/disk read/write), and write responses back (I/O). If a thread blocks for each I/O operation in such a request-response cycle, then the web-server would need a large number of threads to provide satisfactory experience to a large number of concurrent users. A high number of threads is not efficient since threads are not very lightweight kernel objects — they have memory overhead and add to scheduling load on the operating system’s scheduler.<br>Async I/O allows for a design where a single thread does not need to follow through for the whole request response cycle. As soon as an I/O operation finishes, the Operating System wakes up “some thread” to do the computation work on the result of the I/O operation (for example, parsing of the user request to figure out what to do). This allows for interesting application architectures (and language/library features such as async/await syntax in languages such as C#) to realize such applications.</p><p>All right, so this article is about illustrating IOCP, which is one of the fundamental and probably most used async I/O enabling concepts in Windows. I will walk through typical actions taken by a thread that initiates an I/O operation and a special thread that waits for I/O operations to finish &amp; execute the operation’s follow up code. The decoupling is enabled by a special Kernel object in Windows called IOCP. Note and maybe take a moment to realize that this fundamental notion of decoupling the IO issuance from the follow-up (in terms of which thread needs to execute those) is what unlocks awesome features such as async/await the way they work in C#.</p><p>Diag 0 below shows the state of the program before the I/O operation is started. Something (could be a runtime like .NET’s CLR) has setup an IOCP object for the process and created these special IOCP threads that have blocked themselves on the IOCP by calling the <a href="https://learn.microsoft.com/en-us/windows/win32/api/ioapiset/nf-ioapiset-getqueuedcompletionstatus">GetQueuedCompletionStatus</a> function. This function does not return (hence blocks the calling thread) until the IOCP has something to serve. We’ll ignore the timeout options in this text (but they do add another dimension for the creative programmer).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*8sfKVIhctdZu22jy_CZciA.jpeg" /><figcaption>Diag 0: Initial State</figcaption></figure><p>The code running in the regular program thread (on the left) needs to do I/O at some point, and its technology of choice happens to be IOCP. For this, it allocates a special MyOVERLAPPED structure in the heap (Diag 1). MyOVERLAPPED extends <a href="https://learn.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-overlapped">Windows’ OVERLAPPED</a> structure, and let’s say includes a pointer to a function that should be invoked as a follow-up when the I/O operation finishes.<br>The regular thread also allocates a data buffer on the heap, since I/O generally involves moving data to or from outside the computer. This buffer holds such data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*JPybgrkqg0zUjsiCUrHmgQ.jpeg" /><figcaption>Diag 1: Allocation of OVERLAPPED structure and Data buffer on the heap.</figcaption></figure><p>These objects are allocated on the heap because the thread that needs to follow-through after the completion of the I/O operation would need access to these objects as well. It would, for example, need the function pointer so it can execute the follow-up code, and it would need to data buffer so that something can be done with that data.</p><p>Now the regular thread creates a device Kernel object — could be a file object, or a network socket object, or anything else that requires I/O and is supported by the computer where all this is happening — and obtains a HANDLE to it (Diag 2).<br>The device object creation APIs on Windows, typically have a way to specify that the handle that should be returned would be used for async I/O. This helps Windows not block threads calling I/O operations (read/write) on such device handles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*_6ParDvWK2wM0XPZghv6Eg.jpeg" /><figcaption>Diag 2: Device kernel object creation</figcaption></figure><p>The regular thread then registers the obtained device handle with the IOCP object using the <a href="https://learn.microsoft.com/en-us/windows/win32/fileio/createiocompletionport">CreateIoCompletionPort</a> api (Diag 3). On platforms like the .NET CLR, where the runtime manages and owns an IOCP, it provides its own wrapper APIs e.g. <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.threadpool.bindhandle?view=net-8.0">ThreadPool.BindHandle</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*xQYa7Dja2nWBQm_G6fJFSw.jpeg" /><figcaption>Diag 3: Registration of device handle with IOCP</figcaption></figure><p>At this point, the regular thread is ready to issue the I/O system call. It does so, while providing the address of the Overlapped and data buffer objects (Diag 4).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*tpOrRclb2kvMsmtsty5e4g.jpeg" /><figcaption>Diag 4: Async I/O call issuance by the regular thread.</figcaption></figure><p>Since the device handle was created with async flag set, the API returns without waiting for the underlying I/O operation to finish. So, the regular thread just moves on after issuing the API to execute any other code it may have in front of it — which might very well include a call to GetQueuedCompletionStatus to get blocked on the IOCP. It is completely up-to the creativity of the programmer on what kind of application architecture she wants to build.</p><p>At some point in future, the I/O operation finishes. Complex interactions happen between the device driver, hardware and other OS code including the use of hardware interrupts (device interrupts the cpu to say that it has some data and something needs to be done about it), finally leading to a notification delivered to the IOCP kernel object (Diag 5; such notifications can also be simulated using the <a href="https://learn.microsoft.com/en-us/windows/win32/fileio/postqueuedcompletionstatus">PostQueuedCompletionStatus </a>api from user mode code).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*1ncSq_DVsDyN7uOr0jV5fg.jpeg" /><figcaption>Diag 5: IOCP gets notified of completed I/O</figcaption></figure><p>When IOCP gets notified, it wakes up one of the threads blocking on it via the GetQueuedCompletionStatus function. The mechanism is that the GetQueuedCompletionStatus eventually returns for the blocked thread with heap addresses that are needed to perform the follow-up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*i__Hjg0A3eyuT9qDkb4CXQ.jpeg" /><figcaption>Diag 6: GetQueuedCompletionStatus returns and IOCP thread executes code</figcaption></figure><p>In our example, we had assumed that a function pointer is saved in the MyOverlapped object. This pointer can be used to execute the function’s code using the data buffer that might have relevant data to act as input to the function.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8773d51ac19f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualizing the toy Ref Counting Pointer]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@rahulsingh_88457/visualizing-the-toy-ref-counting-pointer-5731e3faca0a?source=rss-5a893db7f56f------2"><img src="https://cdn-images-1.medium.com/max/1017/1*Keaf8FoI77pvTjlZ2Nm0Dw.jpeg" width="1017"></a></p><p class="medium-feed-snippet">Visualization is a great technique to help internalize things. This is not just true for technical concepts in the software engineering&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@rahulsingh_88457/visualizing-the-toy-ref-counting-pointer-5731e3faca0a?source=rss-5a893db7f56f------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@rahulsingh_88457/visualizing-the-toy-ref-counting-pointer-5731e3faca0a?source=rss-5a893db7f56f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5731e3faca0a</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[diagrams]]></category>
            <category><![CDATA[pointers]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Rahul Singh]]></dc:creator>
            <pubDate>Tue, 05 Dec 2023 11:13:09 GMT</pubDate>
            <atom:updated>2023-12-05T11:14:17.901Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Implementing a toy Single Threaded Ref Counting Pointer in Rust]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">Rust standard library provides std::rc::Rc (and the accompanying std::rc::Weak). It is a single threaded reference counting pointer that&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@rahulsingh_88457/implementing-a-toy-single-threaded-ref-counting-pointer-in-rust-6d7aec102288?source=rss-5a893db7f56f------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@rahulsingh_88457/implementing-a-toy-single-threaded-ref-counting-pointer-in-rust-6d7aec102288?source=rss-5a893db7f56f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d7aec102288</guid>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[pointers]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Rahul Singh]]></dc:creator>
            <pubDate>Sun, 03 Dec 2023 11:38:42 GMT</pubDate>
            <atom:updated>2023-12-03T11:38:42.700Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Rust program to query IP Address data]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">For various reasons, I sometimes find myself looking for geolocation and/or ownership data of a public IP address. For example, when I get&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@rahulsingh_88457/rust-program-to-query-ip-address-data-a50f167efab5?source=rss-5a893db7f56f------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@rahulsingh_88457/rust-program-to-query-ip-address-data-a50f167efab5?source=rss-5a893db7f56f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a50f167efab5</guid>
            <category><![CDATA[network-programming]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[network-protocols]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tls]]></category>
            <dc:creator><![CDATA[Rahul Singh]]></dc:creator>
            <pubDate>Sun, 26 Nov 2023 10:44:23 GMT</pubDate>
            <atom:updated>2023-11-26T10:44:23.658Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Implementing a toy Semaphore in Rust]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">Rust standard library comes equipped with Mutex and Condition Variable primitives.</p><p class="medium-feed-link"><a href="https://medium.com/@rahulsingh_88457/implementing-a-toy-semaphore-in-rust-cca7ccaf00da?source=rss-5a893db7f56f------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@rahulsingh_88457/implementing-a-toy-semaphore-in-rust-cca7ccaf00da?source=rss-5a893db7f56f------2</link>
            <guid isPermaLink="false">https://medium.com/p/cca7ccaf00da</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[concurrent-programming]]></category>
            <dc:creator><![CDATA[Rahul Singh]]></dc:creator>
            <pubDate>Fri, 24 Nov 2023 11:33:31 GMT</pubDate>
            <atom:updated>2023-11-24T11:33:31.046Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[The Wonder of Computer Programming]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">Let&#x2019;s try to see a point of view on why might Computer Programming be so fascinating.</p><p class="medium-feed-link"><a href="https://medium.com/@rahulsingh_88457/the-wonder-of-computer-programming-f04e4295db3b?source=rss-5a893db7f56f------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@rahulsingh_88457/the-wonder-of-computer-programming-f04e4295db3b?source=rss-5a893db7f56f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f04e4295db3b</guid>
            <category><![CDATA[wonder]]></category>
            <category><![CDATA[fascinating]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[build]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Rahul Singh]]></dc:creator>
            <pubDate>Thu, 23 Nov 2023 04:39:09 GMT</pubDate>
            <atom:updated>2023-11-23T04:41:25.800Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Implementing a Simple ThreadPool in Rust]]></title>
            <link>https://medium.com/@rahulsingh_88457/implementing-a-simple-threadpool-in-rust-c9b99450f475?source=rss-5a893db7f56f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9b99450f475</guid>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[concurrent-programming]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Rahul Singh]]></dc:creator>
            <pubDate>Tue, 21 Nov 2023 08:34:42 GMT</pubDate>
            <atom:updated>2023-11-21T10:57:31.036Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I’ll describe the implementation of a toy ThreadPool program in Rust. I wrote it a few months ago while learning about some of the concurrency primitives provided by the Rust standard library.</p><h4>What and Why</h4><p>Let’s spend a few minutes to understand what a ThreadPool is and what its potential applications are. At a high level, a ThreadPool is a collection of Operating System threads that perform computation work posted to the ThreadPool. It allows its users to post work to it as the most basic operation. Why ThreadPools exist is fundamentally nothing different from the reason any software component that has ever existed, exists — to make things easier for someone else. In this case, the audience would be programmers who need to spread computation work on multiple threads, that can potentially execute on multiple processor cores concurrently. For example, programmers writing concurrent server applications or frameworks for such applications. Such programmers would many a times want to process client requests concurrently, so they can provide a good user experience to their own users (making things easier for them :)).</p><p>Now production grade ThreadPool implementations employ sophisticated algorithms. My goal in this article is just to talk through the implementation of the basic agenda of a ThreadPool — allow work units to be posted, and execute them concurrently — and doing so using the Rust Programming Language.</p><h4><strong>The Test</strong></h4><p>In the spirit of Test Driven Development methodology, let’s first take a look at a happy path test that we would like to see pass. It also demonstrates the API that MyThreadPool would provide to its users.</p><pre>use std::sync::{Mutex, Arc};<br><br>#[test]<br>fn the_test() {<br>    let outputs: Arc&lt;Mutex&lt;(usize, usize)&gt;&gt; <br>        = Arc::new(Mutex::new((0_usize, 0_usize))); // A. (counter, num_increments)<br><br>    let pool: MyThreadPool = MyThreadPool::new(5);       // B.<br>    let numloops: usize = 100000;<br>    let increment: usize = 10000;<br>    for _idx in 0..numloops {<br>        let outputs_copy = outputs.clone();<br>        pool.queue_work(Box::new(move || {               // C.<br>            for _i in 0..increment {<br>                let mut g = outputs_copy.lock().unwrap();<br>                (*g).0 += 1;<br>            }<br><br>            let mut g = outputs_copy.lock().unwrap();<br>            (*g).1 += 1;<br>        }));<br>    }<br><br>    let val: usize;<br>    loop {                                               // D.<br>        let g = outputs.lock().unwrap();<br>        if (*g).1 &lt; numloops {<br>            std::thread::yield_now();<br>        }<br>        else {<br>            val = (*g).0;<br>            break;<br>        }<br>    }<br><br>    assert_eq!(increment*numloops, val);               // E.<br>}</pre><p><strong>A:</strong> the test creates a Mutex protected Tuple of 2 numbers, which is allocated on the heap behind an Arc. Arc allows multiple threads to obtain shared references to the object it manages — the object being Mutex here. And Mutexes allow thread-safe read/write access to data through shared references (a.k.a. interior mutability in various Rust documentations). So, this setup allows us to read/write the Tuple in a thread-safe manner from multiple threads, which is something I need to happen by design in this test.</p><p><strong>B:</strong> A new MyThreadPool object is created. The number supplied to the method ‘new’ tells the ThreadPool to use 5 worker threads to process the work that will be enqueued to the pool. There are no Rust insights here, this is just how I happened to design the MyThreadPool api.</p><p><strong>C:</strong> Work is enqueued to the pool using its ‘queue_work’ method, by supplying it with a closure. The closure code runs on one of the threads owned by the pool. The Tuple of numbers introduced at ‘A’ is mutated inside the closure code. <br>The closure is Boxed because MyThreadPool’s API is designed that way. In MyThreadPool implementation, I keep track of these closures using dynamic trait objects (see MyThreadPool::work_queue definition under MyThreadPool struct below) added to a VecDeque. When I tried without using Box, the compiler complained that objects added to a VecDeque need to be Sized, which dynamic trait objects are not. So, I got around the problem by Boxing these objects.<br>I enjoy this aspect of Rust. It forces me to think about memory and object ownership, which forces clarity of thought and adds joy to programming work.</p><p><strong>D:</strong> After enqueuing all the work to the pool, the thread running the test itself loops until one of the data elements of the Tuple indicates that all the work is finished. This could have been implemented more efficiently, but I intended to keep the test code simple.<br><strong>E:</strong> Here, the other data element of the Tuple is compared to an expected value to ensure that things worked as expected.</p><h4><strong>The MyThreadPool struct</strong></h4><p>The pieces of data that need to be tracked by MythreadPool are dynamically sized queue of work items (enqueued closures), the worker thread handles, and some synchronization data so that threads can coordinate their activity.</p><pre>use std::{collections::VecDeque, sync::{Mutex, Arc, Condvar}, thread::JoinHandle};<br><br>pub struct MyThreadPool {<br>    work_queue: Arc&lt;Mutex&lt;VecDeque&lt;Box&lt;dyn Send + FnOnce()-&gt;()&gt;&gt;&gt;&gt;, // A.<br>    join_handles: Vec&lt;Option&lt;JoinHandle&lt;()&gt;&gt;&gt;,              // B.<br><br>    work_item_count: Arc&lt;Mutex&lt;i32&gt;&gt;, // C. // -1 implies that threads should wind down.<br>    signal: Arc&lt;Condvar&gt; // D.<br>}</pre><p><strong>A:</strong> work_queue is the heap allocated queue of closures that represent the work that the MyThreadPool worker threads have to perform. A VecDeque is used because it provides push_front and pop_back APIs, allowing it to be used as a FIFO queue. Mutex and Arc are used for the same reasons as mentioned for the test code’s Tuple data above — the queue would be read and written to from multiple threads, so a setup is needed where Rust allows that to happen in a safe way.</p><p><strong>B:</strong> join_handles are the handles to worker threads. They are kept so that <a href="https://doc.rust-lang.org/std/thread/struct.JoinHandle.html#method.join">join()</a> can be called on them when MyThreadPool is destroyed/dropped. The join_handles vector is only going to be accessed from the thread that creates and destroys the pool (it will be clear from implementations shown below). In the case of test code above, it is the thread that executes the test code.</p><p><strong>C:</strong> work_item_count keeps the count of work items in the work_queue. It is also used to indicate to worker threads when a MyThreadPool object is being dropped. The worker threads use the signal as a cue to wind themselves down. Arc and Mutex are used for similar multi-threaded access reasons as mentioned before.</p><p><strong>D:</strong> signal is a Condition Variable used by the worker threads to wait This helps not wasting cpu cycles when there is no work queued to the pool (remember that the test code up above is written to actually do that opposite thing, loop and waste cpu cycles. I suppose I cared less about the test code when I did this work :)). It is managed by an Arc since all the pool threads will need to execute wait operation on it.</p><h4>Drop implementation for MyThreadPool</h4><pre>impl Drop for MyThreadPool {<br>    fn drop(&amp;mut self) {<br>        {                                    // A.<br>            let mut g = self.work_item_count.lock().unwrap();<br>            (*g) = -1;                       // B.<br>            self.signal.notify_all();<br>        }<br><br>        for h in &amp;mut self.join_handles {      // C.<br>            let x: JoinHandle&lt;()&gt; = std::mem::replace(h, None).unwrap();<br>            _ = x.join();<br>        }<br>    }<br>}</pre><p>When a Type implements the Drop trait, the Rust compiler generates code for its drop method to be called when it determines that an object of the Type can be safely dropped. For example, in the test code up-above, it might happen to the MyThreadPool object between the loops containing points ‘C’ and ‘D’. <br>For MyThreadPool, I wanted to ensure that all pending work-items get processed and worker threads predictably exit before drop finishes.</p><p>The drop implementation above does arranges for any sleeping worker threads to wake up while signaling to them that they should wind-down (‘<strong>B</strong>’ in the code fragment above). The scope introduced at ‘<strong>A</strong>’ in the fragment above is to ensure that the work_item_count Mutex gets unlocked before ‘<strong>C</strong>’, so that worker threads can acquire it to execute their logic. The loop at point ‘<strong>C</strong>’ invokes join on the JoinHandles of each of the worker threads to ensure their exit.</p><h4>MyThreadPool implementation</h4><pre>impl MyThreadPool {<br>    pub fn new(n: usize) -&gt; Self {<br>        let workq = Arc::new(Mutex::new(VecDeque::new()));<br>        let itemcount = Arc::new(Mutex::new(0_i32));<br>        let signal = Arc::new(Condvar::new());<br><br>        let mut pool: ThreadPool = ThreadPool {        // A.<br>            work_queue: workq.clone(), <br>            join_handles: Vec::with_capacity(n),<br>            work_item_count: itemcount.clone(),<br>            signal: signal.clone()<br>        };<br><br>        for _idx in 0..n {<br>            let wq = workq.clone();<br>            let itmcnt = itemcount.clone();<br>            let sig = signal.clone();<br><br>            let h: JoinHandle&lt;()&gt; = std::thread::spawn(move || {    // B.<br>                loop {<br>                    let shouldbreak: bool = {<br>                        let mut g = itmcnt.lock().unwrap();<br>                        while *g == 0 {<br>                            g = sig.wait(g).unwrap();     // C.<br>                            if (*g) == 0 {<br>                                println!(&quot;{:?} Spurious Wakeup.&quot;, std::thread::current().id());<br>                            }<br>                        }<br><br>                        if (*g) &gt; 0 {            // E.<br>                            (*g) -= 1;<br>                        }<br><br>                        // F.<br>                        (*g) == -1     <br>                    };<br><br>                    if shouldbreak {              // G.<br>                        break;<br>                    }<br><br>                    let workfnopt = {<br>                        let mut g = wq.lock().unwrap();<br>                        g.pop_back()<br>                    };<br><br>                    if let Some(workfn) = workfnopt {<br>                        workfn();                          // H.<br>                    }<br>                    else {<br>                        println!(&quot;Worker {:?} SOMETHING IS WRONG!&quot;, std::thread::current().id());<br>                    }<br>                }<br><br>                // Wind-down loop<br>                loop {                      // I.<br>                    let workfnopt = {<br>                        let mut g = wq.lock().unwrap();<br>                        g.pop_back()<br>                    };<br><br>                    if let Some(workfn) = workfnopt {<br>                        println!(&quot;Worker {:?} Cleanup. Executing work.&quot;, std::thread::current().id());<br>                        workfn();<br>                    }<br>                    else {<br>                        break;<br>                    }<br>                }<br>            });<br><br>            pool.join_handles.push(Some(h));    // J.<br>        }<br><br>        pool<br>    }<br><br>    pub fn queue_work(&amp;self, work: Box&lt;dyn Send + FnOnce() -&gt; ()&gt;) {  // K.<br>        let mut g = self.work_item_count.lock().unwrap();<br>        assert!((*g) &gt;= 0);<br>        (*g) += 1;<br>        let mut guard = self.work_queue.lock().unwrap();<br>        guard.push_front(work);<br>        self.signal.notify_one();     // L.<br>    }<br>}</pre><p>The method ‘new()’ setup up a new MyThreadPool object (‘<strong>A</strong>’). It spawns off all the worker threads, and returns the ownership of the created pool object to its caller so that it can queue work to it (or drop it, as it sees fit).</p><p><strong>B:</strong> std::thread::spawn from the Rust standard library is used to spawn off worker threads. Interfacing with the underlying Operating System’s Thread management APIs is left to this library. A closure is supplied to the std::thread::spawn API as the entry point code for the spawned thread.</p><p>Inside the worker thread closure function, the code block used to compute the value of the boolean ‘shouldbreak’ returns false if there is work it can dequeue from work_queue, or if work_item_count has been set to -1 (as a result of drop being called on the pool) indicating that the thread should wind down. ‘<strong>C</strong>’ is where blocking on the condition variable ‘signal’ happens.</p><p><strong>E:</strong> work_item_count is decremented. You should analyze carefully and convince yourself that if this decrement is executed, then this worker thread is guaranteed to find a work item to dequeue from work_queue. Kindly leave a comment if you reach a conviction that this is not true, for my own learning as well.</p><p><strong>F:</strong> The value of ‘shouldbreak’ is computed as true only if the value of work_item_count is found to be -1, which indicates wind-down signal from drop. Otherwise, ‘shouldbreak’ is false indicating to the worker thread that it can expect to dequeue a work item, process it, and go back to waiting on the Condition Variable (by looping around to recompute ‘shouldbreak’).<br><strong>G:</strong> This is break out of the main processing loop for the worker thread, in case shouldbreak was computed to be true.<br><strong>H:</strong> Here, the dequeued work (closure) executes on the worker thread. Note that this code is not written to accommodate for situations such as panics in the code provided by users.<br><strong>I:</strong> This is the wind-down loop for worker threads. The threads execute the remaining enqueued work items as quickly as possible before exiting.</p><p><strong>J:</strong> Note that this code is outside the closure provided to worker threads. This is the thread where MyThreadPool::new() method is executing after calling the std::thread::spawn function. The JoinHandle returned by std::thread::spawn is added to the pool’s join_handles vector, and the pool is returned to the caller.</p><p><strong>K:</strong> This is the queue_work method that users can call on the pool, as the test code above does a hundred thousand times. It adds the closure given by the caller to the pool before (<strong>L</strong>) notifying the condition variable to wake one of the worker threads, if necessary.</p><p>The various println! statements that you see in the code were added while I was debugging a runtime bug in the code. This code was implemented many months ago, so I am unable to recall their details. They would have made a couple of potentially interesting short paragraphs as well if only I could remember them. What I do remember though is that there was just a single bug, which in my humble opinion, is a testament to how much easier it is to implement correct code with Rust since its compile time rules prevent mistakes upfront.<br>Of course, this is just toy programming lacking extensive testing. So there may be bugs that I didn’t run into at all. I’d love to engage with any such analysis in the comments.</p><p>Please consider helping me improve my writing skills by leaving any feedback you may have. And of course, any comments or questions on the actual content are welcome as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9b99450f475" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Perspectives on Final of ODI Cricket World Cup 2023]]></title>
            <link>https://medium.com/@rahulsingh_88457/perspectives-on-final-of-odi-cricket-world-cup-2023-8b7be509570f?source=rss-5a893db7f56f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b7be509570f</guid>
            <category><![CDATA[cricket-world-cup]]></category>
            <category><![CDATA[cricket]]></category>
            <category><![CDATA[sports]]></category>
            <dc:creator><![CDATA[Rahul Singh]]></dc:creator>
            <pubDate>Mon, 20 Nov 2023 06:23:43 GMT</pubDate>
            <atom:updated>2023-11-20T06:59:06.208Z</atom:updated>
            <content:encoded><![CDATA[<h3>Perspectives on the Final of ODI Cricket World Cup 2023</h3><p>Australia won the ODI Cricket World Cup 2023 by defeating India in a largely 1-sided game, in <a href="https://www.espncricinfo.com/series/icc-cricket-world-cup-2023-24-1367856/india-vs-australia-final-1384439/full-scorecard">the Final</a> a few hours ago. I watched the whole game as a Team India supporter, and wanted to write down my perspectives on certain stages of the game. By the way, if you wish to read similar analytical sentiments from another but established writer, I’d recommend <a href="https://www.espncricinfo.com/story/icc-cricket-world-cup-2023-final-india-lost-to-the-conditions-but-could-they-have-been-braver-with-the-bat-1409782">this article</a> by Siddarth Monga.</p><p><strong>Toss</strong></p><p>Indian captain Rohit Sharma said after losing the toss and being put in to bat first, that he would have chosen to bat first anyway. I have really admired Rohit’s confidence and attitude as a captain during this whole tournament, but I couldn’t help but feel that he didn’t mean what he said here.</p><p>The pitch looked very slow and horrible to bat on unless either moisture helped quicken it up, or opposition bowlers bowled freebies. It’s hard to imagine a cricketing world where battle hardened Australians would do the latter, and only the team batting second under floodlights would enjoy the effects of the former.</p><p>Ahmedabad, the city where the Final was played, had seen plenty of evening dew in the days leading up-to the game, leaving the team batting second overwhelming favorites on this pitch. Rohit probably did not want to concede the mental edge even before the actual play had begun, but the difference in conditions was expected to be so huge that he couldn’t really hide the disappointment — well it appeared that way to me at least.</p><p><strong>Overs 1-10, First Inning</strong></p><p>While Rohit must have been disappointed losing the toss, and under immense pressure in front of more than a 100,000 spectators, but he once again produced a scintillating counter attack in the first powerplay of Indian inning. He batted proactively, put bowlers off their lengths and created an environment where his team-mates could feel lesser pressure.</p><p>The key events among the ones that went against India in that powerplay were the wickets of Shubhman Gill and Shreyas Iyer. <br>Shubhman Gill is a versatile stroke player who also runs extremely well between the wickets; a notable contribution from his bat would have been critical, specially after the start Rohit had provided. <br>More importantly though, the fact that Shreyas Iyer couldn’t face Australian spin bowlers later in the inning, was a huge disadvantage. He is arguably the best player of spin bowling in world cricket at the moment, well at least in my opinion, and could have produced frequent boundaries in the very tough batting conditions that were to follow. The legendary Ricky Ponting said at some point in the on-air commentary that margin of error for Australian bowlers was very big in the first inning; I have a strong feeling that Shreyas has the game to reduce that margin for spin bowlers even in such tough conditions.</p><p><strong>Overs 10-20, India inning</strong></p><p>KL Rahul understandably focused a lot on survival during this period. The plan may have been that India had the run-rate buffer out of the first 10 overs, so could play out a few overs with safety first approach, before milking singles became easier for set batsmen, followed by periods of acceleration towards the end. However, because of how slow the pitch had become and how rather easily the Australian bowlers were able to exploit it, it became increasingly clear during this period that milking singles/doubles was not going to become easy, and the chance of being able to accelerate was next to none.</p><p><strong>Over 20-50, India inning</strong></p><p>This was the most painful period to watch as a Team India supporter. There was a realization that unless an Australian bowler magically has a meltdown in front of the full house Indian support, a phase of acceleration was never going to arrive. Maneuvering the ball in the gaps was not looking risk free and the pitch was not allowing any kind of shots where trusting its pace is the fundamental that a batter relies on to execute a powerful shot: no on the up drives, no pick ups, no on drives or flicks off non half volleys.</p><p>Viral Kohli got out to an innocuous delivery playing an innocuous dab to third man, something that happens more often in conditions like these where batsmen never feel settled. Even part time bowlers like Mitchell Marsh and Travis Head could not be put under pressure. And then to top it all off, the ball started reverse-swinging at some point after 30 overs accounting for the fall of much crucial wickets of Ravindra Jadeja and KL Rahul, along-with a couple of tail-enders.</p><p>A score of 240 in such tough batting conditions was good effort from Team India, with elements of mental bravery and hard-work displayed by different individuals, however frustrating it may have been to watch. Australians did not give a free inch, and India batters squeezed as much as they could under the conditions. The only hope for Indian fans now was that conditions do not change in the second inning, a futile hope; and that the Indian bowlers apply relentless pressure while Australians allow it without punching back, another one not to be.</p><p><strong>Overs 1-10, Australia Inning</strong></p><p>After 40 overs of agony, this should have been a fun period to watch for Indian fans. The new ball jagged around considerably, which Jasprit Bumrah and Mohammad Shami even found somewhat hard to control conceding over 10 runs in extras. But they did bowl for wickets, and managed to pick 3 of them. Australian batters also batted with aggressive intent, again showing no signs of feeling any pressure in front of a massive Indian crowd.</p><p>What was clear in this period though is that the ball was skidding off the pitch, and that once the sideways movement stopped, batting would become much easier; just the exact opposite feeling at similar stage in the first inning.</p><p><strong>Overs 11-end, Australia Inning</strong></p><p>This period started with Indian spinners, Ravindra Jadeja and Kuldeep Yadav, coming onto the attack. There was anticipation that they might produce some magic deliveries, and some deliveries did turn for them as well. But only very few deliveries were such, and they did not produce wickets.<br>For the most part, the ease with which Travis Head played them, pretty much sealed the fate of the game. The ball hardly ever hit anything but the middle of his bat, and he played with such freedom and nonchalance, that it stopped mattering which result the game was headed towards. He attacked, defended, maneuvered, drove, cut, pulled and slogged at will, playing a truly memorable knock of the ODI format full of crunching sounds of the ball hitting the that in front of a 100,000 plus stunned spectators. Head is still only 29 years old, and is arguably the most exciting player to watch in Test and ODI formats in the coming 5–6 years, assuming he stays motivated and high quality international cricket tournaments continue to get organized in these formats.</p><p>Learning and practicing the skill of writing is a goal of mine behind writing articles on Medium. I’d highly appreciate any feedback from readers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b7be509570f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing a ‘Guess the Number’ game application using Tauri]]></title>
            <link>https://medium.com/@rahulsingh_88457/developing-a-guess-the-number-game-application-using-tauri-0eadd28f7cb8?source=rss-5a893db7f56f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0eadd28f7cb8</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tauri]]></category>
            <category><![CDATA[writing]]></category>
            <dc:creator><![CDATA[Rahul Singh]]></dc:creator>
            <pubDate>Sat, 18 Nov 2023 07:12:02 GMT</pubDate>
            <atom:updated>2023-11-18T07:12:02.185Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently read <a href="https://blog.developerpurpose.com/a-great-first-project-random-number-guesser-f051847bc072">an article </a>stating that a Random Number Guesser was a good first project when learning a new programming technology. It seemed like a good idea to me as well.</p><p>In this article, I’ll share my experience of creating such an application using <a href="https://tauri.app/">Tauri</a>. The article should provide a beginner’s perspective, relatively speaking, since I am not much experienced in any of the technologies involved, namely, Rust, Html, JavaScript and GUI development.</p><p><strong>Prerequisites<br></strong>I have been writing simple programs in Rust for some time, so I had Rust toolchain already setup on my Windows 11 computer. Tauri website has the steps documented <a href="https://tauri.app/v1/guides/getting-started/prerequisites/">here</a>. Main idea is to ensure that the relevant Windows libraries and Rust are installed.</p><p>Tauri’s documentation mentions that the “front-end” of the application can be developed using many popular frameworks, such as, React. However, since I do not have any development experience with such technologies, I wanted to keep things as simple as possible, in order to gain as much basic understanding as possible. I followed the steps documented in the <a href="https://tauri.app/v1/guides/getting-started/setup/html-css-js">simplest Tauri tutorial</a> to see how a Hello World app can be developed using just Rust, Html and JavaScript. This article was very useful for me to see what the basic tooling and project structure looks like.</p><p>I am attaching a picture of what the project structure looks for the application like on VS Code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q5wFC_ZrAcAnVhGUkdUgdA.png" /></figure><p><strong>Application UX</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LM_i5EmDJUjd6SAeSn_KlQ.png" /><figcaption>Application UI (the command prompt in background is showing activity in the Rust backend process)</figcaption></figure><p>The diagram above shows an application run. It’s workings should hopefully be self evident. There is an input box where user would enter their guess and click Submit. They get a response whether the guess is correct or too low or too high or invalid. The operation history list on the right lets the user see their actions. Lastly, there is a Reset button using which user can restart the game.</p><p>Let’s look at the source code for various pieces now.</p><p><strong>Declarative GUI using HTML</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>    &lt;head&gt;<br>        &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>        &lt;title&gt;Random Number Guesser&lt;/title&gt;<br>    &lt;/head&gt;<br><br>    &lt;body&gt;<br>        &lt;div style=&quot;display: grid; grid-template-columns: 1fr 1fr;&quot;&gt;<br>            &lt;div&gt;<br>                &lt;h3&gt;Enter your guess&lt;/h3&gt;<br>                &lt;div&gt;<br>                    &lt;input type=&quot;text&quot; id=&quot;the-guess&quot; /&gt;<br>                    &lt;button id=&quot;submit-btn&quot;&gt;Submit&lt;/button&gt;<br>                &lt;/div&gt;<br><br>                &lt;h3/&gt;<br>                &lt;div&gt;<br>                    &lt;label&gt;Response: &lt;/label&gt;<br>                    &lt;label id=&quot;response&quot;&gt;Enter a guess&lt;/label&gt;<br>                &lt;/div&gt;<br><br>                &lt;h3/&gt;<br>                &lt;button id=&quot;Reset&quot;&gt;Reset&lt;/button&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;<br>                &lt;h3&gt;Operation history&lt;/h3&gt;<br>                &lt;div&gt;<br>                    &lt;ul id=&quot;history&quot; style=&quot;list-style-type: none; font-weight: normal; font-size: 14px;&quot; /&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;script src=&quot;appcode.js&quot; /&gt;<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><p>I am sure there are better, more maintainable ways to declare the GUI elements using HTML and CSS. For this simple toy application though, above was sufficient.<br>Some of the Google searches I had to do to land on above code are: “side by side divs in html”, “html list javascript”, “html list css” etc.</p><p><strong>Frontend JavaScript Logic</strong></p><pre><br>const inputBox = document.querySelector(&#39;#the-guess&#39;);<br>const submitButton = document.querySelector(&#39;#submit-btn&#39;);<br>const responseLabel = document.querySelector(&#39;#response&#39;);<br>const resetButton = document.querySelector(&#39;#Reset&#39;);<br>const historyList = document.querySelector(&#39;#history&#39;)<br><br>submitButton.addEventListener(&#39;click&#39;, () =&gt; {<br>    //responseLabel.textContent = &#39;Submit button clicked with : &#39; + inputBox.value;<br>    const val = inputBox.value;<br>    window.__TAURI__.invoke(&#39;process_guess&#39;, {<br>        gsstr: val<br>    })<br>    .then(response =&gt; { <br>        responseLabel.textContent = response;<br><br>        const h = historyList.innerHTML;<br>        const newelement = `&lt;li&gt;${val} - ${response}&lt;/li&gt;`;<br>        historyList.innerHTML = newelement + h;<br>    });<br>});<br><br>resetButton.addEventListener(&#39;click&#39;, () =&gt; {<br>    window.__TAURI__.invoke(&#39;reset_state&#39;).then(() =&gt; {<br>        responseLabel.textContent = &#39;Enter a guess&#39;;<br>        inputBox.value = &#39;&#39;;<br><br>        historyList.innerHTML = &#39;&#39;;<br>    });<br>});</pre><p>The “window.__TAURI__invoke(…” stuff in this JavaScript code are APIs provided by Tauri to invoke Rust code (Rust code will be showed soon). The Rust code runs in a separate process than the process hosting the GUI and these APIs <a href="https://tauri.app/v1/references/architecture/inter-process-communication/">IPC</a> facilitate IPC between the two processes to simulate a web application like request-response pattern. These seem to be called ‘Commands’ in Tauri documentation. ‘Events’ seems to be another kind of IPC pattern supported by Tauri, but they are not used in my application.<br>Other than that, the JavaScript logic is quite simple. Submit button’s click results in the guess value sent back to Rust backend (invocation of a function called ‘process_guess’ there), and the response is displayed as well as pre-pended to the Operation history list. Clicking Reset button results in invocation of ‘reset_state’ function in the Rust backend while also resetting the various GUI elements.</p><blockquote>This application didn’t really need Rust invocation since the state could have been managed in the Frontend itself. But the idea here was to try different things.</blockquote><p><strong>Rust Backend Logic</strong></p><pre>// Prevents additional console window on Windows in release, DO NOT REMOVE!!<br>#![cfg_attr(not(debug_assertions), windows_subsystem = &quot;windows&quot;)]<br><br>use std::sync::atomic::{AtomicUsize, Ordering};<br><br>fn main() {<br>    let state = AtomicUsize::new(100 + (rand::random::&lt;usize&gt;() % 400));<br>    println!(&quot;State Generated: {}&quot;, state.load(Ordering::SeqCst));<br><br>    tauri::Builder::default()<br>        .manage(state)<br>        .invoke_handler(tauri::generate_handler![reset_state, process_guess])<br>        .run(tauri::generate_context!())<br>        .expect(&quot;error while running tauri application&quot;);<br>}<br><br>#[tauri::command]<br>fn reset_state(state: tauri::State&lt;&#39;_, AtomicUsize&gt;) {<br>    let currentval = state.load(Ordering::SeqCst);<br>    let newval = 100 + (rand::random::&lt;usize&gt;() % 400);<br>    state.store(newval, Ordering::SeqCst);<br>    println!(&quot;State changed from {} to {}&quot;, currentval, newval);<br>}<br><br>#[tauri::command]<br>fn process_guess(gsstr: String, state: tauri::State&lt;&#39;_, AtomicUsize&gt;) -&gt; String {<br>    println!(&quot;Received guess string: {}&quot;, gsstr);<br>    let guess_val_res = gsstr.parse::&lt;usize&gt;();<br>    let guess_val = match guess_val_res {<br>        Ok(v) =&gt; v,<br>        Err(e) =&gt; return e.to_string(),<br>    };<br><br>    let state_value = state.load(Ordering::SeqCst);<br>    if guess_val == state_value {<br>        return &quot;CORRECT !!!&quot;.to_string();<br>    }<br>    else if guess_val &lt; state_value {<br>        return &quot;Too Low&quot;.to_string();<br>    }<br>    else {<br>        return &quot;Too High&quot;.to_string();<br>    }<br>}</pre><p>The ‘reset_state’ and ‘process_guess’ functions are the ‘APIs’ that the JavaScript logic in the Frontend is invoking.</p><p>“reset_state” generates a new random number (using the rand crate) and stores it in the “state” managed by Tauri. The reason the state being managed is declared as an AtomicUsize as opposed to a simple usize is because or Rust compiler’s ownership rules. From compiler’s perspective, it cannot be deduced where the state data will be accessed from, hence Rust’s Interior Mutability is the only way to access this data from different functions. AtomicUsize allows interior mutability — there are other ways to achieve the same, but in this application, I just used AtomicUsize.</p><p>“process_guess” processes the user’s input and sends back a response. The response could be a parsing error (in case the user’s input cannot be parsed to a Rust’s usize Type), or a string indicating to the user how their guess compares to the state. In a better API design, we’d ideally return different kinds of responses to assist better programmability of the client code, but here I intend to keep things simple.</p><p>“main” function sets up Tauri using the boilerplate generated by the project generation tools. Code added by me in there is state generation and registration, and invoke_handler invocation to inform Tauri what functions it should expose to Frontend.</p><p>My primary goal for writing this article is to learn the skill of writing. I’d appreciate any feedback from readers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0eadd28f7cb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>