<?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 Iban Eguia Moraza on Medium]]></title>
        <description><![CDATA[Stories by Iban Eguia Moraza on Medium]]></description>
        <link>https://medium.com/@Razican?source=rss-ec78b1c6dabe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LqBuxwlHiDLlIDA1fE7Mdg.jpeg</url>
            <title>Stories by Iban Eguia Moraza on Medium</title>
            <link>https://medium.com/@Razican?source=rss-ec78b1c6dabe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 09:58:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Razican/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[Learning SIMD with Rust by finding planets]]></title>
            <link>https://medium.com/@Razican/learning-simd-with-rust-by-finding-planets-b85ccfb724c3?source=rss-ec78b1c6dabe------2</link>
            <guid isPermaLink="false">https://medium.com/p/b85ccfb724c3</guid>
            <category><![CDATA[simd]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[high-performance]]></category>
            <dc:creator><![CDATA[Iban Eguia Moraza]]></dc:creator>
            <pubDate>Mon, 02 Jul 2018 20:47:57 GMT</pubDate>
            <atom:updated>2018-09-05T15:36:36.403Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to get the most of Rust while keeping your code portable</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NaJpI2kX7SAZc0u_gM5czA.jpeg" /></figure><p>Rust 1.27.0 has brought SIMD (Single Instruction Multiple Data), also known as vectorization, to stable Rust. If you read <a href="https://blog.rust-lang.org/2018/06/21/Rust-1.27.html#simd">the announcement</a>, you will see that SIMD should bring performance enhancements to our applications if we learn how to use it properly. But, for that let&#39;s first dive into how SIMD works.</p><blockquote>If you feel fairly comfortable with Rust but are still having issues following this text, you might want to read <a href="https://www.packtpub.com/application-development/rust-high-performance">my book</a> about improving the performance of your Rust applications. It should give you all the previous knowledge required for this read.</blockquote><p>Imagine you have the following code:</p><pre>let a = 10;<br>let b = 20;<br>let c = 30;<br>let d = 40;</pre><pre>let ab = a * b;<br>let cd = c * d;</pre><p>As you can see, there are only 2 operations being done with the variables: 2 multiplications (ab and cd). This will take at least 2 instructions in the CPU, depending on the CPU model, but with SIMD, we can do it in only one instruction.</p><p>You might be thinking why do we care about one or two instructions in our whole program, right? Well, we usually don’t have only one multiplication in our code, we most of the time will do these operations in iterations, so it would be nice to be able to perform them in parallel with only one instruction every 2, 4, 8 or even more of them.</p><p>Also, we sometimes have time/money constraints for our code, and we need to be able to run a high performance implementation of our code. Different kinds of SIMD instructions will allow us to do that for our various operations.</p><p>Let’s learn how to do this with an example.</p><h3>VSOP87 algorithm</h3><p>If we want to know where the planets of the solar system are at a given point in time (around 2,000 AD± 4,000 years, depending on the planet), a great tool we can use is the <a href="https://en.wikipedia.org/wiki/VSOP_(planets)">VSOP87 algorithm</a>. This algorithm has 6 variations, but for our example here, we will just take the main variant into account.</p><p>The algorithm just computes a series of polynomials for each of the orbital elements of the planet in question. For each planet, we will get 6 orbital parameters, that can easily be later converted to <a href="https://en.wikipedia.org/wiki/Orbital_elements#Keplerian_elements">Keplerian orbital elements</a>. We won’t go into much detail on which parameters get generated, but you can learn more in the <a href="https://docs.rs/vsop87/2.0.3/vsop87/struct.VSOP87Elements.html">documentation</a> for the parameters in my Rust VSOP87 library.</p><p>The 6 parameters are named, by the variables given in the algorithm paper, as <em>a</em>, <em>l</em>, <em>k</em>, <em>h</em>, <em>q</em> and <em>p</em>. We don’t really need to know what they mean, but let’s see how they get calculated:</p><blockquote>a = a₀t + a₁t² + a₂t³ + a₃t⁴ + a₄t⁵<br>l = l₀t + l₁t² + l₂t³ + l₃t⁴ + l₄t⁵<br>k = k₀t + k₁t² + k₂t³ + k₃t⁴ + k₄t⁵<br>h = h₀t + h₁t² + h₂t³ + h₃t⁴ + h₄t⁵<br>q = q₀t + q₁t² + q₂t³ + q₃t⁴ + q₄t⁵<br>p = p₀t + p₁t² + p₂t³</blockquote><p>Many new things here, I know, but, as you can see, the calculation is simple, only a few polinomials, and only done once, so even if we can optimize these calculations with SIMD, it doesn’t make much of a difference. At least if we don’t need to calculate the position for the planet many times per second, which could be a real use case in a simulation, for example.</p><p>In any case, let’s see what those variables are. The <em>t</em> variable is the time variable, the variable that tells the algorithm for what moment does it need to calculate the position of the planet. It’s a <a href="https://en.wikipedia.org/wiki/Epoch_(astronomy)#Julian_years_and_J2000">Julian year</a>, and can be calculated from a <a href="https://en.wikipedia.org/wiki/Julian_day#Variants">Julian date</a>.</p><p>Then, for each variable, we have from 3 to 5 coefficients, depending on the variable being calculated, and then are multiplied by the <em>t</em> variable with different orders. Those coefficients depend on the <em>t</em> variable, as we will see now.</p><p>First, we should know that the VSOP87 algorithm provides some huge data-sets of constants that are used in the calculation of those variables. For each variable (<em>a₀</em>, <em>a₁</em>, <em>a₂</em>, <em>a₃</em>, <em>a₄</em>, <em>l₀</em>, <em>l₁</em>, <em>l₂</em>…) we have one bi-dimensional matrix or array for each planet. Each matrix, has 3 columns and <em>n</em> rows. For example, <a href="https://github.com/Razican/vsop87-rs/blob/master/src/mars.rs">here</a> you can see the ones for Mars.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*97F5R1KzOcqkIJUKqyatqQ.png" /></figure><p>Then, to calculate each variable, we need to apply the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YYMRrNS9vyQJ1OxXWrVZ9g.png" /><figcaption>Where <em>v</em> is one of a₀, a₁, a₂, l₀, l₁… and n is the number of rows in the matrix / array.</figcaption></figure><p>This formula might be a bit complex, but let’s see what it’s doing. For each 3 elements in each matrix / array row (we call them <em>Vᵢ₀</em>, <em>Vᵢ₁</em> and <em>Vᵢ₂</em>, or simply <em>a</em>, <em>b</em> and <em>c</em> in the code) in , we calculate a * (b + c * t).cos(), (note that this is Rust notation) and then we just sum all of them. And this is where what we saw before gets handy: this function can be optimized with SIMD, since we are performing multiple operations that could be done in parallel. Let’s learn how to do it.</p><h3>Optimizing variable generation with SIMD</h3><p>SIMD is the general name that receive multiple parallel computing implementations for different CPUs. In the case of Intel, we have SSE and AVX implementations, each of them with different versions (SSE, SSE2, SSE3, SSE4, AVX, AVX2 and AVX-512), ARM has Neon instructions, and so on.</p><p>Rust enables SSE and SSE2 optimizations for x86 and x86_64 targets by default. These are pretty old and any x86 processor being used today should handle them properly. In any case, these optimizations are done by the compiler, and it’s not as good as we as programmers can be.</p><p>With Rust 1.27, we can use SSE3, SSE4, AVX and AVX2 manually in the stable channel. AVX-512 is not yet included in the standard library, but it should come <a href="https://twitter.com/rustlang/status/981465404353720322">soon enough</a>. In any case, only specialized processors, and processors coming later this year bring that instruction set.</p><p>If we want to use vectorization in our Rust code, we have to use the <a href="https://doc.rust-lang.org/std/arch/index.html">std::arch</a> or <a href="https://doc.rust-lang.org/core/arch/index.html">core::arch</a> modules (depending if we are using std or not). In there, we have modules for different architectures. For this example, nevertheless, we will be using the AVX instruction set in the x86 and x86_64 sub-modules.</p><p>Why AVX, you might ask? Well, it has all the instructions we need to compute the calculations 4 by 4 (we will be working with 64-bit floating point numbers) and we don’t have access to AVX-512, that would allow 8 by 8 computations.</p><p>AVX has 256-bit registers, that can compute 4 64-bit computations at the same time, or 8 32-bit computations, or 16 16-bit computation, or even 32 8-bit computations. We will be using 2 functions: multiplication and addition. AVX functions start with _mm256_, then, they get the name of the operation (add, mul or abs, for example ) and then the type they will be used on (_pd for doubles or 64-bit floats, _ps for 32-bit floats, _epi32 for 32-bit integers and so on).</p><p>We will therefore be using _mm256_add_pd() and _mm256_mul_pd() functions in this example. We will also use a Rust macro that will enable us to compile the code for CPUs that don’t support AVX, and we will decide to use AVX at <strong>runtime</strong>, if supported. Let’s start by defining the equation above with a nice Rust iterator:</p><pre>#[inline]<br>fn calculate_var(t: f64, var: &amp;[(f64, f64, f64)]) -&gt; f64 {<br>    var.iter()<br>        .fold(0_f64, |term, &amp;(a, b, c)| term + a * (b + c * t).cos())<br>}</pre><p>I added the #[inline] attribute to ask the compiler to inline the function whenever possible, it’s just one expression. This will iterate through the <em>V</em> array, called var, and will for each row, add the result of a * (b + c * t).cos(), just what we need. This will be compiled with some SSE2 optimizations, but we want to do more if AVX is detected. Let’s see how to do it:</p><pre>#[inline]<br>#[allow(unsafe_code)]<br>fn calculate_var(t: f64, var: &amp;[(f64, f64, f64)]) -&gt; f64 {<br>    if is_x86_feature_detected!(&quot;avx&quot;) {<br>        // Safe because we already checked that we have<br>        // AVX instruction set.<br>        unsafe { calculate_var_avx(t, var) }<br>    } else {<br>        var.iter()<br>            .fold(0_f64, |term, &amp;(a, b, c)| {<br>                term + a * (b + c * t).cos()<br>            })<br>    }<br>}</pre><p>The is_x86_feature_detected!() macro will check <strong>at runtime</strong> if the current CPU has the AVX instruction set. If it does, it will execute the calculate_var_avx() unsafe function. If not, it will just fall back to the default, non-AVX implementation. This makes the code portable: compile once, run everywhere.</p><blockquote>Beware, using SIMD in Rust is unsafe, so make sure you check every line of code for safety, like you do in C++, right? ;)</blockquote><p>Now, let’s first import some functions we will use. Note that some of this code will be much nicer once <a href="https://doc.rust-lang.org/unstable-book/library-features/stdsimd.html">stdsimd</a> gets stabilized.</p><pre>use std::{f64, mem};</pre><pre>#[cfg(target_arch = &quot;x86_64&quot;)]<br>use std::arch::x86_64::*;</pre><pre>#[cfg(target_arch = &quot;x86&quot;)]<br>use std::arch::x86::*;</pre><p>Now, let’s define the SIMD function that will be called for each 4 elements:</p><pre>unsafe fn vector_term(<br>    (a1, b1, c1): (f64, f64, f64),<br>    (a2, b2, c2): (f64, f64, f64),<br>    (a3, b3, c3): (f64, f64, f64),<br>    (a4, b4, c4): (f64, f64, f64),<br>    t: f64,<br>) -&gt; (f64, f64, f64, f64) {<br>    unimplemented!()<br>}</pre><p>This function, as you can see, receives 4 tuples <em>(aᵢ, bᵢ, cᵢ)</em> and the <em>t</em> variable. It will return the 4 intermediate terms after computing aᵢ * (bᵢ + cᵢ * t).cos() for each of the tuples. For that, we will follow the strategy of computing first cᵢ * t, with the 4 tuples, then bᵢ + cᵢ * t, then, (bᵢ + cᵢ * t).cos(), and finally, we will multiply <em>aᵢ</em> by the result of the cosine.</p><p>We will need to use core::arch::x86_64::__m256d as the type holding 4 f64, since the _mm256_add_pd() and _mm256_mul_pd() functions only understand that type. Let’s see how to create those types:</p><pre>let a = _mm256_set_pd(a1, a2, a3, a4);<br>let b = _mm256_set_pd(b1, b2, b3, b4);<br>let c = _mm256_set_pd(c1, c2, c3, c4);<br>let t = _mm256_set1_pd(t);</pre><p>The _mm256_set_pd() function will receive 4 f64 and create one __m256d. The _mm256_set1_pd() function will just repeat the given f64 in the 4 positions of a newly created __m256d, so it&#39;s the same as _mm256_set_pd(t, t, t, t). So, now that we have the 4 vectors, let’s start the computation:</p><pre>// Safe because both values are created properly and checked.<br>let ct = _mm256_mul_pd(c, t);<br>// Safe because both values are created properly and checked.<br>let bct = _mm256_add_pd(b, ct);</pre><p>Here, ct will be the vector containing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/166/1*7s74j7UemU4vxMWCgMt6dA.png" /></figure><p>Then, bct will add the 4 b variables to the vector, so bct will be this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*1BhZQW8FYNE1hPdcfv_P3Q.png" /></figure><p>Then, we need to compute the cosine of the 4 results, but Rust does not provide the Intel _mm256_cos_pd() instruction yet. This means that we will need to unpack the vector, calculate the 4 cosines one by one and then pack them again in a vector to calculate the addition of all the <em>a</em> variables. Let’s do it:</p><pre>// Safe because bct_unpacked is 4 f64 long.<br>let bct_unpacked: (f64, f64, f64, f64) = mem::transmute(bct);</pre><pre>// Safe because bct_unpacked is 4 f64 long, and x86/x86_64 is little endian.<br>let bct = _mm256_set_pd(<br>    bct_unpacked.3.cos(),<br>    bct_unpacked.2.cos(),<br>    bct_unpacked.1.cos(),<br>    bct_unpacked.0.cos(),<br>);</pre><p>Here, we have to take something into account: x86/x86_64 is a little endian architecture, which means that the bytes will be stored with the highest value at the lowest index. What means that when we unpack the bct vector, the first element will be b₄ + c₄ * t₄, instead of b₁ + c₁ * t₁.</p><p>Finally, we can compute the terms:</p><pre>// Safe because both values are created properly and checked.<br>let term = _mm256_mul_pd(a, bct);<br>let term_unpacked: (f64, f64, f64, f64) = mem::transmute(term);</pre><p>And we just return that tuple. Let&#39;s now define the calculate_var_avx() function. This function should receive the whole matrix and return the value of the given variable. The way to do it, is to use the chunks() iterator in the array, so that we can get 4 rows each time. Let&#39;s first see how the definition of the function would look like:</p><pre>#[target_feature(enable = &quot;avx&quot;)]<br>#[cfg(any(target_arch = &quot;x86&quot;, target_arch = &quot;x86_64&quot;))]<br>#[allow(unsafe_code)]<br>unsafe fn calculate_var_avx(t: f64, var: &amp;[(f64, f64, f64)]) -&gt; f64 {<br>    unimplemented!()<br>}</pre><p>We are asking the Rust compiler to enable the AVX feature for this particular function. This means that the function must be an unsafe function: we will need to check if the current CPU supports AVX before calling it safely. If you remember from before, we were already doing it.</p><p>Then, we can iterate through the var array:</p><pre>var.chunks(4)<br>    .map(|vec| match vec {<br>       &amp;[(a1, b1, c1), (a2, b2, c2), (a3, b3, c3), (a4, b4, c4)] =&gt; {<br>            // The result is little endian in x86/x86_64.<br>            let (term4, term3, term2, term1) =<br>                vector_term((a1, b1, c1), (a2, b2, c2),<br>                            (a3, b3, c3), (a4, b4, c4), t);</pre><pre>            term1 + term2 + term3 + term4<br>        }<br>        _ =&gt; unimplemented!(),<br>    })<br>    .sum::&lt;f64&gt;()</pre><p>As you can see, using the chunks() iterator, we get arrays that we can pattern-match since Rust 1.26. The first and obvious pattern is having a chunk of 4 tuples that we can directly use in the vector_term() function we defined earlier. The issue with the chunks() iterator is that it will return non-complete chunks if the array length is not a multiple of the chunk size — in this case, 4. It wouldn&#39;t happen with exact_chunks() iterator, but it would discard the extra tuples. At the end of the iterator, that will return intermediate terms, we call the sum() iterator to add everything into a f64. Note that this could be SIMD-optimized by taking elements 8 by 8, adding them 4 by 4, and then 2 by 2 and so on, but it&#39;s out of the scope of this explanation.</p><p>To manage those non-even chunks cases, we can do something like this:</p><pre>&amp;[(a1, b1, c1), (a2, b2, c2), (a3, b3, c3)] =&gt; {<br>    // The result is little endian in x86/x86_64.<br>    let (_term4, term3, term2, term1) = vector_term(<br>        (a1, b1, c1),<br>        (a2, b2, c2),<br>        (a3, b3, c3),<br>        (f64::NAN, f64::NAN, f64::NAN),<br>        t,<br>    );</pre><pre>    term1 + term2 + term3<br>}<br>&amp;[(a1, b1, c1), (a2, b2, c2)] =&gt; {<br>    a1 * (b1 + c1 * t).cos() + a2 * (b2 + c2 * t).cos()<br>},<br>&amp;[(a, b, c)] =&gt; a * (b + c * t).cos(),</pre><p>For the case of 3 tuples, we can just add some NaN on the fourth tuple and discard the result when calling vector_term(). For the case of 2 tuples, we just compute the terms and let the compiler try to optimize it, and for one tuple, we just do it right away.</p><h3>Benchmarks</h3><p>We have learned how to use SIMD in our code, but is it worth it? We cannot improve what we cannot measure, so let’s dive into benchmarking. Using <a href="https://crates.io/crates/criterion">criterion</a>, we can compare the before and after of the change. We will need these lines in our Cargo.toml file:</p><pre>[dev-dependencies]<br>rand = &quot;0.5.2&quot;<br>criterion = &quot;0.2.3&quot;</pre><pre>[[bench]]<br>name = &quot;vsop87&quot;<br>harness = false</pre><p>And then, in benches/vsop87.rs:</p><pre>#[macro_use]<br>extern crate criterion;<br>extern crate rand;<br>extern crate vsop87;</pre><pre>use criterion::Criterion;<br>use rand::{thread_rng, Rng};</pre><pre>fn vsop87_mars(c: &amp;mut Criterion) {<br>    let mut rng = thread_rng();<br>    c.bench_function(&quot;VSOP87 Mars&quot;, move |b| {<br>        b.iter(|| vsop87::mars(rng.gen_range(990930.5, 3912521.5)))<br>    });<br>}</pre><pre>criterion_group!(<br>    vsop87_benches,<br>    vsop87_mars<br>);<br>criterion_main!(vsop87_benches);</pre><p>Then, checking first without AVX optimizations and later with AVX optimizations, the difference I get in my i7–5600U is the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rE4FWovnT3Gq2dEEm010xw.png" /></figure><p>After running benchmarks with all the variants and planets, the improvement is about <strong>9%</strong> to <strong>12%</strong>. And this was only optimizing part of the loop and only with some AVX functions. AVX-512 should clearly improve this benchmark, and being able to compute the cosine in AVX should also help.</p><p>There are libraries such as <a href="https://crates.io/crates/faster">faster</a> and <a href="https://github.com/jackmott/simdeez">simdeez</a> that can help you develop this kind of code for different situations. In the case of faster, though, it will use SIMD for the compiling processor, which makes the code run fast in the processor the code is being compiled in, but can have portability issues in other processors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*i2zFlOiphW_FcDhgu9yYYQ.png" /></figure><p>If you would like to improve even further the performance of your Rust applications, you can check my book: <a href="https://www.packtpub.com/application-development/rust-high-performance">Rust High Performance</a>, that was recently released. It will teach you multiple techniques to forget the idea that Rust is not as fast as the rest of the systems programming languages.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b85ccfb724c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Continuous integration and code coverage report for a Rust project]]></title>
            <link>https://medium.com/@Razican/continuous-integration-and-code-coverage-report-for-a-rust-project-5dfd4d68fbe5?source=rss-ec78b1c6dabe------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dfd4d68fbe5</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[code-coverage]]></category>
            <dc:creator><![CDATA[Iban Eguia Moraza]]></dc:creator>
            <pubDate>Mon, 29 May 2017 11:31:00 GMT</pubDate>
            <atom:updated>2017-05-29T11:31:00.678Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NnjTm1JsnC6acMHjw0i9sw.png" /></figure><p>When I start a new project, learn a new language, or simply do some coding, I cannot find myself confident if I don’t have a complete continuous integration for it. When using Rust, that’s a must, not because it’s important (it’s always important) but because it’s <strong>too easy</strong> to setup. There is no excuse.</p><p>I will explain how I setup continuous integration in my Rust projects using <a href="https://travis-ci.org/">Travis CI</a> and how to report code coverage to <a href="https://codecov.io/">Codecov</a>. Why Codecov? you might ask. Well, I’ve been using Coveralls for some time, but I find their website too faulty. I sometimes don’t see my repos (even if I give them access permissions), sometimes reports don’t work, API fails, and the website itself is designed poorly. Codecov, on the other hand, have a great website, with information presented in a proper way. It works perfectly and has examples for a lot of languages, <a href="https://github.com/codecov/example-rust">including Rust</a>. I hope at this time I don’t have to explain why Travis ;)</p><h3>Continuous Integration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cnvXHhEEppZcj416Mk49Ng.png" /></figure><p>Using Travis CI for continuous integration is easy. Simply sign in with GitHub, and add your repository to your account. Then, you will need to create a .travis.yml file in your repo with the build configuration. And here is where it starts to become interesting. Let’s start with a simple configuration file:</p><pre>language: rust<br>cache: cargo<br>dist: trusty<br>os: <br>  - linux<br>  - osx</pre><pre># Run builds for all the supported trains<br>rust:<br>  - nightly<br>  - beta<br>  - stable<br>  - 1.0.0</pre><pre># The main build<br>script:<br>  - cargo build<br>  - cargo test</pre><p>Lots of things going on here. First, we tell Travis that we want to test Rust code (which installs for us the Rust toolchain in the testing VM). We then add cargo packages to the cache, to speed up new builds, and we select trusty as the testing Ubuntu version (by default, it will use 5 years old Ubuntu, better if we test in 3 years old one). Nevertheless, if testing with older software is required, you can remove that line. Finally, we tell Travis that we want to test both in Linux and MacOS X. This depends on the project, of course (no need to test for MacOS in <a href="https://github.com/OpenStratos/server-rs/blob/develop/.travis.yml">OpenStratos</a>, it’s only for Raspberry Pi).</p><p>Then, we run builds for nightly, beta and stable, and the first Rust version supported by the software. Of course, if our software is only designed to work in nightly, for example, we won’t add stable and beta. I like to add the first supported Rust version so that I can keep track if I break compatibility with old code. Old distributions might not have latest Rust, so it’s best to at least keep track of it. Nevertheless, if I need a new feature, I will break compatibility with older versions, and update the minimum required Rust version to the new feature. Testing on beta enables catching <a href="https://github.com/rust-lang/rust/labels/regression-from-stable-to-beta">stable-to-beta</a> compiler regressions.</p><p>As for the testing scripts, this is up to the project itself. In this simple case, I first build the code, then test it. This differentiates between compilation and unit testing errors. In complex projects, such as OpenStratos, I have builds for each feature set. You can also add packaging tests, for crates being published in crates.io.</p><h4>Extra features: clippy tests</h4><p>You can add clippy tests to your <em>nightly</em> CI by adding this before the script tag:</p><pre># Add clippy<br>before_script:<br>  - |<br>      if [[ &quot;$TRAVIS_RUST_VERSION&quot; == &quot;nightly&quot; ]]; then<br>        ( ( cargo install clippy &amp;&amp; export CLIPPY=true ) || export CLIPPY=false );<br>      fi<br>  - export PATH=$PATH:~/.cargo/bin</pre><p>This will install clippy only for nightly, and export a variable, CLIPPY if the installation is successful. This can fail because clippy sometimes doesn’t catch up with upstream nightly release breakages. After that, you can test with clippy lints adding this to the script tag:</p><pre>  - |<br>      if [[ &quot;$TRAVIS_RUST_VERSION&quot; == &quot;nightly&quot; &amp;&amp; $CLIPPY ]]; then<br>        cargo clippy<br>      fi</pre><p>Of course, if you want fine control on those lints, you can <a href="https://github.com/OpenStratos/server-rs/blob/develop/src/lib.rs#L37">add lints</a> to the top of the lib.rs or main.rs files.</p><h4>Extra features: automatic documentation upload</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GRZXsX-Fs0Cb0V__XlOodw.png" /></figure><p>There is a particular feature that amazes me. With GitHub and Travis, you can upload the documentation of the project to GitHub pages, and make it available for everyone. Of course, now we have <a href="https://docs.rs/">docs.rs</a>, but not all projects are in crates.io (for example, many binary projects) or some projects might want <a href="https://medium.com/@Razican/enforcing-documentation-in-a-medium-size-rust-project-7b6a2a47b6d6#4d98">developer documentation</a> too.</p><p>We will want to upload the documentation only on successful builds (doesn’t make sense to upload docs if the project is broken). For this, we add a new section after the script tag:</p><pre># Upload docs<br>after_success:<br>  - |<br>      if [[ &quot;$TRAVIS_OS_NAME&quot; == &quot;linux&quot; &amp;&amp; &quot;$TRAVIS_RUST_VERSION&quot; == &quot;stable&quot; &amp;&amp; &quot;$TRAVIS_PULL_REQUEST&quot; = &quot;false&quot; &amp;&amp; &quot;$TRAVIS_BRANCH&quot; == &quot;master&quot; ]]; then<br>        cargo doc &amp;&amp;<br>        echo &quot;&lt;meta http-equiv=refresh content=0;url=os_balloon/index.html&gt;&quot; &gt; target/doc/index.html &amp;&amp;<br>        git clone <a href="https://github.com/davisp/ghp-import.git">https://github.com/davisp/ghp-import.git</a> &amp;&amp;<br>        ./ghp-import/ghp_import.py -n -p -f -m &quot;Documentation upload&quot; -r https://&quot;$GH_TOKEN&quot;<a href="http://twitter.com/github">@github</a>.com/&quot;$TRAVIS_REPO_SLUG.git&quot; target/doc &amp;&amp;<br>        echo &quot;Uploaded documentation&quot;<br>      fi</pre><p>This first checks that we are building on linux and on stable (only one upload per build), but can be nightly if the project is not targeting stable. Then checks that it was not a pull request, and that the branch is the master branch (we want the documentation to be only available for the official branch). In that build, we generate the documentation with cargo doc (or with the more complex development documentation <a href="https://medium.com/@Razican/enforcing-documentation-in-a-medium-size-rust-project-7b6a2a47b6d6#4d98">command</a>), and we add a small file as the index. This file will redirect visitors to our main crate documentation, in this case <em>os_balloon</em>.</p><p>After that, we clone a repository that was created to import github pages easily, generate the commit using our GitHub token. Wait, a token? Yes, we don’t want anybody to be able to push docs (or whatever) to our repos. That’s why GitHub enforces the use of a token. You can generate one <a href="https://github.com/settings/tokens">here</a>. Make sure you only give it access to the minimum resources needed.</p><p>After that, and to protect the token for appearing publicly on build logs, we add it to Travis online configuration. In Travis CI, go to your repo settings, and add the GH_TOKEN environment variable, making sure that “Display value in build log” is off:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lXTR4CaHGA9TpmsjFh3i3Q.png" /><figcaption>GH_TOKEN in Travis CI repository configuration.</figcaption></figure><p>After your first successful build in the master branch, you will see the documentation being uploaded to your GitHub pages. You can get the link from the repository configuration in GitHub.</p><h3>Coverage report with Codecov</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*ovkUCR-1GGBf-sviIA2J1g.png" /></figure><p>As promised, I wasn’t going to talk only about the continuous integration. Code coverage is as important as the CI, since even if we do lots of unit testing during our CI builds, we might not know how to check if we are properly testing all our code paths. That’s where code coverage checking starts to make sense.</p><p>Luckily Codecov gives us a great interface and integration with GitHub, BitBucket and GitLab, by using Travis CI or even Circle CI. To enable this, we will need to add some parameters to our travis.yml, as shown in the <a href="https://github.com/codecov/example-rust/blob/master/.travis.yml">exmaple</a>. First, after the Rust versions, we will need to add:</p><pre>sudo: true</pre><pre>before_install:<br>  - sudo apt-get update</pre><pre>addons:<br>  apt:<br>    packages:<br>      - libcurl4-openssl-dev<br>      - libelf-dev<br>      - libdw-dev<br>      - cmake<br>      - gcc<br>      - binutils-dev</pre><p>This will first update all packages in the VM distribution, and then install some packages required to compile <em>kcov</em>, the tool we will use to collect Rust project coverage results. Then, in the after_success tag, we will add this:</p><pre># Coverage report<br>  - |<br>      if [[ &quot;$TRAVIS_OS_NAME&quot; == &quot;linux&quot; &amp;&amp; &quot;$TRAVIS_RUST_VERSION&quot; == &quot;stable&quot; ]]; then<br>        wget <a href="https://github.com/SimonKagstrom/kcov/archive/master.tar.gz">https://github.com/SimonKagstrom/kcov/archive/master.tar.gz</a> &amp;&amp;<br>        tar xzf master.tar.gz &amp;&amp;<br>        cd kcov-master &amp;&amp;<br>        mkdir build &amp;&amp;<br>        cd build &amp;&amp;<br>        cmake .. &amp;&amp;<br>        make &amp;&amp;<br>        sudo make install &amp;&amp;<br>        cd ../.. &amp;&amp;<br>        rm -rf kcov-master &amp;&amp;<br>        for file in target/debug/examplerust-*[^\.d]; do mkdir -p &quot;target/cov/$(basename $file)&quot;; kcov --exclude-pattern=/.cargo,/usr/lib --verify &quot;target/cov/$(basename $file)&quot; &quot;$file&quot;; done &amp;&amp;<br>        bash &lt;(curl -s <a href="https://codecov.io/bash">https://codecov.io/bash</a>) &amp;&amp;<br>        echo &quot;Uploaded code coverage&quot;<br>      fi</pre><p>This first makes sure it will only generate coverage reports for stable builds in linux (only once per build). But it will generate reports for all branches and pull requests (ideal if you want to enforce some coverage in PRs). It will then download <em>kcov</em> from its repo, decompress it, compile it, and install it. It will then remove the downloaded repo.</p><p>Then, in the for, all the magic happens. It will search for all files in the target/debug starting, in this case, with <em>examplerust-</em>, and report coverage on them. The [^\.d] regex is there because Rust generates some .d ended files without coverage information, that break kcov. You will need to change that beginning of files by your project’s stem. In projects with multiple libs, or external tests/ dir, or both binaries and libraries more than one could be generated.</p><p>A simple way of knowing what files get generated is to simply cargo test the project in your local computer. Then you will be able to check all generated files in target/debug :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B7AIArzG5-EnT29o8BQ19g.png" /><figcaption>Generated files for OpenStratos.</figcaption></figure><p>In the case of openstratos, we see that some of them start with <em>launcher-</em> and others start with <em>os_balloon-</em>. This is because it has a lib.rs and a main.rs file, but it does not have an external tests directory. In this case, we will need to add two for loops. The loop is required because we might generate more than one test for each binary:</p><pre>for file in target/debug/os_balloon-*[^\.d]; do mkdir -p &quot;target/cov/$(basename $file)&quot;; kcov --exclude-pattern=/.cargo,/usr/lib --verify &quot;target/cov/$(basename $file)&quot; &quot;$file&quot;; done &amp;&amp;<br>for file in target/debug/launcher-*[^\.d]; do mkdir -p &quot;target/cov/$(basename $file)&quot;; kcov --exclude-pattern=/.cargo,/usr/lib --verify &quot;target/cov/$(basename $file)&quot; &quot;$file&quot;; done &amp;&amp;</pre><p>The script ends by getting and executing a bash script from Codecov, that directly sends all the data to their services. You can check OpenStratos coverage reports <a href="https://codecov.io/gh/OpenStratos/server-rs/branch/develop">here</a>. I know, 77% (at the time of this writing) is not enough. We are still on heavy development :)</p><h3>Extra: badges</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*hCjXunrmVK50AJKpm5zvGQ.png" /></figure><p>What would a repository be without badges? don’t want to know/remember. We can add both Travis CI and CodeCov badges to the repository README, or even to crates.io. For that, we will need to get the badge from Travis at the repo build results. We can get it in markdown, which will look pretty well. Codecov badge can be obtained from the repository settings. <a href="https://github.com/OpenStratos/server-rs/blob/develop/README.md#openstratos">Here</a> is how it looks in OpenStratos, you can check the source code for the badges.</p><p>For crates.io is even easier. Simply add the badges section to the Cargo.toml:</p><pre>[badges]<br>travis-ci = { repository = &quot;Razican/vsop87-rs&quot;, branch = &quot;master&quot; }<br>codecov = { repository = &quot;Razican/vsop87-rs&quot;, branch = &quot;master&quot;, service = &quot;github&quot; }</pre><p>You will need to change repository and branch. Note that codecov badge is only available on nightly, and will need a couple of months before you can use it in stable cargo. You can nevertheless use cargo +nightly publish.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dfd4d68fbe5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enforcing documentation in a medium-size Rust project]]></title>
            <link>https://medium.com/@Razican/enforcing-documentation-in-a-medium-size-rust-project-7b6a2a47b6d6?source=rss-ec78b1c6dabe------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b6a2a47b6d6</guid>
            <category><![CDATA[documentation]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[tricks]]></category>
            <category><![CDATA[linter]]></category>
            <category><![CDATA[balloons]]></category>
            <dc:creator><![CDATA[Iban Eguia Moraza]]></dc:creator>
            <pubDate>Mon, 22 May 2017 11:31:01 GMT</pubDate>
            <atom:updated>2017-05-22T11:31:01.396Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ugmV6yRlO5BibETuZs7stA.png" /></figure><p>In the <a href="https://medium.com/@Razican/going-to-the-edge-of-space-safely-with-openstratos-and-rust-f58fba8bf151">last post</a>, I explained what OpenStratos was and how the main logic was being implemented with a finite state machine checked in compilation time.</p><p>In a medium-size project like sending balloons to the stratosphere (4k-5k C++ code in the old version), documentation is a must. I’m not the only developer working with the code, and I hope I can get more contributions in the future, so I must document the code-base properly and extensively.</p><p>Rust, fortunately, gives us a great documentation system: add some comments using three slashes instead of two at the beginning of each line and run cargo doc --open. All public items will be documented with a lot of information, and the documentation will be opened in your browser (remove the --open flag if you do not want to open the browser). You can even add #![deny(missing_docs)] at the top of your <em>lib.rs</em> or <em>main.rs</em> and the compiler itself will refuse to compile the code if there is any public item without documentation.</p><p>This is great if you are creating a library that you only want to upload<a href="https://crates.io/"> to crates.io</a>, but it might not be enough if what you want is to have proper documentation for other developers. You will also want to have private items documented, and you will also want to be able to generate HTML documentation for those private members.</p><h3>Clippy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*tSlSa0ECREsm7DbEi2CVIw.png" /><figcaption>A bunch of clippy / rustc lints on top of a lib.rs file.</figcaption></figure><p>Here is where <a href="https://crates.io/crates/clippy">clippy</a> has something to say. Clippy is a collection of lints that can be activated on top of those provided by the Rust compiler itself to lint against common <em>spaghetti</em> code or improper API usage. You can find the complete list of lints in <a href="https://github.com/Manishearth/rust-clippy/wiki">its wiki</a>, with a clear description of each of them and an explanation of why should you use them. Clippy turns on some lints by default, and if you follow its guidelines you will create more correct Rust code.</p><p>To install clippy you will need Cargo nightly. If you installed Rust with rustup, you can simply install it by running rustup toolchain install nightly. After that, you can install clippy by running cargo +nightly install clippy.</p><p>Among clippy’s lints, there is <a href="https://github.com/Manishearth/rust-clippy/wiki#missing_docs_in_private_items">one</a> that is not active by default and that it can make sure we don’t forget our development-oriented private item documentation. Adding #[forbid(missing_docs_in_private_items)] at the top of your <em>lib.rs</em> or <em>main.rs</em> will make the crate to stop compiling (if you compile with cargo clippy instead of cargo build) until you add comments to all private items.</p><h3>Generating developer documentation</h3><p>In Rust, if you run cargo doc, you will get the public API documentation for a crate. Once again, if what you want is to have a proper internal documentation, that won’t be enough. There is <a href="https://github.com/rust-lang/cargo/issues/1520">an open issue</a> to add a command to Cargo to generate documentation to private items, but until then, you will need to run this:</p><pre>cargo rustdoc --open -- --no-defaults --passes collapse-docs --passes unindent-comments --passes strip-priv-imports</pre><p>Not as easy as it should be, but it works. Once again, you should remove the --open flag if you do not want it to open the browser. You can find the documentation for OpenStratos library <a href="https://openstratos.github.io/server-rs/os_balloon/index.html">here</a>, and <a href="https://openstratos.github.io/server-rs/launcher/index.html">here</a> for the launcher.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b6a2a47b6d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going to the edge of space safely, with OpenStratos and Rust]]></title>
            <link>https://medium.com/@Razican/going-to-the-edge-of-space-safely-with-openstratos-and-rust-f58fba8bf151?source=rss-ec78b1c6dabe------2</link>
            <guid isPermaLink="false">https://medium.com/p/f58fba8bf151</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[space]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[balloons]]></category>
            <dc:creator><![CDATA[Iban Eguia Moraza]]></dc:creator>
            <pubDate>Mon, 15 May 2017 11:31:01 GMT</pubDate>
            <atom:updated>2017-05-15T11:31:01.138Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qj_Jn6ImYLX-wGB8BNIpkg.jpeg" /></figure><p>Hi there, I’m Iban, a software developer that loves to try new things, currently loving the Rust programming language. I will be publishing coding examples about how I solve certain issues in <strong>Rust</strong>. Feel free to comment or ask for help ;)</p><p>From the huge amount of projects that I would like to implement, I’m currently focusing my time in two. <a href="http://superanalyzer.rocks/">SUPER Android Analyzer</a> and <a href="https://openstratos.org/">OpenStratos</a>. The first is an Android application analyzer for desktop where you can get reports about potential vulnerabilities in Android apps. The second is a project to send balloons to the stratosphere while developing all the code and the final hardware integration directly by me and some collaborators. I will talk about <strong>OpenStratos</strong> in this post.</p><p>OpenStratos has gone to the stratosphere twice, and things didn’t go really well. The first time, we lost the probe after receiving some mayday messages. We were able to recover it a month later though, thanks to my mobile phone number being attached to the capsule, and we learned tons of useful information.</p><p>The second time was even worse. After the launch confirmation message, we didn’t receive any extra communication, and never recovered the probe. This means we almost didn’t learn anything from it, since all the logs get stored in the probe itself.</p><p>After these issues, I decided to do something about it. I had been learning Rust for some time (almost two years now) and I knew the potential of that memory-safe, concurrent language. Two of the features I knew would impact OpenStratos positively were the type-level control flows checked at compilation time and the exhaustive pattern matching: no way to forget about one possible outcome.</p><p>The original OpenStratos version was <a href="https://github.com/OpenStratos/server">written in C++</a>, so I would need to port the whole code-base to a new language. Not only that: since in the first version we had issues with SMS messaging and information not reaching the ground, I wanted to add real-time telemetry to the probe.</p><h3>Hardware overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5qZB1g9pRaIzEsFRqsqDsw.jpeg" /><figcaption>Hardware setup for OpenStratos Hypathia (first launch).</figcaption></figure><p>Before diving into the code, I would like to give a small explanation of the hardware in OpenStratos. The main computer is a <strong>Raspberry Pi</strong>. Originally it was a Raspberry Pi A+, but in the new version it will be changed for a Raspberry Pi Zero. This platform gives us a great tested hardware with upstream Linux support. It gives us a great camera accessory that we will use to take pictures and video with surprisingly good quality, and its weight and power consumption are really low: ideal for going to the edge of space.</p><p>Apart from the main computer and camera, the probe needs to know its current position (in 3D, to detect launch and balloon burst). For this, the probe is equipped with a stratosphere-tested <a href="https://store.uputronics.com/index.php?route=product/product&amp;path=60_64&amp;product_id=84">GPS module</a>. Of course, we wanted to do all the GPS frame parsing ourselves, and that will be part of another post.</p><p>Additionally, OpenStratos has one communication mechanism, a GSM module (<a href="https://medium.com/@Razican/going-to-the-edge-of-space-safely-with-openstratos-f58fba8bf151">Adafruit FONA</a>) that has an ADC (analog-digital converter) connector that we use to check main battery usage. It can also report about the second (GSM) battery. Once again, the whole GSM messaging is implemebted by us using the message protocol for the FONA module. This module is used to send SMSs in different milestones of the mission (such as launch preparation, launch confirmation and landing, among others). The main issue is that it must be powered off to save battery once we get over 1.5km altitude or so (there is no GSM connectivity there).</p><p>For this new version, and due to the issues we had with the GSM, we’re adding a <strong>real-time telemetry</strong> mechanism. For that, we are using some long range <a href="https://www.digi.com/products/xbee-rf-solutions/embedded-rf-modules-modems/xbee-pro-900hp">XBee PRO</a> modules. These modules can connect up to 45km in direct line of sight, and since our balloon will get to about 30–35km in altitude, it should be enough for most of the time (we will follow the balloon from ground). Even if we lose some telemetry, it’s not critical as long as we can find the probe after landing and as long as we get enough information in case of a failure. GSM will be used as a backup. XBees will be preconfigured with XCTU (Digi’s software to configure XBees) to be able to use transparent serial. No need to implement all XBee logic if we have only two modules, one server (in the probe) and one client (in a laptop in the chasing car).</p><p>Of course, all this needs power, and the probe uses one lightweight LiPo (lithium polymer) <a href="https://www.banggood.com/ZOP-Power-6000MAH-7_4V-25C-Lipo-Battery-T-Plug-p-991459.html">battery</a> to power it for at least 6 hours (potentially even 10). This battery might need upgrading for the new XBee modules. Some extra components such as a heatsink for the computer and some connectors are used, but they are not needed to understand the software-facing hardware setup.</p><h3>Software logic</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*IWdmQWcM8gl52GEiCQ-umA.png" /></figure><p>OpenStratos’ balloon logic is pretty straightforward. It has a <strong>state machine</strong>, that starts with an initialization state and ends with a shut down. It has also two special states: an eternal loop if there is no GPS to detect launch or landing, and a safe mode, in case something goes wrong. The original version had a recovery mode in case the safe mode went wrong, which is not expected in the new Rust version.</p><p>I don’t want to go into details for each state, but I would like to introduce a bit of each so that the final implementation can be understood.</p><p>The initialization state is in charge of checking the camera, turning on the GPS, the GSM and once implemented, it will be in charge of initializing the telemetry and connecting with the client. Logging will also be initialized even before the state machine is in place. Once this is finished, the balloon will switch to a new state, where it will wait until the GPS gets a fix from satellites.</p><p>Once the fix is in place, a new state will send an SMS (I still have to check if this is really needed once we have telemetry) to confirm that the balloon is ready for launch. Until this SMS is sent, errors will shut down the probe with the logs being stored in a <em>data</em> folder. Once this SMS is sent, the balloon assumes that it could be launched anytime, so it will never shut down (the OS could restart/shut down in extreme temperatures, but not the core software, except on really critical conditions).</p><p>The balloon will then start recording video and wait for launch, detected by a change in altitude. Once in flight, it will send a launch confirmation SMS (once again, I will have to check if it’s needed), and enter a new state. Going up is a simple state. It will log the altitude milestones (5km, 10km…) once in a while in a log file, and will wait for the balloon burst. Meanwhile, another thread will be in charge of taking pictures, videos and so on. Not important right now.</p><p>The balloon burst will be detected by a sudden change in the altitude (going down) or by detecting that the balloon has gone down 1km from the maximum altitude if the first check fails. Once the balloon starts its descent slowed down by the parachute, no more pictures will be taken (only video), and the new state will log the altitude milestones backwards. It will detect the landing once it stays below 4 km in the same altitude for some time. It will try to send up to 3 SMSs when going down, just in case something goes wrong on landing (you know, <a href="https://twitter.com/elonmusk/status/743097668725940225">RUD</a>s happen).</p><p>This will change its state to a landing state. Once landed, It will send an SMS with the landing coordinates, then wait for 10 minutes and send another SMS. The second one is just in case it landed in a moving element, such as a river or the top of a truck.</p><p>Once the second SMS is sent, the shut-down state will shut down all peripherals and shut the probe down.</p><h3>Implementing a compile-time safe state machine in Rust</h3><p>The whole point of this post was not only to introduce OpenStratos, but to give some insights on how I implemented its state machine in 100% safe and compile-time checked Rust. In the C++ version, <a href="https://github.com/OpenStratos/server/blob/88064679bf692c06b4ad1484c030d97df84b73af/logic/main_while.cc#L7">the implementation</a> was rather rudimentary. Only a simple while with an enumeration: I had to implement all the error-prone logic by hand. I knew Rust could do better.</p><p>The whole idea lays behind these three <a href="http://rust-lang.github.io/book/second-edition/ch10-02-traits.html">traits</a>:</p><pre>/// Trait representing a state machine.<br>pub trait StateMachine {<br>    /// The logic to run after the current state.<br>    type Next: MainLogic;</pre><pre>    /// Executes this state and returns the next one.<br>    fn execute(self) -&gt; Result&lt;Self::Next&gt;;<br>}</pre><pre>/// Trait to get the current state in the `State` enum for the<br>/// current state in the state machine.<br>pub trait GetState {<br>    /// Gets the state enumeration variant for the current state.<br>    fn get_state(&amp;self) -&gt; State;<br>}</pre><pre>/// Trait implementing the main logic of the program.<br>pub trait MainLogic: GetState {<br>    /// Performs the main logic of the state.<br>    fn main_logic(self) -&gt; Result&lt;()&gt;;<br>}</pre><p>The StateMachine trait makes sure that every state that implements StateMachine will have a next state. And not only that, it makes sure that next state will have some sort of logic implementation. Moreover, both the execute() and main_logic() functions will consume its current structure, so there is no way for a state to be called twice. It will also make sure in compile time that all states with logic will have a function that returns the current state in the State enum. This enables us to add the following default implementation:</p><pre>lazy_static! {<br>    static ref CURRENT_STATE: Mutex&lt;State&gt; = Mutex::new(State::Init);<br>}</pre><pre>impl&lt;S&gt; MainLogic for S<br>    where S: StateMachine + GetState<br>{<br>    fn main_logic(self) -&gt; Result&lt;()&gt; {<br>        let new_state = self.execute()?;<br>        {<br>            let mut current_state = match CURRENT_STATE.lock() {<br>                Ok(guard) =&gt; guard,<br>                Err(poisoned) =&gt; poisoned.into_inner(),<br>            };<br>            *current_state = new_state.get_state();<br>        }<br>        new_state.main_logic()<br>    }<br>}</pre><p>Here we implement the MainLogic trait for all state machines, and it’s as simple as executing the current state, changing the global CURRENT_STATE, and then executing the main logic of the next state. This means that we now only have to write the execute() function for each state, and define the proper traits. For the last state, we will implement MainLogic but not StateMachine, since it won’t have a next state. Here is an example state:</p><pre>impl StateMachine for OpenStratos&lt;GoingUp&gt; {<br>    type Next = OpenStratos&lt;GoingDown&gt;;</pre><pre>    fn execute(self) -&gt; Result&lt;Self::Next&gt; {<br>        unimplemented!()<br>    }<br>}</pre><p>We have defined three more structures and an enumeration here:</p><pre>pub struct OpenStratos&lt;S: GetState&gt; {<br>    state: S,<br>}</pre><pre>impl&lt;S&gt; GetState for OpenStratos&lt;S&gt;<br>    where S: GetState<br>{<br>    fn get_state(&amp;self) -&gt; State {<br>        self.state.get_state()<br>    }<br>}</pre><pre>#[derive(Debug, Clone, Copy, PartialEq, Eq)]<br>pub enum State {<br>    Init,<br>    AcquiringFix,<br>    FixAcquired,<br>    WaitingLaunch,<br>    GoingUp,<br>    GoingDown,<br>    Landed,<br>    ShutDown,<br>    SafeMode,<br>}</pre><pre>pub struct GoingUp;</pre><pre>impl GetState for GoingUp {<br>    fn get_state(&amp;self) -&gt; State {<br>        State::GoingUp<br>    }<br>}</pre><pre>pub struct GoingDown;</pre><pre>impl GetState for GoingDown {<br>    fn get_state(&amp;self) -&gt; State {<br>        State::GoingDown<br>    }<br>}</pre><p>As it can be seen, except the State enum, GoingDown, GoingUp or OpenStratos occupy zero bytes in memory, so they have no information. This means that all the logic will be implemented at compile time, no need for extra information at runtime. Those structures are there for type checking, a common practice in Rust. You can specify that the next state after going up is going down, at type level.</p><p>The only points of failure of this approach are the StateMachine implementation for each state (it will have to be checked so that the next state is the proper one) and the GetState implementation for each state, that can be checked with simple tests to ensure it will always return the proper state enumeration variant:</p><pre>#[cfg(test)]<br>mod tests {<br>    use super::*;</pre><pre>    #[test]<br>    fn it_get_state_init() {<br>        let state = Init;<br>        assert_eq!(state.get_state(), State::Init);<br>    }<br>}</pre><h3>Conclusion</h3><p>Even if the current implementation is still in its beginnings (the current source code can be found <a href="https://github.com/OpenStratos/server-rs">in GitHub</a>), I’m already seeing the benefits of using Rust. Much less information to check by myself, so much less error-prone.</p><p>Please feel free to comment this code, improve it or contribute to the main repository. I will be posting more insights on the new implementation as it progresses. Thanks for reading!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5FpV4kkwJ-baJ_uaN9cCdQ.jpeg" /><figcaption>OpenStratos Hypathia launch squad.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f58fba8bf151" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>