<?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 Kofi Otuo on Medium]]></title>
        <description><![CDATA[Stories by Kofi Otuo on Medium]]></description>
        <link>https://medium.com/@otukof?source=rss-e3ee6219320c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2xEcUKy5TUuNVW2dlFZpJQ.png</url>
            <title>Stories by Kofi Otuo on Medium</title>
            <link>https://medium.com/@otukof?source=rss-e3ee6219320c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 10:41:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@otukof/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[Build A Web + Desktop Application With Rust: I]]></title>
            <link>https://levelup.gitconnected.com/build-a-web-desktop-application-with-rust-i-8eb12cf160b6?source=rss-e3ee6219320c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8eb12cf160b6</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Kofi Otuo]]></dc:creator>
            <pubDate>Sun, 09 Mar 2025 17:50:01 GMT</pubDate>
            <atom:updated>2025-03-09T17:50:01.999Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous article, “<a href="https://medium.com/gitconnected/create-a-web-desktop-application-with-rust-c8449f661ecc">Build A Web + Desktop Application With Rust,”</a> we asked if Rust could replace JavaScript for full-stack development. Well, let’s see how that is possible.</p><p>If you’ve ever felt trapped by JavaScript’s tooling labyrinth—where npm install snowballs into dependency hell and Webpack updates feel like unpaid overtime—this series is just for you. If you just started Rust, Web, or Desktop development, this series is also for you. This series is designed to be beginner-friendly, exposing you to rust development’s technicalities.</p><p>In this tutorial, we’ll set up our repository for development. Don’t worry. It is very easy to set up. First, make sure to install Rust</p><h4>Install Rust</h4><p>For Linux and macOS, run:</p><pre>curl --proto &#39;=https&#39; --tlsv1.2 https://sh.rustup.rs -sSf | sh</pre><p>For Windows, visit <a href="https://www.rust-lang.org/tools/install">https://www.rust-lang.org/tools/install</a></p><h4>Create a Tauri Project</h4><p>Moving on to the main deal, let’s create a Tauri project. For this tutorial, we’ll use Tauri’s default template, which comes with most of what we need already set up.</p><p>First, we need to install the create-tauri-app binary. This binary is what we would use as our starting point.</p><pre>cargo install create-tauri-app --locked # install it</pre><p>Now open your desired folder and run the following</p><pre>cd your-desired-folder<br>cargo create-tauri-app</pre><p>The command cargo create-tauri-app is an interactive one. It asks for our project name. Let’s name it resume-ui. Next is an identifier; press Enter to use the default.</p><p>The following prompt is the language. Select Rust and then Enter. For the UI template, use the arrow keys to select Leptos. And that’s it! You have successfully created your own GUI project in Rust. Now, let’s run it</p><h4>Running A Tauri App</h4><p>To run our app, we need the <a href="https://v2.tauri.app/reference/cli/"><strong>Tauri 2.0 CLI</strong></a><strong>. </strong>Install it by running the cargo command:</p><pre>cargo install tauri-cli --version &quot;^2.0.0&quot; --locked</pre><p>This command installs the CLI, enabling us to run the program. Change to the project directory and run the build command:</p><pre>cargo tauri dev</pre><p>This command opens a new desktop window similar to this, depending on the current system mode (either dark or light):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z0QRAIR0gP869rKnag9jig.png" /><figcaption>Demo UI</figcaption></figure><p>You can also open <a href="http://127.0.0.1:1420/">http://127.0.0.1:1420/</a> on your browser to view it! This command watches for file changes and updates the UI accordingly.</p><h4>Set Up Tailwind Css</h4><p>To install Tailwind, you would need to <a href="https://docs.npmjs.com/downloading-and-installing-node-js-and-npm/">install </a><a href="https://docs.npmjs.com/downloading-and-installing-node-js-and-npm/">npm</a>. Using npm, we can install Tailwind as follows:</p><pre>npm install tailwindcss @tailwindcss/cli</pre><p>Next, add @import “tailwindcss”; to the top of styles.css. This points the tailwindcss to know which file your main CSS is.</p><p>Next, we’ve got to set up Tailwind to watch changes in our source files so that the new CSS file gets generated on the fly when we update our code. Open a background terminal and run this code:</p><pre>npx @tailwindcss/cli -i ./styles.css -o ./output.css --watch</pre><p>Finally, replace the CSS file path here &lt;link data-trunk rel=”css” href=”styles.css” /&gt; in index.html with output.css. So index.html Looks like this:</p><pre>&lt;!doctype html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot; /&gt;<br>    &lt;title&gt;Tauri + Leptos App&lt;/title&gt;<br>    &lt;link data-trunk rel=&quot;css&quot; href=&quot;output.css&quot; /&gt; # styles.css -&gt; output.css<br>    &lt;link data-trunk rel=&quot;copy-dir&quot; href=&quot;public&quot; /&gt;<br>    &lt;link data-trunk rel=&quot;rust&quot; data-wasm-opt=&quot;z&quot; /&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;&lt;/body&gt;<br>&lt;/html&gt;</pre><h4>Trying It Out</h4><p>Let’s try it out to make sure it works. Let us increase the image size of the Tauri logo displayed in the UI. Navigate to src/app.rs.</p><p>Add the scale-200 class to the image class of the Tauri logo. This scales the image to 200%, or 2x.</p><pre>&lt;div class=&quot;row&quot;&gt;<br>    &lt;a href=&quot;https://tauri.app&quot; target=&quot;_blank&quot;&gt;<br>        &lt;img src=&quot;public/tauri.svg&quot; class=&quot;logo tauri scale-200&quot; /*add scale-200 class*/ alt=&quot;Tauri logo&quot;/&gt;<br>    &lt;/a&gt;<br>    &lt;a href=&quot;https://docs.rs/leptos/&quot; target=&quot;_blank&quot;&gt;<br>        &lt;img src=&quot;public/leptos.svg&quot; class=&quot;logo leptos&quot; alt=&quot;Leptos logo&quot;/&gt;<br>    &lt;/a&gt;<br>&lt;/div&gt;</pre><p>Since we rancargo tauri devThe code should automatically update and see a UI change. It should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xQm4k6FariT9ZYzbIZFkBw.png" /><figcaption>Updated Demo UI</figcaption></figure><h3>Conclusion &amp; What’s Next</h3><p>We’ve laid the groundwork for a <strong>unified Rust stack</strong> that eliminates the need for JavaScript in full-stack development. Here’s what we achieved:</p><ul><li><strong>Workspace Configured</strong>: A shared codebase for web (Leptos) and desktop (Tauri)</li><li><strong>Tailwind Integrated</strong>: Styled components <em>without</em> Node.js or CSS files</li><li><strong>WASM Ready</strong>: Leptos’ dual rendering engine prepped for hydration</li><li><strong>Tauri Shell Live</strong>: Desktop builds now compile to binaries under 5MB</li></ul><p>The result? A starter template that proves Rust can handle:<br>✅ Reactive UIs<br>✅ Cross-platform builds<br>✅ Modern styling workflows</p><p><strong>No compromises. No JavaScript.</strong></p><h3>Coming in Part 2: Crafting the UI</h3><p>We’ll transform this skeleton into a polished resume app by:</p><ul><li>Building interactive components with Leptos’ signals.</li><li>Implementing dark mode with Tailwind’s dark: modifier.</li><li>Animating timelines with Rust-driven keyframes.</li></ul><p>Repository:</p><p><a href="https://github.com/Kofituo/Kofituo.github.io/tree/part1">https://github.com/Kofituo/Kofituo.github.io/tree/part1</a></p><h3>👋 Let’s Connect!</h3><p><strong>Do you need a Rust/Tauri/Leptos/Yew developer? Do you need to inquire about your Rust, Web, or Desktop Project?</strong></p><h4>Contact Me On <a href="https://www.upwork.com/freelancers/~0196d30a485de56f48">UpWork</a></h4><p><em>Open for contracts, consulting, or collaborations!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8eb12cf160b6" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/build-a-web-desktop-application-with-rust-i-8eb12cf160b6">Build A Web + Desktop Application With Rust: I</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create A Web + Desktop Application With Rust]]></title>
            <link>https://levelup.gitconnected.com/create-a-web-desktop-application-with-rust-c8449f661ecc?source=rss-e3ee6219320c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8449f661ecc</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[learning]]></category>
            <dc:creator><![CDATA[Kofi Otuo]]></dc:creator>
            <pubDate>Wed, 05 Mar 2025 01:32:22 GMT</pubDate>
            <atom:updated>2025-03-09T18:07:14.352Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CapcrlvBTGmhCeh2nO03EQ.jpeg" /><figcaption>Tauri and Leptos</figcaption></figure><h3>Build A Web + Desktop Application With Rust</h3><p><em>What if you could build a blazing-fast web app</em> <strong><em>and</em></strong> <em>a native desktop application — using a single codebase, with no JavaScript, but the safety guarantees of Rust?</em></p><p>As developers, we’ve all felt the pain of maintaining separate codebases for web and desktop apps. The JavaScript ecosystem’s endless tooling, Node version headaches, and Electron’s performance overhead can turn even simple projects into maintenance nightmares.</p><p>But what if I told you there’s a better way?</p><p>In this article series, I’ll show you how <strong>Rust</strong> — the language redefining systems programming — can revolutionize full-stack development. We’ll combine two groundbreaking frameworks:</p><ul><li><strong>Leptos</strong>: A reactive frontend framework compiling to WebAssembly (WASM) for near-native browser speed</li><li><strong>Tauri</strong>: A Rust-powered alternative to Electron that builds lightweight desktop apps with system-native binaries</li><li><strong>Tailwind CSS</strong>: A utility-first CSS framework for rapid, responsive UI development</li></ul><p>Together, they let us create <strong>one codebase that deploys as</strong>:<br>✅ A server-rendered web app (via Leptos)<br>✅ A native desktop app (via Tauri)<br>✅ Even mobile-ready PWA (with the same components!)</p><p><strong>Here’s what we’ll build</strong>:<br>A dynamic <em>interactive resume </em>website like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*sk4tm_eFPWVzsFDnIbutPA.gif" /><figcaption>Demo Ui</figcaption></figure><p><strong>Why this stack is productive:</strong></p><ul><li><strong>No CSS headaches</strong>: Tailwind’s utility classes keep UIs consistent without context-switching</li><li><strong>Type safety from backend to buttons</strong>: Rust types propagate through Leptos components <em>and </em>Tailwind class validation (via plugins)</li><li><strong>Compile once, run everywhere</strong>: Web, Windows/macOS/Linux desktop, or mobile-ready application</li></ul><h3>🔗 Series Roadmap</h3><p><em>(No code in this intro — hands-on starts next!)</em></p><ol><li><a href="https://medium.com/gitconnected/build-a-web-desktop-application-with-rust-i-8eb12cf160b6"><strong>Part 1</strong>: Architecture &amp; Setup — Rust Meets the Frontend</a></li></ol><p>Configure Leptos + Tauri + Tailwind</p><p>2.<strong> Part 2 &amp; 3</strong>: Crafting UI with Tailwind in Rust</p><h3>👨‍💻 Why Follow Along?</h3><ul><li><strong>Kill context switching</strong>: Write backend logic <em>and</em> UI in Rust.</li><li><strong>Learn by shipping</strong>: End with a deployable project for your portfolio.</li><li><strong>Future-proof</strong>: This stack is gaining rapid adoption (Leptos 0.8 just dropped!).</li></ul><h3>👋 Let’s Connect!</h3><p><strong>Need a Rust/Tauri/Leptos/Yew developer? Need to make enquiries about your Rust, Web or Desktop Project?</strong></p><h4>Contact Me On <a href="https://www.upwork.com/freelancers/~0196d30a485de56f48">UpWork</a></h4><p><em>Open for contracts, consulting, or collaborations!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8449f661ecc" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/create-a-web-desktop-application-with-rust-c8449f661ecc">Create A Web + Desktop Application With Rust</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Sender to Receiver: Rust’s Approach to Local File Transfers]]></title>
            <link>https://levelup.gitconnected.com/from-sender-to-receiver-rusts-approach-to-local-file-transfers-e6a778020d90?source=rss-e3ee6219320c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6a778020d90</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[networking]]></category>
            <dc:creator><![CDATA[Kofi Otuo]]></dc:creator>
            <pubDate>Wed, 12 Jun 2024 09:29:14 GMT</pubDate>
            <atom:updated>2024-06-13T20:17:21.645Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rlD76kuUKCuf_EW-4CF7lw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@brlimaproj?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">David Bruno Silva</a> on <a href="https://unsplash.com/photos/blue-yellow-red-and-green-papers-Z19vToWBDIc?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>In the contemporary landscape of digital interconnectedness, the efficient and secure transfer of files over local networks stands as a cornerstone of modern data management. Have you ever found yourself staring at your screen, wondering, “How do I smoothly shuffle files between devices on my local network? 🤔”. If that’s the case, this tutorial is just right for you.</p><p>This beginner-friendly tutorial delves into the nuances of leveraging Rust for seamless file exchanges across platforms like Android, Windows, Mac, Linux, and more. For those eager to dive straight into practical application, kindly skip to the end of the tutorial where you’ll find ready-to-use binaries tailored for your system.</p><p>Join us as we navigate the technical terrain, shedding light on Rust’s pragmatic solutions for local file transfers. By the end, you’ll be equipped with knowledge and a practical skill set to efficiently transfer files over local networks using Rust. Let’s embark on this exploration of Rust’s networking capabilities together.</p><h3>Methods for Local Network File Transfers in Rust</h3><p>Whether you’re building a collaborative editing tool, a peer-to-peer file synchronization application, or need to move large data sets efficiently, understanding the available methods for local network transfer in Rust empowers you with the foundation to do so. Here are some of the common methods available:</p><h4>1. Sockets and Streams: The Building Blocks of Network Communication</h4><p>As the bedrock of network communication, sockets offer low-level control over data exchange. Rust’s powerful networking API allows you to work directly with <a href="https://en.wikipedia.org/wiki/Transmission_Control_Protocol">TCP</a> and <a href="https://en.wikipedia.org/wiki/User_Datagram_Protocol">UDP</a> sockets, building custom protocols and tailoring interactions to your specific needs. While this approach offers unparalleled flexibility, it also demands a deeper understanding of network protocols and requires significant boilerplate code to handle tasks like serialization and error handling.</p><h4>2. Third-Party Libraries and Frameworks</h4><p>Rust’s vibrant ecosystem extends beyond the standard library, with a plethora of third-party libraries and frameworks designed to simplify networking tasks. Leverage libraries like mio and reqwest for high-level abstractions, simplifying development, and letting you focus on the core logic.</p><p>In this tutorial, we’ll take the more low-level approach and explore the standard library’s <strong>Sockets and Streams.</strong> We’ll use that to transfer files across a local network such as a WIFI network. Let’s begin by creating a Rust project. I’ll do my best to explain the terms and technicalities along the way.</p><h3>Creating a Rust Project</h3><p>Before we start writing code, we’ve to ensure we have the required prerequisites.</p><p><strong>Prerequisites</strong>:</p><ul><li><strong>Rust and Cargo</strong>: The dynamic duo! Make sure you have Rust and Cargo installed on your system. Most operating systems offer convenient installation packages or scripts. Check the official Rust website for detailed instructions and download options: <a href="https://www.rust-lang.org/tools/install">https://www.rust-lang.org/tools/install</a>.</li></ul><p>Once installed, navigate to the folder you’d like to put the project in. Within that directory, run the following command to create a new cargo binary called file-transfer:</p><pre>cargo new file-transfer</pre><p>You’ll receive a prompt indicating that the project has been created.</p><h3>Understanding TCP: The Foundation for Reliable Network File Transfers in Rust</h3><h4>Demystifying TCP in Network File Transfers</h4><p>Think of TCP as a well-organized postal service for your digital data. TCP employs a structured approach, ensuring every byte reaches its destination in the correct order and without errors. This intricate choreography involves several key steps:</p><ul><li><strong>Handshaking</strong>: Before any data travels, TCP establishes a two-way communication channel between sender and receiver. This ensures a dedicated pathway for your file, preventing it from getting lost in the network’s digital wilderness.</li><li><strong>Packet Segmentation</strong>: Your hefty file is meticulously chopped into smaller, numbered packets, making them easier to transmit and manage. Think of it as sending your data in individually labeled boxes, rather than one unwieldy crate.</li><li><strong>Sequence and Acknowledgements</strong>: Each packet receives a unique sequence number, acting as a digital fingerprint. The receiver acknowledges receipt of each packet, allowing the sender to identify any missing ones and trigger retransmission. Imagine the postal service meticulously checking off each delivered box and requesting replacements for any that go astray.</li><li><strong>Flow Control</strong>: To prevent overwhelming the recipient, TCP dynamically adjusts the sending rate based on network congestion. Just like a postman wouldn’t flood your doorstep with packages simultaneously, TCP ensures a smooth and efficient delivery flow.</li><li><strong>Error Detection and Correction</strong>: Built-in <a href="https://en.wikipedia.org/wiki/Checksum"><em>checksums</em></a> verify the integrity of each packet. If errors occur, corrupted data is identified and retransmitted, ensuring your file arrives unscathed. Picture the postal service meticulously checking each box for damage and replacing any with torn corners or faded labels.</li></ul><p>Converting this flow to code can be roughly simplified as:</p><p><em>Connecting sender (server) to receiver (client) -&gt; sending data (upload)-&gt; downloading data (download) -&gt; concatenating received data to something meaningful.</em></p><p>Let’s try to implement this in the Rust code.</p><h3>Programming the Server and Client</h3><p>Before diving into the Rust code, let’s have an overview of how to go about it.</p><p>Here’s a very high-level illustration meant to simplify things. On a local network, each device gets assigned an <a href="https://en.wikipedia.org/wiki/IP_address"><strong>IP address</strong></a> by the router. An IP address typically looks like this 192.168.100.46. The IP address serves as the location of a device on a network. Once we know its location, we can open a <a href="https://en.wikipedia.org/wiki/Port_(computer_networking)">port</a> through which communication can be done. Think of a busy building with different offices. Each office serves a specific purpose, like one for receiving mail, another for phone calls, and so on. In computer terms, a port is like those different offices. Some common ports are <strong>80</strong> for HTTP, <strong>443</strong> for HTTPS, and less commonly <strong>9100</strong> for printers connected over a network. Port numbers range from 0 to 65535. Port numbers 0 to 1023 are system ports and typically require root access to access them. Ports 1024 through 49151 are known as registered ports. While we don’t need root access for these ports, chances are another program might be using them. For instance, if you have a printer connected to your network, port 9100 for the printer’s IP might be in use. For our application, we’d pick a random port number from 49152 to 65535. That way, we’re more guaranteed to have a smooth operation.</p><p>Now that we understand IP and Ports a bit, let’s plan how our program should work. First, we need to establish a connection between the server and the client. The server would <strong>listen</strong> for TCP connections through our custom port. The client, on the other hand, would simply <strong>connect</strong> to the server’s socket address, ie ip + port number. Here’s what that looks like in the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43bdd19461135afe4c3a1cff4d55025e/href">https://medium.com/media/43bdd19461135afe4c3a1cff4d55025e/href</a></iframe><p>Using TcpListener, we can listen for TCP connections at the address 0.0.0.0:55515. In the address, the section before the colon is an IP address used by a TCP server (<a href="https://stackoverflow.com/a/20778887/12258661">it’s the same for every computer</a>). The number after the colon refers to the port number. For the client code, note that we specify the IP address of the server and our custom port as well. Replace the IP address there with that of your PC and run it. It should produce an output saying connection established. Data: Hello world.</p><blockquote>TCP is a two way connection so both client and server can send and receive data.</blockquote><h3>Serializing the Data</h3><p>Now that we’ve looked at the very basics of socket connections, let’s improve our program. Since this is a simple file transfer program, we’d implement our custom protocol. Our protocol is simple: first, send the information of the file to the client. If the client responds with <strong>YES</strong>, then we send the file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a044452b8f68b6671ef6ce488b981071/href">https://medium.com/media/a044452b8f68b6671ef6ce488b981071/href</a></iframe><p>In this example, we’re trying to send a file called test-image.png. You can specify the file path you’d like to send. We serialise the file information in a JSON using <a href="https://docs.rs/serde/1.0.193/serde/">serde</a> and <a href="https://docs.rs/serde_json/1.0.108/serde_json/">serde-json</a>. Those are handy rust crates to work with JSON data. After sending the file information, we wait for a response from the client either <strong>YES</strong> or <strong>NO</strong>. That way, the client knows what file is being sent and its size before accepting. Now let’s modify the client and server code to send the file data as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce49b8c2d95aa75c577b2b5fd5f105e3/href">https://medium.com/media/ce49b8c2d95aa75c577b2b5fd5f105e3/href</a></iframe><p>Now that we’ve all these in place, you can replace the file path with the one you prefer and run the program. The file could be an image, video, pdf, etc. Your output should be similar to this:</p><pre>Downloading: test-image.png<br>Received 32664 of 283043 bytes 11.540%<br>Received 65432 of 283043 bytes 23.117%<br>Received 98200 of 283043 bytes 34.694%<br>Received 130968 of 283043 bytes 46.271%<br> ---  ---- ---  --<br>Received 283043 of 283043 bytes 100.000%<br>done</pre><p>Whew!</p><p>Let’s now segregate the code so a user can specify whether to be a client or a sender.</p><h3>Specifying Device Type</h3><p>Now that we’ve ensured that our server-client code works well, let’s modify our program so a user can pass an argument to specify whether he’s a receiver or a sender. To do that, we’ll follow a <a href="https://doc.rust-lang.org/book/ch12-01-accepting-command-line-arguments.html#accepting-command-line-arguments">similar tutorial found in the Rust book</a>.</p><pre>use std::env; <br><br>fn main() -&gt; thread::Result&lt;io::Result&lt;()&gt;&gt; {<br>    let args: Vec&lt;String&gt; = env::args().collect();<br>    let device_type = args.get(1).expect(&quot;Please specify either client or server&quot;).as_str().to_lowercase();<br>    match device_type.as_str() {<br>        &quot;client&quot; =&gt; {<br>            thread::spawn(|| {<br>                client()<br>            }).join()<br>        }<br>        &quot;server&quot; =&gt; {<br>            thread::spawn(|| {<br>                server()<br>            }).join()<br>        }<br>        _ =&gt; panic!(&quot;Please specify either client or server&quot;)<br>    }<br>}<br><br>// -- snip --</pre><p>To confirm our setup, open up one terminal and run the server as follows: cargo run -- server. Now open another terminal and run cargo run -- client. You’ll see an output similar to that in the previous section in the client terminal.</p><h3>Trying It Out On Multiple Devices</h3><p>It’s time to try what we’ve coded on multiple devices. First, you’d need to <a href="https://doc.rust-lang.org/rustc/platform-support.html#platform-support">compile the program for your target device</a>. Suppose you want to try it out between Android and macOS, you’d need the program compiled for the respective OS. To compile the program for a specific OS, specify the OS architecture using the — target flag of Cargo.</p><p>For instance:</p><pre>cargo build --target x86_64-apple-darwin #for mac os</pre><p>Alternatively, you can get the precompiled binaries from my repository along with an <strong>updated source code ready for production</strong>.</p><blockquote>For Android, kindly check out my story on <a href="https://medium.com/dev-genius/integrating-rust-with-android-development-ef341c2f9cca?source=your_stories_page-------------------------------------">Integrating Rust With Android Development</a>, to learn how to add this library to your Android application.</blockquote><h3>Conclusion</h3><p>In wrapping up, Rust’s local file transfer approach isn’t just a tech marvel; it’s like having a trusty sidekick in your coding adventures. With its safety nets and lightning-fast performance, Rust ensures your file transfers are smooth sailing, leaving you with more time to enjoy your coffee and ponder over the mysteries of programming. So, whether you’re zapping files across your local network or crafting the next big app, Rust has got your back — and your bytes — covered!</p><h3>Repository</h3><p>This repository contains a much more structured and documented source code with additional features such as setting a unique name for each device in the network and sending text messages. It comes as a binary and library so feel free to use it how you please 😁!</p><h4><a href="https://github.com/Kofituo/rust-file-transfer.git">https://github.com/Kofituo/rust-file-transfer.git</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6a778020d90" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/from-sender-to-receiver-rusts-approach-to-local-file-transfers-e6a778020d90">From Sender to Receiver: Rust’s Approach to Local File Transfers</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breaking Tradition: Why Rust Might Be Your Best First Language]]></title>
            <link>https://blog.stackademic.com/breaking-tradition-why-rust-might-be-your-best-first-language-d10afc482ac1?source=rss-e3ee6219320c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d10afc482ac1</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[explore]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Kofi Otuo]]></dc:creator>
            <pubDate>Mon, 04 Sep 2023 19:06:14 GMT</pubDate>
            <atom:updated>2023-12-29T01:45:56.395Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZEk0yvZUriQIM32iRhQtrw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@marvelous?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Marvin Meyer</a> on <a href="https://unsplash.com/photos/SYTO3xs06fU?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Ah, the firsts in life! Your first bike, first crush, first taste of a bizarre foreign delicacy, and… your first programming language? Okay, maybe that last one doesn’t send shivers of nostalgia down everyone’s spine, but in the coding world, it’s a BIG deal. Think of it as choosing your first pet. Sure, Python might be that cute, cuddly kitten that everyone oohs and aahs over. Java? Perhaps the loyal golden retriever. But what if I told you that Rust is like that underrated, brainy parrot that not only talks but also ensures you don’t leave the gas on?</p><p>Jokes aside (but not entirely, because where’s the fun in that?), diving into the world of programming with Rust might seem like opting to learn to drive in a manual-transmission sports car instead of the automatic family sedan. It’s daunting, sure, but oh, the thrill! In this piece, we’ll unpack why Rust, a language traditionally hailed for its systems prowess and memory management magic, could be an excellent contender for your coding debut.</p><h3>Understanding the Rust learning curve</h3><p>When venturing into the realm of programming, the choice of your inaugural language is pivotal. It sets the tone for your foundational understanding, shapes your early experiences, and can either inspire or deter your continued journey in the software world. The learning curve, therefore, is not just a graph of progress; it’s a trajectory of inspiration and challenge.</p><p>At a glance, Rust might appear to present a steeper learning curve than some of its counterparts. Languages like Python, with its English-like syntax and forgiving nature, often get the limelight as the “go-to starter language.” Rust, on the other hand, doesn’t always extend the same courtesies. It demands precision, and its compiler is known for its uncompromising feedback. For the uninitiated, this could be construed as unfriendly. However, there’s a method to this seeming madness.</p><h4>Challenges of the Rust learning curve:</h4><ul><li><strong>Strict compiler feedback</strong>: One of the early hurdles Rust beginners encounter is the compiler’s stringent requirements. It will flag issues until the code aligns with Rust’s safety and efficiency principles. This rigorous feedback, though potentially daunting, ensures that budding developers grasp the importance of writing precise and efficient code from day one.</li><li><strong>Ownership and borrowing</strong>: Concepts like ownership and borrowing, while central to Rust’s memory safety guarantees, can be challenging to grasp initially. These concepts are less explicit or even absent in some other languages, making them a unique challenge to Rust newcomers.</li><li><strong>Syntax nuances</strong>: Rust’s syntax, while expressive, has nuances that can be unfamiliar, especially to those who haven’t encountered the programming paradigms it draws from.</li></ul><h4>Rewards of the Rust learning curve:</h4><ul><li><strong>Solid foundation</strong>: By overcoming the initial challenges posed by Rust, beginners acquire a strong foundation not just in the language, but in universally valuable programming principles. This foundation pays dividends when transitioning to or adding other languages to one’s repertoire.</li><li><strong>Safety and efficiency</strong>: Once over the early hurdles, developers can leverage Rust’s features to write code that’s both safe and efficient, a balance that’s often hard to achieve in many languages.</li><li><strong>Robust community support</strong>: While the journey might be harrowing, the Rust community is renowned for its support and inclusivity. Beginners have many resources, from forums to documentation, to lean on.</li></ul><p>In essence, Rust offers a rich tapestry of learning. It demands rigor but rewards persistence with a deep, foundational understanding of programming. For those who navigate its challenges, the payoff is not just proficiency in Rust, but a broadened perspective on coding as a craft.</p><h3>The Cornerstones of Rust: Ownership, Borrowing, and Lifetimes</h3><p>One cannot journey far into Rust without encountering its triad of foundational concepts: ownership, borrowing, and lifetimes. While initially daunting to many newcomers, these principles form the bedrock of Rust’s promise of memory safety without sacrificing performance.</p><h4>Ownership: The solo dance of data</h4><p>In Rust, every value has a single ‘<em>owner</em>’, and this ownership can be transferred, but never duplicated without explicit cloning. This ensures that at any given time, only one part of your code can make modifications to a piece of data, preventing unpredictable behaviors.</p><p><em>For a beginner, this might seem restrictive, but this system eradicates a slew of common bugs related to invalid data references, which even seasoned developers in other languages grapple with.</em></p><h4>Borrowing: Sharing without carelessness</h4><p>If ownership sounds a tad possessive, borrowing comes to the rescue, allowing data to be accessed by multiple parts of your program without relinquishing ownership. Rust distinguishes between mutable and immutable borrows, ensuring that data can either be read by many or written by one, but never both simultaneously. This eradicates race conditions right at the source, a common pitfall in concurrent programming.</p><h4>Lifetimes: Defining the span of relevance</h4><p>In Rust, lifetimes are annotations that specify how long references to data should be valid. While the compiler often infers lifetimes implicitly, understanding them allows developers to ensure references stay valid as long as intended and no longer. This prevents “<strong>dangling references</strong>,” which could lead to undefined behavior in many languages.</p><h4>Why are these concepts crucial for beginners?</h4><p>While these concepts present an initial learning challenge, they offer a unique advantage to beginners:</p><ol><li><strong>Built-In discipline</strong>: By internalizing these principles early on, new programmers develop habits that promote writing safe and efficient code from the get-go.</li><li><strong>Reduced debugging</strong>: The rigorous checks associated with these concepts mean fewer runtime bugs, enabling beginners to focus more on logic and design rather than hunting elusive memory errors.</li><li><strong>A solid foundation</strong>: Understanding these core principles provides a sturdy foundation, not just for mastering Rust, but for appreciating memory management and concurrency issues, even if one transitions to other languages.</li></ol><p>In the grand tapestry of programming, Rust’s approach to ownership, borrowing, and lifetimes offers a fresh perspective. It’s akin to learning architectural integrity before building a skyscraper. With these principles at heart, a beginner is not just coding in Rust; they are architecting resilient and efficient software systems.</p><h3>Harnessing the Rust Ecosystem: Resources and Community</h3><p>While Rust’s principles set it apart, its ecosystem ensures that beginners aren’t set adrift in uncharted waters. The language is complemented by a vibrant and welcoming community, which has painstakingly created a myriad of resources to assist newcomers.</p><p><strong>Rich documentation</strong>: Rust’s official documentation, especially “<a href="https://doc.rust-lang.org/book/">The Rust Programming Language” book</a>, often affectionately termed the “Rust Book”, provides a comprehensive introduction to the language. Its clarity and depth make it an invaluable guide for those starting their journey.</p><p><strong>Cargo and Crates.io</strong>: Rust’s package manager, Cargo, coupled with its package registry, Crates.io, offers a seamless experience for managing dependencies, and building, and distributing Rust packages. This integrated tooling reduces initial setup friction and lets beginners focus on coding.</p><p><strong>Vibrant community</strong>: Rustaceans, as members of the Rust community are called, are known for their helpfulness. Platforms like the <a href="https://users.rust-lang.org/"><em>Rust forum</em></a>, <a href="https://www.reddit.com/r/rust/"><em>Reddit’s r/rust</em></a>, <a href="https://stackoverflow.com/questions/tagged/rust"><em>StackOverflow</em></a>, and the <a href="https://discord.com/invite/rust-lang-community"><em>Rust Discord server</em></a> are buzzing with enthusiasts eager to assist, discuss, and share.</p><h3>Conclusion: Rust as the Unconventional First Language Choice</h3><p>The coding universe is vast, filled with a plethora of languages beckoning beginners with their unique allure. While Rust might seem like an unorthodox first choice, its robust principles, coupled with a supportive ecosystem, make it a formidable contender. Starting with Rust is akin to training with weights; once mastered, you’re not only proficient in Rust but also primed for excellence in the broader world of programming. So, to the brave souls contemplating this path: in the words of the Rust community, “Happy coding!”</p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d10afc482ac1" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/breaking-tradition-why-rust-might-be-your-best-first-language-d10afc482ac1">Breaking Tradition: Why Rust Might Be Your Best First Language</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginner’s Guide to Rust Procedural Macros: Creating a JSON Derive Macro]]></title>
            <link>https://blog.devgenius.io/a-beginners-guide-to-rust-procedural-macros-creating-a-json-derive-macro-eb44279e7244?source=rss-e3ee6219320c------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb44279e7244</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Kofi Otuo]]></dc:creator>
            <pubDate>Fri, 09 Jun 2023 12:43:54 GMT</pubDate>
            <atom:updated>2023-09-18T07:43:06.064Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="An novice software developer excited" src="https://cdn-images-1.medium.com/max/1024/1*TkgeXSNXtRy_jqPpYhhBMA.jpeg" /></figure><p>Rust procedural macros (proc macro) have emerged as a game-changer in the world of programming, empowering developers to extend the capabilities of the Rust language itself. If you’re a beginner eager to learn about Rust procedural macros and their practical applications, you’ve come to the right place. In this comprehensive beginner’s guide, we will explore the ins and outs of Rust procedural macros and demonstrate their usage through the creation of a powerful JSON derive macro.</p><p>With the growing demand for efficient and flexible data serialization formats, understanding how to leverage procedural macros for JSON conversion becomes essential. By following this step-by-step tutorial, you will not only grasp the core concepts of procedural macros but also gain hands-on experience in building a custom JSON serialization macro for Rust structures and enums.</p><p>This guide serves as an invaluable resource for developers of all levels. Whether you’re a seasoned Rust programmer seeking to enhance your code or an aspiring developer looking to expand your skill set, mastering procedural macros will undoubtedly accelerate your Rust journey. So, let’s dive into the world of Rust procedural macros together and unlock their immense potential!</p><h4>Simplifying Code Generation with Rust Derive Macros 📦📈</h4><p>Derive macros in Rust are a powerful feature that allows developers to automatically generate code implementations based on the structure and properties of custom data types. By leveraging the derive attribute, Rust programmers can derive common traits and behaviors for their types, saving time and effort in writing repetitive code. Derive macros enable the automatic implementation of traits like Clone, Debug, Serialize, and more, based on the structure of a custom type. This ability to derive implementations simplifies the process of generating boilerplate code and promotes code reuse, making Rust codebases more concise and maintainable. In the following sections, we will explore how to harness the potential of derive macros by building a JSON derive macro from scratch.</p><h4>Creating the derive Crate 🛠</h4><p>This section will start building the foundation for our JSON derive macro by creating the derive crate. The derive crate will serve as the container for our custom procedural macros and provide the necessary functionality for deriving JSON serialization implementations for Rust structures and enums.</p><p>To begin, we’ll set up a new Rust crate using the Cargo package manager. Open your preferred terminal or command prompt and navigate to the directory where you want to create the derive crate. Then, execute the following command:</p><pre>cargo new json-derive --lib</pre><p>This command creates a new directory named json-derive and generates the basic project structure for our crate. Once the crate is created, navigate into the json-derive directory:</p><pre>cd json-derive</pre><p>Let’s now set up our crate so it can use the procedural macro features.</p><p>In the Cargo.toml file, add the following:</p><pre>[lib]<br>proc-macro = true<br><br>[dependencies]<br>quote = &quot;1&quot;<br>proc-macro2 = &quot;1.0&quot;<br>syn = &quot;2.0&quot;</pre><p>First, we declare our crate as a procedural macro crate. We then add the required dependencies for writing a procedural macro in Rust.</p><p>Modify the lib.rs file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b1fd6b436678afbe74ef49162435253/href">https://medium.com/media/7b1fd6b436678afbe74ef49162435253/href</a></iframe><p>Lines 6 and 7 show the function signature of a typical derive macro. For a derive macro, we use <a href="https://docs.rs/syn/2.0.17/syn/macro.parse_macro_input.html">parse_macro_input!</a>. That macro allows us to convert the input to a desired format. For instance, if we wanted to ensure that our macro should be used on only structs, we could implement our <a href="https://docs.rs/syn/2.0.17/syn/parse/index.html">parser</a>. For a derive macro, we can simply use the DeriveInput format provided by syn.</p><p>The <a href="https://docs.rs/syn/2.0.17/syn/struct.DeriveInput.html">DeriveInput</a> struct has 5 fields.</p><ol><li>The attrs field refers to the attributes associated to struct, enum, or union.</li><li>The vis field refers to the visibility ie pub, pub(crate), etc.</li><li>The ident field refers to the name of the struct, enum, or union.</li><li>The <a href="https://docs.rs/syn/2.0.17/syn/struct.Generics.html">generics</a> field refers to any generics or lifetimes associated with the data structure. e.g. struct &lt;T&gt; {name:T}</li><li>The data contains the remaining info about the struct, enum, or union.</li></ol><p>The line quote!().into() is where we input our macro logic.</p><p>Let’s create a second crate that stores the derive trait. Navigate to the projects directory and run:</p><pre>cargo new json-trait --lib</pre><p>For a simple JSON serialization trait, we can write our trait as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5755fa4ef826b6c29d5d8f986cfcdc9a/href">https://medium.com/media/5755fa4ef826b6c29d5d8f986cfcdc9a/href</a></iframe><p>Anyone who implements our trait can return an <strong>invalid JSON </strong>string. But that’s fine for now since it’s just a short beginner guide.</p><blockquote><strong>If you’d like consultation and an in-depth overview on how to implement a more production ready serialisable trait that handles invalid JSON among others, </strong><a href="https://www.upwork.com/services/consultation/development-it-kofi-1567829700305080320?ref=project_share&amp;tier=1"><strong>feel free to reach out.</strong></a><strong> I would love to hear from you!</strong></blockquote><p>To complete our setup, we need another crate that uses our derive macro. We’ll create a binary crate so we can easily run the project.</p><p>Navigate to the projects directory ie the directory in which you created json-derive. Run the following command</p><pre>cargo new test-derive</pre><p>Navigate to the test-derive folder. Modify the dependencies within the Cargo.toml file:</p><pre>[dependencies]<br>json-derive = { path = &quot;../json-derive&quot; }<br>json-trait = { path = &quot;../json-trait&quot; }</pre><p>Then in the main.rs file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e4ed276926ffe86eb802abacd224672/href">https://medium.com/media/0e4ed276926ffe86eb802abacd224672/href</a></iframe><p>For now, our derive macro doesn’t do anything. Let’s work on that!</p><h4>Implementing derive(Json) 👨‍💻</h4><p>Let’s navigate to the json-derive crate. Before we begin, let’s refresh our minds on what a typical JSON looks like:</p><pre>{<br>   &quot;name&quot;: &quot;Kofi Otuo&quot;,<br>   &quot;age&quot;: 21,<br>   &quot;is_student&quot;: true,<br>   &quot;address&quot;: {<br>      &quot;street&quot;: &quot;123 Main St&quot;,<br>      &quot;city&quot;: &quot;Exampleville&quot;,<br>      &quot;country&quot;: &quot;Sampleland&quot;<br>   },<br>   &quot;hobbies&quot;: [<br>      &quot;hiking&quot;,<br>      &quot;coding&quot;,<br>      &quot;sleeping&quot;<br>   ],<br>   &quot;food&quot;: &quot;Chicken&quot;,<br>   &quot;friends&quot;: [<br>      {<br>         &quot;name&quot;: &quot;Abigail Smith&quot;,<br>         &quot;age&quot;: 22,<br>         &quot;is_student&quot;: false,<br>         &quot;address&quot;: {<br>            &quot;street&quot;: &quot;Maple Street&quot;,<br>            &quot;city&quot;: &quot;Springfield&quot;,<br>            &quot;country&quot;: &quot;United States&quot;<br>         },<br>         &quot;hobbies&quot;: null,<br>         &quot;food&quot;: &quot;Ham&quot;,<br>         &quot;friends&quot;: []<br>      },<br>      {<br>         &quot;name&quot;: &quot;David Johnson&quot;,<br>         &quot;age&quot;: 19,<br>         &quot;is_student&quot;: true,<br>         &quot;address&quot;: null,<br>         &quot;hobbies&quot;: null,<br>         &quot;food&quot;: &quot;Chicken&quot;,<br>         &quot;friends&quot;: []<br>      },<br>      {<br>         &quot;name&quot;: &quot;John Doe&quot;,<br>         &quot;age&quot;: 94,<br>         &quot;is_student&quot;: true,<br>         &quot;address&quot;: {<br>            &quot;street&quot;: &quot;456 Elm St&quot;,<br>            &quot;city&quot;: &quot;Randomville&quot;,<br>            &quot;country&quot;: &quot;Wonderland&quot;<br>         },<br>         &quot;hobbies&quot;: [<br>            &quot;being lazy&quot;<br>         ],<br>         &quot;food&quot;: &quot;Bacon&quot;,<br>         &quot;friends&quot;: []<br>      }<br>   ]<br>}</pre><p>Add the following within the json_derive function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79d324d4c18353e75dea04e75991dda3/href">https://medium.com/media/79d324d4c18353e75dea04e75991dda3/href</a></iframe><p>First, we try to get the fields from the data structure. Similar to DeriveInput ident, the ident used above also refers to the name of the field. Note that, in JSON, objects aren’t named, so we don’t need the name of the struct or enum. We just need the names of the field within that data structure.</p><p>We use panic! here as a form of “debugging” to ensure the fields contain what we desire. And yes it does as shown by the panic message after running cargo run within the test-derive directory:</p><pre>error: proc-macro derive panicked<br> --&gt; src/main.rs:3:10<br>  |<br>3 | #[derive(Json)]<br>  |          ^^^^<br>  |<br>  = help: message: <br>           [<br>              &quot;name&quot;,<br>              &quot;age&quot;,<br>          ]</pre><p>Now let’s derive json for structs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73e8b3ea91070e4f2448a489adbfcf6a/href">https://medium.com/media/73e8b3ea91070e4f2448a489adbfcf6a/href</a></iframe><p>We reused some of the code from early on. Let’s explain what’s new here.</p><p>impl json_trait::Json for #name {:</p><p>This line allows us to implement our struct for the specified struct. Recall that name refers to the name of the struct. To use the name variable <em>within</em> the quote macro, we have to prefix it with # i.e. #name.</p><p>fn to_json(&amp;self) -&gt; String { is the function signature of the JSON trait.</p><p>let mut json = &quot;{ &quot;.to_string();</p><p>Here, we create a new string object that stores our JSON output. Let’s move on to where most of the magic happens.</p><pre>#(<br>    json.push_str(&amp;format!(&quot;\&quot;{}\&quot;: {}, &quot;, stringify!(#fields), json_trait::Json::to_json(&amp;self.#fields)));<br>)*</pre><p>For those familiar with <a href="https://doc.rust-lang.org/book/ch19-06-macros.html#declarative-macros-with-macro_rules-for-general-metaprogramming">macro_rules! syntax</a>, you’ve seen the expression $($expression)* or something similar. They are quite similar. Similar to $()* in macro_rules!, <a href="https://github.com/dtolnay/quote#repetition"><strong>#(...)*</strong></a> are used to define a repetition block. They indicate that the code within the block should be repeated for each occurrence of a specified pattern. Let’s break down how it works:</p><ol><li>#(: This symbol starts the repetition block. It indicates that the code following it will be repeated for each occurrence of a specified pattern.</li><li>...: The ellipsis (...) represents the pattern that will be repeated. In this case, it represents the code generated for each field in the struct. <em>Note that the variable to be expanded should be an iterator or should implement IntoIterator. You could also use a </em><em>Vec or similar collections directly. In our case, the variable </em><em>#fields is a </em><em>map and thus an iterator.</em></li><li>)*: This symbol ends the repetition block. It indicates that the repetition should stop.</li></ol><p>Here’s an example to illustrate how the repetition block works:</p><p>Suppose you have a struct with two fields: name and age. During macro expansion, the repetition block will generate code for each field, resulting in:</p><pre>json<br>  .push_str(&amp;format!(&quot;\&quot;{}\&quot;: {}, &quot;, stringify!(name), json_trait::Json::to_json(&amp;self.name))); <br>json<br>  .push_str(&amp;format!(&quot;\&quot;{}\&quot;: {}, &quot;, stringify!(age), json_trait::Json::to_json(&amp;self.age)));</pre><p>As you can see, the code inside the repetition block is repeated for each field, resulting in serialized key-value pairs for each field being appended to the json string.</p><p>In simpler terms, the #( and )* symbols help the macro generate code for each field in the struct. It allows the macro to automatically generate code that serializes each field into a key-value pair and adds it to the json string.</p><p>Let’s explain the latter part of that line:</p><pre>/*... */ stringify!(#fields), json_trait::Json::to_json(&amp;self.#fields))</pre><p>We use the <a href="https://doc.rust-lang.org/core/macro.stringify.html">stringify!</a> macro which allows us to use the field name as is and converts it to a string. That way we can produce our JSON with the field names as those of the struct.</p><p>json_trait::Json::to_json(&amp;self.#fields) is a function call that serializes the <strong>value</strong> of the field to its JSON representation. As shown in the explanation above, this expands to json_trait::Json::to_json(&amp;self.name) for a struct with a field called name e.g. struct Person {name : String}. This method also ensures that each field of the struct implements json_trait::Json. That way, the whole struct can be serialized with each field having a value.</p><pre>json.remove(json.len() - 2); // remove trailling comma<br>json.push(&#39;}&#39;);<br>json</pre><p>These final lines remove the trailing comma, close the JSON string, and return it.</p><p>Now that we’ve implemented derive(Json) for structs, let’s implement it for enums:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/089088aca5a395cc4aa657cabfc04026/href">https://medium.com/media/089088aca5a395cc4aa657cabfc04026/href</a></iframe><p>The implementation is quite similar to structs. The match statement allows you to perform pattern matching on a value and execute different codes based on the matched pattern.</p><p>Self::#variants: The #variants, as explained above, is a placeholder that will be replaced with each variant of the enum during macro expansion. Self:: is used to specify that we are referring to the enum itself.</p><p>Let’s consider an example enum called Direction with variants Up, Down, Right and Left. During macro expansion, the code snippet will be expanded to:</p><pre>match &amp;self {<br>    Self::Up =&gt; format!(&quot;{}&quot;, stringify!(Up)),<br>    Self::Down =&gt; format!(&quot;{}&quot;, stringify!(Down)),<br>    Self::Right =&gt; format!(&quot;{}&quot;, stringify!(Right)),<br>    Self::Left =&gt; format!(&quot;{}&quot;, stringify!(Left)),<br>}</pre><p>Now that we are all set, let’s implement our trait for common types such as integers, strings, slices, maps, etc.</p><h4>Using trait Json ✍️</h4><p>Navigate to json-trait crate. You should have a lib.rs file containing this code:</p><pre>pub trait Json {<br>    fn to_json(&amp;self) -&gt; String;<br>}</pre><p>Let’s implement our trait for common types:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7e2261af7ecfc2ec39f6497cde147d2/href">https://medium.com/media/a7e2261af7ecfc2ec39f6497cde147d2/href</a></iframe><p><em>As an assignment, try implementing </em><em>&lt;K:Json, V:Json&gt; Json for HashMap&lt;K, V&gt;.</em></p><p>Finally, let’s test our implementation. Navigate to the test-derive binary.</p><p>Create some structs in the main.rs file and use println! to visualize the JSON produced: For instance:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4baa3bb6eadc78b655a451de213fcec7/href">https://medium.com/media/4baa3bb6eadc78b655a451de213fcec7/href</a></iframe><p>Here’s the output:</p><pre>{ &quot;street&quot;: &quot;123 Main St&quot;, &quot;city&quot;: &quot;Exampleville&quot;, &quot;country&quot;: &quot;Sampleland&quot; }<br>{ &quot;street&quot;: &quot;Maple Street&quot;, &quot;city&quot;: &quot;Springfield&quot;, &quot;country&quot;: &quot;United States&quot; }<br>{ &quot;street&quot;: &quot;123 Random S&quot;, &quot;city&quot;: &quot;Cityville&quot;, &quot;country&quot;: &quot;Countryland&quot; }<br>{ &quot;street&quot;: &quot;Wonderland&quot;, &quot;city&quot;: &quot;Springfield&quot;, &quot;country&quot;: &quot;456 Elm St&quot; }<br>{ &quot;street&quot;: &quot;456 Elm St&quot;, &quot;city&quot;: &quot;Randomville&quot;, &quot;country&quot;: &quot;Wonderland&quot; }<br>{ &quot;name&quot;: &quot;Kofi&quot;, &quot;age&quot;: 21, &quot;is_student&quot;: true, &quot;address&quot;: { &quot;street&quot;: &quot;123 Main St&quot;, &quot;city&quot;: &quot;Exampleville&quot;, &quot;country&quot;: &quot;Sampleland&quot; }, &quot;hobbies&quot;: [ &quot;hiking&quot;, &quot;coding&quot;, &quot;sleeping&quot; ], &quot;food&quot;: &quot;Chicken&quot;, &quot;friends&quot;: [ { &quot;name&quot;: &quot;Jane Smith&quot;, &quot;age&quot;: 28, &quot;is_student&quot;: false, &quot;address&quot;: { &quot;street&quot;: &quot;Maple Street&quot;, &quot;city&quot;: &quot;Springfield&quot;, &quot;country&quot;: &quot;United States&quot; }, &quot;hobbies&quot;: null, &quot;food&quot;: &quot;Ham&quot;, &quot;friends&quot;: [  ] }, { &quot;name&quot;: &quot;David Johnson&quot;, &quot;age&quot;: 19, &quot;is_student&quot;: true, &quot;address&quot;: null, &quot;hobbies&quot;: null, &quot;food&quot;: &quot;Chicken&quot;, &quot;friends&quot;: [  ] }, { &quot;name&quot;: &quot;John Doe&quot;, &quot;age&quot;: 94, &quot;is_student&quot;: true, &quot;address&quot;: { &quot;street&quot;: &quot;456 Elm St&quot;, &quot;city&quot;: &quot;Randomville&quot;, &quot;country&quot;: &quot;Wonderland&quot; }, &quot;hobbies&quot;: [ &quot;being lazy&quot; ], &quot;food&quot;: &quot;Bacon&quot;, &quot;friends&quot;: [  ] } ] }</pre><p>Applying a custom JSON format function:</p><pre>{<br>   &quot;name&quot;: &quot;Kofi&quot;,<br>   &quot;age&quot;: 21,<br>   &quot;is_student&quot;: true,<br>   &quot;address&quot;: {<br>      &quot;street&quot;: &quot;123 Main St&quot;,<br>      &quot;city&quot;: &quot;Exampleville&quot;,<br>      &quot;country&quot;: &quot;Sampleland&quot;<br>   },<br>   &quot;hobbies&quot;: [<br>      &quot;hiking&quot;,<br>      &quot;coding&quot;,<br>      &quot;sleeping&quot;<br>   ],<br>   &quot;food&quot;: &quot;Chicken&quot;,<br>   &quot;friends&quot;: [<br>      {<br>         &quot;name&quot;: &quot;Jane Smith&quot;,<br>         &quot;age&quot;: 28,<br>         &quot;is_student&quot;: false,<br>         &quot;address&quot;: {<br>            &quot;street&quot;: &quot;Maple Street&quot;,<br>            &quot;city&quot;: &quot;Springfield&quot;,<br>            &quot;country&quot;: &quot;United States&quot;<br>         },<br>         &quot;hobbies&quot;: null,<br>         &quot;food&quot;: &quot;Ham&quot;,<br>         &quot;friends&quot;: []<br>      },<br>      {<br>         &quot;name&quot;: &quot;David Johnson&quot;,<br>         &quot;age&quot;: 19,<br>         &quot;is_student&quot;: true,<br>         &quot;address&quot;: null,<br>         &quot;hobbies&quot;: null,<br>         &quot;food&quot;: &quot;Chicken&quot;,<br>         &quot;friends&quot;: []<br>      },<br>      {<br>         &quot;name&quot;: &quot;John Doe&quot;,<br>         &quot;age&quot;: 94,<br>         &quot;is_student&quot;: true,<br>         &quot;address&quot;: {<br>            &quot;street&quot;: &quot;456 Elm St&quot;,<br>            &quot;city&quot;: &quot;Randomville&quot;,<br>            &quot;country&quot;: &quot;Wonderland&quot;<br>         },<br>         &quot;hobbies&quot;: [<br>            &quot;being lazy&quot;<br>         ],<br>         &quot;food&quot;: &quot;Bacon&quot;,<br>         &quot;friends&quot;: []<br>      }<br>   ]<br>}</pre><h3>Conclusion 📝</h3><blockquote><strong>If you’ve made it this far, you should probably </strong><a href="https://bmc.link/otuokofi"><strong>buy me a coffee</strong></a><strong> 🍵</strong></blockquote><p>In this comprehensive beginner’s guide to Rust procedural macros, we explored the fascinating world of code generation and customization. We delved into the concept of derive macros and their ability to automatically generate code implementations based on custom data types. Our focus was on creating a powerful JSON derive macro, enabling seamless conversion of Rust structures and enums into JSON format.</p><p>Throughout the article, we demystified the process of building the JSON derive macro step by step, providing practical examples and insights into the inner workings of Rust procedural macros. By mastering this essential feature, you can unlock new possibilities for code reuse, conciseness, and maintainability in your Rust projects.</p><p>If you need further assistance or guidance with Rust procedural macros, I’m here to help! <strong>Feel free to contact me via email at otukof@gmail.com.</strong> Together, we can explore advanced techniques, troubleshoot issues, and accelerate your understanding of this powerful Rust feature.</p><p>Remember, mastering procedural macros opens doors to endless possibilities in Rust programming. So, don’t hesitate to reach out, and let’s collaborate on taking your Rust projects to the next level.</p><h4>Explore 🧑‍🔬🦾</h4><p>You can think of ways to enhance the macro. By enhancing the macro, you will gain a deeper understanding of how procedural macros can be tailored to specific requirements and learn to overcome challenges that arise when working with more intricate data structures.</p><p>Here are a few suggestions to expand the functionality of the JSON derive macro:</p><ol><li>Custom Attribute Annotations: Introduce custom attribute annotations that can be applied to struct fields to influence the JSON serialization process. For example, you can define an attribute that skips the serialization of a particular field or specify a custom key name for the JSON representation of a field. Implement the necessary logic in the macro to honor these attribute annotations during code generation.</li><li>Serialization Options: Allow users to specify serialization options through macro attributes. This could include options like pretty-printing the JSON output for improved readability, sorting the fields alphabetically, or customizing indentation levels. Implement the logic in the macro to respect these options and generate the JSON output accordingly.</li><li>Deserialization: Expand the macro’s functionality to support deserialization from JSON back into Rust data structures. Enable the macro to automatically generate deserialization code based on the JSON representation, allowing users to convert JSON data back into Rust objects conveniently.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb44279e7244" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/a-beginners-guide-to-rust-procedural-macros-creating-a-json-derive-macro-eb44279e7244">A Beginner’s Guide to Rust Procedural Macros: Creating a JSON Derive Macro</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[Integrating Rust With Android Development — Final Part]]></title>
            <link>https://blog.devgenius.io/integrating-rust-with-android-development-final-part-7c752a7cab1d?source=rss-e3ee6219320c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c752a7cab1d</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Kofi Otuo]]></dc:creator>
            <pubDate>Thu, 25 Aug 2022 16:30:06 GMT</pubDate>
            <atom:updated>2023-09-18T07:48:21.247Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XwjoQAiQpHHvNpWE-_fRKQ.jpeg" /></figure><h3>Integrating Rust With Android Development — Final Part</h3><p>This is the second and final part of the series which explains how to add <strong>Rust </strong>code to your Android project without the hassle of studying or utilizing JNI, or C in your project. In the <a href="https://blog.devgenius.io/integrating-rust-with-android-development-ef341c2f9cca"><strong>first part of the series</strong></a>, we created a simple Android Studio project and a simple library written in Rust to log information. In this second and final part, we shall go through a practical example where we apply Rust functions to our work.</p><p>In this walkthrough, we would create a simple calculator app that evaluates the result when the user presses the ‘equal to’ button. The application would take 2 inputs and then perform 3 operations on the inputs: Addition, Subtraction, and Multiplication. This simple knowledge would be helpful in real-life cases where you might have to perform time-consuming or low-level operations on Android. Without further ado, let’s create the backend of our application (You could design the U.I initially, but for this walkthrough, I feel writing the Rust backend first is more convenient)</p><h4>Designing The Backend ⚙️</h4><p>As summarized earlier, we’d create a struct that holds 2 values and also create functions that would return the corresponding addition, subtraction, and multiplication. We would add this struct to lib.rs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c37d8da4e8a9365aacdde81fbddec97/href">https://medium.com/media/3c37d8da4e8a9365aacdde81fbddec97/href</a></iframe><p>Self in method arguments is <em>syntactic sugar</em> for the receiving type of the method, that is, the type whose impl this method is in, and in this case, UIit is Inputs. You could replace Self with Inputs and the code would work fine.</p><p>Remember #[generate_interface] originates from the <a href="https://crates.io/crates/rifgen"><strong>rifgen</strong></a><strong> </strong>crate as described in the <a href="https://blog.devgenius.io/integrating-rust-with-android-development-ef341c2f9cca">first part of the series</a>.</p><p>Now let us implement the U.I.</p><h4>Designing the U.I. 📱</h4><p>As described earlier, the U.I. would have 2 input text fields and 3 output text fields. It would be a simple layout to illustrate:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2a1da04ad46226611cd039ab7e68539/href">https://medium.com/media/e2a1da04ad46226611cd039ab7e68539/href</a></iframe><p>And that’s it! This is what the application should <a href="https://github.com/Kofituo/RustApplication/blob/main/app/src/main/java/com/example/rustapplication/Illustration.jpg"><strong>look like</strong></a>. Here’s a gif of it</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Ffeistyvaluablechinesecrocodilelizard&amp;display_name=Gfycat&amp;url=https%3A%2F%2Fgfycat.com%2Ffeistyvaluablechinesecrocodilelizard&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FFeistyValuableChinesecrocodilelizard-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="246" height="546" frameborder="0" scrolling="no"><a href="https://medium.com/media/567341c381f5a67481875cae77df57a2/href">https://medium.com/media/567341c381f5a67481875cae77df57a2/href</a></iframe><p>Whenever the user taps the ‘equal to’ button, the numbers from the text boxes are passed to the struct written in Rust. The values are then computed and the result is displayed in the textbox. Feel free to modify the code and try out other ways of adding some Rust variety to your Android project.</p><h4>Next Steps 👣</h4><p><strong>If you faced any problems while trying this walkthrough or have any questions, feel free to reach me via email at otukof@gmail.com!</strong></p><h4>Support</h4><p>If you’ve enjoyed this series and would like to show gratitude, you can support the author through <a href="https://bmc.link/otuokofi"><strong>Buy Me A Coffee</strong></a><strong>.</strong></p><h4>Further Reading 📖</h4><p>Learn more about the dependencies used in this walkthrough:</p><ul><li><a href="https://github.com/Dushistov/flapigen-rs"><strong>Dushistov/flapigen-rs: Tool for connecting programs or libraries written in Rust with other languages</strong></a></li><li><a href="https://github.com/Kofituo/rifgen"><strong>Kofituo/rifgen:Program for translating libraries written in Rust to interface files. It works with flapigen</strong></a></li><li><a href="https://github.com/sfackler/rust-jni-sys"><strong>sfackler/rust-jni-sys</strong></a></li></ul><h4><a href="https://github.com/Kofituo/RustApplication">Repository</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c752a7cab1d" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/integrating-rust-with-android-development-final-part-7c752a7cab1d">Integrating Rust With Android Development — Final Part</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[Integrating Rust With Android Development]]></title>
            <link>https://levelup.gitconnected.com/integrating-rust-with-android-development-ef341c2f9cca?source=rss-e3ee6219320c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef341c2f9cca</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Kofi Otuo]]></dc:creator>
            <pubDate>Thu, 24 Feb 2022 14:57:17 GMT</pubDate>
            <atom:updated>2024-06-13T20:17:19.007Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*asJ0X12wzo_gN_zxscdV5Q.jpeg" /></figure><p><a href="https://www.rust-lang.org/"><strong>Rust</strong></a> is a general-purpose, systems programming language that has been around for quite some time now. Being a systems programming language, it can be used to perform tasks similar to languages such as <strong>C</strong> and<strong> C++</strong> but with much more memory safety. This allows Rust to be used to write programs or scripts on numerous operating systems including Android. You may wonder how this could be possible and if there is a simple way to do so. Well, that’s what this article is about!</p><p>Currently, there isn’t much information on how to write Rust code for an android application. There is some information provided by Google <a href="https://source.android.com/setup/build/rust/building-rust-modules/overview">here</a> but it’s complicated for a beginner to understand. The goal of this walkthrough is to provide a simple but efficient guide to integrating Rust code with android development and ultimately become <strong>the go-to guide. No prior knowledge of C or C++ or JNI is required!</strong></p><p>We will use <a href="https://developer.android.com/studio">Android Studio</a>. Let’s begin by setting it up.</p><h3>Setup 🌱</h3><h4>Rust Plugin ⚙️</h4><p>First, we need the Rust plugin. Open up Android Studio. A dialog similar to what is displayed below would open up. Select the Plugins tab, search for “Rust” and then install the official Rust plugin by JetBrains. Alternatively, if you have a project already opened, click on File at the top left corner of Android Studio and select Settings. Click on Plugins.</p><blockquote>The Rust Plugin requires Rust installed on your system. You can follow this <a href="https://www.rust-lang.org/tools/install"><strong>link</strong></a> to install Rust on your system.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vIp429xNBAmk56_FdhOZmw.png" /></figure><h4>Creating An Empty Application 📱</h4><p>Now let’s create a new empty app. Start by going through the standard new project setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*eMtX0LGhY1ZVlBt7p12CGg.png" /></figure><p>Let’s name our project Rust Application and click on finish.</p><p>A window similar to the one shown below would appear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*75wCKhDm7MfQ0UPu3m8ZSQ.png" /></figure><h4>Incorporating A Cargo Project 💼</h4><p>Let’s now add a <a href="https://doc.rust-lang.org/cargo/">Cargo project</a>, following the tutorial provided <a href="https://doc.rust-lang.org/cargo/guide/creating-a-new-project.html"><strong>here</strong></a>. To embed a Rust project, simply click on the <strong>Terminal</strong> <strong>in Android Studio</strong> and type cargo new rust_lib --lib, then press enter.</p><pre>C:\Users\USER1\AndroidStudioProjects\RustApplication&gt;<strong>cargo new rust_lib --lib</strong></pre><p>This creates a new library so it can be used from within our application. We named the library rust_lib. Take note of where the folder is created.</p><p>To view the folder in Android Studio, navigate to the Project pane and select Project from the dropdown menu instead of Android.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*T-2-mcR6WYG_qKYLfgj0ZQ.png" /></figure><p>You would then see a new folder named rust_lib. This folder contains a new git repository by default, a Cargo.toml file, and an src folder containing lib.rs. Now let’s modify the <a href="https://doc.rust-lang.org/cargo/reference/cargo-targets.html#configuring-a-target">type of library</a> we just created using the Cargo.toml file. For mobile app development, the library should be a dynamic one.</p><p>Add the following to the contents of the Cargo.toml file.</p><pre>[lib]<br>name = &quot;rust_lib&quot;<br>crate-type = [&quot;cdylib&quot;]</pre><p>View the gist <a href="https://gist.github.com/Kofituo/e02bd971b75866103438961e98e3711f">here</a>.</p><h4>Adding Dependencies 🧶</h4><p>Let’s add dependencies that would create the necessary files to make linking our rust code to the Android end a smooth process.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81e0b27094f9d3d5fdf74c5715affe35/href">https://medium.com/media/81e0b27094f9d3d5fdf74c5715affe35/href</a></iframe><p>Use the “<strong>*</strong>” to pull the latest version of the dependency.</p><p><a href="https://crates.io/crates/flapigen"><strong>flapigen</strong></a><strong> </strong>is the main build dependency to generate the appropriate code from our rust code to use it in our android app. flapigen works with an interface file but having to modify the interface file every time there’s a code change could get tedious. That’s where <a href="https://crates.io/crates/rifgen"><strong>rifgen</strong></a><strong> </strong>comes it. It makes the creation of the interface file such a breeze.</p><p>The extra dependencies are for logging.</p><h4>Creating A Build File 📄</h4><p>As mentioned earlier, flapigen and rifgen are build dependencies and interact with the <a href="https://doc.rust-lang.org/cargo/reference/build-scripts.html#build-scripts">build.rs</a> file. Right-click on rust_lib folder and select New &gt; Rust File.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*N7IPHePJFtDux9YTVt0JwA.png" /></figure><p>Name the file build.rs.</p><p>Following the tutorial given by <a href="https://dushistov.github.io/flapigen-rs/java-android-example.html">flapigen</a> and <a href="https://docs.rs/rifgen/latest/rifgen/">rifgen</a>, our build.rs should look similar to the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecdeb62ec83469128cf5f4ec76262896/href">https://medium.com/media/ecdeb62ec83469128cf5f4ec76262896/href</a></iframe><p>You might be wondering what’s happening in the build.rs. flapigen converts what’s in the interface file to a java_glue rust file. So we first specify the source file for the interface file (in_src) and then the out file (java_glue.rs). The directory of the java_glue.rs has to be the same as the OUT_DIR environment variable. After doing that, use rifgen to generate the interface file, specifying our preference depending on the language we’re adding the rust project to. The last parameter of Generator::new specifies the start of the folder containing our rust code and the generate_interface function takes the path of the interface file. i.e. in_scr. The java_folder specifies where the java files created should go to. Calling swig_gen.expand tells flapigen to generate the appropriate files. Note these parameters as we use them in the Gradle build.</p><p>Finally, create a file named java_glue.rs in the rust_lib/src folder and put the following contents:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/651e3fbf913743c331238dab1b5926ff/href">https://medium.com/media/651e3fbf913743c331238dab1b5926ff/href</a></iframe><p>And add:</p><pre>mod java_glue;<br>pub use crate::java_glue::*;</pre><p>To your lib.rs file. Doing this connects your rust code to the one generated.</p><h4>Add Android Toolchains And Linkers ⛓</h4><p>To compile Rust for android, we need to add the android toolchains to rustup. To do so, simply run the following in the Terminal:</p><pre>&gt;<strong>rustup default nightly<br></strong>&gt;<strong>rustup target add aarch64-linux-android armv7-linux-androideabi</strong></pre><p>Since the rifgen crate works with nightly, you’ve to install Rust nightly first.</p><p>Then you add the rust toolchains and standard library for 64-bit and 32-bit android versions respectively. Now, let’s add the <a href="https://en.wikipedia.org/wiki/Linker_(computing)">compiler linkers</a>. It should be added to rust_lib/.cargo/config.toml file.</p><p>Right-click on the rust_lib folder, create a new directory called .cargo then create a new file in the .cargo directory called config.toml.</p><p>The appropriate linkers come with <strong>Android NDK</strong> and should therefore be <a href="https://developer.android.com/studio/projects/install-ndk#default-version">downloaded</a> before continuing.</p><p>Add the following to the config file you created.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f09938506d02fbbff12aaa797ab4a2a/href">https://medium.com/media/1f09938506d02fbbff12aaa797ab4a2a/href</a></iframe><p>Replace <strong>ANDROID SDK</strong> with the android SDK path (or the folder containing the NDK-bundle). Also, replace the <strong>OS VERSION</strong> with your OS version. For instance, on my Windows pc, the full path is:</p><pre>[<strong>target.aarch64-linux-android</strong>]<br>linker = &quot;<strong>C:\\Users\\taimoor\\AppData\\Local\\Android\\Sdk\\</strong>ndk-bundle\\toolchains\\llvm\\prebuilt\\<strong>windows-x86_64</strong>\\bin\\<strong>aarch64-linux-android21-clang++.cmd</strong>&quot;</pre><p>Notice the .cmd at the end for a Windows build.</p><blockquote>If you’re using Mac OS with NDK v25, you may face an issue. If you do face an issue, you can try previous versions of the NDK. Alternatively, you can <a href="https://www.upwork.com/freelancers/~0196d30a485de56f48">contact more for more assistance</a>.</blockquote><h4>Using Gradle To Automate Build 🐘</h4><p>Gradle can be used to automatically run cargo build whenever we want to test out the app. This would cause changes we made at the Rust side to be automatically updated into our application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac6943d858ac4d6feb36e91a4d82346d/href">https://medium.com/media/ac6943d858ac4d6feb36e91a4d82346d/href</a></iframe><p>Note that this is the <strong>app or module level</strong> Gradle file and not the Project level Gradle file. Add lines<strong> 20 to 27</strong> and line <strong>65 onwards</strong>. Line 65 onwards just instructs Gradle to run cargo build whenever we run the app. After running the cargo build command, we then copy the java files and the dynamic library file (.<strong>so</strong>) created and paste them into the directory which can be read by Android and used in our Kotlin code.</p><p>The application now should run 😄. If you’re having difficulty running it, leave a comment below or feel free to mail me at <em>otukof@gmail.com</em>!</p><h4><strong>Bonus Section: Logging </strong>📃</h4><p>Let’s quickly implement logging to help with debugging our Rust code. In the lib.rs file, add the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21271dbe0ba0ef6681e9a55603c77b73/href">https://medium.com/media/21271dbe0ba0ef6681e9a55603c77b73/href</a></iframe><p>We use the <a href="https://docs.rs/android_logger/0.10.1/android_logger/index.html">android_logger</a> crate for generating logs and then call <a href="https://docs.rs/log-panics/2.0.0/log_panics/fn.init.html">log_panics::init()</a> to redirect all panics to be logged rather than printed to standard error. Notice the attribute #[generate_interface]. This tells rifgen that we’re going to call this function from Kotlin so it should add that method call to the interface file.</p><blockquote><strong>Enjoying this tutorial? Why not </strong><a href="https://bmc.link/otuokofi"><strong>buy me a coffee?</strong></a><strong> </strong>☕️</blockquote><h4>Loading The Library From Kotlin 📲</h4><p>Now that we have set up the Rust side, let’s move on to the Kotlin side. We will now load the library from a singleton:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae1e6b3debf6adeab175d873954355ad/href">https://medium.com/media/ae1e6b3debf6adeab175d873954355ad/href</a></iframe><p>Add the various import for the Logs class we created. Note how even though we named the function initialise_logging, we’re able to use it as initialiseLogging. This is because we specified CamelCase when setting up rifgen.</p><p>Run the program to see the information from the Rust code being logged.</p><h3>Next Steps 🍀</h3><p>That concludes the first part of this series. In the <a href="https://medium.com/dev-genius/integrating-rust-with-android-development-final-part-7c752a7cab1d"><strong>next part</strong></a>, we would mix our Rust code with some GUI to finalize this walkthrough.</p><h3>References</h3><h4><a href="https://github.com/Kofituo/RustApplication/tree/FirstPart">Repository</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef341c2f9cca" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/integrating-rust-with-android-development-ef341c2f9cca">Integrating Rust With Android Development</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your Text Editor With Rust! Final Part]]></title>
            <link>https://medium.com/@otukof/build-your-text-editor-with-rust-final-part-4c841a649900?source=rss-e3ee6219320c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c841a649900</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[editor]]></category>
            <dc:creator><![CDATA[Kofi Otuo]]></dc:creator>
            <pubDate>Fri, 22 Oct 2021 18:57:35 GMT</pubDate>
            <atom:updated>2024-05-01T12:25:11.285Z</atom:updated>
            <content:encoded><![CDATA[<p>This part concludes the series “<em>Build Your Text Editor With Rust</em>”. For those who may have stumbled on this page without going through the other parts, here is a summary of what we’ve done so far: We started with “<a href="https://medium.com/@otukof/build-your-text-editor-with-rust-678a463f968b"><strong>Setup</strong></a>” to <a href="https://medium.com/@otukof/build-your-text-editor-with-rust-part-2-74e03daef237"><strong>reading keypress and entering “raw mode”</strong></a>, to <a href="https://medium.com/@otukof/build-your-text-editor-with-rust-part-3-b030670fa815"><strong>drawing on the screen and moving the cursor around</strong></a>, to <a href="https://medium.com/@otukof/build-your-text-editor-with-rust-part-4-fd4a8b8641f8"><strong>displaying text files (making our program a text view)</strong></a>, to <a href="https://medium.com/@otukof/build-your-text-editor-with-rust-part-5-e363c16f542b"><strong>editing text files and saving changes</strong></a>, to <a href="https://medium.com/@otukof/build-your-text-editor-with-rust-part-6-3cff61dc2de5"><strong>implementing a cool search feature</strong></a> and finally to this part where we <strong>add syntax highlighting.</strong></p><p>Let’s begin by coloring each digit cyan:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9ff157139b0cba413350499f97021c1/href">https://medium.com/media/e9ff157139b0cba413350499f97021c1/href</a></iframe><p>We no longer add the text we want to display right to editor_contents. Instead, we loop through all the characters and then check if the current character is a digit. If it is, we add the escape sequence for cyan color, add the character and finally, reset the color (You can find what each escape sequence maps to in terms of ANSI codes on <a href="https://en.wikipedia.org/wiki/ANSI_escape_code">wikipedia</a>). The colors that we’ll use are supported by many terminals. If the terminal doesn’t support colors then we just add the digit and ignore the error; <em>let _ = ... syntax just prevents the compiler from complaining of unhandled errors.</em></p><h4>Refactor Syntax Highlighting ✨</h4><p>Now we know how to color digits, but what we want is to actually highlight entire strings, keywords, comments, and so on. We can’t just decide what color to use based on the class of each character, like we’re doing with digits currently. What we want to do is figure out the highlighting for each row of text before we display it, and then re-highlight a line whenever it gets changed.</p><p>The highlighting rules might differ from from one programming language to another. For instance how we might want to highlight the syntax in say a Python file might be different for how we’d like to highlight it if it were a Rust file. But what would like to do is to write a “generic” method for highlighting syntax which could be easily modified or specialized for different programming languages. So we’re going to create a <a href="https://doc.rust-lang.org/std/keyword.trait.html">trait</a> (a.k.a <em>interface </em>in most object oriented programming languages such as Java and Kotlin) to help us implement that.</p><p>But even before creating the trait, let’s add a new field, highlight, to Row which would contain the highlight information for that Row.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/815c2c3e24f3ff3cb7538deb15b1c44f/href">https://medium.com/media/815c2c3e24f3ff3cb7538deb15b1c44f/href</a></iframe><p>Now let’s add the trait.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/694ef4afcf683914a1dbcf394b2f340f/href">https://medium.com/media/694ef4afcf683914a1dbcf394b2f340f/href</a></iframe><p>For now, the trait has a method which will go through the characters of a Row and highlight them by setting each value in the highlight array. Let’s write one implementation of SyntaxHighlight:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27ac6f148fd76f3f8fd6fb30b0bd6567/href">https://medium.com/media/27ac6f148fd76f3f8fd6fb30b0bd6567/href</a></iframe><p>The code is wrapped in a macro before we implement SyntaxHighlight. This kind of provides a #[derive] for that struct, just that we’re using macro_rules so <a href="https://doc.rust-lang.org/book/ch19-06-macros.html#how-to-write-a-custom-derive-macro">it’s less complex</a>. The macro has one parameter and that’s the name of the struct you want to create. The macro then creates the struct and derives SyntaxHighlight for it.</p><p>In the update_syntax method, we get the Row we have to update and then loop through the chars of that Row and then update Row.highlight. We add the simple assert_eq!() to make sure our code works as expected. You can remove it after you’re sure the program works fine.</p><p>Next, let’s make an syntax_color() function that maps values in highlight to the actual color codes we want to draw them with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2b2843ebb8284f1a07fdb97bd205db2/href">https://medium.com/media/e2b2843ebb8284f1a07fdb97bd205db2/href</a></iframe><p>Note that Color is from <a href="https://docs.rs/crossterm/0.21.0/crossterm/style/enum.Color.html"><em>crossterm::style::Colors</em></a>.</p><p>Now let’s finally and the function that would draw the colored text:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0030c3c2d0050b39d61a45a0f650b19/href">https://medium.com/media/c0030c3c2d0050b39d61a45a0f650b19/href</a></iframe><p>The color_row function is the same as we had in draw_rows but modified a bit to use the trait methods instead. Let’s now add SyntaxHighlight to Output:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cba43205f4d1de615a72e8a383bc158/href">https://medium.com/media/7cba43205f4d1de615a72e8a383bc158/href</a></iframe><p>Since we’re using <a href="https://doc.rust-lang.org/book/ch17-02-trait-objects.html">dynamic dispatch</a>, we use the Box&lt;dyn &gt; syntax. Not every file type might have a syntax highlight method implemented, hence we wrap that the field in Option&lt;T&gt;. We’re using the RustHighlight struct that we created from the macro as the default value for now. In draw_rows, we replace the coloring code to use syntax_highlight if it’s available.</p><p>To the code working, let’s add update_syntax everywhere that modifies Row, similar to how we implemented render_row():</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8173427e88d0c8c1f1a7b9765932f4e/href">https://medium.com/media/d8173427e88d0c8c1f1a7b9765932f4e/href</a></iframe><p>Now whenever there’s a change in any of the rows, update_syntax would be called to reflect the changes. That concludes our refactoring of the syntax highlighting system.</p><h4>Colorful Search Results 🔭</h4><p>Before we start highlighting strings and keywords and all that, let’s use our highlighting system to highlight search results. We’ll start by adding SearchMatch to the HighlightType enum, and mapping it to the color blue:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c61ec781ffb8aeed891bdf20724826b9/href">https://medium.com/media/c61ec781ffb8aeed891bdf20724826b9/href</a></iframe><p>Now all we have to do is set the matched substring’s highlight to SearchMatch in our search code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/260c758e4fcb7f79990d394b55ccdd53/href">https://medium.com/media/260c758e4fcb7f79990d394b55ccdd53/href</a></iframe><p>First, we get a mutable reference to the Row with the query. To highlight the matched word, we just loop through the highlight array, starting from the index to index + query‘s length, setting the corresponding highlight value to SearchMatch</p><h4>Restore Syntax Highlighting After Search ⚖️</h4><p>Currently, search results stay highlighted in blue even after the user is done using the search feature. We want to restore the highlight values to its previous value after each search. We’re going to derive Clone for HighlightType, similar to what we did for CursorController. Then we’ll save the original highlight and the corresponding row_index in SearchIndex:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39552b6695bd70f377d031a5a128d7a8/href">https://medium.com/media/39552b6695bd70f377d031a5a128d7a8/href</a></iframe><p>Now let’s modify find_callback:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e241069a7f099d895f5d71d96377b93d/href">https://medium.com/media/e241069a7f099d895f5d71d96377b93d/href</a></iframe><p>At the start of the function we use <a href="https://doc.rust-lang.org/core/option/enum.Option.html#method.take">.take()</a> to return the owned version of the value in previous_highlight, if any. take() replaces the original value with None, which is what we want in this case. If there was a previous match, we reset that row’s highlight. When there’s a match we store the previous highlight before modifying.</p><blockquote>Assignment for the reader:</blockquote><blockquote><em>You’d realize that that when you’re on the last match (irrespective of the direction) and you </em>keep pressing the Arrow key that got you to the last match, the color for that row resets<em>. This is the expected behavior. What if we want the color to remain? Before you continue, you should try modifying the program to fix that.</em></blockquote><h4>Optimize color_row() ⚡️</h4><p>So far the coloring works fine but color_row performs 3 operations which may not be necessary. First, it writes the escape sequence for the color, then it writes a single letter and finally it writes the escape sequence to reset the color. In practice, most characters are going to be the same color as the previous character, so most of the escape sequences are redundant. Let’s keep track of the current text color as we loop through the characters, and only print out an escape sequence when the color changes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90a689c7aafdee3954c154ab8cbf5fe1/href">https://medium.com/media/90a689c7aafdee3954c154ab8cbf5fe1/href</a></iframe><p>After looping through the chars we reset the color so that the remaining rows aren’t affected.</p><h4>Colorful Numbers 🖍</h4><p>Alright, let’s start working on highlighting numbers properly. First, we’ll change our for loop in update_syntax to a while loop, to allow us to consume multiple characters each iteration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3246b756633b9439ae0cafe69929bfa/href">https://medium.com/media/a3246b756633b9439ae0cafe69929bfa/href</a></iframe><p>Now let’s define an is_separator() function that takes a character and returns true if it’s considered a separator character:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dee7f5787077e5ca203e37887b8f66bb/href">https://medium.com/media/dee7f5787077e5ca203e37887b8f66bb/href</a></iframe><p>Since many programming languages have similar separators, we make is_separator a default method.</p><p>Right now, numbers are highlighted even if they’re part of an identifier, such as the 32 in int32_t. To fix that, we’ll require that numbers are preceded by a separator character, which includes whitespace or punctuation characters. Let’s add a previous_separator variable to update_syntax() that keeps track of whether the previous character was a separator. Then let’s use it to recognize and highlight numbers properly:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bda41c8d2d40709f36d007716c64312e/href">https://medium.com/media/bda41c8d2d40709f36d007716c64312e/href</a></iframe><p>We initialize previous_separator to true because we consider the beginning of the line to be a separator. (Otherwise numbers at the very beginning of the line wouldn’t be highlighted.)</p><p>previous_highlight is set to the highlight type of the previous character. To highlight a digit, we now require the previous character to either be a separator, or to also be highlighted with HightlightType::NUMBER.</p><p>When we decide to highlight the current character a certain way, we increment i to “consume” that character, set previous_separator to false to indicate we are in the middle of highlighting something, and then continue the loop. We will use this pattern for each thing that we highlight.</p><p>If we end up at the bottom of the while loop, we set previous_separator according to whether the current character is a separator, and we increment i to consume the character.</p><p>Now let’s support highlighting numbers that contain decimal points:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82af443031ef3667c3a9c22fef3e0710/href">https://medium.com/media/82af443031ef3667c3a9c22fef3e0710/href</a></iframe><p>A . character that comes after a character that we just highlighted as a number will now be considered part of the number.</p><h4>Detect File Type 🧑‍🔬</h4><p>Before we go on to highlight other things, we’re going to add file type detection to our editor. This will allow us to have different rules for how to highlight different types of files. For example, text files wouldn’t have any highlighting, and Rust files should highlight numbers, strings, comments, and many different keywords specific to Rust.</p><p>To begin, we’ll add an extensions() to SyntaxHighlight so that all types that implement SyntaxHighlight would have to specify the corresponding file extensions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c72c7ba3ab0b5abbd6958f2bfedf9d11/href">https://medium.com/media/c72c7ba3ab0b5abbd6958f2bfedf9d11/href</a></iframe><p>After creating the extensions function, we then implement it in our macro. First, we create a new parameter extensions,which also takes an expression (expr), and name it ext. We then create a struct with a field named extensions of type &amp;<em>’static </em>[&amp;<em>’static </em>str] (We have to explicitly specify the type ‘static since we’re using it in a struct field). We also create a new method to return an instance of the struct with the specified extensions.</p><p>Now let’s create a select_syntax method which would return a SyntaxHighlight object or None if there’s no corresponding SyntaxHighlight for that file extension:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f3d923ff561ccf96f23f7a244ac2747/href">https://medium.com/media/3f3d923ff561ccf96f23f7a244ac2747/href</a></iframe><p>select_syntax now returns the right SyntaxHighlight object. To add a new SyntaxHighlight object, just insert it to the array. Since EditorRows is the struct with the filename, we pass mutable syntax_highlight to EditorRows::new() so that the it would be modified to return the right SyntaxHighlight object.</p><p>Let’s not forget to update the syntax_highlight when the user uses SaveAs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/863618c22016658e0d9d84aa59b8d1ea/href">https://medium.com/media/863618c22016658e0d9d84aa59b8d1ea/href</a></iframe><p>After giving the file a new name, we have to go through all the rows and then highlight them appropriately.</p><p>Next, we’ll show the current file type. Some programming languages such as c could have files with different extensions (e.g .h and .c) so we can’t use the extension for the file type. We want the file type to just show which programming language the file belongs to. To do that, let’s add a new method to SyntaxHighlight which returns the corresponding file type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8c45f1ca23d9a4e726d8123fe6884a8/href">https://medium.com/media/a8c45f1ca23d9a4e726d8123fe6884a8/href</a></iframe><p>Now let’s show the file type, if SyntaxHighlight has been implemented for it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54326729c18601e1a28f6d55ff2b3693/href">https://medium.com/media/54326729c18601e1a28f6d55ff2b3693/href</a></iframe><p>If there’s no corresponding SyntaxHighlight for that file type, we show “no ft” (no file type).</p><h4>Colorful Strings 📝</h4><p>Now let’s start highlighting proper. We’ll begin by highlighting strings:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3559819856713c57cff9ffbae3161552/href">https://medium.com/media/3559819856713c57cff9ffbae3161552/href</a></iframe><p>We’re coloring strings green. In some programming languages (such as Rust) the single quote refers to character literal while in others like python, it refers to a string. For now we’ll color the “character literal” dark green. (Later, you can use a boolean or similar to indicate whether or not that distinction should be made) We will use an in_string variable to keep track of whether we are currently inside a string. If we are, then we’ll keep highlighting the current character as a string until we hit the closing quote:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc82ddb999f3501e14da4caa34c16f74/href">https://medium.com/media/fc82ddb999f3501e14da4caa34c16f74/href</a></iframe><p>We actually store either a double-quote (&quot;) or a single-quote (&#39;) character as the value of in_string, so that we know which one closes the string.</p><p>So, going through the code from top to bottom: If in_string is set, then we know the current character can be highlighted with HightlightType::String. Then we check if the current character is the closing quote (val == c), and if so, we reset in_string to None. Then, since we highlighted the current character, we have to consume it by incrementing i and continuing out of the current loop iteration. We also set previous_separator to true so that if we’re done highlighting the string, the closing quote is considered a separator.</p><p>If we’re not currently in a string, then we have to check if we’re at the beginning of one by checking for a double- or single-quote. If we are, we store the quote in in_string, highlight it with HightlightType::String, and consume it.</p><p>Usually when the sequence \&#39; or \&quot; occurs in a string, then the escaped quote doesn’t close the string in the vast majority of languages. For instance, in the line:</p><pre>else if c == &#39;&quot;&#39; || c == &#39;\&#39;&#39; {</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/568007ed52148dfd6d590bef6bd7c274/href">https://medium.com/media/568007ed52148dfd6d590bef6bd7c274/href</a></iframe><p>If we’re in a string and the current character is a backslash (\), <em>and</em> there’s at least one more character in that line that comes after the backslash, then we highlight the character that comes after the backslash with HightlightType::String and consume it. We increase i by 2 to consume both characters at once.</p><h4>Colorful Single Line Comments 📎</h4><p>Next let’s highlight single-line comments. We’ll give comments a dark grey color:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bd011c6d41a39b1d14773406dcaa9ff/href">https://medium.com/media/5bd011c6d41a39b1d14773406dcaa9ff/href</a></iframe><p>We’ll let each language specify its own single-line comment pattern, as they differ a lot between languages. Let’s create a comment_start field and method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b37caccaf5072a0866db700073c3a98b/href">https://medium.com/media/b37caccaf5072a0866db700073c3a98b/href</a></iframe><p>Now to the highlighting code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21169c82f3c93c30adb204d97a29a733/href">https://medium.com/media/21169c82f3c93c30adb204d97a29a733/href</a></iframe><p>Perhaps an empty string was passed as comment_start, so in that case we won’t highlight any comments. We wrap our comment highlighting code in an if statement that makes sure we’re not in a string, since we’re placing this code above the string highlighting code (order matters in this function). We use <a href="https://doc.rust-lang.org/alloc/string/struct.String.html#method.as_bytes">.as_bytes</a> method since render too returns the bytes of that row.</p><p>We then check if this character is the start of a comment. If so we give the rest of the line a HighlightType::Comment setting and then we break out the loop; The range i..i+ comment_start.len() spans chars that is the exact len of the comment_start. But since i + comment_start.len() can overflow we use cmp::min to prevent that.</p><h4>Colorful Keywords 🔑</h4><p>Now let’s turn to highlighting keywords. We’re going to allow languages to specify arbitrary number of keywords and their corresponding colors. For now we’re going to have only 3 types of key words but you can always expand it. We’ll highlight actual keywords in one color and common type names in the other color and keywords that go with macro_rules in another color:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43085113258d862bf0918226b2b644dc/href">https://medium.com/media/43085113258d862bf0918226b2b644dc/href</a></iframe><p>What we simply do in the macro is to add a new field named keywords which could contain an <a href="https://doc.rust-lang.org/reference/macros-by-example.html#repetitions">arbitrary number of items</a> such that each item should first have a color specified, followed by ; and then the keywords we want to color with the color specified. We also added &amp; as a separator so strings like &amp;str and &amp;mut self and signatures would be rendered properly. (Also added [])</p><blockquote>Note how using a macro we’re able to write our own syntax to build our struct</blockquote><p>Let’s modify our HighlightType enum so we can pass a color directly:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3fdd04dd11a473d47151d2388e83ccb/href">https://medium.com/media/d3fdd04dd11a473d47151d2388e83ccb/href</a></iframe><p>Now let’s highlight them:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7c6aa20bdd25d8c244b11ef5ee0fe48/href">https://medium.com/media/c7c6aa20bdd25d8c244b11ef5ee0fe48/href</a></iframe><p>Keywords require a separator <strong>both before and after</strong> the keyword. Otherwise, the match in rematch, matching, or matched would be highlighted as a keyword, which is definitely a problem we want to avoid. So we check previous_separator to make sure a separator came before the keyword, before looping through each possible keyword. Recall that keywords could contain any any number of color, arbitrary number of keywords pair. So we <a href="https://doc.rust-lang.org/book/ch19-06-macros.html#declarative-macros-with-macro_rules-for-general-metaprogramming">expand the macro (</a><a href="https://doc.rust-lang.org/book/ch19-06-macros.html#declarative-macros-with-macro_rules-for-general-metaprogramming">$( )*)</a> to get each color, arbitrary number of keywords pair. We then expand the macro again so we can now operate on each keyword. Note that the color is still available in this scope.</p><p>Similar to how we implemented commenting, for each keyword we determine whether indexing it into render would cause an overflow. We do that check before comparing whether that character is the start of a keyword. We also check whether the character after the keyword is a separator. If the keyword is the last word on the line, we consider it as a keyword. Next, we highlight the whole keyword. After highlighting, we increase i by the keyword’s length, set previous_separator and then continue the loop.</p><h4>Colorful Multi-line Comments 🖇</h4><p>We have one last feature to implement: multi-line comment highlighting. We’ll color multi-line comments with the same color as single line comments. We’ll let each language specify a multi line comment start and end. In Rust these are /* and */ respectively.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a411caaf1b81ba0900f82ec35ffb7f4e/href">https://medium.com/media/a411caaf1b81ba0900f82ec35ffb7f4e/href</a></iframe><p>We use a tuple to hold the information about the start and end of multi line comments. The first value refers to the start and the last value refers to the end.</p><p>Now for the highlighting code. We won’t worry about multiple lines just yet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e1590e5d5e991208c27f161f6a6a38f/href">https://medium.com/media/4e1590e5d5e991208c27f161f6a6a38f/href</a></iframe><p>First we add an in_comment boolean variable to keep track of whether we’re currently inside a multi-line comment. Moving down into the while loop, we check to make sure we’re not in a string, because having /* inside a string doesn’t start a comment in virtually all languages. If we’re currently in a multi-line comment, then we can safely highlight the current character. We then check whether we’re at the end of the comment. If we’re, then we highlight the <em>remaining string</em> which indicates the comment’s end. If we’re not at the end of the comment, we simply consume the current character which we already highlighted.</p><p>If we’re not currently in a multi-line comment, then we check if we’re at the beginning of a multi-line comment. If so, we highlight the whole multi line comment start string, set in_comment to true, and then increase i appropriately.</p><p>Now let’s fix a bit of a complication that multi-line comments add: single-line comments should not be recognized inside multi-line comments</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2151acfc58cc3ad6f6300d1f4d93199a/href">https://medium.com/media/2151acfc58cc3ad6f6300d1f4d93199a/href</a></iframe><p>Now let’s work on highlighting multi-line comments that actually span over multiple lines. To do this, we need to know if the previous line is part of an un-closed multi-line comment. Let’s add an is_comment boolean variable to the Row struct:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccc7a53a13e49750fb03dda81e47d260/href">https://medium.com/media/ccc7a53a13e49750fb03dda81e47d260/href</a></iframe><p>Now, the final step:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b494c86ceb815cf81ac88c92dbcfe7f3/href">https://medium.com/media/b494c86ceb815cf81ac88c92dbcfe7f3/href</a></iframe><p>We now assign in_comment before current_row since in_comment borrows editor_rows immutable but current_row borrows it mutably and <a href="https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html">we can’t borrow a mutable variable as immutable while it’s been used</a>. We initialize in_comment to true if the previous row has an un-closed multi-line comment. If that’s the case, then the current row will start out being highlighted as a multi-line comment.</p><p>At the bottom of update_syntax(), we set the value of the current row’s is_comment to whatever state in_comment got left in after processing the entire row. That tells us whether the row ended as an un-closed multi-line comment or not. Then we have to consider updating the syntax of the next lines in the file. So far, we have only been updating the syntax of a line when the user changes that specific line. But with multi-line comments, a user could comment out an entire file just by changing one line. So it seems like we need to update the syntax of all the lines following the current line. However, we know the highlighting of the next line will not change if the value of this line’s is_comment did not change. So we check if it changed, and only call update_syntax() on the next line if is_comment changed (and if there is a next line in the file). Because update_syntax keeps calling itself with the next line, the change will continue to propagate to more and more lines until one of them is unchanged, at which point we know that all the lines after that one must be unchanged as well.</p><h3>That’s It! 🎊🎉</h3><p>Our text editor is finished. You can find the <a href="https://github.com/Kofituo/pound"><strong>repository here</strong></a>. You can create an <a href="https://github.com/Kofituo/pound/issues/new"><strong>issue</strong></a> if you have any questions, or if you detected a typo or so. You can also email me. If you’d also like to support me, you can donate using this <a href="https://p.hbtl.co/tHBHce"><strong>link</strong></a><strong> </strong>and suggest more cool tutorials you’d like to have.</p><p>I’ll also release some more tutorial like these so if you haven’t already followed, you probably should!</p><h4><a href="https://www.upwork.com/freelancers/~0196d30a485de56f48"><strong>We can link up on Upwork to work together or if you’d like more assistance in your of become a proficient software engineer.</strong></a></h4><h4>Ideas For Features To Implement On Your Own</h4><p>You can add some more features that you’d like. May I suggest some.</p><p>If you want to extend the program on your own, I suggest trying to actually <em>use</em> it as your text editor for a while. You will very quickly become painfully aware of all sorts of features you’re used to having in a text editor, but are missing in pound. Those are the features you should try to add.</p><p>Here are some ideas you could try, roughly in order of increasing difficulty:</p><ul><li><strong>More File Types</strong>: <em>Add more syntax rules for various programming languages. You can simply do this by using the </em><em>syntax_struct! macro and don’t forget to include it </em><em>Output::select_syntax().</em></li><li><strong>Line Numbers: </strong><em>Display the line number to the left of each line of the file.</em></li><li><strong>Soft indent</strong>: <em>If you like using spaces instead of tabs, make the Tab key insert spaces instead of </em><em>\t.</em></li><li><strong>Auto indent</strong>: <em>When starting a new line, indent it to the same level as the previous line.</em></li><li><strong>Soft-wrap lines</strong>: <em>When a line is longer than the screen width, use multiple lines on the screen to display it instead of horizontal scrolling.</em></li><li><strong>Copy and paste</strong>: <em>Give the user a way to select text, and then copy the selected text when they press </em><em>Ctrl-C, and let them paste the copied text when they press </em><em>Ctrl-V.</em></li><li><strong>Mouse Control</strong>: <em>Allow the user to scroll through the file using the mouse. You can also use this to prevent the user from scrolling out of the file when scrolling down. You can also allow the user to insert characters where the last left mouse button click occurred. You can find a head start </em><a href="https://github.com/crossterm-rs/crossterm/issues/593"><em>here</em></a><em>.</em></li><li><strong>More Coloring: </strong><em>Other expressions such as function names, various “types” such as </em><em>String, </em><em>Option and so on, along with </em><em>macro_rules and various macros could use some highlighting. Currently, “</em><a href="https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#lifetime-annotation-syntax"><em>lifetimes</em></a><em>” aren’t highlighted well so you might also want to fix that.</em></li><li><strong>Config file</strong>: <em>Have the editor read a config file (maybe named </em><em>.{opened_file}.pc) to set options that are currently constants, like </em><em>TAB_STOP and </em><em>QUIT_TIMES. Try to make more things configurable.</em></li><li><strong>Multiple buffers</strong>: <em>Allow having multiple files open at once, and have some way of switching between them.</em></li><li><strong>UTF-8:</strong> <em>This might seem as though it isn’t a big issue but as the </em><a href="https://doc.rust-lang.org/book/ch08-02-strings.html#strings-are-not-so-simple"><em>Rust book says, strings aren’t so simple</em></a><em>. Currently, invalid UTF-8 characters would crash the editor. Also, characters which are more than 1 byte (such as emojis) would cause the editor to crash when scrolling through those characters. </em><a href="https://doc.rust-lang.org/book/ch08-02-strings.html#methods-for-iterating-over-strings"><em>You could use iterators</em></a><em> to such as </em><a href="https://doc.rust-lang.org/std/primitive.str.html#method.chars"><em>chars()</em></a><em>. </em><a href="https://doc.rust-lang.org/std/iter/struct.Skip.html"><em>skip()</em></a><em>. </em><a href="https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.take"><em>take()</em></a><em> instead of direct indexing (which panics). This also includes modifying the editing features of the program to insert and delete characters without panicking, along as fixing the cursor position in the presence of these multi bytes characters.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c841a649900" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your Text Editor With Rust! Part 6]]></title>
            <link>https://medium.com/@otukof/build-your-text-editor-with-rust-part-6-3cff61dc2de5?source=rss-e3ee6219320c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cff61dc2de5</guid>
            <category><![CDATA[ide]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Kofi Otuo]]></dc:creator>
            <pubDate>Wed, 13 Oct 2021 13:40:10 GMT</pubDate>
            <atom:updated>2021-10-22T20:21:26.218Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the penultimate part of this walk-through. In <a href="https://medium.com/@otukof/build-your-text-editor-with-rust-part-5-e363c16f542b">part 5</a>, we enabled the user to write to the file and save it. In this part, we’ll implement a search feature and in the final part we’ll add syntax highlighting.</p><p>Let’s begin by using prompt to implement a simple search. When the user types a search query and presses Enter, we’ll loop through all the rows of the file, and if a row contains their query string, we’ll move the cursor to the match:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef29edf1cb19a51cfd9890f9e27e051f/href">https://medium.com/media/ef29edf1cb19a51cfd9890f9e27e051f/href</a></iframe><p>Recall that prompt!() returns None if the user aborted the prompt so we have to check if prompt!() returned a search keyword. If it did, we loop through all the rows and use .find() to check if the keyword provided is in that row. If it is, we set the cursor position to where the query is. Lastly, we set row_offset so that we are scrolled to the very bottom of the file, which will cause scroll() to scroll upwards at the next screen refresh so that the matching line will be at the very top of the screen. This way, the user doesn’t have to look all over their screen to find where their cursor jumped to, and where the matching line is.</p><p>But there’s a little problem. We assigned a get_render index to cursor_x, but cursor_x is an index into row_content. If there are tabs to the left of the match, the cursor is going to be in the wrong position. We need to convert the render index into a row_content index before assigning it to cursor_x. Let’s create a get_row_content_x() function, which is the opposite of the get_render_x() function we wrote in <a href="https://medium.com/@otukof/build-your-text-editor-with-rust-part-4-fd4a8b8641f8">part 4</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edc501b32222ff73f0b8a0e69fbd82a4/href">https://medium.com/media/edc501b32222ff73f0b8a0e69fbd82a4/href</a></iframe><p>To convert a render_x into a cursor_x, we do pretty much the same thing when converting the other way: loop through the chars of row_content, calculating the current render_x value as we go. At the point, when current_render_x becomes more than the render_x provided, it means we’ve reached the corresponding cursor_x. Note that the function would always return cursor_x as long as the render_x provided is valid. We return 0 if the function was called on an empty row.</p><p>Now let’s call get_row_content_x() in the find method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fab3b885c016ba98288e1fdb366bfa2/href">https://medium.com/media/3fab3b885c016ba98288e1fdb366bfa2/href</a></iframe><p>Finally, let’s map Ctrl-F to the find function, and add it to the help message we set in StatusMessage::new():</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f037149693513dcb534359f962295bd7/href">https://medium.com/media/f037149693513dcb534359f962295bd7/href</a></iframe><h4>Incremental Search 🔍</h4><p>Let’s add a feature to our search, similar to how many searches work. We want to support incremental search, meaning the file is searched after each keypress as the user is typing in their search query.</p><p>To implement this, we’re going to get prompt!() to take a callback function as an argument. We’ll have it call this function after each keypress, passing the current search query inputted by the user and the last key they pressed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8be01d63651f647eb17fd3863c582e2b/href">https://medium.com/media/8be01d63651f647eb17fd3863c582e2b/href</a></iframe><p>We add a new parameter, callback which takes a function or closure which would be called when there’s an input. Since we don’t want to refactor parts of our code where prompt!() is called, we add a new pattern to the prompt! macro and modify the previous one. This enables us to call prompt!() with either 2 or 3 arguments. The first pattern,</p><pre>($output:expr,$args:tt) =&gt; {<br>    prompt!($output, $args, callback = |&amp;_, _, _| {})<br>};</pre><p>, takes 2 arguments and then calls prompt!() with 3 arguments. The last argument is an empty callback which does nothing. (We use &amp;_ since we don’t want the closure to take ownership of Output)</p><p>Now let’s move the actual searching code from find() to a new function find_callback():</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80d96eaa0a8095ef1922eeaaa0b46718/href">https://medium.com/media/80d96eaa0a8095ef1922eeaaa0b46718/href</a></iframe><p>In the callback, we check if the user pressed Enter or Escape, in which case they are leaving search mode so we return immediately instead of doing another search. Otherwise, after any other keypress, we do another search for the current query string. And that’s it for incremental search.</p><h4>Restore Cursor Position ↩️</h4><p>When the user presses Escape to cancel a search, we want the cursor to go back to where it was when they started the search. To do that, we’ll have to save their cursor position and scroll position, and restore those values after the search is cancelled. First, let’s derive <a href="https://doc.rust-lang.org/core/marker/trait.Copy.html">Copy</a> and <a href="https://doc.rust-lang.org/core/clone/trait.Clone.html">Clone </a>for CursorController:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94a8f5f8e72b476c558600169cbd261e/href">https://medium.com/media/94a8f5f8e72b476c558600169cbd261e/href</a></iframe><p>Now let’s restore the cursor position:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5a627ff0e235033f255faeb9a5ac589/href">https://medium.com/media/a5a627ff0e235033f255faeb9a5ac589/href</a></iframe><h4>Search Forward And Backward ♾</h4><p>The last feature we’d like to add is to allow the user to advance to the next or previous match in the file using the arrow keys. The ↑ and ↓ keys will go to the match <em>above or below the current line respectively</em>, while the ← and → keys will go to the match before or after (respectively) the current match on <em>the same line</em>. We’ll use 2 variables, x_index and y_index, to determine how the search would take place. x_index would show where on the row the search should begin while y_index would show which row the search should begin. Their corresponding x_direction and y_direction will determine whether we should search in the forward or backward direction. We’ll create a new struct to hold these values:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42189378e4451779ac9b2d05f5ee2b46/href">https://medium.com/media/42189378e4451779ac9b2d05f5ee2b46/href</a></iframe><p>Now let’s implement vertical scrolling during search:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3755ae3d2d6e6458330bd170f481caf/href">https://medium.com/media/f3755ae3d2d6e6458330bd170f481caf/href</a></iframe><p>When the user presses either ArrowUp or ArrowDown, we set the direction accordingly. If any other key was pressed, we reset the direction. In the for loop, we calculate the row_index. When there’s no direction <em>i.e when the user presses any key apart from </em><em>Enter, </em><em>Esc, </em><em>ArrowUp or </em><em>ArrowDown</em>, we reset y_index and use i as the index, just as we did when we implemented incremental search above. It gets a bit tricky when a direction is provided.</p><p>If ArrowDown was pressed, we add i to y_index and then add 1. This would get us to the next row, from which we’d start the search. <em>For instance, if the first match was on the second row, we want the next search to start from the third row onward. Since </em><em>y_index was assigned index of </em><em>1 (in the line </em><em>y_index = row_index), we can get the search to start from index of </em><em>2 onward by simply adding </em><em>1 to y_index. We also add </em><em>i to keep increasing the index.</em></p><p>We do the opposite for reverse direction. We subtract i from y_index. If it is 0, it simply means we’re on the very first line with a match and so we return. If it’s greater than 0, we move to the previous line and start the search from there upward. We also check if the row_index is valid before using it in get_editor_row.</p><p>Let us now allow the user to move to the next match on the same line:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39238dd6f412ef2fb83a38fdfab9b431/href">https://medium.com/media/39238dd6f412ef2fb83a38fdfab9b431/href</a></iframe><p>If we want our search to be on the same line, when we have to keep row_index as search_index.y_index when the user presses the various arrow keys. When the user isn’t navigating with the left and right arrow keys, we perform our search like how we did it initially. If the user pressed ArrowRight then we perform the search from the current x position onward and then we add the amount of characters before the start position. That way we can get the total index. If the user pressed ArrowLeft, we use <a href="https://doc.rust-lang.org/std/primitive.str.html#method.rfind">.rfind()</a> to reverse the direction of the search. Note that if no index is returned, then it means we’re currently on the last match on that line (depending on the direction) so we just break out of the for loop.</p><p>Finally, let’s not forget to update the prompt text to let the user know they can use the arrow keys:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65e9e5e8b728527cf9a0a6d2c6c272b8/href">https://medium.com/media/65e9e5e8b728527cf9a0a6d2c6c272b8/href</a></iframe><p>In the <a href="https://medium.com/@otukof/build-your-text-editor-with-rust-final-part-4c841a649900">final part</a> we would implement syntax highlighting 🎨!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cff61dc2de5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your Text Editor With Rust! Part 5]]></title>
            <link>https://medium.com/@otukof/build-your-text-editor-with-rust-part-5-e363c16f542b?source=rss-e3ee6219320c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e363c16f542b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[editor]]></category>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Kofi Otuo]]></dc:creator>
            <pubDate>Mon, 11 Oct 2021 15:29:20 GMT</pubDate>
            <atom:updated>2021-10-13T13:45:00.196Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@otukof/build-your-text-editor-with-rust-part-4-fd4a8b8641f8">4th part</a> of this walk-through, we converted our program to a text viewer, allowing us to scroll through text files using keys such as PageUp, PageDown, End, Home, ArrowLeft and ArrowRight. In this part, we would allow the user to edit text and also save the changes to the disk.</p><h4>Insert Ordinary Characters 🔡</h4><p>Let’s begin by writing a function that inserts a single character into a row, at a given position:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51423148fc636fce1900fac85351fd01/href">https://medium.com/media/51423148fc636fce1900fac85351fd01/href</a></iframe><p>First we changed the type of row_content to String to make it mutable. Then we modify the function signature of new. Note how this little change doesn’t break the rest of our program 😀. We use <a href="https://doc.rust-lang.org/alloc/string/struct.String.html#method.insert">String::insert</a> to insert the new letter. If at is equal to the string’s len, the letter would be appended to the string. Finally we call render_row so that render would be updated.</p><p>Recall that we allow the user to move the cursor up to 1 line beneath the file. What if the user decides to move the cursor to that line and insert characters over there? We should create an insert_row function which would first add a new empty row to the file contents, then we can insert characters there.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1d56e88481e580bf5e8bd6d838b6ca8/href">https://medium.com/media/c1d56e88481e580bf5e8bd6d838b6ca8/href</a></iframe><p>We use the<a href="https://doc.rust-lang.org/reference/procedural-macros.html#derive-macros"> </a><a href="https://doc.rust-lang.org/reference/procedural-macros.html#derive-macros">#[derive]</a> procedural macro to implement a <a href="https://doc.rust-lang.org/core/default/trait.Default.html">Default</a> method for Row. This default trait can be used as a fall back to some kind of default value, a value we don’t particularly care what it is. In this case, the default value creates a new Row instance with both row_content and render being empty strings with no memory allocations.</p><blockquote>If you would like a tutorial on #derive macro (what it is about and how to write your own), “clap” on this tutorial. At about 100 claps, I would do a tutorial on #derive. You can also comment a tutorial you’d like to have.</blockquote><p>Let’s put our function into effect:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/524b3a76d0a84b07bb33938c0f0c4650/href">https://medium.com/media/524b3a76d0a84b07bb33938c0f0c4650/href</a></iframe><p>We added a new function get_editor_mut which returns a mutable reference to Row (it’s quite common in Rust to see functions with a _mut counterpart). As explained earlier, first we check if the cursor is on the line beneath the file. If so, we add a new row. After inserting the character, we increase the cursor_x by 1. In process_keypress function, any key which isn’t already mapped to a function would be passed to insert_char. Note that we restrict the modifiers so that something like Ctrl+ p won’t insert p;</p><p>We’ve now officially upgraded our text viewer to a text editor. We’re ready to save the new file.</p><h4>Save To Disk 💾</h4><p>Now let’s add a save function which would handle all the saving:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0d88d1b1cb3ce43f1678f9b16672203/href">https://medium.com/media/c0d88d1b1cb3ce43f1678f9b16672203/href</a></iframe><p>First we convert the row_contents, which is a Vec, to a string. We do that by first creating an iterator of the elements of row_contents, then we limit the iterator to only the row_content field of Row and then collect it as a Vec&lt;&amp;str&gt;. Then we use the <a href="https://doc.rust-lang.org/std/primitive.slice.html#method.join">join()</a> function to create one string consisting of sub-strings joined by \n i.e the new line separator. (You do not have to explicitly specify the type as String as I did. I just specified it for clarity).</p><p>When opening the file, we specified write(true) and create(true). create(true) creates a new file if the file doesn’t already exist. write(true) makes the file writable. Usually to write to files, you could simply use <a href="https://doc.rust-lang.org/std/fs/fn.write.html">std::fs::write()</a>. But that truncates the file completely before writing the contents. By truncating the file ourselves to the same length as the data we are planning to write into it, we are making the whole overwriting operation a little bit safer in case the set_len function succeeds but the write() call fails. In that case, the file would still contain most of the data it had before. But if the file was truncated completely and then the write failed, you’d end up with all of your data lost.</p><p>Also note that we don’t have to “close” the file, as in most programming languages. Rust automatically closes the file when the file instance is dropped</p><p>All we have to do now is map a key to save(), so let’s do it! We’ll use Ctrl-S:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/546624d1cff71633c2a06e087fe2867b/href">https://medium.com/media/546624d1cff71633c2a06e087fe2867b/href</a></iframe><p>We’ll now notify the user how much data was written using set_message(). Will also all Ctrl+S to our initial message displayed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/580e195b40822d067837deab02a1e0cf/href">https://medium.com/media/580e195b40822d067837deab02a1e0cf/href</a></iframe><h4>Dirty Flag 🏴</h4><p>We’d like to keep track of whether the text loaded in our editor differs from what’s in the file. Then we can warn the user that they might lose unsaved changes when they try to quit.</p><p>We call a text buffer “dirty” if it has been modified since opening or saving the file. Let’s add dirty to Output and initialize it to 0:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03f581b627b42527d23498b8e9decc12/href">https://medium.com/media/03f581b627b42527d23498b8e9decc12/href</a></iframe><p>Let’s show the state of dirty in the status bar, by displaying (modified) after the filename if the file has been modified.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6c39c930d01208847b2c583255d48b1/href">https://medium.com/media/c6c39c930d01208847b2c583255d48b1/href</a></iframe><p>Now let’s increment dirty after each operation that makes a change to the text:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ff204e159da383ba9ffd2b92f3727a7/href">https://medium.com/media/2ff204e159da383ba9ffd2b92f3727a7/href</a></iframe><p>We could have used E.dirty = 1 instead of E.dirty++, but by incrementing it we can have a sense of “how dirty” the file is, which could be useful.</p><p>Now we want (modified) to disappear when we save the file so let’s simply set dirty to 0 after the save method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc7f37b1780e021bbb6f284c2e9441fb/href">https://medium.com/media/cc7f37b1780e021bbb6f284c2e9441fb/href</a></iframe><p>Now you should see (modified) appear in the status bar when you first insert a character, and you should see it disappear when you save the file to disk.</p><h4>Quit confirmation 🙅‍♂️</h4><p>Now we’re ready to warn the user about unsaved changes when they try to quit. If dirty is set, we will display a warning in the status bar, and require the user to press Ctrl-Q three more times in order to quit without saving:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc79269c0ccfda5c62a2d68eef47b97d/href">https://medium.com/media/cc79269c0ccfda5c62a2d68eef47b97d/href</a></iframe><p>We use quit_times to track the number of times the user pressed Ctrl-Q. Each time they press Ctrl-Q with unsaved changes, we set the status message and decrement quit_times. When quit_times gets to 0, we finally allow the program to exit. When they press any key other than Ctrl-Q, then quit_times gets reset back to 3 at the end of the process_keypress function.</p><h4>Backspacing 🔙</h4><p>Let’s implement backspacing next. First we’ll create an delete_char function, which deletes a character in row_content. It would be very similar to insert_char:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c21c541aa04a675ce24cfaa916dec772/href">https://medium.com/media/c21c541aa04a675ce24cfaa916dec772/href</a></iframe><p>Now let’s create a similar function in Output, which does the various checks, similar to how we implemented Output.insert_char:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9445a6fe2baaa860dbe50e9882afa4ce/href">https://medium.com/media/9445a6fe2baaa860dbe50e9882afa4ce/href</a></iframe><p>If the cursor’s past the end of the file, then there is nothing to delete, and we return immediately. Otherwise, we get the Row the cursor is on, and if there is a character to the left of the cursor, we delete it and move the cursor one to the left. We also increase dirty in that case.</p><p>Let’s map Backspace and Delete to delete_char():</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f8c1b81364ef67609ebba5ab6b9d49f/href">https://medium.com/media/1f8c1b81364ef67609ebba5ab6b9d49f/href</a></iframe><p>Pressing the → key and then Backspace is equivalent to what you would expect from pressing the Delete key in a text editor: it deletes the character to the right of the cursor. So that is how we implement the Delete key above.</p><h4>Backspacing At The Start Of The Line ◀️</h4><p>Currently, delete_char() doesn’t do anything when the cursor is at the beginning of a line. When the user backspaces at the beginning of a line, we want to append the contents of that line to the previous line, and then delete the current line. This therefore backspaces the implicit \n character in between the two lines to join them into one line.</p><p>Let’ create a join_adjacent_rows() method to do that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a66fc5502a67193fd030ca6a51fcb99/href">https://medium.com/media/5a66fc5502a67193fd030ca6a51fcb99/href</a></iframe><p>First, we remove the next row and then we join it to the current row. After that, we call render_row to update the render field of Row.</p><p>Now we modify our delete_char function in Output:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1c0b893548f3d97edf36e2bd64668f4/href">https://medium.com/media/d1c0b893548f3d97edf36e2bd64668f4/href</a></iframe><p>If the cursor is at the beginning of the <em>first</em> line, then there’s nothing to do, so we return immediately. Otherwise, if we find that cursor_x == 0, we call join_adjacent_rows. We also set cursor_x to the end of the contents of the previous row before appending to that row. That way, the cursor will end up at the point where the two lines joined. Also note that we moved dirty so it is increased when a character is deleted or when lines are joined.</p><p>Notice that pressing the Delete key at the end of a line works as the user would expect, joining the current line with the next line. This is because moving the cursor to the right at the end of a line moves it to the beginning of the next line. So making the Delete key an alias for the → key followed by the Backspace key still works.</p><h4>Enter ¶</h4><p>The last editor operation we have to implement is the Enter key. The Enter key allows the user to insert new lines into the text, or split a line into two lines, depending on where the cursor is. Let’s modify our insert_row function to able to insert a row at the index specified by the new at argument:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00ec00936ff71f7b4f76f5de64cf84d2/href">https://medium.com/media/00ec00936ff71f7b4f76f5de64cf84d2/href</a></iframe><p>We have to update insert_char:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9778d4a42712321080e7ad41d1d69ac5/href">https://medium.com/media/9778d4a42712321080e7ad41d1d69ac5/href</a></iframe><p>Now let’s add insert_newline method which would be mapped to the Enter key:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcc979fcc1c7b869515b1ad33372196e/href">https://medium.com/media/dcc979fcc1c7b869515b1ad33372196e/href</a></iframe><p>If we’re at the beginning of a line, all we have to do is insert a new blank row before the line we’re on.</p><p>Otherwise, we have to split the line we’re on into two rows. We have to truncate the current line the cursor is on to a size equal to cursor_x. We also have to call render_row to update the contents of render. We then insert a new row with contents of the previous line from cursor_x onward.</p><p>After adding the new row, we increase cursor_y and set cursor_x as 0 so the cursor moves to the start of the new row. And don’t forget to increase dirty</p><blockquote>Note that if you rather try truncating current_row after inserting new row, the program won’t compile. You’d get cannot borrow `self.editor_rows` as mutable more than once at a time. This is because current_row refers to a reference to a Row within Vec&lt;Row&gt; and we obtained that reference using cursor_y. So inserting a new row might change the actual position of current_row to a new position which isn’t indexed by cursor_y. For instance, if after inserting a new row, the current row’s position is rather cursor_y+1 and not cursor_y, current_row would then be pointing to another Row reference and that’s not what we want. A workaround would be to reassign current_row after the insertion as that would return the right reference that we want.</blockquote><p>Finally, let’s actually map the Enter key to the insert_newline:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbebfd21409c6ee16288006069a66588/href">https://medium.com/media/cbebfd21409c6ee16288006069a66588/href</a></iframe><p>That concludes all of the text editing operations we are going to implement. If you wish, and if you are brave enough, you may now start using the editor to modify its own code for the rest of the tutorial. If you do, you should probably backup every now and then (using git or similar).</p><h4>Save As ✉️</h4><p>Currently, when the user runs our program with no arguments, they get a blank file to edit but have no way of saving. We need a way of prompting the user to input a filename when saving a new file. We want our prompt method to be able to accept something like Save as: {}, and then fill {} with the input received from the user. Fortunately <a href="https://doc.rust-lang.org/book/ch19-06-macros.html">macros</a> can help us do just that!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eea102605bda8072ce94837646c392cc/href">https://medium.com/media/eea102605bda8072ce94837646c392cc/href</a></iframe><p>Let’s try to understand what prompt!() does. It takes “2” arguments. The first one is an <a href="https://doc.rust-lang.org/reference/expressions.html">expression</a> which we have restricted the type of the expression to only Output using the line</p><pre>let output:&amp;mut Output = &amp;mut $output;</pre><p>This forces only instances of Output to be passed into the macro.</p><p>The second argument is args which is a <a href="https://doc.rust-lang.org/reference/macros.html#macro-invocation">token tree (</a><a href="https://doc.rust-lang.org/reference/macros.html#macro-invocation">tt)</a>. The token tree refers to a single <a href="https://doc.rust-lang.org/reference/tokens.html">token</a> or tokens in matching delimiters (), [], or {}). The tt type enables our macro to take format arguments similar to println!().</p><p>This would allow us to use the macro just as we use println!(). The <a href="https://doc.rust-lang.org/reference/macros-by-example.html#repetitions">* operator</a> means the tokens can repeat any number of types.</p><p>The user’s input is stored in a String. We then enter an infinite loop that repeatedly sets the status message, refreshes the screen, and waits for a keypress to handle. Not that in setting the status message, we pass $($arg)* into the format!() macro. This is because the format!() macro also takes tokens. We pass $($args)* before passing input. This would cause input to be the last format argument. So if something like Save as {} or {} is passed into prompt!(), the user input would be inserted in the last {}.</p><p>When the user presses Enter, and their input is not empty, the status message is cleared and their input is returned. Otherwise, when they input a character, we append it to input. We then return None if there was no input or Some(input) is there was some input.</p><blockquote>Depending on where you defined the prompt!() macro, you may have to add <a href="https://doc.rust-lang.org/reference/macros-by-example.html#scoping-exporting-and-importing">#[macro_export] or </a><a href="https://doc.rust-lang.org/reference/macros-by-example.html#scoping-exporting-and-importing">#[macro_use]</a> so that various functions can have access to the macro. If you defined the macro after the function definition, you have to add #[macro_export] or #[macro_use] appropriately.</blockquote><p>Now let’s prompt the user for a filename before saving if filename is None:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/358c16a2e9bfbb97cb87def549817f61/href">https://medium.com/media/358c16a2e9bfbb97cb87def549817f61/href</a></iframe><p>Next, let’s allow the user to press Escape to cancel the input prompt:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66de266e2e7843065044b40760e113c1/href">https://medium.com/media/66de266e2e7843065044b40760e113c1/href</a></iframe><p>When the prompt is cancelled, we clear input and then return None. Now let’s check if the prompt was None. If it’s we’d show “Save Aborted”:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf6be057f3e4dc2dcfe96c6e77c517c3/href">https://medium.com/media/bf6be057f3e4dc2dcfe96c6e77c517c3/href</a></iframe><p>Let’s conclude this part by allowing the user to press Backspace or Delete in the input prompt:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b71f5b476bc40d3f01406869c0b8151/href">https://medium.com/media/0b71f5b476bc40d3f01406869c0b8151/href</a></iframe><p>We simply use <a href="https://doc.rust-lang.org/alloc/string/struct.String.html#method.pop">.pop</a> to remove the last char.</p><p>In the <a href="https://medium.com/@otukof/build-your-text-editor-with-rust-part-6-3cff61dc2de5">next part</a>, we’ll make use of prompt!() to implement an incremental search feature in our editor.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e363c16f542b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>