<?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 Ahmed Ali on Medium]]></title>
        <description><![CDATA[Stories by Ahmed Ali on Medium]]></description>
        <link>https://medium.com/@1xahmed?source=rss-d34e7ee43e8f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MEU9lq-CY2Wc96NGlCuX1g.jpeg</url>
            <title>Stories by Ahmed Ali on Medium</title>
            <link>https://medium.com/@1xahmed?source=rss-d34e7ee43e8f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 09:29:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@1xahmed/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[1.9 Vectors]]></title>
            <link>https://medium.com/@1xahmed/1-9-vectors-7c5dfb2804ea?source=rss-d34e7ee43e8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c5dfb2804ea</guid>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[růst]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[rustpro]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Ahmed Ali]]></dc:creator>
            <pubDate>Thu, 15 Aug 2024 11:46:42 GMT</pubDate>
            <atom:updated>2024-08-15T11:46:42.203Z</atom:updated>
            <content:encoded><![CDATA[<p>Vectors are like arrays, but can change size. They are stored on the heap, so they are slower than arrays, but they are still fast. They are the most common collection type in Rust. Vectors guarantee that everything will be stored contiguously. They also allocate spare space — so you are using more memory than you need, but you don’t have to reallocate as often. Vectors double in size every time you run out of capacity — -which makes them fast, but you can waste a lot of memory if you don’t need it.</p><p>Let’s create a vector of users:</p><pre>pub fn get_users() -&gt; Vec&lt;User&gt; {<br>    vec![<br>        User::new(&quot;admin&quot;, &quot;password&quot;, Role::Admin),<br>        User::new(&quot;bob&quot;, &quot;password&quot;, Role::User),<br>    ]<br>}</pre><p>The vec! macro is a helper that moves a list of entries in array format into a vector. You can also do:</p><pre>pub fn get_users() -&gt; Vec&lt;User&gt; {<br>    let mut users = Vec::new();<br>    users.push(User::new(&quot;admin&quot;, &quot;password&quot;, Role::Admin));<br>    users.push(User::new(&quot;bob&quot;, &quot;password&quot;, Role::User));<br>    users<br>}</pre><p>Now the great part is that the login function doesn&#39;t need to change. Iterators are standardized across most collection types, so you can use the same code for arrays and vectors.</p><h3>Vector Growth</h3><blockquote><em>Tip: if you know how big a vector should be, you can create it with </em><em>Vec::with_capacity(n) to avoid reallocation.</em></blockquote><p>Let’s create a quick side project to see how vectors grow. Create a new project with cargo new vector_growth. Don&#39;t forget to update the workspace! Add this to src/main.rs:</p><pre>fn main() {<br>    let mut my_vector = Vec::new();<br>    for _ in 0..20 {<br>        my_vector.push(0);<br>        println!(&quot;Size: {}, Capacity: {}&quot;, my_vector.len(), my_vector.capacity());<br>    }<br>}</pre><p>This shows:</p><pre>Size: 1, Capacity: 4<br>Size: 2, Capacity: 4<br>Size: 3, Capacity: 4<br>Size: 4, Capacity: 4<br>Size: 5, Capacity: 8<br>Size: 6, Capacity: 8<br>Size: 7, Capacity: 8<br>Size: 8, Capacity: 8<br>Size: 9, Capacity: 16<br>Size: 10, Capacity: 16<br>Size: 11, Capacity: 16<br>Size: 12, Capacity: 16<br>Size: 13, Capacity: 16<br>Size: 14, Capacity: 16<br>Size: 15, Capacity: 16<br>Size: 16, Capacity: 16<br>Size: 17, Capacity: 32<br>Size: 18, Capacity: 32<br>Size: 19, Capacity: 32<br>Size: 20, Capacity: 32</pre><p>Now imagine that you are downloading 1,000,000 items from a database. You want to be careful that you aren’t using 2,000,000 capacity slots when you only need 1,000,000. You can use Vec::shrink_to_fit() to reduce the capacity to the size of the vector. This is a hint to the compiler, so it may not actually shrink the vector. You can also use Vec::reserve(n) to reserve n slots in the vector. This is a hint to the compiler, so it may not actually reserve the slots.</p><h3>Collecting from Iterators</h3><p>You can collect from an iterator into a vector. This is useful if you want to filter or map a vector. For example, let’s say that you want to get all of the users with a role of User. You can do this:</p><pre>let users: Vec&lt;User&gt; = get_users().into_iter().filter(|u| u.role == Role::User).collect();</pre><h3>Deleting from a Vector — -using Retain</h3><p>You can delete vector entries with retain. This will delete all users except for “kent”. Retain takes a function — -closure — -that returns true if an entry should be kept.</p><pre>users.retain(|u| u.username == &quot;kent&quot;);</pre><h3>Deleting from a Vector — -using Remove</h3><p>You can delete vector entries with remove. This will delete the first user. Remove takes an index.</p><pre>users.remove(0);</pre><h3>Deleting from a Vector — -using Drain</h3><p>Drain is a special type of delete. It will delete everything, and give it to you as an iterator on the way out. This is useful if you want to delete everything, but you want to do something with the data before you delete it.</p><pre>let deleted_users: Vec&lt;User&gt; = users.drain(..).collect();</pre><p>Or more usefully:</p><pre>let deleted_users: Vec&lt;User&gt; = users.drain(..).for_each(|user| println!(&quot;Deleting {user:?}&quot;));</pre><p>Vectors really are a swiss-army knife: they can do almost anything. They are fast, and they are easy to use. They are the most common collection type in Rust.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c5dfb2804ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[1.8 Structures]]></title>
            <link>https://medium.com/@1xahmed/1-8-structures-827094d7fbbf?source=rss-d34e7ee43e8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/827094d7fbbf</guid>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[rustpro]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[růst]]></category>
            <dc:creator><![CDATA[Ahmed Ali]]></dc:creator>
            <pubDate>Thu, 15 Aug 2024 11:35:51 GMT</pubDate>
            <atom:updated>2024-08-15T11:35:51.743Z</atom:updated>
            <content:encoded><![CDATA[<p>You probably don’t really want to have to write an if statement covering every user in your enterprise. Instead, you want to store usernames and passwords in a structure, along with the user&#39;s role.</p><h3>Basic Structures</h3><p>You can define a simple structure like this:</p><pre>pub struct User {<br>    pub username: String,<br>    pub password: String,<br>    pub role: Role,<br>}</pre><p>Structs aren’t object-oriented, but they share some commonality with objects from other languages. You can define methods on them, and you can define associated functions (functions that are called on the type, not on an instance of the type). Let’s make a constructor:</p><pre>impl User {<br>    pub fn new(username: &amp;str, password: &amp;str, role: LoginRole) -&gt; User {<br>        User {<br>            username: username.to_lowercase(),<br>            password: password.to_string(),<br>            role,<br>        }<br>    }<br>}</pre><h3>Array of Structures</h3><p>Let’s create a function that creates an array of users:</p><pre>pub fn get_users() -&gt; [User; 2] {<br>    [<br>        User::new(&quot;admin&quot;, &quot;password&quot;, LoginRole::Admin),<br>        User::new(&quot;bob&quot;, &quot;password&quot;, LoginRole::User),<br>    ]<br>}</pre><p>Arrays can never change in size, so with an array you are stuck with two users. Arrays do have the advantage of remaining on the stack, making them very fast to access.</p><p>Let’s modify the login function to use this array:</p><pre>pub fn login(username: &amp;str, password: &amp;str) -&gt; Option&lt;LoginAction&gt; {<br>    let users = get_users();<br>    if let Some(user) = users.iter().find(|user| user.username == username) {<br>        if user.password == password {<br>            return Some(LoginAction::Granted(user.role));<br>        } else {<br>            return Some(LoginAction::Denied);<br>        }<br>    }<br>    None<br>}</pre><p>if let works just like match, but for a single case. You can also write match users.iter().find(|user| user.username == username &amp;&amp; user.password == password) { Some(user) =&gt; LoginAction::from(user.role), None =&gt; LoginAction::Denied } if you prefer.</p><p>This doesn’t compile. Enumerations aren’t copyable by default, because there’s no guaranty that the contents are copyable. Add #[derive(Clone)] to the Role enumeration to make it clonable, and return a <em>clone</em> of the role:</p><pre>pub fn login(username: &amp;str, password: &amp;str) -&gt; Option&lt;LoginAction&gt; {<br>    let users = get_users();<br>    if let Some(user) = users.iter().find(|user| user.username == username) {<br>        if user.password == password {<br>            return Some(LoginAction::Granted(user.role.clone()));<br>        } else {<br>            return Some(LoginAction::Denied);<br>        }<br>    }<br>    None<br>}</pre><p>We can test this with the login program, which hasn’t changed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=827094d7fbbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enumerations in Rust]]></title>
            <link>https://medium.com/@1xahmed/enumerations-in-rust-489ae630a94f?source=rss-d34e7ee43e8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/489ae630a94f</guid>
            <category><![CDATA[rustpro]]></category>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <dc:creator><![CDATA[Ahmed Ali]]></dc:creator>
            <pubDate>Thu, 15 Aug 2024 11:23:17 GMT</pubDate>
            <atom:updated>2024-08-15T11:23:35.908Z</atom:updated>
            <content:encoded><![CDATA[<h3>1.7 Enumerations in Rust</h3><p>Enumerations in Rust are <em>very</em> powerful — -they are “algebraic data types” that can capture a lot of data. They are also “sum types” — -meaning they only contain one of the types they are defined to contain.</p><p>You probably want more options than just “you are allowed in” and “you aren’t permitted”. You want to know <em>why</em> you aren’t permitted. You want to know if the user is locked out, or if they have the wrong password, or if they are a new user and need to register. If the login succeeds, you want to know if they are an admin or a regular user.</p><h3>Basic Enumerations</h3><p>Let’s start with the most basic enumeration, which should be familiar from other languages:</p><pre>pub enum LoginAction {<br>    Admin,<br>    User,<br>    Denied,<br>}</pre><p>Now we can update the login function to return this enumeration:</p><pre>pub fn login(username: &amp;str, password: &amp;str) -&gt; LoginAction {<br>    let username = username.to_lowercase();<br>    if username == &quot;admin&quot; &amp;&amp; password == &quot;password&quot; {<br>        LoginAction::Admin<br>    } else if username == &quot;bob&quot; &amp;&amp; password == &quot;password&quot; {<br>        LoginAction::User<br>    } else {<br>        LoginAction::Denied<br>    }<br>}</pre><p>And we can update the application to use it:</p><pre>let mut tries = 0;<br>loop {<br>    println!(&quot;Enter your username:&quot;);<br>    let username = read_line();<br>    println!(&quot;Enter your password:&quot;);<br>    let password = read_line();<br>    match login(&amp;username, &amp;password) {<br>        LoginAction::Admin =&gt; {<br>            println!(&quot;Welcome {username}, you are an admin.&quot;);<br>            break;<br>        }<br>        LoginAction::User =&gt; {<br>            println!(&quot;Welcome {username}, you are a regular user.&quot;);<br>            break<br>        }<br>        LoginAction::Denied =&gt; {<br>            println!(&quot;Login failed.&quot;);<br>            tries += 1;<br>            if tries &gt;= 3 {<br>                println!(&quot;Too many failed attempts. Exiting.&quot;);<br>                break;<br>            }<br>        }<br>    }<br>}</pre><blockquote><em>match is exhaustive: not matching a pattern will fail to compile. You can use </em><em>_ as a catch-all.</em></blockquote><p>Let’s add a unit test to the library:</p><pre>#[test]<br>fn test_enums() {<br>    assert_eq!(login(&quot;admin&quot;, &quot;password&quot;), LoginAction::Admin);<br>    assert_eq!(login(&quot;bob&quot;, &quot;password&quot;), LoginAction::User);<br>    assert_eq!(login(&quot;admin&quot;, &quot;wrong&quot;), LoginAction::Denied);<br>    assert_eq!(login(&quot;wrong&quot;, &quot;password&quot;), LoginAction::Denied);<br>}</pre><p>And everything goes red in the IDE! That’s because enumerations don’t support comparison by default. Fortunately, it’s easy to fix. Let’s support debug printing while we’re at it:</p><pre>#[derive(PartialEq, Debug)]<br>pub enum LoginAction {<br>    Admin,<br>    User,<br>    Denied,<br>}</pre><p>#[derive] is a procedural macro that writes code for you.</p><h3>Enumerations with Data</h3><p>Let’s clean up our enumerations a bit, and store some data in them:</p><pre>#[derive(PartialEq, Debug)]<br>pub enum LoginAction {<br>    Granted(LoginRole),<br>    Denied,<br>}<br><br>#[derive(PartialEq, Debug)]<br>pub enum LoginRole {<br>    Admin,<br>    User,<br>}<br>pub fn login(username: &amp;str, password: &amp;str) -&gt; LoginAction {<br>    let username = username.to_lowercase();<br>    if username == &quot;admin&quot; &amp;&amp; password == &quot;password&quot; {<br>        LoginAction::Granted(LoginRole::Admin)<br>    } else if username == &quot;bob&quot; &amp;&amp; password == &quot;password&quot; {<br>        LoginAction::Granted(LoginRole::User)<br>    } else {<br>        LoginAction::Denied<br>    }<br>}</pre><p>Now we can update the application to use the new data:</p><pre>match login(&amp;username, &amp;password) {<br>    LoginAction::Granted(LoginRole::Admin) =&gt; {<br>        println!(&quot;Welcome {username}, you are an admin.&quot;);<br>        break;<br>    }<br>    LoginAction::Granted(LoginRole::User) =&gt; {<br>        println!(&quot;Welcome {username}, you are a regular user.&quot;);<br>        break<br>    }<br>    LoginAction::Denied =&gt; {<br>        println!(&quot;Login failed.&quot;);<br>        tries += 1;<br>        if tries &gt;= 3 {<br>            println!(&quot;Too many failed attempts. Exiting.&quot;);<br>            break;<br>        }<br>    }<br>}</pre><p>Notice how match lets you peer inside multiple levels of enumeration. This type of pattern matching is very useful.</p><h3>Optional Users</h3><p>Maybe we want the login system to know that a user doesn’t exist. You might want to offer suggestions, or an option to create a new user. You can do this with an Option. Options are an enumeration that either contain Some(data) or None. They use generics to store whatever type you want to put inside them - but they are a sum type, you are storing one or the other, never both.</p><pre>pub fn login(username: &amp;str, password: &amp;str) -&gt; Option&lt;LoginAction&gt; {<br>    let username = username.to_lowercase();<br>    if username != &quot;admin&quot; &amp;&amp; username != &quot;bob&quot; {<br>            return None;<br>        }<br>        if username == &quot;admin&quot; &amp;&amp; password == &quot;password&quot; {<br>            Some(LoginAction::Granted(LoginRole::Admin))<br>        } else if username == &quot;bob&quot; &amp;&amp; password == &quot;password&quot; {<br>            Some(LoginAction::Granted(LoginRole::User))<br>        } else {<br>            Some(LoginAction::Denied)<br>        }<br>}</pre><p>Now we can update the login program to know if a user doesn’t exist:</p><pre>match login(&amp;username, &amp;password) {<br>    Some(LoginAction::Granted(LoginRole::Admin)) =&gt; {<br>        println!(&quot;Welcome {username}, you are an admin.&quot;);<br>        break;<br>    }<br>    Some(LoginAction::Granted(LoginRole::User)) =&gt; {<br>        println!(&quot;Welcome {username}, you are a regular user.&quot;);<br>        break<br>    }<br>    Some(LoginAction::Denied) =&gt; {<br>        println!(&quot;Login failed.&quot;);<br>        tries += 1;<br>        if tries &gt;= 3 {<br>            println!(&quot;Too many failed attempts. Exiting.&quot;);<br>            break;<br>        }<br>    }<br>    None =&gt; {<br>        println!(&quot;User does not exist.&quot;);<br>        break;<br>    }<br>}</pre><p>match allows for very deep pattern matching. You usually don&#39;t need to nest match statements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=489ae630a94f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[1.6 World’s Simplest Login System]]></title>
            <link>https://medium.com/@1xahmed/1-6-worlds-simplest-login-system-1ffbfe44f543?source=rss-d34e7ee43e8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ffbfe44f543</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[rustpro]]></category>
            <dc:creator><![CDATA[Ahmed Ali]]></dc:creator>
            <pubDate>Thu, 15 Aug 2024 11:15:40 GMT</pubDate>
            <atom:updated>2024-08-15T11:15:40.732Z</atom:updated>
            <content:encoded><![CDATA[<p>Now that we have a library and an application that uses it, let’s build the world’s most primitive login system.</p><p>In the library:</p><pre>pub fn login(username: &amp;str, password: &amp;str) -&gt; bool {<br>    username == &quot;admin&quot; &amp;&amp; password == &quot;password&quot;<br>}</pre><p>And we’ll test it:</p><pre>#[test]<br>fn test_login() {<br>    assert!(login(&quot;admin&quot;, &quot;password&quot;));<br>    assert!(!login(&quot;admin&quot;, &quot;wrong&quot;));<br>    assert!(!login(&quot;wrong&quot;, &quot;password&quot;));<br>}</pre><p>That looks good. But we haven’t checked for case. The password should be case-sensitive, but do we really care if the username is Herbert or herbert?</p><pre>pub fn login(username: &amp;str, password: &amp;str) -&gt; bool {<br>    username.to_lowercase() == &quot;admin&quot; &amp;&amp; password == &quot;password&quot;<br>}</pre><p>Now, let’s go to the application and use it:</p><pre>fn main() {<br>    let mut tries = 0;<br>    loop {<br>        println!(&quot;Enter your username:&quot;);<br>        let username = read_line();<br>        println!(&quot;Enter your password:&quot;);<br>        let password = read_line();<br>        if login(&amp;username, &amp;password) {<br>            println!(&quot;Welcome, {username}!&quot;);<br>            break;<br>        } else {<br>            println!(&quot;Login failed.&quot;);<br>            tries += 1;<br>            if tries &gt;= 3 {<br>                println!(&quot;Too many failed attempts. Exiting.&quot;);<br>                break;<br>            }<br>        }<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ffbfe44f543" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[1.5 Create a Library, Test & Use it in Rust]]></title>
            <link>https://medium.com/@1xahmed/1-5-create-a-library-test-use-it-in-rust-1b63d3fbfec6?source=rss-d34e7ee43e8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b63d3fbfec6</guid>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[rustpro]]></category>
            <dc:creator><![CDATA[Ahmed Ali]]></dc:creator>
            <pubDate>Sat, 27 Jul 2024 04:22:27 GMT</pubDate>
            <atom:updated>2024-07-27T04:22:27.918Z</atom:updated>
            <content:encoded><![CDATA[<h3>1.5 Create a Library, Test&amp; Use it in Rust</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h8zW9Ixv4698e69Nu3auWw.png" /></figure><p>Terminology Time</p><ul><li>A library is a generic term for shared code.</li><li>A crate is a Cargo-managed bundle of code, often a library.</li><li>A module is a section inside a crate.</li></ul><p>These are often thrown around somewhat interchangeably — be careful!</p><h3>Create a new library</h3><p>Go to your workspace root (c:\users\1xahmed\rust\login_system in my case):</p><pre>cargo new --lib authentication</pre><p>(authentication is the name of the library to create)</p><p>Once again, you’ll get a big warning that really means <em>don’t forget to update your workspace members</em>. Let’s do that:</p><pre>members = [<br>    &quot;login&quot;, # Test login program<br>    &quot;authentication&quot;, # Authenticator library<br>]</pre><blockquote><em>You can find the code referred to in this section </em><a href="https://github.com/thebracket/ArdanUltimateRust-5Days/blob/main/src/hello_auth"><em>here</em></a><em>.</em></blockquote><p>Cargo has once again created a Cargo.toml file, which is pretty much unchanged:</p><pre>[package]<br>name = &quot;hello_auth&quot;<br>version = &quot;0.1.0&quot;<br>edition = &quot;2021&quot;</pre><pre># See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html<br><br>[dependencies]</pre><p>The only change is the package name.</p><p>Cargo has also created a lib.rs file instead of a main.rs file. As we said earlier, this makes the package a <em>library</em> --- you can&#39;t run it, it&#39;s designed to be used from other applications. The content of main.rs is <em>very</em> different:</p><pre><br>pub fn add(left: usize, right: usize) -&gt; usize {<br>    left + right<br>}<br><br>#[cfg(test)]<br>mod tests {<br>    use super::*;<br><br>    #[test]<br>    fn it_works() {<br>        let result = add(2, 2);<br>        assert_eq!(result, 4);<br>    }<br>}</pre><p>Cargo has created:</p><ul><li>A single function named add that simply adds two parameters and returns the result.</li><li>An entire unit test system, that asserts that 2+2 still equals 4.</li></ul><h3>Understanding Rust Function Syntax</h3><p>Here’s an annotated version of the add function:</p><pre>//     ⬇️ The function name<br>//          ⬇️ Function parameters<br>//                                    ⬇️ The function return type<br>//⬇️ `pub` means &quot;public&quot; - the function is available from outside the library/module.<br>pub fn add(left: usize, right: usize) -&gt; usize {<br>    left + right // No &quot;return&quot; statement is necessary. Rust functions return the last<br>                 // expression result from a function.<br>}</pre><p>If you prefer return, this is also valid:</p><pre>pub fn add(left: usize, right: usize) -&gt; usize {<br>    return left + right;<br>}</pre><p>Notice that Clippy complains when I do this. Canonical Rust uses the short form. It’s important to know that you <em>can</em> use the return command---and you can do it anywhere in a function. Early return is often preferred.</p><blockquote><em>Enabling Clippy as the default in </em><a href="https://1xahmed.medium.com/setup-your-rust-development-environment-4f60692f2b70"><em>the IDE setup</em></a><em> makes Clippy bug you as you type. I prefer it this way. Clippy helps you write “Rustacean” code, and knows about a LOT of common things that could be done better. If Clippy is annoying you, you can switch back to </em><em>cargo check mode.</em></blockquote><h3>Understanding the Tests</h3><p>The mysterious line:</p><pre>#[cfg(test)]</pre><p>Is a <em>compiler directive</em>. It tells Cargo (and rustc underneath) to <em>only</em> compile the next section if you are compiling in the &quot;test&quot; configuration. Your unit tests won&#39;t take up <em>any</em> extra space in a deployed version of your library.</p><pre>mod tests {<br>    use super::*;<br>    ..<br>}</pre><p>mod tests is declaring a <em>module</em>. Modules can also be declared as files and directories (you&#39;ll see that later). They serve as a namespace (so everything inside is tests::name), a scope (variables inside a module aren&#39;t visible from outside without pub, and won&#39;t pollute the namespaces of other modules), and often a compilation unit - modules can often be compiled in parallel.</p><p>You draw elements from other modules into the current one with use. use super::* means &quot;use everything from the parent module.&quot;</p><p>Finally, the test itself:</p><pre>#[test]<br>fn it_works() {<br>    let result = add(2, 2);<br>    assert_eq!(result, 4);<br>}</pre><p>You can annotate functions, structures, enums and lots of other things in Rust with #[..] annotations. These apply to whatever is defined next. In this case, marking a function as a test adds it to Cargo&#39;s unit-test runner.</p><p>add only works because we imported everything from super. You could also write super::add(2, 2);.</p><p>assert_eq! is an assertion macro that panics your program if the two arguments are not equal.</p><p>Once again, you can use the Command Palette to run Expand Macros and see what it actually does:</p><pre>match (&amp;result, &amp;4) {<br>    (left_val, right_val) =&gt; {<br>        if !(*left_val == *right_val) {<br>            let kind = $crate::panicking::AssertKind::Eq;<br>            $crate::panicking::assert_failed(<br>                kind,<br>                &amp;*left_val,<br>                &amp;*right_val,<br>                $crate::option::Option::None,<br>            );<br>        }<br>    }<br>}</pre><h3>Run the Tests</h3><p>So that’s a very long-winded check that 2+2 equals 4. Let’s run it. You can run unit tests for the current workspace entry at any time by typing:</p><pre>cargo test</pre><p>You’ll see something like this:</p><pre><br>   Compiling hello_auth v0.1.0 (C:\Users\1xahmed\Documents\Rust Foundations\src\hello_auth)<br>    Finished test [unoptimized + debuginfo] target(s) in 0.31s<br>     Running unittests src\lib.rs (C:\Users\1xahmed\Documents\Rust Foundations\target\debug\deps\hello_auth-9e01bca15e1e38fb.exe)<br><br>running 1 test<br>test tests::it_works ... ok<br><br>test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s<br><br>   Doc-tests hello_auth<br><br>running 0 tests<br><br>test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s</pre><p>Good news: 2+2 does equal 4.</p><p>You can also test your whole workspace at once by typing:</p><pre>cargo test --all</pre><h3>The Hello World Service</h3><p>Let’s create a “hello world” service.</p><h3>Step 1: Cleanup the Default Code</h3><p>Delete the add function, and the unit test (keeping the framework).</p><p>Your code now looks like this:</p><pre>#[cfg(test)]<br>mod tests {<br>    use super::*;<br>}</pre><blockquote><em>Clippy complains that we aren’t using any functions from </em><em>super. That&#39;s ok for now.</em></blockquote><h3>Step 2: Add a function</h3><p>Now we’ll add a function:</p><pre>pub fn greet_user(name: &amp;str) -&gt; String {<br>    format!(&quot;Hello {name}&quot;)<br>}</pre><p>There’s a few things to notice here:</p><ul><li>We made the function <em>public</em> with pub. That means we can call it from programs that use the library.</li><li>Rust has TWO types of string!</li></ul><p>&amp;str is an immutable buffer of characters in memory.</p><p>You usually use this for literals, such as &quot;Ahmed&quot;.</p><p>You can refer to any String as an &amp;str by borrowing it - with &amp;my_string.</p><ul><li>String is an all-singing, all dancing buffered string designed for modification.</li></ul><p>Internally, String is a buffer of characters with the length stored.</p><p>Changing a String updates or replaces the buffer.</p><ul><li>format! is another macro, used under the hood by printn! and other Rust formatters. <a href="https://doc.rust-lang.org/std/macro.format.html">It&#39;s very powerful</a> - it can do formatting and placeholders.</li></ul><h3>Step 3: Test the New Function</h3><p>Before we integrate this with our main program, let’s add a unit test to ensure that it does what we think:</p><pre>#[cfg(test)]<br>mod tests {<br>    use super::*;<br>    <br>    #[test]<br>    fn test_greet_user() {<br>        assert_eq!(&quot;Hello Ahmed&quot;, greet_user(&quot;Ahmed&quot;));<br>    }<br>}</pre><p>And run it with cargo test:</p><pre>running 1 test<br>test tests::test_greet_user ... ok<br><br>test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s</pre><h3>Step 3: Integration</h3><blockquote><em>This is in the Github repo </em><a href="https://github.com/1xAhmed/rust_foundations/tree/main/Session1/login"><em>here</em></a></blockquote><p>Now we return to the login project (c:\users\1xahmed\rust\login in my case).</p><p>Open Cargo.toml, and let&#39;s add our project as a dependency:</p><pre>[dependencies]<br>authentication = { path = &quot;../authentication&quot; }</pre><blockquote><em>You can specify </em>version numbers<em> (e.g. </em><em>library = &quot;1&quot; using semantic versioning. Provide as many significant numbers as you need; &quot;1&quot; will load the latest in the &quot;1.x.y&quot; tree. You can also use </em><em>{ git = &quot;git path&quot; } and load directly from a shared Git repository. Useful if you are working with a team, or want to grab some code from Github.)</em></blockquote><p>We’ll update main.rs to use our new function:</p><pre>use authentication::greet_user;<br><br>fn main() {<br>    println!(&quot;{}&quot;, greet_user(&quot;Herbert&quot;));<br>}</pre><p>Run it with cargo run:</p><pre>Compiling hello_service_exe v0.1.0 (C:\Users\1xahmed\Documents\Rust Foundations\src\hello_service_exe)<br>    Finished dev [unoptimized + debuginfo] target(s) in 0.17s<br>     Running `C:\Users\1xahmed\Documents\Rust Foundations\target\debug\hello_service_exe.exe`<br>Hello Ahmed Ali</pre><p><em>Congratulations, you’ve made and used your first library.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b63d3fbfec6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[1.3 Cargo Workspaces]]></title>
            <link>https://medium.com/@1xahmed/cargo-workspaces-6482af5ee0ea?source=rss-d34e7ee43e8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6482af5ee0ea</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[rustpro]]></category>
            <dc:creator><![CDATA[Ahmed Ali]]></dc:creator>
            <pubDate>Fri, 26 Jul 2024 10:42:48 GMT</pubDate>
            <atom:updated>2024-07-26T11:15:59.971Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tczfmKpvDqjJS-7q5MgdVQ.png" /></figure><p>If you’re working with more than one related project, workspaces can help you:</p><ul><li>Workspaces combine all of your builds into a single target folder. No need to find every single target/ folder when cleaning up.</li><li>Workspaces share downloads. If you have a bunch of projects with shared dependencies, workspaces build them once — -and share the result. Faster compilation, less disk space usage.</li><li>A lot of cargo commands can be run in the “workspace root” with --all as a command-line flag, and will operate on all of them. Run all of your tests with cargo test --all, or build everything with cargo build --all. Beware: cargo run --all really will try and run every program you&#39;ve created in this workspace.</li></ul><blockquote><em>While working on Hands-on Rust, I had so many examples outside of a workspace which took alot of disk space meaning multiple copies. Moving into a workspace meant we only had a single copy of each library, and was using a reasonable amount of disk space.</em></blockquote><h3>Our Current Setup</h3><p>Go back to your source folder for today. In my case c:\users\1xahmed\rust\.</p><p>Open Cargo.toml and add a workspace section:</p><pre>[workspace]<br>members = []</pre><p>The workspace automatically includes the top-level src directory. This is the <em>parent</em> workspace.</p><p>It’s often confusing if you open a workspace with several projects in it and cargo run just happens to run the first project you created!</p><p>Edit src/main.rs to change the message printed:</p><pre>fn main() {<br>    println!(&quot;You probably wanted to run one of the nested workspaces.&quot;);<br>}</pre><p>Now, if someone accidentally runs the parent project they are notified of their mistake.</p><p>Let’s get back to where we were by creating a project <em>inside</em> the workspace.</p><pre>cd c:\users\1xahmed\rust\<br>cargo new login</pre><p>You will see a warning:</p><pre>warning: compiling this new package may not work due to invalid workspace configuration</pre><pre>current package believes it&#39;s in a workspace when it&#39;s not:<br>current:   C:\Users\1xahmed\Documents\Rust Foundations 4 Day\src\hello_login_system\Cargo.toml<br>workspace: C:\Users\1xahmed\Documents\Rust Foundations 4 Day\Cargo.toml<br>error: failed to load manifest for workspace member `C:\Users\1xahmed\Documents\Rust Foundations\hello_login_system`</pre><pre>Caused by:<br>  failed to read `C:\Users\1xahmed\Documents\Rust Foundations\hello_login_system\Cargo.toml`</pre><pre>Caused by:<br>  The system cannot find the path specified. (os error 3)</pre><blockquote><em>The paths will vary on your computer. In this case, it’s referring to this Github repo.</em></blockquote><p>This is a really long-winded way of saying: <em>Don’t forget to add the new project to your workspaces’ members</em></p><p>Add the newly created project by re-opening the parent’s Cargo.toml and adding it to your workspace:</p><pre>members = [<br>    &quot;login&quot;, # I find it helpful to include a note about what the project does, here.<br>]</pre><h3>Try It Out</h3><ol><li>Change directory to your workspace root.</li><li>Type cargo run. You&#39;ll see the message that you probably didn&#39;t mean to run this one.</li><li>Change directory to your login program.</li><li>Type cargo run and see &quot;Hello World&quot;.</li><li>Notice that there’s only one target folder for the whole workspace. ALL compilation artifacts go here.</li></ol><p>And that’s it — you have a working workspace with all of its benefits.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6482af5ee0ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[1.4 Console Text Input in Rust]]></title>
            <link>https://medium.com/@1xahmed/console-text-input-3403871ec80d?source=rss-d34e7ee43e8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3403871ec80d</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[rustpro]]></category>
            <dc:creator><![CDATA[Ahmed Ali]]></dc:creator>
            <pubDate>Fri, 26 Jul 2024 10:33:25 GMT</pubDate>
            <atom:updated>2024-07-26T11:16:10.768Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s create a function that will read a line of text from the console.</p><pre>fn read_line() -&gt; String {<br>    let mut input = String::new();<br>    std::io::stdin().read_line(&amp;mut input).expect(&quot;Failed to read line&quot;);<br>    input<br>}</pre><p>What’s the expect? Accessing standard input might fail - so Rust is returning a Result type. We&#39;re going to look at those later. For now, we&#39;re just going to crash if it fails. You can also use unwrap, but expect lets you specify an error message.</p><p>Now let’s test it:</p><pre>fn main() {<br>    let input = read_line();<br>    println!(&quot;You typed: [{input}]&quot;);<br>}</pre><p>Notice how there’s an extra carriage return. Reading input keeps the control characters. This is rarely what you want, so let’s trim it:</p><pre>fn read_line() -&gt; String {<br>    let mut input = String::new();<br>    std::io::stdin().read_line(&amp;mut input).expect(&quot;Failed to read line&quot;);<br>    input.trim().to_string()<br>}</pre><p>Now let’s test it:</p><pre>fn main() {<br>    let input = read_line();<br>    println!(&quot;You typed: [{input}]&quot;);<br>}</pre><p>Bingo — trimmed text input.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3403871ec80d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[1.2 Rust Fundamentals]]></title>
            <link>https://blog.devgenius.io/rust-fundamentals-c36d4906340f?source=rss-d34e7ee43e8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c36d4906340f</guid>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[rustpro]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Ahmed Ali]]></dc:creator>
            <pubDate>Thu, 25 Jul 2024 07:58:56 GMT</pubDate>
            <atom:updated>2024-07-26T16:20:07.967Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s play around a bit in the variables program, and learn some Rust fundamentals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6YAXad7Eos6JxzRivYCQw.png" /></figure><blockquote><em>You’re encouraged to code along.</em></blockquote><h3>Variables, Mutability and Shadowing</h3><blockquote><em>These are included in this </em><a href="https://github.com/1xAhmed/rust_foundations/tree/main/Session1/variables">Github Repo</a><em> , in the </em><em>Session1 directory.</em></blockquote><p>Let’s add a variable to our program.</p><pre>fn main() {<br>    let n = 5;<br>    println!(&quot;{n}&quot;);<br>}</pre><p>You declare a variable with let. Variables are immutable by default. You can&#39;t do this:</p><pre>fn main() {<br>    let n = 5;<br>    n = n + 1; // &lt;-- Will not compile<br>    println!(&quot;{n}&quot;);<br>}</pre><p>So how do I change n?</p><p>Option 1: Make it mutable*</p><pre>fn main() {<br>    let mut n = 5;<br>    n += 1;<br>    println!(&quot;{n}&quot;);<br>}</pre><p>Option 2: Replace it with shadowing</p><pre>fn main() {<br>    let n = 5;<br>    let n = n + 1;<br>    // Where did n go?<br>    println!(&quot;{n}&quot;);<br>}</pre><p>n was <em>shadowed</em> by the new n. The first n is no longer accessible. This is a common pattern in Rust code, but you have to be careful. Don&#39;t accidentally create a new variable that replaces one you still need!</p><blockquote><em>Also: don’t use single letter names in real code. Please! Future you will thank you.</em></blockquote><h3>Scope Return, the Unit Type and Functions</h3><p>Rust uses <em>scopes</em> everywhere. What is a scope? Anything between { and }. Variables declared inside a scope cease to exist when the scope finishes (and clean up after themselves!).</p><pre>fn main() {<br>    let n = 5;<br>    {<br>        let n = 6;<br>        println!(&quot;{n}&quot;);<br>    }<br>    println!(&quot;{n}&quot;);<br>}</pre><p>Shadowing obeys scopes! n in the outer scope is 5, and is 6 in the inner scope.</p><p>The last line of a function is the return value. You can assign a scope result to a variable:</p><pre>fn main() {<br>    let n = {<br>        let mut accumulator = 0;<br>        for i in 1..10 {<br>            accumulator += i;<br>        }<br>        accumulator // No semicolon - this is the return value<br>    };<br>    println!(&quot;{n}&quot;);<br>}</pre><p>Even scopes that don’t return values, quietly <em>do</em> return something — — the Unit Type: ():</p><pre>fn main() {<br>    let n = {<br>        println!(&quot;Hello World!&quot;);<br>    };<br>    println!(&quot;{n:?}&quot;); // :? is a debug formatter<br>}</pre><p>This returns () - a <em>unit type</em>. You usually won&#39;t need this, but it&#39;s important to understanding how Rust really works. It&#39;s mostly a functional language, under the hood. It also allows an error to be thrown when you try to use a value that doesn&#39;t exist.</p><p>So what about functions? Functions work just like scopes, but with a name. Functions can take parameters:</p><pre>fn double(n: i32) -&gt; i32 {<br>    n * 2<br>}<br><br>fn main() {<br>    let n = double(5);<br>    println!(&quot;{n}&quot;);<br>}</pre><p>So n in the function is completely independent of n outside of the function, and ceases to exist (except as a return value) when the function ends.</p><p>You can use explicit return, also — at any point in the function:</p><pre>fn double_or_nothing(n: i32) -&gt; i32 {<br>    if n &gt; 0 {<br>        return n * 2;<br>    }<br>    0<br>}<br><br>fn main() {<br>    println!(&quot;{}&quot;, double_or_nothing(5));<br>    println!(&quot;{}&quot;, double_or_nothing(-5));<br>    println!(&quot;{}&quot;, {<br>        let n = 12;<br>        return n;<br>    });<br>}</pre><p>Notice that return n is the exception to the early return rule. Return <em>always</em> exits a <em>function</em> - not the scope block. Instead, use n (no semicolon) to return from a scope.</p><blockquote><em>Some people find explicit returns easier to read. Clippy — the linter — will complain. If you find it easier to read, use it. If you don’t, don’t.</em></blockquote><h3>Move by Default — Except when you Copy</h3><blockquote><em>The code for this is in the </em><em>function_returns example.</em></blockquote><p>This is confusing to a lot of people, so let’s walk through the topic. Rust is a <em>move by default</em> language, and the borrow checker will complain if you try to use a variable after it’s been moved. Let’s see what that means:</p><pre>fn greet(s: String) {<br>    println!(&quot;Hello, {s}&quot;);<br>}<br><br>fn main() {<br>    let mut name = &quot;Hello&quot;.to_string();<br>    greet(name);<br>    name = name + &quot; World&quot;; // This won&#39;t compile!<br>}</pre><p>The n we&#39;ve been using was a <em>primitive type</em> - a built-in number. It&#39;s faster to copy these around, so they default to &quot;copy&quot; instead of &quot;move&quot;. Just about every other type defaults to being a <em>move</em> type. When you pass it to a function, it&#39;s moved to the function, and you can&#39;t use it anymore - unless the function gives it back:</p><pre>fn greet(s: String) -&gt; String {<br>    println!(&quot;Hello, {s}&quot;);<br>    s<br>}<br><br>fn main() {<br>    let mut name = &quot;Hello&quot;.to_string();<br>    name = greet(name);<br>    name = name + &quot; World&quot;; // This will compile<br>}</pre><p>You can also <em>clone</em> types that support it:</p><pre>fn greet(s: String) {<br>    println!(&quot;Hello, {s}&quot;);<br>}<br><br>fn main() {<br>    let mut name = &quot;Hello&quot;.to_string();<br>    greet(name.clone());<br>    name = name + &quot; World&quot;; // This won&#39;t compile!<br>}</pre><p>Cloning can be slow, so you don’t want to do this everywhere.</p><h3>Borrowing &amp; References</h3><p>So how do you pass a variable to a function, and still use it afterwards? You <em>borrow</em> it. Borrowing is a <em>reference</em> to the variable. You can borrow a variable with &amp;:</p><pre>fn greet(s: &amp;String) {<br>    println!(&quot;Hello, {s}&quot;);<br>}<br><br>fn main() {<br>    let mut name = &quot;Hello&quot;.to_string();<br>    greet(&amp;name);<br>    name = name + &quot; World&quot;;<br>}</pre><p>Adding the ampersand (&amp;) has <em>borrowed</em> the variable. The main function retains <em>ownership</em> - it&#39;s still main&#39;s variable, and it&#39;s main&#39;s responsibility to clean it up. But the function can use it, it isn&#39;t altered, and you&#39;ve saved a clone---your just passing a pointer.</p><p>You can borrow mutably, too:</p><pre>fn greet(s: &amp;mut String) {<br>    *s = format!(&quot;Hello {s}&quot;);<br>    println!(&quot;{s}&quot;);<br>}<br><br>fn main() {<br>    let mut name = &quot;Hello&quot;.to_string();<br>    greet(&amp;mut name);<br>    name += &quot; World&quot;;<br>    println!(&quot;{name}&quot;);<br>}</pre><p>Notice that we are using * to <em>de-reference</em> the variable - point back at the original. You only need to do this if you aren&#39;t accessing a member of the variable.</p><p>You can only have one mutable borrow to a variable at a time. This becomes important for global variables and when you start using concurrency. The infamous “borrow checker” strictly enforces this rule to prevent data races.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c36d4906340f" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/rust-fundamentals-c36d4906340f">1.2 Rust Fundamentals</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[1.1 Setup Your Rust Development Environment & IDE (Integrated Development Environment)]]></title>
            <link>https://medium.com/@1xahmed/setup-your-rust-development-environment-4f60692f2b70?source=rss-d34e7ee43e8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f60692f2b70</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <dc:creator><![CDATA[Ahmed Ali]]></dc:creator>
            <pubDate>Wed, 24 Jul 2024 15:31:51 GMT</pubDate>
            <atom:updated>2024-07-25T08:20:14.332Z</atom:updated>
            <content:encoded><![CDATA[<h3>Rust Setup with RustUp</h3><p>If you haven’t already, you need to have Rust installed on your computer. Visit <a href="https://rustup.rs/">RustUp</a> and install from there. Instructions will vary by platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*04nwFXXsnEKiGR9d.png" /></figure><h3>Things to Know About RustUp</h3><p>There are some caveats about RustUp that you need to know:</p><ul><li>RustUp installs Rust <em>for your user account</em>. It doesn’t perform a shared installation.</li><li>You <em>can</em> get a working environment through package managers such as snap, apt, homebrew and similar. It&#39;s better to use the native Rust setup, you get much faster access to updates.</li><li>On Windows, if you don’t already have it installed you will be prompted to also install the Visual C++ build tools.</li><li>On a Mac, you will be prompted to install the OS X development tools if you haven’t already.</li><li>On Linux, make sure you have LLVM installed.</li></ul><h3>Verify that you have a working RustUp</h3><p>Enter the command rustup --version. You should see something like this:</p><pre>rustup 1.27.1 (54dd3d00f 2024-04-24)<br>info: This is the version for the rustup toolchain manager, not the rustc compiler.<br>info: The currently active `rustc` version is `rustc 1.77.0 (aedd173a2 2024-03-17)`The version numbers will change.</pre><blockquote>The version numbers will change.</blockquote><h3>Update to the Latest Stable Rust</h3><p>Let’s take a second to make sure you have an up-to-date Rust install. We’re going to use some of the more recent additions to the language, so you don’t want to find yourself wondering why something didn’t work. In particular, the borrow checker rules have eased up and printing with placeholders has become a lot easier.</p><p>From time to time (like monthly), it’s a good idea to update your Rust setup. Bug fixes and performance improvements are applied periodically. Rust won’t break <em>stable</em> unless a major security vulnerability emerges.</p><p>To update RustUp itself:</p><p>rustup self update</p><p>You’ll see something like this:</p><pre>info: checking for self-updates<br>info: downloading self-update<br>  rustup updated - 1.25.2 (from 1.25.1)</pre><p>To update Rust to the latest:</p><p>Enter:</p><pre>rustup update</pre><p>Rust will update all the toolchains you have installed. You’ll see something like this:</p><pre>info: syncing channel updates for &#39;stable-x86_64-pc-windows-msvc&#39;<br>info: latest update on 2023-01-26, rust version 1.67.0 (fc594f156 2023-01-24)<br>info: downloading component &#39;llvm-tools&#39;<br> 44.2 MiB /  44.2 MiB (100 %)   7.3 MiB/s in  6s ETA:  0s<br>info: downloading component &#39;rust-std&#39; for &#39;wasm32-unknown-unknown&#39;<br> 18.9 MiB /  18.9 MiB (100 %)   8.0 MiB/s in  2s ETA:  0s<br>info: downloading component &#39;rust-src&#39;<br>info: downloading component &#39;cargo&#39;<br>info: downloading component &#39;clippy&#39;<br>info: downloading component &#39;rust-docs&#39;<br> 19.3 MiB /  19.3 MiB (100 %)   7.4 MiB/s in  2s ETA:  0s<br>info: downloading component &#39;rust-std&#39;<br> 26.8 MiB /  26.8 MiB (100 %)   6.4 MiB/s in  3s ETA:  0s<br>info: downloading component &#39;rustc&#39;<br> 62.7 MiB /  62.7 MiB (100 %)   7.4 MiB/s in  8s ETA:  0s<br>info: downloading component &#39;rustfmt&#39;<br>info: removing previous version of component &#39;llvm-tools&#39;<br>info: removing previous version of component &#39;rust-std&#39; for &#39;wasm32-unknown-unknown&#39;<br>info: removing previous version of component &#39;rust-src&#39;<br>info: removing previous version of component &#39;cargo&#39;<br>info: removing previous version of component &#39;clippy&#39;<br>info: removing previous version of component &#39;rust-docs&#39;<br>info: removing previous version of component &#39;rust-std&#39;<br>info: removing previous version of component &#39;rustc&#39;<br>info: removing previous version of component &#39;rustfmt&#39;<br>info: installing component &#39;llvm-tools&#39;<br> 44.2 MiB /  44.2 MiB (100 %)  18.6 MiB/s in  4s ETA:  0s<br>info: installing component &#39;rust-std&#39; for &#39;wasm32-unknown-unknown&#39;<br> 18.9 MiB /  18.9 MiB (100 %)  18.4 MiB/s in  1s ETA:  0s<br>info: installing component &#39;rust-src&#39;<br>  2.4 MiB /   2.4 MiB (100 %)   1.9 MiB/s in  1s ETA:  0s<br>info: installing component &#39;cargo&#39;<br>info: installing component &#39;clippy&#39;<br>info: installing component &#39;rust-docs&#39;<br> 19.3 MiB /  19.3 MiB (100 %)  60.0 KiB/s in  5m 13s ETA:  0s<br>info: installing component &#39;rust-std&#39;<br> 26.8 MiB /  26.8 MiB (100 %)  17.0 MiB/s in  1s ETA:  0s<br>info: installing component &#39;rustc&#39;<br> 62.7 MiB /  62.7 MiB (100 %)  20.3 MiB/s in  3s ETA:  0s<br>info: installing component &#39;rustfmt&#39;<br> 13 IO-ops /  13 IO-ops (100 %)   0 IOPS in  5s ETA: Unknown<br>info: checking for self-updates<br>stable-x86_64-pc-windows-msvc updated - rustc 1.67.0 (fc594f156 2023-01-24) (from rustc 1.65.0 (897e37553 2022-11-02))<br>info: cleaning up downloads &amp; tmp directories</pre><p>You’ll often see “nothing to update”, and you probably won’t have as many platforms installed as I do!</p><blockquote><em>Once you have a stable project, you may want to coordinate updates with your team to ensure that you are all on the same version.</em></blockquote><h3>Adding Toolchains</h3><p>You may want to target platforms other than the one you are using for development. Rust includes cross-compilation.</p><p>For example, you can support WASM by running:</p><pre>rustup target add wasm32-unknown-unknown</pre><p>Once that’s present, you can build for WASM with cargo build --target wasm32-unknown-unknown.</p><h3>Install Clippy!</h3><p>It should be installed by default, but some older — -updated — -setups don’t always have it. Run the following:</p><pre>rustup component add clippy</pre><p>Hopefully, you’ll see:</p><pre>info: component &#39;clippy&#39; for target &#39;x86_64-pc-windows-msvc&#39; is up to date</pre><blockquote><em>Really stuck? You can use most of this online at </em><a href="https://replit.com/~"><em>Replit</em></a><em>. It won’t be as fast as working locally.</em></blockquote><p>This is some basic Visual Studio Code setup. If you’re using a different IDE, skip this. The goal is to ensure that everyone can setup the IDE without any hassle.</p><h3>Setup your Integrated Development Environment</h3><h3>Extensions You Need</h3><blockquote><em>You should have Rust Analyzer installed as a pre-requesite. If you don’t, let me know and I’ll help at the first break.</em></blockquote><ul><li><a href="https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer">Rust Analyzer</a></li><li>Provides everything from syntax highlighting to inline error checking, macro expansion and debugger integration.</li><li>Part of the core RustUp distribution.</li><li>Regularly Updated.</li><li><a href="https://marketplace.visualstudio.com/items?itemName=vadimcn.vscode-lldb">CodeLLDB</a></li><li>Integrates well with Rust-Analyzer.</li><li>Provides inline debugging.</li><li><em>This is optional but you probably want it anyway</em></li></ul><h3>Extensions You Don’t Need — But Probably Want</h3><ul><li><a href="https://marketplace.visualstudio.com/items?itemName=serayuzgur.crates">Crates</a></li></ul><p>Let’s you know when dependencies are outdated.</p><ul><li><a href="https://marketplace.visualstudio.com/items?itemName=bungcip.better-toml">Better TOML</a></li></ul><p>Makes editing Rust’s TOML configuration easier</p><h3>Enable Breakpoints Everywhere</h3><pre>* Open Settings (`crtl` + `comma`)<br>* Search for &quot;everywhere&quot;.<br>* Check &quot;Allow Setting Breakpoints in any file&quot;<br>    * This helps the debugger work with Rust, even if optimizations have moved your code around.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/0*l-UeHXZ83BqTy4Fl.png" /></figure><h3>Enable Realtime Clippy</h3><pre>* Open Settings (`ctrl` + `comma`)<br>* Search for &quot;cargo check&quot;<br>* Change &quot;Rust Analyzer &gt; Check Command&quot; to &quot;clippy&quot;<br>    * By default, `cargo check` provides a very quick &quot;did it compile?&quot; check for your code.<br>    * Rust has a great linter called &quot;Clippy&quot; built in.<br>    * This helps reduce errors as you work, and often provides quick refactors into idiomatic Rust.</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f60692f2b70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Build a Thumbnail Server in Rust]]></title>
            <link>https://medium.com/@1xahmed/lets-build-a-thumbnail-server-in-rust-6c9f5b064bd4?source=rss-d34e7ee43e8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c9f5b064bd4</guid>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[rustpro]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <dc:creator><![CDATA[Ahmed Ali]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 07:34:35 GMT</pubDate>
            <atom:updated>2024-06-25T07:35:11.756Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Today we will build a fully functional server with all the bells and whistles.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RCKkIVLGUM8jBqGK8gLoSQ.png" /></figure><h3>The Design Idea</h3><p>We want to create a simple web server that displays thumbnails of images. It will need the following endpoints:</p><ul><li>/ - Display thumbnails of all images. Includes a form for adding an image.</li><li>/images - JSON list of all uploaded images.</li><li>(post) — /upload - Upload a new image and create a thumbnail.</li><li>/image/&lt;id&gt; - Display a single image.</li><li>/thumb/&lt;id&gt; - Display a single thumbnail.</li><li>(post) /search - find images by tag.</li></ul><blockquote><em>The code for this is in this </em><a href="https://github.com/1xAhmed/thumbnail_server_rust"><em>Github Repo</em></a></blockquote><h3>Add Dependencies</h3><p>We’re going to be pulling together much of the dependencies to make it work:</p><pre>cargo add tokio -F full<br>cargo add serde -F derive<br>cargo add axum -F multipart<br>cargo add sqlx -F runtime-tokio-native-tls -F sqlite<br>cargo add anyhow<br>cargo add dotenv<br>cargo add futures<br>cargo add dotenv<br>cargo add tokio_util -F io<br>cargo add image</pre><h3>Create the Database</h3><p>Create a .env file in your project containing:</p><pre>DATABASE_URL=&quot;sqlite:images.db&quot;</pre><p>Then create the database:</p><pre>sqlx database create</pre><p>Let’s also create a migration to make our initial database:</p><pre>sqlx migrate add initial</pre><p>A file has appeared in the migrations directory. Let&#39;s flesh out a minimal images database:</p><pre>-- Create images table<br>CREATE TABLE IF NOT EXISTS images<br>(<br>    id          INTEGER PRIMARY KEY NOT NULL,<br>    tags        TEXT                NOT NULL<br>);</pre><p>Now we’ll build our main.rs file to run with Tokio, read the .env file, connect to the database and run any migrations:</p><pre>#[tokio::main]<br>async fn main() -&gt; anyhow::Result&lt;()&gt; {<br>    // Read the .env file and obtain the database URL<br>    dotenv::dotenv()?;<br>    let db_url = std::env::var(&quot;DATABASE_URL&quot;)?;<br>    // Get a database connection pool<br>    let pool = sqlx::SqlitePool::connect(&amp;db_url).await?;<br>    // Run Migrations<br>    sqlx::migrate!(&quot;./migrations&quot;)<br>        .run(&amp;pool)<br>        .await?;<br>    Ok(())<br>}</pre><p>This is a good time to test that everything is working. We can run the server with cargo run and see that it compiles and runs.</p><h3>Setup Axum with a Layer to Offer Dependency Injection for the Database</h3><p>Axum can help with global state and dependency injection. We’ll use this to inject the database connection pool into our handlers.</p><p>First, let’s create the Axum application:</p><pre>// Build Axum with an &quot;extension&quot; to hold the database connection pool<br>let app = Router::new()<br>    .route(&quot;/&quot;, get(test))<br>    .layer(Extension(pool));<br>let addr = SocketAddr::from(([127, 0, 0, 1], 3000));<br>axum::Server::bind(&amp;addr)<br>    .serve(app.into_make_service())<br>    .await<br>    .unwrap();</pre><p>We’ll also make a handler named test that just returns a string:</p><pre>async fn test(Extension(pool): Extension&lt;sqlx::SqlitePool&gt;) -&gt; String {<br>    let result = sqlx::query(&quot;SELECT COUNT(id) FROM images&quot;)<br>        .fetch_one(&amp;pool)<br>        .await<br>        .unwrap();<br>    let count = result.get::&lt;i64, _&gt;(0);<br>    format!(&quot;{count} images in the database&quot;)<br>}</pre><p>Now run the program. Go to http://localhost:3000 and you will see &quot;0 images in the database&quot;. We&#39;ve injected our database pool, successfully queries the database and returned dynamic data.</p><h3>Create a Basic Homepage</h3><p>Let’s create the beginnings of a web page that will display our thumbnails. Create a new file named index.html in your src directory:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;My Awesome Thumbnail Server&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1&gt;Welcome to the thumbnail server&lt;/h1&gt;<br>    &lt;div id=&quot;thumbnails&quot;&gt;&lt;/div&gt;<br>    &lt;hr /&gt;<br>    &lt;h2&gt;Add an Image&lt;/h2&gt;<br>    &lt;form method=&quot;post&quot; action=&quot;/upload&quot; enctype=&quot;multipart/form-data&quot;&gt;<br>        &lt;input type=&quot;text&quot; name=&quot;tags&quot; value=&quot;&quot; placeholder=&quot;Tags&quot; /&gt; &lt;br /&gt;<br>        &lt;input type=&quot;file&quot; name=&quot;image&quot; /&gt; &lt;br /&gt;<br>        &lt;input type=&quot;submit&quot; value=&quot;Upload New Image&quot; /&gt;<br>    &lt;/form&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Now comment out the test function, and add a replacement for loading the index page from disk:</p><pre>async fn index_page() -&gt; Html&lt;String&gt; {<br>    let path = Path::new(&quot;src/index.html&quot;);<br>    let content = tokio::fs::read_to_string(path).await.unwrap();<br>    Html(content)<br>}</pre><p>Adjust the route to point to the new page: .route(&quot;/&quot;, get(index_page)).</p><p>Run the program now (cargo run) and you can see the HTML form. We&#39;re making progress!</p><h3>Uploading Images</h3><p>Axum has great support for forms built-in, but files are always a little more complicated. The easiest way is to use a multipart form, which we&#39;ve done in the HTML file. (You can normally use the Form type to automatically deserialize forms; we&#39;ll do that in the search system).</p><p>Create a new handler named uploader:</p><pre>async fn uploader(mut multipart: Multipart) -&gt; String {<br>    while let Some(field) = multipart.next_field().await.unwrap() {<br>        let name = field.name().unwrap().to_string();<br>        let data = field.bytes().await.unwrap();</pre><pre>        println!(&quot;{name} is {} bytes&quot;, data.len());<br>    }<br>    &quot;Ok&quot;.to_string()<br>}</pre><p>And add it to your routes:</p><pre>.route(&quot;/upload&quot;, post(uploader))</pre><p>Now run the program and submit an image and some tags. You’ll see something like this on the server console:</p><pre>tags is 11 bytes<br>image is 1143067 bytes</pre><p>The data made it! Now we need to turn it into useful data. Let’s extract the fields we want:</p><pre>async fn uploader(mut multipart: Multipart) -&gt; String {<br>    let mut tags = None; // &quot;None&quot; means &quot;no tags yet&quot;<br>    let mut image = None;<br>    while let Some(field) = multipart.next_field().await.unwrap() {<br>        let name = field.name().unwrap().to_string();<br>        let data = field.bytes().await.unwrap();</pre><pre>        match name.as_str() {<br>            &quot;tags&quot; =&gt; tags = Some(String::from_utf8(data.to_vec()).unwrap()), // Using Some means we can check we received it<br>            &quot;image&quot; =&gt; image = Some(data.to_vec()),<br>            _ =&gt; panic!(&quot;Unknown field: {name}&quot;),<br>        }<br>    }</pre><pre>    if let (Some(tags), Some(image)) = (tags, image) { // Destructuring both Options at once</pre><pre>    } else {<br>        panic!(&quot;Missing field&quot;);<br>    }</pre><pre>    &quot;Ok&quot;.to_string()<br>}</pre><p>This gives a relatively robust extractor — -we can be sure that we’ve received both fields we need, and will throw an error if we haven’t.</p><p>You can run the program now and resubmit the form — -if it doesn’t error out, it’s all good.</p><h3>Saving the Image</h3><p>The first thing to do is to add the image with tags to the database, and obtain the new primary key. Let’s create a function to do this:</p><pre>async fn insert_image_into_database(pool: &amp;Pool&lt;Sqlite&gt;, tags: &amp;str) -&gt; anyhow::Result&lt;i64&gt; {<br>    let row = sqlx::query(&quot;INSERT INTO images (tags) VALUES (?) RETURNING id&quot;)<br>        .bind(tags)<br>        .fetch_one(pool)<br>        .await?;</pre><pre>    Ok(row.get(0))<br>}</pre><p>The function simply inserts the tags and returns the new id. We’ve used anyhow to simplify error handling.</p><p>Now let’s call it:</p><pre>if let (Some(tags), Some(image)) = (tags, image) {<br>    let new_image_id = insert_image_into_database(&amp;pool, &amp;tags).await.unwrap();<br>} else {<br>    panic!(&quot;Missing field&quot;);<br>}</pre><p>We need to save the image to disk. Let’s create a function to do this:</p><pre>async fn save_image(id: i64, bytes: &amp;[u8]) -&gt; anyhow::Result&lt;()&gt; {<br>    // Check that the images folder exists and is a directory<br>    // If it doesn&#39;t, create it.<br>    let base_path = Path::new(&quot;images&quot;);<br>    if !base_path.exists() || !base_path.is_dir() {<br>        tokio::fs::create_dir_all(base_path).await?;<br>    }</pre><pre>    // Use &quot;join&quot; to create a path to the image file. Join is platform aware,<br>    // it will handle the differences between Windows and Linux.<br>    let image_path = base_path.join(format!(&quot;{id}.jpg&quot;));<br>    if image_path.exists() {<br>        // The file exists. That shouldn&#39;t happen.<br>        anyhow::bail!(&quot;File already exists&quot;);<br>    }</pre><pre>    // Write the image to the file<br>    tokio::fs::write(image_path, bytes).await?;<br>    Ok(())<br>}</pre><p>And let’s call it from the uploader:</p><pre>if let (Some(tags), Some(image)) = (tags, image) {<br>    let new_image_id = insert_image_into_database(&amp;pool, &amp;tags).await.unwrap();<br>    save_image(new_image_id, &amp;image).await.unwrap();<br>} else {<br>    panic!(&quot;Missing field&quot;);<br>}</pre><p>We’re not making any thumbnails yet, but we should test our progress so far. Run the program, upload an image and check that it appears in the images folder.</p><h3>Displaying all the Images</h3><p>Now that we have an image in both the database and the filesystem, let’s display it. We’ll need to create a new handler:</p><pre>async fn get_image(Path(id): Path&lt;i64&gt;) -&gt; impl IntoResponse {<br>    let filename = format!(&quot;images/{id}.jpg&quot;);<br>    let attachment = format!(&quot;filename={filename}&quot;);<br>    let mut headers = HeaderMap::new();<br>    headers.insert(<br>        header::CONTENT_TYPE,<br>        header::HeaderValue::from_static(&quot;image/jpeg&quot;),<br>    );<br>    headers.insert(<br>        header::CONTENT_DISPOSITION,<br>        header::HeaderValue::from_str(&amp;attachment).unwrap()<br>    );<br>    let file = tokio::fs::File::open(&amp;filename).await.unwrap();<br>    axum::response::Response::builder()<br>        .header(header::CONTENT_TYPE, header::HeaderValue::from_static(&quot;image/jpeg&quot;))<br>        .header(header::CONTENT_DISPOSITION, header::HeaderValue::from_str(&amp;attachment).unwrap())<br>        .body(StreamBody::new(ReaderStream::new(file)))<br>        .unwrap()<br>}</pre><p>This is a bit boilerplatey, but it shows you the options you have. In this case, we build the appropriate HTTP headers and use StreamBody to stream the contents of the image file to the client.</p><p>The Path(id) is a very handy Axum extractor. You can specify placeholders in the URL, and use Path to fill variables.</p><p>We’ll also need to add the route:</p><pre>.route(&quot;/image/:id&quot;, get(get_image))</pre><p>Now run the program and go to http://localhost:3000/image/1 to see the image we just uploaded.</p><h3>Making a thumbnail</h3><p>The Rust image crate makes creating thumbnails easy. It also uses Rayon under the hood, so it&#39;s fast. Let&#39;s create a function to make a thumbnail:</p><pre>fn make_thumbnail(id: i64) -&gt; anyhow::Result&lt;()&gt; {<br>    let image_path = format!(&quot;images/{id}.jpg&quot;);<br>    let thumbnail_path = format!(&quot;images/{id}_thumb.jpg&quot;);<br>    let image_bytes: Vec&lt;u8&gt; = std::fs::read(image_path)?;<br>    let image = if let Ok(format) = image::guess_format(&amp;image_bytes) {<br>        image::load_from_memory_with_format(&amp;image_bytes, format)?<br>    } else {<br>        image::load_from_memory(&amp;image_bytes)?<br>    };<br>    let thumbnail = image.thumbnail(100, 100);<br>    thumbnail.save(thumbnail_path)?;<br>    Ok(())<br>}</pre><p>We’re doing a little dance here and not trusting that the file uploaded is actually a good jpeg. I kept uploading a PNG by mistake. So we load the image as bytes, and then use guess_format to let Image figure it out for us!</p><p>Since our first image doesn’t have a thumbnail yet, let’s use it as test data. We’ll build a function that grabs a list of all of the images in our database, checks to see if a thumbnail exists and makes one if it doesn’t:</p><pre>async fn fill_missing_thumbnails(pool: &amp;Pool&lt;Sqlite&gt;) -&gt; anyhow::Result&lt;()&gt; {<br>    let mut rows = sqlx::query(&quot;SELECT id FROM images&quot;)<br>        .fetch(pool);</pre><pre>    while let Some(row) = rows.try_next().await? {<br>        let id = row.get::&lt;i64, _&gt;(0);<br>        let thumbnail_path = format!(&quot;images/{id}_thumb.jpg&quot;);<br>        if !std::path::Path::new(&amp;thumbnail_path).exists() {<br>            spawn_blocking(move || {<br>                make_thumbnail(id)<br>            }).await??;<br>        }<br>    }</pre><pre>    Ok(())<br>}</pre><p>Now let’s add this to the beginning of the program (before we start Axum):</p><pre>// Check thumbnails<br>    fill_missing_thumbnails(&amp;pool).await?;</pre><blockquote><em>You could easily run this in the background by spawning it separately. You could also not </em><em>await on the </em><em>spawn_blocking call to have the background threads all run concurrently.</em></blockquote><p>Now run the program and check that the thumbnail exists.</p><p>Finally, let’s also make the thumbnail on upload:</p><pre>if let (Some(tags), Some(image)) = (tags, image) {<br>    let new_image_id = insert_image_into_database(&amp;pool, &amp;tags).await.unwrap();<br>    save_image(new_image_id, &amp;image).await.unwrap();<br>    spawn_blocking(move || {<br>        make_thumbnail(new_image_id).unwrap();<br>    });<br>} else {<br>    panic!(&quot;Missing field&quot;);<br>}</pre><h3>Listing Available Images</h3><p>Let’s be lazy since it’s the end of the day and copy/paste get_image and make a thumbnail fetching version.</p><pre>async fn get_thumbnail(Path(id): Path&lt;i64&gt;) -&gt; impl IntoResponse {<br>    let filename = format!(&quot;images/{id}_thumb.jpg&quot;);</pre><p>(The rest of the function is unchanged)</p><p>Now let’s add the route:</p><pre>.route(&quot;/thumb/:id&quot;, get(get_thumbnail))</pre><p>You can test this if you like. Go to http://localhost:3000/thumb/1 and you should see the thumbnail.</p><p>Now let’s build a JSON service that returns all of the stored images:</p><pre>#[derive(Deserialize, Serialize, FromRow, Debug)]<br>struct ImageRecord {<br>    id: i64,<br>    tags: String,<br>}</pre><pre>async fn list_images(Extension(pool): Extension&lt;sqlx::SqlitePool&gt;) -&gt; Json&lt;Vec&lt;ImageRecord&gt;&gt; {<br>    sqlx::query_as::&lt;_, ImageRecord&gt;(&quot;SELECT id, tags FROM images ORDER BY id&quot;)<br>        .fetch_all(&amp;pool)<br>        .await<br>        .unwrap()<br>        .into()<br>}</pre><p>And of course, we add a route for it:</p><pre>.route(&quot;/images&quot;, get(list_images))</pre><p>Let’s test that real quick. Go to http://localhost:3000/images and you should see a JSON list of all of the images.</p><h3>Client Side Thumbnail Display</h3><p>Now let’s modify the HTML. You can leave the server running for live testing. We need to call the /images endpoint and display the thumbnails.</p><pre>&lt;script&gt;<br>    async function getImages() {<br>        const response = await fetch(&#39;/images&#39;);<br>        const images = await response.json();</pre><pre>        let html = &quot;&quot;;<br>        for (let i=0; i&lt;images.length; i++) {<br>            html += &quot;&lt;div&gt;&quot; + images[i].tags + &quot;&lt;br /&gt;&quot;;<br>            html += &quot;&lt;a href=&#39;/image/&quot; + images[i].id + &quot;&#39;&gt;&quot;;<br>            html += &quot;&lt;img src=&#39;/thumb/&quot; + images[i].id + &quot;&#39; /&gt;&quot;;<br>            html += &quot;&lt;/a&gt;&lt;/div&gt;&quot;;<br>            <br>        }<br>        document.getElementById(&quot;thumbnails&quot;).innerHTML = html;<br>    }</pre><pre>    getImages();<br>&lt;/script&gt;</pre><h3>Redirect on POST</h3><p>Rather than just saying “Ok” when someone uploads an image, let’s redirect back to the list of images.</p><p>We’ll make a simple file, src/redirect.html:</p><pre>&lt;html&gt;<br>    &lt;body&gt;<br>        Image Uploaded!</pre><pre>        &lt;script&gt;<br>            function redirect() {<br>                window.location.href=&quot;/&quot;;<br>            }<br>            setTimeout(redirect, 1000);<br>        &lt;/script&gt;<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Now change the uploader function signature to return Html&lt;String&gt;:</p><pre>async fn uploader(<br>    Extension(pool): Extension&lt;sqlx::SqlitePool&gt;,<br>    mut multipart: Multipart,<br>) -&gt; Html&lt;String&gt; {</pre><p>And change the bottom to load redirect.html and return it as HTML:</p><pre>let path = std::path::Path::new(&quot;src/redirect.html&quot;);<br>    let content = tokio::fs::read_to_string(path).await.unwrap();<br>    Html(content)<br>}</pre><p>Now run the program and add a file. You should go back to the list of images, with your new image displayed.</p><h3>Add Search</h3><p>Finally, a search function.</p><p>Let’s start by adding another form to index.html:</p><pre>&lt;body&gt;<br>    &lt;h1&gt;Welcome to the thumbnail server&lt;/h1&gt;<br>    &lt;div id=&quot;thumbnails&quot;&gt;&lt;/div&gt;<br>    &lt;hr /&gt;<br>    &lt;form method=&quot;post&quot; action=&quot;/search&quot;&gt;<br>        &lt;input type=&quot;text&quot; name=&quot;tags&quot; value=&quot;&quot; placeholder=&quot;Tags&quot; /&gt; &lt;br /&gt;<br>        &lt;input type=&quot;submit&quot; value=&quot;Search&quot; /&gt;<br>    &lt;/form&gt;<br>    &lt;hr /&gt;<br>    &lt;h2&gt;Add an Image&lt;/h2&gt;</pre><p>Next, we create a Rust structure to receive the contents of the form post:</p><pre>#[derive(Deserialize)]<br>struct Search {<br>    tags: String<br>}</pre><p>Now we can build a handler to server-side render the results:</p><pre>async fn search_images(Extension(pool): Extension&lt;sqlx::SqlitePool&gt;, Form(form): Form&lt;Search&gt;) -&gt; Html&lt;String&gt; {<br>    let tag = format!(&quot;%{}%&quot;, form.tags);</pre><pre>    let rows = sqlx::query_as::&lt;_, ImageRecord&gt;(&quot;SELECT id, tags FROM images WHERE tags LIKE ? ORDER BY id&quot;)<br>        .bind(tag)<br>        .fetch_all(&amp;pool)<br>        .await<br>        .unwrap();</pre><pre>    let mut results = String::new();<br>    for row in rows {<br>        results.push_str(&amp;format!(&quot;&lt;a href=\&quot;/image/{}\&quot;&gt;&lt;img src=&#39;/thumb/{}&#39; /&gt;&lt;/a&gt;&lt;br /&gt;&quot;, row.id, row.id));<br>    }</pre><pre>    let path = std::path::Path::new(&quot;src/search.html&quot;);<br>    let mut content = tokio::fs::read_to_string(path).await.unwrap();<br>    content = content.replace(&quot;{results}&quot;, &amp;results);</pre><pre>    Html(content)<br>}</pre><p>It is referring to src/search.html, so let&#39;s make that too. Notice the {results} placeholder.</p><blockquote><em>Tip: There are some great placeholder libraries!</em></blockquote><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;</pre><pre>&lt;head&gt;<br>    &lt;title&gt;My Awesome Thumbnail Server&lt;/title&gt;<br>&lt;/head&gt;</pre><pre>&lt;body&gt;<br>    &lt;h1&gt;Welcome to the thumbnail server&lt;/h1&gt;<br>    &lt;div id=&quot;thumbnails&quot;&gt;{results}&lt;/div&gt;<br>    &lt;hr /&gt;<br>    &lt;form method=&quot;post&quot; action=&quot;/search&quot;&gt;<br>        &lt;input type=&quot;text&quot; name=&quot;tags&quot; value=&quot;&quot; placeholder=&quot;Tags&quot; /&gt; &lt;br /&gt;<br>        &lt;input type=&quot;submit&quot; value=&quot;Search&quot; /&gt;<br>    &lt;/form&gt;</pre><pre>&lt;/body&gt;</pre><pre>&lt;/html&gt;</pre><p>And run the program and you can search!</p><p>What you’ve done:</p><ul><li>Setup a database with migrations.</li><li>Auto-run the migrations on start.</li><li>Made a thumbnail of any image that has been uploaded and doesn’t have one.</li><li>Setup a multi-part from post that saves image information to the database and saves the file.</li><li>Called into system thread land to generate an image thumbnail.</li><li>Added a redirect to handle a POSTed form.</li><li>Added a simple search function.</li></ul><p>Not bad — Rust is <em>very</em> productive once you get going.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c9f5b064bd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>