{"id":376,"date":"2024-03-25T21:48:00","date_gmt":"2024-03-25T20:48:00","guid":{"rendered":"https:\/\/noiseonthenet.space\/noise\/?p=376"},"modified":"2024-04-07T21:46:41","modified_gmt":"2024-04-07T20:46:41","slug":"prime-time","status":"publish","type":"post","link":"https:\/\/noiseonthenet.space\/noise\/2024\/03\/prime-time\/","title":{"rendered":"Prime Time"},"content":{"rendered":"<p> <img data-recalc-dims=\"1\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/noiseonthenet.space\/noise\/wp-content\/uploads\/2024\/03\/by-pils-GiudN8NZhGY-unsplash-reduced.jpg?ssl=1\" alt=\"by-pils-GiudN8NZhGY-unsplash-reduced.jpg\" \/> Photo by <a href=\"https:\/\/unsplash.com\/@bypils?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash\">By Pils<\/a> on <a href=\"https:\/\/unsplash.com\/photos\/a-green-plant-sitting-on-top-of-a-cement-floor-GiudN8NZhGY?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash\">Unsplash<\/a> <\/p>\n\n<p> In this post I will create a prime number iterator to demonstrate how to emulate a coroutine in Rust using a &rsquo;Typestate&rsquo; finite state machine. <\/p>\n\n<p> This exercise will also show how to use phantom types and ownership to guarantee proper function call and how to use <code>take<\/code> to consume a value behind a mutable reference. <\/p>\n\n<p> This is a second digression from the tree posts I started, but will prove useful with them. <\/p>\n\n<p> previous posts were <\/p>\n\n<ul class=\"org-ul\">\n<li><a href=\"https:\/\/noiseonthenet.space\/noise\/2024\/03\/growing-a-binary-tree-in-rust\/\">Growing a (binary)Tree<\/a><\/li>\n<li><a href=\"https:\/\/noiseonthenet.space\/noise\/2024\/03\/growing-a-sorting-tree\/\">Growing a (sorting) Tree<\/a><\/li>\n<li><a href=\"https:\/\/noiseonthenet.space\/noise\/2024\/03\/stacking-bits\/\">Stacking Bits<\/a><\/li>\n<\/ul>\n\n<p> The source code for this post is <a href=\"https:\/\/github.com\/noiseOnTheNet\/post015_prime_coroutine\">here<\/a> <\/p>\n<div id=\"outline-container-orgd691b4d\" class=\"outline-2\">\n<h2 id=\"orgd691b4d\">What is a coroutine?<\/h2>\n<div class=\"outline-text-2\" id=\"text-orgd691b4d\">\n<p> a <a href=\"https:\/\/en.wikipedia.org\/wiki\/Coroutine\">coroutine<\/a> is a code unit whose execution can be suspended and resumed multiple times. It reminds of low level interrupts, and it is used among other to implement cooperative concurrent code. <\/p>\n\n<p> Many languages implement this functionality, including the possibility to receive some value when the coroutine suspend and (in some languages) to send some data when it is resumed. <\/p>\n\n<p> Another interesting usage of coroutines is to write generators, i.e. iterators which creates their content. <\/p>\n\n<p> When I write this post, Rust language support for coroutines is not in the stable distribution yet, so I will try to emulate it using a Finite State Machine. Possiby a rusty one. <\/p>\n<\/div>\n<\/div>\n<div id=\"outline-container-org94d93b2\" class=\"outline-2\">\n<h2 id=\"org94d93b2\">A Prime example in Python<\/h2>\n<div class=\"outline-text-2\" id=\"text-org94d93b2\">\n<p> In order to show the algorithm we are using as an example I will write it in Python first <\/p>\n\n<div class=\"org-src-container\">\n<label class=\"org-src-name\"><em><\/em><\/label>\n<pre class=\"src src-python\" id=\"nil\"><span style=\"color: #51afef;\">def<\/span> <span style=\"color: #c678dd;\">prime_coroutine<\/span>():\n    <span style=\"color: #5B6268;\"># <\/span><span style=\"color: #5B6268;\">first we create a list of prime numbers discovered so far<\/span>\n    <span style=\"color: #dcaeea;\">primes<\/span> = []\n    <span style=\"color: #5B6268;\"># <\/span><span style=\"color: #5B6268;\">let's start with 2<\/span>\n    <span style=\"color: #dcaeea;\">current<\/span> = <span style=\"color: #da8548; font-weight: bold;\">2<\/span>\n    <span style=\"color: #5B6268;\"># <\/span><span style=\"color: #5B6268;\">loop forever<\/span>\n    <span style=\"color: #51afef;\">while<\/span> <span style=\"color: #a9a1e1;\">True<\/span>:\n        <span style=\"color: #5B6268;\"># <\/span><span style=\"color: #5B6268;\">check if the current number is prime<\/span>\n        <span style=\"color: #dcaeea;\">found<\/span> = <span style=\"color: #a9a1e1;\">True<\/span>\n        <span style=\"color: #51afef;\">for<\/span> prime <span style=\"color: #51afef;\">in<\/span> primes:\n            <span style=\"color: #5B6268;\"># <\/span><span style=\"color: #5B6268;\">we wish to check all primes which are<\/span>\n            <span style=\"color: #5B6268;\"># <\/span><span style=\"color: #5B6268;\">smaller than the sqrt(current)<\/span>\n            <span style=\"color: #51afef;\">if<\/span> prime * prime &gt; current:\n                <span style=\"color: #51afef;\">break<\/span>\n            <span style=\"color: #5B6268;\"># <\/span><span style=\"color: #5B6268;\">check primality<\/span>\n            <span style=\"color: #51afef;\">if<\/span> current % prime == <span style=\"color: #da8548; font-weight: bold;\">0<\/span>:\n                <span style=\"color: #dcaeea;\">found<\/span> = <span style=\"color: #a9a1e1;\">False<\/span>\n                <span style=\"color: #51afef;\">break<\/span>\n        <span style=\"color: #51afef;\">if<\/span> found:\n            primes.append(current)\n            <span style=\"color: #5B6268;\"># <\/span><span style=\"color: #5B6268;\">this does the magic<\/span>\n            <span style=\"color: #51afef;\">yield<\/span> current\n        <span style=\"color: #5B6268;\"># <\/span><span style=\"color: #5B6268;\">let's go with the next<\/span>\n        <span style=\"color: #dcaeea;\">current<\/span> += <span style=\"color: #da8548; font-weight: bold;\">1<\/span>\n\n<span style=\"color: #5B6268;\"># <\/span><span style=\"color: #5B6268;\">create the coroutine object<\/span>\n<span style=\"color: #dcaeea;\">coroutine<\/span> = prime_coroutine()\n\n<span style=\"color: #5B6268;\"># <\/span><span style=\"color: #5B6268;\">each call will restart from the latest yield<\/span>\n<span style=\"color: #c678dd;\">print<\/span>(<span style=\"color: #c678dd;\">next<\/span>(coroutine))\n<span style=\"color: #c678dd;\">print<\/span>(<span style=\"color: #c678dd;\">next<\/span>(coroutine))\n<span style=\"color: #c678dd;\">print<\/span>(<span style=\"color: #c678dd;\">next<\/span>(coroutine))\n<\/pre>\n<\/div>\n\n<pre class=\"example\">\n2\n3\n5\n<\/pre>\n<\/div>\n<\/div>\n<div id=\"outline-container-org991a529\" class=\"outline-2\">\n<h2 id=\"org991a529\">Finite Typestate Machine<\/h2>\n<div class=\"outline-text-2\" id=\"text-org991a529\">\n<p> Rust has a reserved word for <code>yield<\/code> which is not active yet. The Unstable Rust Book reports the current <a href=\"https:\/\/doc.rust-lang.org\/beta\/unstable-book\/language-features\/coroutines.html\">implementation<\/a> in the nightly based on a <a href=\"https:\/\/en.wikipedia.org\/wiki\/Finite-state_machine\">finite state machine<\/a> . <\/p>\n\n<div id=\"orgb5f0292\" class=\"figure\"> <p><img data-recalc-dims=\"1\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/noiseonthenet.space\/noise\/wp-content\/uploads\/2024\/03\/post015_coroutine_state.png?ssl=1\" alt=\"post015_coroutine_state.png\" \/> <\/p> <\/div>\n\n<p> A finite state machine can be represented by a directed graph where each node represent a state and each edge a transition. <\/p>\n\n<p> Usually transitions are used to perform some kind of operation: in our case we&rsquo;d like to return a prime number from 2 upward. Each coroutine call will return the next one. Of course this can be easily done with a <code>struct<\/code> and a <code>trait<\/code> but coroutines fit to a more general case. <\/p>\n\n<p> In our case we want to express the possibility to have our coroutine to <\/p>\n\n<ul class=\"org-ul\">\n<li>arrive in a <code>stop<\/code> state where it can&rsquo;t ever exit<\/li>\n<li>resume one or multiple time from the <code>suspended<\/code> state, performing some operation and re-entering the <code>suspended<\/code> state<\/li>\n<li>allow to exit from the <code>suspended<\/code> state when no more operation can be performed<\/li>\n<li>fail its initialization by movig directly to the <code>stop<\/code> state<\/li>\n<\/ul>\n\n<p> Let&rsquo;s first define a few data types representing our status <\/p>\n\n<div class=\"org-src-container\">\n<label class=\"org-src-name\"><em><\/em><\/label>\n<pre class=\"src src-rust\" id=\"nil\"><span style=\"color: #51afef;\">struct<\/span> <span style=\"color: #ECBE7B;\">Uninitialized<\/span>;\n<span style=\"color: #51afef;\">struct<\/span> <span style=\"color: #ECBE7B;\">Suspended<\/span>;\n<span style=\"color: #51afef;\">struct<\/span> <span style=\"color: #ECBE7B;\">Completed<\/span>;\n<\/pre>\n<\/div>\n\n<p> these are empty strcuts we will use as type labels. <\/p>\n\n<p> We need a structure where to store our coroutine status, this changes depending on the kind of output we are looking for. in our case we want to emulate the prime algorithm in the previous section so we need <\/p>\n\n<ul class=\"org-ul\">\n<li>a vector of prime numbers found so far<\/li>\n<li>the number we are checking<\/li>\n<\/ul>\n\n<div class=\"org-src-container\">\n<label class=\"org-src-name\"><em><\/em><\/label>\n<pre class=\"src src-rust\" id=\"nil\"><span style=\"color: #51afef;\">use<\/span> <span style=\"color: #a9a1e1;\">std<\/span>::<span style=\"color: #a9a1e1;\">marker<\/span>::<span style=\"color: #ECBE7B;\">PhantomData<\/span>;\n\n<span style=\"color: #51afef;\">struct<\/span> <span style=\"color: #ECBE7B;\">PrimesCoroutine<\/span><span style=\"color: #51afef;\">&lt;<\/span><span style=\"color: #ECBE7B;\">State<\/span> = <span style=\"color: #ECBE7B;\">Uninitialized<\/span><span style=\"color: #51afef;\">&gt;{<\/span>\n    <span style=\"color: #dcaeea;\">primes<\/span> : <span style=\"color: #ECBE7B;\">Vec<\/span><span style=\"color: #c678dd;\">&lt;<\/span><span style=\"color: #ECBE7B;\">u64<\/span><span style=\"color: #c678dd;\">&gt;<\/span>,\n    <span style=\"color: #dcaeea;\">current<\/span> : <span style=\"color: #ECBE7B;\">u64<\/span>,\n    <span style=\"color: #dcaeea;\">state<\/span> : <span style=\"color: #a9a1e1;\">std<\/span>::<span style=\"color: #a9a1e1;\">marker<\/span>::<span style=\"color: #ECBE7B;\">PhantomData<\/span><span style=\"color: #c678dd;\">&lt;<\/span><span style=\"color: #ECBE7B;\">State<\/span><span style=\"color: #c678dd;\">&gt;<\/span>,\n<span style=\"color: #51afef;\">}<\/span>\n<\/pre>\n<\/div>\n<p> this structure is parametrized with a type which represents our state: the <code>PhantomData<\/code> field tells the compiler to not use any space for this &ldquo;label&rdquo; type, but to consider it when evaluating the type of the object <\/p>\n\n<p> The whole idea is to use the type checker as a <a href=\"https:\/\/en.wikipedia.org\/wiki\/Type_theory\">theorem prover<\/a> which will demonstrate that a well formed program only performs the allowed transitions from the current state. <\/p>\n\n<p> First we implement the transition from <code>Uninitialized<\/code> to <code>Suspended<\/code>. We want to express the following ideas <\/p>\n\n<ul class=\"org-ul\">\n<li>this first step can already return either a value and the <code>suspended<\/code> state or a failed initialization: this is represented by the <code>Result<\/code> enumeration<\/li>\n<li>the current status is <b>consumed<\/b> i.e. it is passed to the transition function and cannot be used anymore: this is represented by a signature <b>not<\/b> using a reference<\/li>\n<\/ul>\n\n<div class=\"org-src-container\">\n<label class=\"org-src-name\"><em><\/em><\/label>\n<pre class=\"src src-rust\" id=\"nil\"><span style=\"color: #51afef;\">impl<\/span> <span style=\"color: #ECBE7B;\">PrimesCoroutine<\/span>::<span style=\"color: #51afef;\">&lt;<\/span><span style=\"color: #ECBE7B;\">Uninitialized<\/span><span style=\"color: #51afef;\">&gt;{<\/span>\n    <span style=\"color: #51afef;\">fn<\/span> <span style=\"color: #c678dd;\">init<\/span><span style=\"color: #c678dd;\">(<\/span><span style=\"color: #51afef;\">self<\/span><span style=\"color: #c678dd;\">)<\/span> -&gt; <span style=\"color: #ECBE7B;\">Result<\/span><span style=\"color: #c678dd;\">&lt;<\/span><span style=\"color: #98be65;\">(<\/span><span style=\"color: #ECBE7B;\">u64<\/span>, <span style=\"color: #ECBE7B;\">PrimesCoroutine<\/span><span style=\"color: #a9a1e1;\">&lt;<\/span><span style=\"color: #ECBE7B;\">Suspended<\/span><span style=\"color: #a9a1e1;\">&gt;<\/span><span style=\"color: #98be65;\">)<\/span>, <span style=\"color: #ECBE7B;\">PrimesCoroutine<\/span><span style=\"color: #98be65;\">&lt;<\/span><span style=\"color: #ECBE7B;\">Completed<\/span><span style=\"color: #98be65;\">&gt;<\/span><span style=\"color: #c678dd;\">&gt;{<\/span>\n        <span style=\"color: #ECBE7B;\">Ok<\/span><span style=\"color: #98be65;\">(<\/span><span style=\"color: #a9a1e1;\">(<\/span>\n            <span style=\"color: #da8548; font-weight: bold;\">2<\/span>,\n        <span style=\"color: #ECBE7B;\">PrimesCoroutine<\/span><span style=\"color: #51afef;\">{<\/span>\n            <span style=\"color: #dcaeea;\">primes<\/span> : <span style=\"color: #51afef;\">self<\/span>.primes,\n            <span style=\"color: #dcaeea;\">current<\/span> : <span style=\"color: #da8548; font-weight: bold;\">2<\/span>,\n            <span style=\"color: #dcaeea;\">state<\/span> : <span style=\"color: #ECBE7B;\">PhantomData<\/span>,\n        <span style=\"color: #51afef;\">}<\/span>\n        <span style=\"color: #a9a1e1;\">)<\/span><span style=\"color: #98be65;\">)<\/span>\n    <span style=\"color: #c678dd;\">}<\/span>\n<span style=\"color: #51afef;\">}<\/span>\n<\/pre>\n<\/div>\n\n<p> Then we implement the <code>suspended<\/code> state which contains most of our algorithm: <\/p>\n\n<ul class=\"org-ul\">\n<li>we want to avoid to look up for numbers that cannot be stored in our <code>u64<\/code> so we iterate until <code>u64::MAX<\/code><\/li>\n<\/ul>\n\n<div class=\"org-src-container\">\n<label class=\"org-src-name\"><em><\/em><\/label>\n<pre class=\"src src-rust\" id=\"nil\"><span style=\"color: #51afef;\">impl<\/span> <span style=\"color: #ECBE7B;\">PrimesCoroutine<\/span><span style=\"color: #51afef;\">&lt;<\/span><span style=\"color: #ECBE7B;\">Suspended<\/span><span style=\"color: #51afef;\">&gt;{<\/span>\n    <span style=\"color: #51afef;\">fn<\/span> <span style=\"color: #c678dd;\">resume<\/span><span style=\"color: #c678dd;\">(<\/span><span style=\"color: #51afef;\">mut<\/span> <span style=\"color: #51afef;\">self<\/span><span style=\"color: #c678dd;\">)<\/span> -&gt; <span style=\"color: #ECBE7B;\">Result<\/span><span style=\"color: #c678dd;\">&lt;<\/span><span style=\"color: #98be65;\">(<\/span><span style=\"color: #ECBE7B;\">u64<\/span>, <span style=\"color: #ECBE7B;\">PrimesCoroutine<\/span><span style=\"color: #a9a1e1;\">&lt;<\/span><span style=\"color: #ECBE7B;\">Suspended<\/span><span style=\"color: #a9a1e1;\">&gt;<\/span><span style=\"color: #98be65;\">)<\/span>, <span style=\"color: #ECBE7B;\">PrimesCoroutine<\/span><span style=\"color: #98be65;\">&lt;<\/span><span style=\"color: #ECBE7B;\">Completed<\/span><span style=\"color: #98be65;\">&gt;<\/span><span style=\"color: #c678dd;\">&gt;{<\/span>\n        <span style=\"color: #51afef;\">self<\/span>.primes.push<span style=\"color: #98be65;\">(<\/span><span style=\"color: #51afef;\">self<\/span>.current<span style=\"color: #98be65;\">)<\/span>;\n        <span style=\"color: #51afef;\">while<\/span> <span style=\"color: #51afef;\">self<\/span>.current &lt; <span style=\"color: #ECBE7B;\">u64<\/span>::<span style=\"color: #ECBE7B;\">MAX<\/span><span style=\"color: #98be65;\">{<\/span>\n            <span style=\"color: #51afef;\">self<\/span>.current += <span style=\"color: #da8548; font-weight: bold;\">1<\/span>;\n            <span style=\"color: #51afef;\">let<\/span> <span style=\"color: #51afef;\">mut<\/span> <span style=\"color: #dcaeea;\">found<\/span> : <span style=\"color: #ECBE7B;\">bool<\/span> = <span style=\"color: #51afef;\">true<\/span>;\n            <span style=\"color: #51afef;\">for<\/span> <span style=\"color: #dcaeea;\">prime<\/span> <span style=\"color: #51afef;\">in<\/span> <span style=\"color: #51afef;\">self<\/span>.primes.iter<span style=\"color: #a9a1e1;\">(){<\/span>\n                <span style=\"color: #51afef;\">if<\/span> prime * prime &gt; <span style=\"color: #51afef;\">self<\/span>.current<span style=\"color: #51afef;\">{<\/span>\n                    <span style=\"color: #5B6268;\">\/\/ <\/span><span style=\"color: #5B6268;\">early interruption for square rule<\/span>\n                    <span style=\"color: #51afef;\">break<\/span>;\n                <span style=\"color: #51afef;\">}<\/span>\n                <span style=\"color: #51afef;\">if<\/span> <span style=\"color: #51afef;\">self<\/span>.current % prime == <span style=\"color: #da8548; font-weight: bold;\">0<\/span> <span style=\"color: #51afef;\">{<\/span>\n                    <span style=\"color: #5B6268;\">\/\/ <\/span><span style=\"color: #5B6268;\">early interruption for division<\/span>\n                    found = <span style=\"color: #51afef;\">false<\/span>;\n                    <span style=\"color: #51afef;\">break<\/span>;\n                <span style=\"color: #51afef;\">}<\/span>\n            <span style=\"color: #a9a1e1;\">}<\/span>\n            <span style=\"color: #51afef;\">if<\/span> found <span style=\"color: #a9a1e1;\">{<\/span>\n                <span style=\"color: #5B6268;\">\/\/ <\/span><span style=\"color: #5B6268;\">this is a prime number<\/span>\n                <span style=\"color: #51afef;\">return<\/span> <span style=\"color: #ECBE7B;\">Ok<\/span><span style=\"color: #51afef;\">(<\/span>\n                    <span style=\"color: #c678dd;\">(<\/span><span style=\"color: #51afef;\">self<\/span>.current\n                    ,<span style=\"color: #51afef;\">self<\/span><span style=\"color: #c678dd;\">)<\/span>\n                <span style=\"color: #51afef;\">)<\/span>\n            <span style=\"color: #a9a1e1;\">}<\/span>\n        <span style=\"color: #98be65;\">}<\/span>\n\n        <span style=\"color: #ECBE7B;\">Err<\/span><span style=\"color: #98be65;\">(<\/span>\n            <span style=\"color: #ECBE7B;\">PrimesCoroutine<\/span><span style=\"color: #a9a1e1;\">{<\/span>\n                <span style=\"color: #dcaeea;\">primes<\/span> : <span style=\"color: #51afef;\">self<\/span>.primes,\n                <span style=\"color: #dcaeea;\">current<\/span> : <span style=\"color: #da8548; font-weight: bold;\">0<\/span>,\n                <span style=\"color: #dcaeea;\">state<\/span> : <span style=\"color: #ECBE7B;\">PhantomData<\/span>\n            <span style=\"color: #a9a1e1;\">}<\/span>\n        <span style=\"color: #98be65;\">)<\/span>\n    <span style=\"color: #c678dd;\">}<\/span>\n<span style=\"color: #51afef;\">}<\/span>\n<\/pre>\n<\/div>\n\n<p> We may wish to have the list of all primes so far: it is possible to add a &ldquo;generic&rdquo; trait implementation <\/p>\n\n<div class=\"org-src-container\">\n<label class=\"org-src-name\"><em><\/em><\/label>\n<pre class=\"src src-rust\" id=\"nil\"><span style=\"color: #51afef;\">impl<\/span><span style=\"color: #51afef;\">&lt;<\/span><span style=\"color: #ECBE7B;\">T<\/span><span style=\"color: #51afef;\">&gt;<\/span> <span style=\"color: #ECBE7B;\">PrimesCoroutine<\/span><span style=\"color: #51afef;\">&lt;<\/span><span style=\"color: #ECBE7B;\">T<\/span><span style=\"color: #51afef;\">&gt;{<\/span>\n    <span style=\"color: #51afef;\">fn<\/span> <span style=\"color: #c678dd;\">get_primes<\/span><span style=\"color: #c678dd;\">(<\/span>&amp; <span style=\"color: #51afef;\">self<\/span><span style=\"color: #c678dd;\">)<\/span> -&gt; &amp; <span style=\"color: #ECBE7B;\">Vec<\/span><span style=\"color: #c678dd;\">&lt;<\/span><span style=\"color: #ECBE7B;\">u64<\/span><span style=\"color: #c678dd;\">&gt;{<\/span>\n        <span style=\"color: #bbc2cf; background-color: #282c34;\">&amp;<\/span><span style=\"color: #51afef;\">self<\/span>.primes\n    <span style=\"color: #c678dd;\">}<\/span>\n<span style=\"color: #51afef;\">}<\/span>\n<\/pre>\n<\/div>\n\n<p> finally it is convenient to have a starting point for our state object: this can be done by creating an associated function <\/p>\n\n<div class=\"org-src-container\">\n<label class=\"org-src-name\"><em><\/em><\/label>\n<pre class=\"src src-rust\" id=\"nil\"><span style=\"color: #51afef;\">impl<\/span> <span style=\"color: #ECBE7B;\">PrimesCoroutine<\/span><span style=\"color: #51afef;\">{<\/span>\n    <span style=\"color: #51afef;\">fn<\/span> <span style=\"color: #c678dd;\">new<\/span><span style=\"color: #c678dd;\">()<\/span> -&gt; <span style=\"color: #ECBE7B;\">PrimesCoroutine<\/span><span style=\"color: #c678dd;\">&lt;<\/span><span style=\"color: #ECBE7B;\">Uninitialized<\/span><span style=\"color: #c678dd;\">&gt;{<\/span>\n        <span style=\"color: #ECBE7B;\">PrimesCoroutine<\/span><span style=\"color: #98be65;\">{<\/span>\n            <span style=\"color: #dcaeea;\">primes<\/span> : <span style=\"color: #ECBE7B;\">Vec<\/span>::new<span style=\"color: #a9a1e1;\">()<\/span>,\n            <span style=\"color: #dcaeea;\">current<\/span> : <span style=\"color: #da8548; font-weight: bold;\">2<\/span>,\n            <span style=\"color: #dcaeea;\">state<\/span> : <span style=\"color: #ECBE7B;\">PhantomData<\/span>,\n        <span style=\"color: #98be65;\">}<\/span>\n    <span style=\"color: #c678dd;\">}<\/span>\n<span style=\"color: #51afef;\">}<\/span>\n<\/pre>\n<\/div>\n\n<p> Now we can test our code <\/p>\n\n<div class=\"org-src-container\">\n<label class=\"org-src-name\"><em><\/em><\/label>\n<pre class=\"src src-rust\" id=\"nil\">    <span style=\"color: #51afef; font-weight: bold;\">#<\/span><span style=\"color: #51afef; font-weight: bold;\">[<\/span><span style=\"color: #51afef; font-weight: bold;\">test<\/span><span style=\"color: #51afef; font-weight: bold;\">]<\/span>\n    <span style=\"color: #51afef;\">fn<\/span> <span style=\"color: #c678dd;\">it_works<\/span><span style=\"color: #51afef;\">()<\/span> <span style=\"color: #51afef;\">{<\/span>\n        <span style=\"color: #51afef;\">let<\/span> <span style=\"color: #dcaeea;\">primes<\/span> = <span style=\"color: #ECBE7B;\">PrimesCoroutine<\/span>::new<span style=\"color: #c678dd;\">()<\/span>;\n        <span style=\"color: #51afef;\">if<\/span> <span style=\"color: #51afef;\">let<\/span> <span style=\"color: #ECBE7B;\">Ok<\/span><span style=\"color: #c678dd;\">(<\/span><span style=\"color: #98be65;\">(<\/span>_result, primes<span style=\"color: #98be65;\">)<\/span><span style=\"color: #c678dd;\">)<\/span> = primes.init<span style=\"color: #c678dd;\">(){<\/span>\n            <span style=\"color: #51afef;\">let<\/span> <span style=\"color: #dcaeea;\">result<\/span> = primes.resume<span style=\"color: #98be65;\">()<\/span>;\n            <span style=\"color: #51afef;\">match<\/span> result<span style=\"color: #98be65;\">{<\/span>\n                <span style=\"color: #ECBE7B;\">Ok<\/span><span style=\"color: #a9a1e1;\">(<\/span><span style=\"color: #51afef;\">(<\/span>value,_<span style=\"color: #51afef;\">)<\/span><span style=\"color: #a9a1e1;\">)<\/span> =&gt; <span style=\"color: #a9a1e1;\">{<\/span><span style=\"color: #51afef; font-weight: bold;\">assert_eq!<\/span><span style=\"color: #51afef;\">(<\/span>value,<span style=\"color: #da8548; font-weight: bold;\">3<\/span><span style=\"color: #51afef;\">)<\/span><span style=\"color: #a9a1e1;\">}<\/span>\n                <span style=\"color: #ECBE7B;\">Err<\/span><span style=\"color: #a9a1e1;\">(<\/span>_<span style=\"color: #a9a1e1;\">)<\/span> =&gt; <span style=\"color: #a9a1e1;\">{<\/span><span style=\"color: #51afef; font-weight: bold;\">panic!<\/span><span style=\"color: #51afef;\">(<\/span><span style=\"color: #98be65;\">\"closed stream\"<\/span><span style=\"color: #51afef;\">)<\/span><span style=\"color: #a9a1e1;\">}<\/span>\n            <span style=\"color: #98be65;\">}<\/span>\n        <span style=\"color: #c678dd;\">}<\/span>\n    <span style=\"color: #51afef;\">}<\/span>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"outline-container-orgb375618\" class=\"outline-2\">\n<h2 id=\"orgb375618\">Iterator<\/h2>\n<div class=\"outline-text-2\" id=\"text-orgb375618\">\n<p> Everybody love <a href=\"https:\/\/en.wikipedia.org\/wiki\/Iterator\">iterators<\/a>. <\/p>\n\n<p> I first met them when the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Standard_Template_Library\">C++ Standard Template Libray<\/a> originally designed by <a href=\"https:\/\/en.wikipedia.org\/wiki\/Standard_Template_Library\">Alexander Stepanov<\/a> became part of standard C++, also exposing some features of parametric polymorphism and functional programming. <\/p>\n\n<p> The basic idea is to explore a data structure by looping over its contents, without the need to know its internal details. Rust defines the <a href=\"https:\/\/doc.rust-lang.org\/std\/iter\/trait.Iterator.html\">Iterator trait<\/a> in the standard library. I will now show how to use our coroutine code to implement it. <\/p>\n\n<p> The first problem to address is to create a place to store the current status of our Finite State Machine: as each state is represented by a different type we need ad enumeration to store them in a single place <\/p>\n\n<div class=\"org-src-container\">\n<label class=\"org-src-name\"><em><\/em><\/label>\n<pre class=\"src src-rust\" id=\"nil\"><span style=\"color: #51afef;\">enum<\/span> <span style=\"color: #ECBE7B;\">CoroutineStatus<\/span><span style=\"color: #51afef;\">{<\/span>\n    <span style=\"color: #ECBE7B;\">Created<\/span><span style=\"color: #c678dd;\">(<\/span><span style=\"color: #ECBE7B;\">PrimesCoroutine<\/span><span style=\"color: #98be65;\">&lt;<\/span><span style=\"color: #ECBE7B;\">Uninitialized<\/span><span style=\"color: #98be65;\">&gt;<\/span><span style=\"color: #c678dd;\">)<\/span>,\n    <span style=\"color: #ECBE7B;\">Ready<\/span><span style=\"color: #c678dd;\">(<\/span><span style=\"color: #ECBE7B;\">PrimesCoroutine<\/span><span style=\"color: #98be65;\">&lt;<\/span><span style=\"color: #ECBE7B;\">Suspended<\/span><span style=\"color: #98be65;\">&gt;<\/span><span style=\"color: #c678dd;\">)<\/span>,\n    <span style=\"color: #ECBE7B;\">Closed<\/span><span style=\"color: #c678dd;\">(<\/span><span style=\"color: #ECBE7B;\">PrimesCoroutine<\/span><span style=\"color: #98be65;\">&lt;<\/span><span style=\"color: #ECBE7B;\">Completed<\/span><span style=\"color: #98be65;\">&gt;<\/span><span style=\"color: #c678dd;\">)<\/span>\n<span style=\"color: #51afef;\">}<\/span>\n<span style=\"color: #5B6268;\">\/\/ <\/span><span style=\"color: #5B6268;\">this is for convenience<\/span>\n<span style=\"color: #51afef;\">use<\/span> <span style=\"color: #ECBE7B;\">CoroutineStatus<\/span>::*;\n<\/pre>\n<\/div>\n\n<p> With this enumeration type we can move the coroutine semantic to an higher level: define a <code>next<\/code> method for the <code>Created<\/code> and <code>Ready<\/code> states which will perform all the required matching, consume the status and <b>optionally<\/b> return a status <\/p>\n\n<div class=\"org-src-container\">\n<label class=\"org-src-name\"><em><\/em><\/label>\n<pre class=\"src src-rust\" id=\"nil\"><span style=\"color: #51afef;\">impl<\/span> <span style=\"color: #ECBE7B;\">CoroutineStatus<\/span><span style=\"color: #51afef;\">{<\/span>\n    <span style=\"color: #51afef;\">fn<\/span> <span style=\"color: #c678dd;\">next<\/span><span style=\"color: #c678dd;\">(<\/span><span style=\"color: #51afef;\">self<\/span><span style=\"color: #c678dd;\">)<\/span> -&gt; <span style=\"color: #c678dd;\">(<\/span><span style=\"color: #ECBE7B;\">CoroutineStatus<\/span>, <span style=\"color: #ECBE7B;\">Option<\/span><span style=\"color: #98be65;\">&lt;<\/span><span style=\"color: #ECBE7B;\">u64<\/span><span style=\"color: #98be65;\">&gt;<\/span><span style=\"color: #c678dd;\">){<\/span>\n        <span style=\"color: #51afef;\">match<\/span> <span style=\"color: #51afef;\">self<\/span><span style=\"color: #98be65;\">{<\/span>\n            <span style=\"color: #ECBE7B;\">Created<\/span><span style=\"color: #a9a1e1;\">(<\/span>coroutine<span style=\"color: #a9a1e1;\">)<\/span> =&gt; <span style=\"color: #a9a1e1;\">{<\/span>\n                <span style=\"color: #51afef;\">match<\/span> coroutine.init<span style=\"color: #51afef;\">(){<\/span>\n                    <span style=\"color: #ECBE7B;\">Ok<\/span><span style=\"color: #c678dd;\">(<\/span><span style=\"color: #98be65;\">(<\/span>result, coroutine<span style=\"color: #98be65;\">)<\/span><span style=\"color: #c678dd;\">)<\/span> =&gt;<span style=\"color: #c678dd;\">{<\/span>\n                        <span style=\"color: #98be65;\">(<\/span> <span style=\"color: #ECBE7B;\">Ready<\/span><span style=\"color: #a9a1e1;\">(<\/span>coroutine<span style=\"color: #a9a1e1;\">)<\/span>,\n                          <span style=\"color: #ECBE7B;\">Some<\/span><span style=\"color: #a9a1e1;\">(<\/span>result<span style=\"color: #a9a1e1;\">)<\/span><span style=\"color: #98be65;\">)<\/span>\n                    <span style=\"color: #c678dd;\">}<\/span>,\n                    <span style=\"color: #ECBE7B;\">Err<\/span><span style=\"color: #c678dd;\">(<\/span>coroutine<span style=\"color: #c678dd;\">)<\/span> =&gt; <span style=\"color: #c678dd;\">{<\/span>\n                        <span style=\"color: #98be65;\">(<\/span> <span style=\"color: #ECBE7B;\">Closed<\/span><span style=\"color: #a9a1e1;\">(<\/span>coroutine<span style=\"color: #a9a1e1;\">)<\/span>,\n                        <span style=\"color: #ECBE7B;\">None<\/span><span style=\"color: #98be65;\">)<\/span>\n                    <span style=\"color: #c678dd;\">}<\/span>\n                <span style=\"color: #51afef;\">}<\/span>\n            <span style=\"color: #a9a1e1;\">}<\/span>\n,\n            <span style=\"color: #ECBE7B;\">Ready<\/span><span style=\"color: #a9a1e1;\">(<\/span>coroutine<span style=\"color: #a9a1e1;\">)<\/span> =&gt; <span style=\"color: #a9a1e1;\">{<\/span>\n                <span style=\"color: #51afef;\">match<\/span> coroutine.resume<span style=\"color: #51afef;\">(){<\/span>\n                    <span style=\"color: #ECBE7B;\">Ok<\/span><span style=\"color: #c678dd;\">(<\/span><span style=\"color: #98be65;\">(<\/span>result, coroutine<span style=\"color: #98be65;\">)<\/span><span style=\"color: #c678dd;\">)<\/span> =&gt;<span style=\"color: #c678dd;\">{<\/span>\n                        <span style=\"color: #98be65;\">(<\/span> <span style=\"color: #ECBE7B;\">Ready<\/span><span style=\"color: #a9a1e1;\">(<\/span>coroutine<span style=\"color: #a9a1e1;\">)<\/span>,\n                          <span style=\"color: #ECBE7B;\">Some<\/span><span style=\"color: #a9a1e1;\">(<\/span>result<span style=\"color: #a9a1e1;\">)<\/span><span style=\"color: #98be65;\">)<\/span>\n                    <span style=\"color: #c678dd;\">}<\/span>,\n                    <span style=\"color: #ECBE7B;\">Err<\/span><span style=\"color: #c678dd;\">(<\/span>coroutine<span style=\"color: #c678dd;\">)<\/span> =&gt; <span style=\"color: #c678dd;\">{<\/span>\n                        <span style=\"color: #98be65;\">(<\/span> <span style=\"color: #ECBE7B;\">Closed<\/span><span style=\"color: #a9a1e1;\">(<\/span>coroutine<span style=\"color: #a9a1e1;\">)<\/span>,\n                        <span style=\"color: #ECBE7B;\">None<\/span><span style=\"color: #98be65;\">)<\/span>\n                    <span style=\"color: #c678dd;\">}<\/span>\n                <span style=\"color: #51afef;\">}<\/span>\n            <span style=\"color: #a9a1e1;\">}<\/span>,\n            _ =&gt; <span style=\"color: #a9a1e1;\">(<\/span><span style=\"color: #51afef;\">self<\/span>, <span style=\"color: #ECBE7B;\">None<\/span><span style=\"color: #a9a1e1;\">)<\/span>,\n        <span style=\"color: #98be65;\">}<\/span>\n    <span style=\"color: #c678dd;\">}<\/span>\n<span style=\"color: #51afef;\">}<\/span>\n<\/pre>\n<\/div>\n\n\n<p> Now we can store this value into a structure; values may change in time but there will be an object which we will always refer to for storing our state. <\/p>\n\n<div class=\"org-src-container\">\n<label class=\"org-src-name\"><em><\/em><\/label>\n<pre class=\"src src-rust\" id=\"nil\"><span style=\"color: #51afef;\">struct<\/span> <span style=\"color: #ECBE7B;\">Prime<\/span><span style=\"color: #51afef;\">{<\/span>\n    <span style=\"color: #dcaeea;\">coroutine<\/span> : <span style=\"color: #ECBE7B;\">CoroutineStatus<\/span>\n<span style=\"color: #51afef;\">}<\/span>\n\n<span style=\"color: #51afef;\">impl<\/span> <span style=\"color: #ECBE7B;\">Prime<\/span><span style=\"color: #51afef;\">{<\/span>\n    <span style=\"color: #51afef;\">fn<\/span> <span style=\"color: #c678dd;\">new<\/span><span style=\"color: #c678dd;\">()<\/span> -&gt; <span style=\"color: #ECBE7B;\">Prime<\/span><span style=\"color: #c678dd;\">{<\/span>\n        <span style=\"color: #ECBE7B;\">Prime<\/span><span style=\"color: #98be65;\">{<\/span>\n            <span style=\"color: #dcaeea;\">coroutine<\/span>: <span style=\"color: #ECBE7B;\">Created<\/span><span style=\"color: #a9a1e1;\">(<\/span><span style=\"color: #ECBE7B;\">PrimesCoroutine<\/span>::new<span style=\"color: #51afef;\">()<\/span><span style=\"color: #a9a1e1;\">)<\/span>\n        <span style=\"color: #98be65;\">}<\/span>\n    <span style=\"color: #c678dd;\">}<\/span>\n<span style=\"color: #51afef;\">}<\/span>\n<\/pre>\n<\/div>\n\n<p> as usual an associated function can guarantee that a proper initialization is done <\/p>\n\n<p> Now let&rsquo;s try to implement the Iterator trait for this struct: <\/p>\n\n<ul class=\"org-ul\">\n<li>we have to define the returned type (will be <code>u64<\/code>)<\/li>\n<li>we have to define a <code>next<\/code> method which return an <code>Option<\/code> enumeration:\n\n<ul class=\"org-ul\">\n<li>when the iterator returns a value we have <code>Some(value)<\/code><\/li>\n<li>when the iterator is exhausted it will returnt <code>None<\/code><\/li>\n<\/ul><\/li>\n<\/ul>\n\n<div class=\"org-src-container\">\n<label class=\"org-src-name\"><em><\/em><\/label>\n<pre class=\"src src-rust\" id=\"nil\"><span style=\"color: #51afef;\">impl<\/span> <span style=\"color: #ECBE7B;\">Iterator<\/span> <span style=\"color: #51afef;\">for<\/span> <span style=\"color: #ECBE7B;\">Prime<\/span><span style=\"color: #51afef;\">{<\/span>\n    <span style=\"color: #51afef;\">type<\/span> <span style=\"color: #ECBE7B;\">Item<\/span> = <span style=\"color: #ECBE7B;\">u64<\/span>;\n    <span style=\"color: #51afef;\">fn<\/span> <span style=\"color: #c678dd;\">next<\/span><span style=\"color: #c678dd;\">(<\/span>&amp; <span style=\"color: #51afef;\">mut<\/span> <span style=\"color: #51afef;\">self<\/span><span style=\"color: #c678dd;\">)<\/span> -&gt; <span style=\"color: #ECBE7B;\">Option<\/span><span style=\"color: #c678dd;\">&lt;<\/span><span style=\"color: #ECBE7B;\">Self<\/span>::<span style=\"color: #ECBE7B;\">Item<\/span><span style=\"color: #c678dd;\">&gt;{<\/span>\n        <span style=\"color: #51afef;\">match<\/span> <span style=\"color: #51afef;\">self<\/span>.coroutine.next<span style=\"color: #98be65;\">(){<\/span>\n            <span style=\"color: #a9a1e1;\">(<\/span>status, <span style=\"color: #ECBE7B;\">Some<\/span><span style=\"color: #51afef;\">(<\/span>value<span style=\"color: #51afef;\">)<\/span><span style=\"color: #a9a1e1;\">)<\/span> =&gt; <span style=\"color: #a9a1e1;\">{<\/span>\n                <span style=\"color: #51afef;\">self<\/span>.coroutine = status;\n                <span style=\"color: #ECBE7B;\">Some<\/span><span style=\"color: #51afef;\">(<\/span>value<span style=\"color: #51afef;\">)<\/span>\n            <span style=\"color: #a9a1e1;\">}<\/span>,\n            <span style=\"color: #a9a1e1;\">(<\/span>status, <span style=\"color: #ECBE7B;\">None<\/span><span style=\"color: #a9a1e1;\">)<\/span> =&gt; <span style=\"color: #a9a1e1;\">{<\/span>\n                <span style=\"color: #51afef;\">self<\/span>.coroutine = status;\n                <span style=\"color: #ECBE7B;\">None<\/span>\n            <span style=\"color: #a9a1e1;\">}<\/span>\n        <span style=\"color: #98be65;\">}<\/span>\n    <span style=\"color: #c678dd;\">}<\/span>\n<span style=\"color: #51afef;\">}<\/span>\n<\/pre>\n<\/div>\n\n<p> But this don&rsquo;t work! <\/p>\n\n<p> Why? when we execute <code>next<\/code> on our coroutine we are consuming this value (this was made by design); but this value is taken from a <b>mutable reference<\/b> thus invalidanting the content of the pointed struct. <\/p>\n\n<p> The solution is to <b>temporarily replace<\/b> the coroutine value with a placeholder (which does not invalidate the referenced struct), then calculate the <b>real<\/b> next state and finally set it. This can be done with the <code>std::mem::take<\/code> function. <\/p>\n\n<p> <code>take<\/code> returns the content a the mutable reference and subsitute it with a &ldquo;default&rdquo; value, thus requiring us to implement the <code>Default<\/code> trait of the type involved. <\/p>\n\n<p> As we wish to minimize the memory copied we just add an empty element in our enumeration and choose it as the default value <\/p>\n\n<div class=\"org-src-container\">\n<label class=\"org-src-name\"><em><\/em><\/label>\n<pre class=\"src src-rust\" id=\"nil\"><span style=\"color: #51afef;\">enum<\/span> <span style=\"color: #ECBE7B;\">CoroutineStatus<\/span><span style=\"color: #51afef;\">{<\/span>\n    <span style=\"color: #ECBE7B;\">Undefined<\/span>,\n    <span style=\"color: #ECBE7B;\">Created<\/span><span style=\"color: #c678dd;\">(<\/span><span style=\"color: #ECBE7B;\">PrimesCoroutine<\/span><span style=\"color: #98be65;\">&lt;<\/span><span style=\"color: #ECBE7B;\">Uninitialized<\/span><span style=\"color: #98be65;\">&gt;<\/span><span style=\"color: #c678dd;\">)<\/span>,\n    <span style=\"color: #ECBE7B;\">Ready<\/span><span style=\"color: #c678dd;\">(<\/span><span style=\"color: #ECBE7B;\">PrimesCoroutine<\/span><span style=\"color: #98be65;\">&lt;<\/span><span style=\"color: #ECBE7B;\">Suspended<\/span><span style=\"color: #98be65;\">&gt;<\/span><span style=\"color: #c678dd;\">)<\/span>,\n    <span style=\"color: #ECBE7B;\">Closed<\/span><span style=\"color: #c678dd;\">(<\/span><span style=\"color: #ECBE7B;\">PrimesCoroutine<\/span><span style=\"color: #98be65;\">&lt;<\/span><span style=\"color: #ECBE7B;\">Completed<\/span><span style=\"color: #98be65;\">&gt;<\/span><span style=\"color: #c678dd;\">)<\/span>\n<span style=\"color: #51afef;\">}<\/span>\n<span style=\"color: #51afef;\">use<\/span> <span style=\"color: #ECBE7B;\">CoroutineStatus<\/span>::*;\n\n<span style=\"color: #5B6268;\">\/\/ <\/span><span style=\"color: #5B6268;\">implementing the Default trait<\/span>\n<span style=\"color: #51afef;\">impl<\/span> <span style=\"color: #ECBE7B;\">Default<\/span> <span style=\"color: #51afef;\">for<\/span> <span style=\"color: #ECBE7B;\">CoroutineStatus<\/span> <span style=\"color: #51afef;\">{<\/span>\n    <span style=\"color: #51afef;\">fn<\/span> <span style=\"color: #c678dd;\">default<\/span><span style=\"color: #c678dd;\">()<\/span> -&gt; <span style=\"color: #ECBE7B;\">Self<\/span> <span style=\"color: #c678dd;\">{<\/span> <span style=\"color: #ECBE7B;\">Undefined<\/span> <span style=\"color: #c678dd;\">}<\/span>\n<span style=\"color: #51afef;\">}<\/span>\n<\/pre>\n<\/div>\n\n<p> Now we can use <code>take<\/code> safely <\/p>\n\n<div class=\"org-src-container\">\n<label class=\"org-src-name\"><em><\/em><\/label>\n<pre class=\"src src-rust\" id=\"nil\"><span style=\"color: #51afef;\">impl<\/span> <span style=\"color: #ECBE7B;\">Iterator<\/span> <span style=\"color: #51afef;\">for<\/span> <span style=\"color: #ECBE7B;\">Prime<\/span><span style=\"color: #51afef;\">{<\/span>\n    <span style=\"color: #51afef;\">type<\/span> <span style=\"color: #ECBE7B;\">Item<\/span> = <span style=\"color: #ECBE7B;\">u64<\/span>;\n    <span style=\"color: #51afef;\">fn<\/span> <span style=\"color: #c678dd;\">next<\/span><span style=\"color: #c678dd;\">(<\/span>&amp; <span style=\"color: #51afef;\">mut<\/span> <span style=\"color: #51afef;\">self<\/span><span style=\"color: #c678dd;\">)<\/span> -&gt; <span style=\"color: #ECBE7B;\">Option<\/span><span style=\"color: #c678dd;\">&lt;<\/span><span style=\"color: #ECBE7B;\">Self<\/span>::<span style=\"color: #ECBE7B;\">Item<\/span><span style=\"color: #c678dd;\">&gt;{<\/span>\n        <span style=\"color: #51afef;\">let<\/span> <span style=\"color: #dcaeea;\">coroutine<\/span> = take<span style=\"color: #98be65;\">(<\/span>&amp; <span style=\"color: #51afef;\">mut<\/span> <span style=\"color: #51afef;\">self<\/span>.coroutine<span style=\"color: #98be65;\">)<\/span>;\n        <span style=\"color: #51afef;\">match<\/span> coroutine.next<span style=\"color: #98be65;\">(){<\/span>\n            <span style=\"color: #a9a1e1;\">(<\/span>status, <span style=\"color: #ECBE7B;\">Some<\/span><span style=\"color: #51afef;\">(<\/span>value<span style=\"color: #51afef;\">)<\/span><span style=\"color: #a9a1e1;\">)<\/span> =&gt; <span style=\"color: #a9a1e1;\">{<\/span>\n                <span style=\"color: #51afef;\">self<\/span>.coroutine = status;\n                <span style=\"color: #ECBE7B;\">Some<\/span><span style=\"color: #51afef;\">(<\/span>value<span style=\"color: #51afef;\">)<\/span>\n            <span style=\"color: #a9a1e1;\">}<\/span>,\n            <span style=\"color: #a9a1e1;\">(<\/span>status, <span style=\"color: #ECBE7B;\">None<\/span><span style=\"color: #a9a1e1;\">)<\/span> =&gt; <span style=\"color: #a9a1e1;\">{<\/span>\n                <span style=\"color: #51afef;\">self<\/span>.coroutine = status;\n                <span style=\"color: #ECBE7B;\">None<\/span>\n            <span style=\"color: #a9a1e1;\">}<\/span>\n        <span style=\"color: #98be65;\">}<\/span>\n    <span style=\"color: #c678dd;\">}<\/span>\n<span style=\"color: #51afef;\">}<\/span>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"outline-container-org45fac2b\" class=\"outline-2\">\n<h2 id=\"org45fac2b\">An alternative to take<\/h2>\n<div class=\"outline-text-2\" id=\"text-org45fac2b\">\n<p> This has been already a long journey. <\/p>\n\n<p> But what if we want to avoid using <code>take<\/code> ? <\/p>\n\n<p> When using our Typestate pattern the state is always consumed to avoid its reuse when invalid at a later time, so <code>take<\/code> is necessary when we want to store this state in a struct. <\/p>\n\n<p> The alternative is to create a simpler Finite State Machine using an enumeration for the states and some pattern matching for each transition. <\/p>\n\n<p> While this works, illegal transitions are detectable only at run time, so we need to create an extra <code>Error<\/code> state and manage it in our code later. This may be inevitable if you can&rsquo;t use the <code>std<\/code> crate, which is the case for <b>embedded<\/b> code. <\/p>\n\n<p> More on this point on other posts <\/p>\n<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"An introduction to coroutines, typestate machine, phantom types, iterators and ownership issues","protected":false},"author":1,"featured_media":379,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","inline_featured_image":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[4],"tags":[5],"class_list":["post-376","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-language-learning","tag-rust"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Prime Time - Noise On The Net<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/noiseonthenet.space\/noise\/2024\/03\/prime-time\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Prime Time - Noise On The Net\" \/>\n<meta property=\"og:description\" content=\"An introduction to coroutines, typestate machine, phantom types, iterators and ownership issues\" \/>\n<meta property=\"og:url\" content=\"https:\/\/noiseonthenet.space\/noise\/2024\/03\/prime-time\/\" \/>\n<meta property=\"og:site_name\" content=\"Noise On The Net\" \/>\n<meta property=\"article:published_time\" content=\"2024-03-25T20:48:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-04-07T20:46:41+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/noiseonthenet.space\/noise\/wp-content\/uploads\/2024\/03\/by-pils-GiudN8NZhGY-unsplash-reduced.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"900\" \/>\n\t<meta property=\"og:image:height\" content=\"1200\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"marco.p.v.vezzoli\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"marco.p.v.vezzoli\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/noiseonthenet.space\\\/noise\\\/2024\\\/03\\\/prime-time\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/noiseonthenet.space\\\/noise\\\/2024\\\/03\\\/prime-time\\\/\"},\"author\":{\"name\":\"marco.p.v.vezzoli\",\"@id\":\"https:\\\/\\\/noiseonthenet.space\\\/noise\\\/#\\\/schema\\\/person\\\/88c3a70f2b23480197bc61d6e1e2e982\"},\"headline\":\"Prime Time\",\"datePublished\":\"2024-03-25T20:48:00+00:00\",\"dateModified\":\"2024-04-07T20:46:41+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/noiseonthenet.space\\\/noise\\\/2024\\\/03\\\/prime-time\\\/\"},\"wordCount\":1197,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\\\/\\\/noiseonthenet.space\\\/noise\\\/#\\\/schema\\\/person\\\/88c3a70f2b23480197bc61d6e1e2e982\"},\"image\":{\"@id\":\"https:\\\/\\\/noiseonthenet.space\\\/noise\\\/2024\\\/03\\\/prime-time\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/i0.wp.com\\\/noiseonthenet.space\\\/noise\\\/wp-content\\\/uploads\\\/2024\\\/03\\\/by-pils-GiudN8NZhGY-unsplash-reduced.jpg?fit=900%2C1200&ssl=1\",\"keywords\":[\"Rust\"],\"articleSection\":[\"Language learning\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/noiseonthenet.space\\\/noise\\\/2024\\\/03\\\/prime-time\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/noiseonthenet.space\\\/noise\\\/2024\\\/03\\\/prime-time\\\/\",\"url\":\"https:\\\/\\\/noiseonthenet.space\\\/noise\\\/2024\\\/03\\\/prime-time\\\/\",\"name\":\"Prime Time - Noise On The Net\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/noiseonthenet.space\\\/noise\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/noiseonthenet.space\\\/noise\\\/2024\\\/03\\\/prime-time\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/noiseonthenet.space\\\/noise\\\/2024\\\/03\\\/prime-time\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/i0.wp.com\\\/noiseonthenet.space\\\/noise\\\/wp-content\\\/uploads\\\/2024\\\/03\\\/by-pils-GiudN8NZhGY-unsplash-reduced.jpg?fit=900%2C1200&ssl=1\",\"datePublished\":\"2024-03-25T20:48:00+00:00\",\"dateModified\":\"2024-04-07T20:46:41+00:00\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/noiseonthenet.space\\\/noise\\\/2024\\\/03\\\/prime-time\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/noiseonthenet.space\\\/noise\\\/2024\\\/03\\\/prime-time\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/noiseonthenet.space\\\/noise\\\/2024\\\/03\\\/prime-time\\\/#primaryimage\",\"url\":\"https:\\\/\\\/i0.wp.com\\\/noiseonthenet.space\\\/noise\\\/wp-content\\\/uploads\\\/2024\\\/03\\\/by-pils-GiudN8NZhGY-unsplash-reduced.jpg?fit=900%2C1200&ssl=1\",\"contentUrl\":\"https:\\\/\\\/i0.wp.com\\\/noiseonthenet.space\\\/noise\\\/wp-content\\\/uploads\\\/2024\\\/03\\\/by-pils-GiudN8NZhGY-unsplash-reduced.jpg?fit=900%2C1200&ssl=1\",\"width\":900,\"height\":1200},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/noiseonthenet.space\\\/noise\\\/2024\\\/03\\\/prime-time\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/noiseonthenet.space\\\/noise\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Prime Time\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/noiseonthenet.space\\\/noise\\\/#website\",\"url\":\"https:\\\/\\\/noiseonthenet.space\\\/noise\\\/\",\"name\":\"Noise On The Net\",\"description\":\"Sharing adventures in code\",\"publisher\":{\"@id\":\"https:\\\/\\\/noiseonthenet.space\\\/noise\\\/#\\\/schema\\\/person\\\/88c3a70f2b23480197bc61d6e1e2e982\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/noiseonthenet.space\\\/noise\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\\\/\\\/noiseonthenet.space\\\/noise\\\/#\\\/schema\\\/person\\\/88c3a70f2b23480197bc61d6e1e2e982\",\"name\":\"marco.p.v.vezzoli\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/b9d9aab1df560bc14d73b0b442198f196ce39e7c7a38df1dc22fec0b97f17da9?s=96&d=mm&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/b9d9aab1df560bc14d73b0b442198f196ce39e7c7a38df1dc22fec0b97f17da9?s=96&d=mm&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/b9d9aab1df560bc14d73b0b442198f196ce39e7c7a38df1dc22fec0b97f17da9?s=96&d=mm&r=g\",\"caption\":\"marco.p.v.vezzoli\"},\"logo\":{\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/b9d9aab1df560bc14d73b0b442198f196ce39e7c7a38df1dc22fec0b97f17da9?s=96&d=mm&r=g\"},\"description\":\"Self taught assembler programming at 11 on my C64 (1983). Never stopped since then -- always looking up for curious things in the software development, data science and AI. Linux and FOSS user since 1994. MSc in physics in 1996. Working in large semiconductor companies since 1997 (STM, Micron) developing analytics and full stack web infrastructures, microservices, ML solutions\",\"sameAs\":[\"https:\\\/\\\/noiseonthenet.space\\\/noise\\\/\",\"https:\\\/\\\/www.linkedin.com\\\/in\\\/marco-paolo-valerio-vezzoli-0663835\\\/\"],\"url\":\"https:\\\/\\\/noiseonthenet.space\\\/noise\\\/author\\\/marco-p-v-vezzoli\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Prime Time - Noise On The Net","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/noiseonthenet.space\/noise\/2024\/03\/prime-time\/","og_locale":"en_US","og_type":"article","og_title":"Prime Time - Noise On The Net","og_description":"An introduction to coroutines, typestate machine, phantom types, iterators and ownership issues","og_url":"https:\/\/noiseonthenet.space\/noise\/2024\/03\/prime-time\/","og_site_name":"Noise On The Net","article_published_time":"2024-03-25T20:48:00+00:00","article_modified_time":"2024-04-07T20:46:41+00:00","og_image":[{"width":900,"height":1200,"url":"https:\/\/noiseonthenet.space\/noise\/wp-content\/uploads\/2024\/03\/by-pils-GiudN8NZhGY-unsplash-reduced.jpg","type":"image\/jpeg"}],"author":"marco.p.v.vezzoli","twitter_card":"summary_large_image","twitter_misc":{"Written by":"marco.p.v.vezzoli","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/noiseonthenet.space\/noise\/2024\/03\/prime-time\/#article","isPartOf":{"@id":"https:\/\/noiseonthenet.space\/noise\/2024\/03\/prime-time\/"},"author":{"name":"marco.p.v.vezzoli","@id":"https:\/\/noiseonthenet.space\/noise\/#\/schema\/person\/88c3a70f2b23480197bc61d6e1e2e982"},"headline":"Prime Time","datePublished":"2024-03-25T20:48:00+00:00","dateModified":"2024-04-07T20:46:41+00:00","mainEntityOfPage":{"@id":"https:\/\/noiseonthenet.space\/noise\/2024\/03\/prime-time\/"},"wordCount":1197,"commentCount":0,"publisher":{"@id":"https:\/\/noiseonthenet.space\/noise\/#\/schema\/person\/88c3a70f2b23480197bc61d6e1e2e982"},"image":{"@id":"https:\/\/noiseonthenet.space\/noise\/2024\/03\/prime-time\/#primaryimage"},"thumbnailUrl":"https:\/\/i0.wp.com\/noiseonthenet.space\/noise\/wp-content\/uploads\/2024\/03\/by-pils-GiudN8NZhGY-unsplash-reduced.jpg?fit=900%2C1200&ssl=1","keywords":["Rust"],"articleSection":["Language learning"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/noiseonthenet.space\/noise\/2024\/03\/prime-time\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/noiseonthenet.space\/noise\/2024\/03\/prime-time\/","url":"https:\/\/noiseonthenet.space\/noise\/2024\/03\/prime-time\/","name":"Prime Time - Noise On The Net","isPartOf":{"@id":"https:\/\/noiseonthenet.space\/noise\/#website"},"primaryImageOfPage":{"@id":"https:\/\/noiseonthenet.space\/noise\/2024\/03\/prime-time\/#primaryimage"},"image":{"@id":"https:\/\/noiseonthenet.space\/noise\/2024\/03\/prime-time\/#primaryimage"},"thumbnailUrl":"https:\/\/i0.wp.com\/noiseonthenet.space\/noise\/wp-content\/uploads\/2024\/03\/by-pils-GiudN8NZhGY-unsplash-reduced.jpg?fit=900%2C1200&ssl=1","datePublished":"2024-03-25T20:48:00+00:00","dateModified":"2024-04-07T20:46:41+00:00","breadcrumb":{"@id":"https:\/\/noiseonthenet.space\/noise\/2024\/03\/prime-time\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/noiseonthenet.space\/noise\/2024\/03\/prime-time\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/noiseonthenet.space\/noise\/2024\/03\/prime-time\/#primaryimage","url":"https:\/\/i0.wp.com\/noiseonthenet.space\/noise\/wp-content\/uploads\/2024\/03\/by-pils-GiudN8NZhGY-unsplash-reduced.jpg?fit=900%2C1200&ssl=1","contentUrl":"https:\/\/i0.wp.com\/noiseonthenet.space\/noise\/wp-content\/uploads\/2024\/03\/by-pils-GiudN8NZhGY-unsplash-reduced.jpg?fit=900%2C1200&ssl=1","width":900,"height":1200},{"@type":"BreadcrumbList","@id":"https:\/\/noiseonthenet.space\/noise\/2024\/03\/prime-time\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/noiseonthenet.space\/noise\/"},{"@type":"ListItem","position":2,"name":"Prime Time"}]},{"@type":"WebSite","@id":"https:\/\/noiseonthenet.space\/noise\/#website","url":"https:\/\/noiseonthenet.space\/noise\/","name":"Noise On The Net","description":"Sharing adventures in code","publisher":{"@id":"https:\/\/noiseonthenet.space\/noise\/#\/schema\/person\/88c3a70f2b23480197bc61d6e1e2e982"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/noiseonthenet.space\/noise\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/noiseonthenet.space\/noise\/#\/schema\/person\/88c3a70f2b23480197bc61d6e1e2e982","name":"marco.p.v.vezzoli","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/b9d9aab1df560bc14d73b0b442198f196ce39e7c7a38df1dc22fec0b97f17da9?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/b9d9aab1df560bc14d73b0b442198f196ce39e7c7a38df1dc22fec0b97f17da9?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/b9d9aab1df560bc14d73b0b442198f196ce39e7c7a38df1dc22fec0b97f17da9?s=96&d=mm&r=g","caption":"marco.p.v.vezzoli"},"logo":{"@id":"https:\/\/secure.gravatar.com\/avatar\/b9d9aab1df560bc14d73b0b442198f196ce39e7c7a38df1dc22fec0b97f17da9?s=96&d=mm&r=g"},"description":"Self taught assembler programming at 11 on my C64 (1983). Never stopped since then -- always looking up for curious things in the software development, data science and AI. Linux and FOSS user since 1994. MSc in physics in 1996. Working in large semiconductor companies since 1997 (STM, Micron) developing analytics and full stack web infrastructures, microservices, ML solutions","sameAs":["https:\/\/noiseonthenet.space\/noise\/","https:\/\/www.linkedin.com\/in\/marco-paolo-valerio-vezzoli-0663835\/"],"url":"https:\/\/noiseonthenet.space\/noise\/author\/marco-p-v-vezzoli\/"}]}},"jetpack_featured_media_url":"https:\/\/i0.wp.com\/noiseonthenet.space\/noise\/wp-content\/uploads\/2024\/03\/by-pils-GiudN8NZhGY-unsplash-reduced.jpg?fit=900%2C1200&ssl=1","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/pdDUZ5-64","jetpack-related-posts":[],"jetpack_likes_enabled":true,"_links":{"self":[{"href":"https:\/\/noiseonthenet.space\/noise\/wp-json\/wp\/v2\/posts\/376","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/noiseonthenet.space\/noise\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/noiseonthenet.space\/noise\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/noiseonthenet.space\/noise\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/noiseonthenet.space\/noise\/wp-json\/wp\/v2\/comments?post=376"}],"version-history":[{"count":5,"href":"https:\/\/noiseonthenet.space\/noise\/wp-json\/wp\/v2\/posts\/376\/revisions"}],"predecessor-version":[{"id":408,"href":"https:\/\/noiseonthenet.space\/noise\/wp-json\/wp\/v2\/posts\/376\/revisions\/408"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/noiseonthenet.space\/noise\/wp-json\/wp\/v2\/media\/379"}],"wp:attachment":[{"href":"https:\/\/noiseonthenet.space\/noise\/wp-json\/wp\/v2\/media?parent=376"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/noiseonthenet.space\/noise\/wp-json\/wp\/v2\/categories?post=376"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/noiseonthenet.space\/noise\/wp-json\/wp\/v2\/tags?post=376"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}