<?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 Ameya Kore on Medium]]></title>
        <description><![CDATA[Stories by Ameya Kore on Medium]]></description>
        <link>https://medium.com/@kore.ameya?source=rss-406b2d568b37------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*evJ1h_RgaP_DHVdb</url>
            <title>Stories by Ameya Kore on Medium</title>
            <link>https://medium.com/@kore.ameya?source=rss-406b2d568b37------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 09:02:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kore.ameya/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[From Rust to Riches: Decoding Finite State Machines]]></title>
            <link>https://medium.com/gdg-vit/implementing-state-machines-in-rust-designing-uno-efba7288a379?source=rss-406b2d568b37------2</link>
            <guid isPermaLink="false">https://medium.com/p/efba7288a379</guid>
            <category><![CDATA[state-machine]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[finite-state-machine]]></category>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[webassembly-weekly]]></category>
            <dc:creator><![CDATA[Ameya Kore]]></dc:creator>
            <pubDate>Fri, 06 Jan 2023 14:48:33 GMT</pubDate>
            <atom:updated>2023-01-19T18:14:53.638Z</atom:updated>
            <content:encoded><![CDATA[<p><em>We will explore how to implement a Finite State Machine using Rust by designing UNO</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*02XBuaZ0b_rwUeaysr_jVw.png" /></figure><h3>Why?</h3><p>State machines find their uses in variety of fields such as pattern matching, handshaking protocols and games. Basically, any task which requires a strict and sequential flow of interactions.</p><p>From a conceptual perspective, state machines can help you break down complex problems to simple states. You can analyse these simple states one by one easily. This will help you gain better understanding of larger systems.</p><p>From a development perspective, state machines are an important tool which can bring structure to an otherwise ugly piece of code. This improves readability and maintainability of any software.</p><p>Rust being a low-level language finds it’s use everywhere. Here, we will see how using rust-like constructs(<a href="https://doc.rust-lang.org/book/ch18-00-patterns.html">exhaustive pattern matching</a>, <a href="https://doc.rust-lang.org/book/ch10-02-traits.html">traits</a> and <a href="https://doc.rust-lang.org/book/ch06-00-enums.html">enums</a> to name a few) help in a clear and a concise implementation.</p><p>Besides, everyone loves games, right? So let’s write a game today. But before all that… let’s start from the beginning</p><h3>What is a State Machine?</h3><p>A state machine is a construct which manages state.</p><p>Simple. Right?</p><p>A state machine is any machine which carries a state and reacts to inputs. When you provide this machine with an input, it gives you an output. The given input may also change it’s internal state.</p><p>Let’s take an example of a standard ceiling fan controlled by a switch. The fan has 2 state, ON and OFF. If you turn the switch on, the fan starts rotating. If you turn the switch off, the fan stops rotating.</p><p>Here, the ceiling fan is a state machine. It carries an inherent state(either it’s rotating or it’s not) and can be given an input(the switch that controls it). Turning the switch on is the same as providing an input to the ceiling fan, if it’s rotating, it changes nothing. If it’s not rotating, the ceiling fan starts to rotate(this is a change in state).</p><figure><img alt="A State Diagram describing a ceiling fan" src="https://cdn-images-1.medium.com/max/923/1*wzAjDPA0Q0gQD9V0dea65Q.jpeg" /><figcaption>A State Diagram of a Ceiling Fan</figcaption></figure><p>The above diagram describes all the states and the inputs of the ceiling fan. Since the number of states a ceiling fan can have is <strong>finite</strong>, it is a <em>Finite State Machine.</em></p><h3>Implementing a State Machine in Rust</h3><p>We can define a state using traits.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72d10537f3ea4e3768feaa68ab53befe/href">https://medium.com/media/72d10537f3ea4e3768feaa68ab53befe/href</a></iframe><p>The state trait defines 3 functions and 3 <a href="https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#specifying-placeholder-types-in-trait-definitions-with-associated-types">associated types</a>. The associated types describe the input, output and the error type associated with a particular state type.</p><p>There are three functions defined on this trait, validate, compute and transition.</p><ol><li>validate(input): This function tests whether the current state has a valid transition with the given input. If no transition exists then an error is returned</li><li>compute(input): This function returns an output, if any, associated with the current state and input.</li><li>transition(input): this function actually mutates the state according to the given input</li></ol><p>These function all act together when the state machine encounters an input. We will also write a new function next which glues the previous three functions together.</p><p>Here’s the updated definition of the state trait with the next function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3768c96d38452f7e34d55996f27f92b0/href">https://medium.com/media/3768c96d38452f7e34d55996f27f92b0/href</a></iframe><p>The next function first validates the given input against the current state. If an error is encountered, it is forwarded back to the caller, otherwise we compute an output and transition the state. The computed output is returned to the caller.</p><p>There are two important points to note in this particular technique of implementing state machines.</p><ol><li>When we transition state, we only mutate the current state instead of creating a new state. This is useful if changing state only modifies certain properties of an object. Otherwise if your state is identifiable by only it’s value and nothing else, (like an enum) you have to use a wrapper type which contains the said enum. In this case it is useful to return a new state in the transition function.</li><li>We have separated the functions which check the validity of the input, compute the output and transition states. This leads to cleaner architecture where one function does only one task. We will see the benefits of this in the example below.</li></ol><p>That’s it! That’s all that we need to implement an application by modelling it as a state machine.</p><h3>UNO</h3><p>Now you may be wondering, why UNO? Well, because:</p><ol><li>At it’s core, it is simple to model using state machines.</li><li>Using state machines leads to a cleaner architecture vs other modelling techniques.</li></ol><p>We will be implementing a small subset of UNO, without the special cards, such as reverse, skip, draw 2, draw 4s or wild. That implementation will be trivial and left as an exercise to the reader.</p><p>Constructing a state diagram for our UNO:</p><figure><img alt="A State diagram detailing the discard, no card and draw events." src="https://cdn-images-1.medium.com/max/1010/1*tG6ePzQDXeu7m1XopNT4TQ.jpeg" /><figcaption>A state diagram for UNO</figcaption></figure><p>But this diagram is not complete, UNO is a multiplayer game, we also need to deal with different players sending events. Here’s the updated diagram,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8gk_zYCMlPQnHxUoHKIhwA.jpeg" /><figcaption>Updated state diagram</figcaption></figure><p>The updated diagram is simple because we do not deal with multiple players interacting during any single player’s turn.</p><p>Now constructing the required <a href="https://doc.rust-lang.org/book/ch05-01-defining-structs.html?highlight=structs#defining-and-instantiating-structs">structures</a> and enums to represent all the entities in a game of UNO.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a4bd99e8b988d11a3170ac79491ab93/href">https://medium.com/media/0a4bd99e8b988d11a3170ac79491ab93/href</a></iframe><p>A couple of things to note in this implementation:</p><p>Firstly, we treat inputs as events. Our game engine reacts to events(inputs) to change it’s internal properties(state).</p><p>Thus, using a state machine means we have naturally transitioned into an event-driven architecture.</p><p>Secondly, we aren’t tracking the current number of cards each player has. That is why we haven’t kept 2 events:</p><ol><li>Uno!: The phrase you’re supposed to shout when you’re one card away from victory.</li><li>Caught: The corresponding phrase you’re supposed to shout when someone doesn’t say Uno in time.</li></ol><p>As you can see from the earlier code snippet, UnoGameState is our state struct. It carries a field called state_type which defines which of the state type it is in. The other important entity is UnoOutput which has one member which is returned when a card is drawn.</p><p>Implementing State for UnoGameState leads us to this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a80928d0e32e2c51058ee328ce6b733/href">https://medium.com/media/1a80928d0e32e2c51058ee328ce6b733/href</a></iframe><p>Most of the implementation functions are self explanatory. Only the Draw Event generates an output. An interesting behaviour is that player turn is not moved after a draw event. This means that the player must keep drawing until he finds a valid card to play. This behaviour is intended and to change it involves the use of more states.</p><p>Note: We used the <a href="https://crates.io/crates/rand">rand</a> <a href="https://doc.rust-lang.org/book/ch07-01-packages-and-crates.html?highlight=crates#packages-and-crates">crate</a> to randomise the input for the draw function.</p><p>(Hint: We can introduce a new state called “WaitingForDiscardAfterDraw” if we want to allow the player to pass his turn after drawing a card. This state can have a skip event associated with it which transitions to the “WaitingForDiscard” state.)</p><h3>Testing our implementation</h3><p>We can manually test our implementation using the following trigger events and states given below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d07d8f9a85abf553a78c558350081427/href">https://medium.com/media/d07d8f9a85abf553a78c558350081427/href</a></iframe><p>Running this will give us the expected output</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e77a3e3acfbcbcd3d362a364693be99/href">https://medium.com/media/5e77a3e3acfbcbcd3d362a364693be99/href</a></iframe><p>The entire code base for this tutorial is available <a href="http://github.com/fa993/uno-fsm">here</a>.</p><p>And if you want to see this code in action, please visit <a href="https://fa993.github.io/uno-fsm/">this site</a> to interact with the above state machine. That site hosts the above code <a href="https://rustwasm.github.io/docs/book/">compiled</a> to <a href="https://webassembly.org/">WebAssembly</a>.</p><p>Feel free to connect with me on <a href="https://www.linkedin.com/in/ameya-kore-925620239">LinkedIn</a>, <a href="https://github.com/fa993">GitHub</a> or <a href="https://www.instagram.com/ameya_kore/">Instagram</a>.</p><p>Thank you and have a good day!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efba7288a379" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gdg-vit/implementing-state-machines-in-rust-designing-uno-efba7288a379">From Rust to Riches: Decoding Finite State Machines</a> was originally published in <a href="https://medium.com/gdg-vit">GDG VIT Vellore</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>