<?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 Pasan Gimhana on Medium]]></title>
        <description><![CDATA[Stories by Pasan Gimhana on Medium]]></description>
        <link>https://medium.com/@pasangimhanaofficial?source=rss-8358f868af8b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*b5eZ_ai33-ffO6kb</url>
            <title>Stories by Pasan Gimhana on Medium</title>
            <link>https://medium.com/@pasangimhanaofficial?source=rss-8358f868af8b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:28:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pasangimhanaofficial/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[Custom Doubly Linked List in Rust]]></title>
            <link>https://medium.com/@pasangimhanaofficial/custom-doubly-linked-list-in-rust-45fd6a4745ee?source=rss-8358f868af8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/45fd6a4745ee</guid>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <dc:creator><![CDATA[Pasan Gimhana]]></dc:creator>
            <pubDate>Sun, 26 May 2024 18:32:49 GMT</pubDate>
            <atom:updated>2024-05-26T18:32:49.340Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e83wiA5XZhSRQjJMZCT4BA.jpeg" /></figure><p>In this article, let me take you through the journey of how I implemented a doubly linked list in Rust using Rc (Reference Counted) and RefCell (Interior Mutability), which together help in managing shared ownership and mutable references.</p><p>If you are not familiar with the concepts of Rc and RefCell, refer to this article about <a href="https://medium.com/@pasangimhanaofficial/understanding-rust-memory-management-93681f202eb1">Rust Memory Management</a>.</p><h3>Pre-requisites</h3><p>A few unique syntax, concepts used in this implementation are explained below as they will assist in understanding the code.</p><h4>Options in Rust</h4><p>In Rust, Option is an enum that represents a value that can either be something or nothing. It&#39;s defined as:</p><pre>enum Option&lt;T&gt; {<br>    None,<br>    Some(T),<br>}</pre><p>Option is used to handle cases where a value may or may not be present. For example, accessing an element in a collection that might be empty returns an Option, where None indicates the absence of a value, and Some(T) contains the value if it exists. This helps avoid null pointer dereferencing issues common in other languages.</p><h4>borrow_mut</h4><p>The borrow_mut method is used with RefCell to obtain a mutable reference to the data it contains. RefCell enforces Rust&#39;s borrowing rules at runtime rather than compile time, allowing for mutable borrows even when there are immutable borrows elsewhere in the code.</p><pre>let mut data = ref_cell.borrow_mut();</pre><h4>try_unwrap</h4><p>try_unwrap is used with Rc to attempt to take ownership of the value if there are no other strong references. If there are other references, it returns an error.</p><pre>let value = Rc::try_unwrap(rc_value).ok().expect(&quot;More than one strong reference exists&quot;).into_inner();</pre><h4>map</h4><p>The map method is used with Option and Result types to apply a function to the contained value if it is Some or Ok, respectively.</p><pre>let doubled = Some(5).map(|x| x * 2);</pre><h4>Closures</h4><p>Closures in Rust are anonymous functions that can capture variables from their enclosing environment. They are defined using | | syntax.</p><pre>let add = |a, b| a + b;</pre><h3>Code Explanation</h3><h4>The Node Struct</h4><p>A node in a doubly linked list contains data and references to both its previous and next nodes. These references need to be shared and mutable. Rc is used to allow multiple ownership and RefCell to enable mutation.</p><pre>use std::cell::RefCell;<br>use std::rc::Rc;<br><br>pub struct Node&lt;T&gt; {<br>    pub data: T,<br>    pub prev: Option&lt;Rc&lt;RefCell&lt;Node&lt;T&gt;&gt;&gt;&gt;,<br>    pub next: Option&lt;Rc&lt;RefCell&lt;Node&lt;T&gt;&gt;&gt;&gt;,<br>}<br><br>impl&lt;T&gt; Node&lt;T&gt; {<br>    pub fn new(data: T) -&gt; Self {<br>        Node {<br>            data,<br>            prev: None,<br>            next: None,<br>        }<br>    }<br>}</pre><h4>The Side Enum</h4><p>The Side enum indicates whether a new node should be inserted before or after a given anchor node.</p><pre>pub enum Side {<br>    Before,<br>    After,<br>}</pre><h4>The DoublyLinkedList Struct</h4><p>The doubly linked list itself maintains references to the head and tail of the list. Both are Option&lt;Rc&lt;RefCell&lt;Node&lt;T&gt;&gt;&gt;&gt;.</p><pre>pub struct DoublyLinkedList&lt;T&gt; {<br>    pub(crate) head: Option&lt;Rc&lt;RefCell&lt;Node&lt;T&gt;&gt;&gt;&gt;,<br>    pub(crate) tail: Option&lt;Rc&lt;RefCell&lt;Node&lt;T&gt;&gt;&gt;&gt;,<br>}<br><br>impl&lt;T&gt; DoublyLinkedList&lt;T&gt; {<br>    pub fn new() -&gt; Self {<br>        DoublyLinkedList {<br>            head: None,<br>            tail: None,<br>        }<br>    }    // Methods for inserting, pushing, popping, and removing nodes<br>}</pre><h4>Insert Method</h4><p>The insert method in our DoublyLinkedList struct allows inserting a new node before or after a given anchor node. Let&#39;s break down the insertion logic:</p><h4>Insert Before</h4><pre>Side::Before =&gt; {<br>    let mut anchor_borrow = anchor.borrow_mut();<br>    let prev_node = anchor_borrow.prev.clone();<br>    new_node.borrow_mut().next = Some(anchor.clone());<br>    new_node.borrow_mut().prev = prev_node.clone();<br>    if let Some(prev) = prev_node {<br>        prev.borrow_mut().next = Some(new_node.clone());<br>    } else {<br>        self.head = Some(new_node.clone());<br>    }<br>    anchor_borrow.prev = Some(new_node);<br>}</pre><ul><li>The method starts by borrowing the anchor node mutably using anchor.borrow_mut(). This allows modifying the anchor node’s pointers.</li><li>The previous node of the anchor is cloned using anchor_borrow.prev.clone(). This provides a reference to the node that currently precedes the anchor.</li><li>The new node’s next pointer is set to the anchor (new_node.borrow_mut().next = Some(anchor.clone())), and its previous pointer is set to the previous node (new_node.borrow_mut().prev = prev_node.clone()).</li><li>If a previous node exists (if let Some(prev) = prev_node), its next pointer is updated to point to the new node (prev.borrow_mut().next = Some(new_node.clone())). If there is no previous node, the new node becomes the new head of the list (self.head = Some(new_node.clone())).</li><li>Finally, the anchor node’s previous pointer is updated to point to the new node (anchor_borrow.prev = Some(new_node)).</li></ul><h4>Insert After</h4><pre>Side::After =&gt; {<br>    let mut anchor_borrow = anchor.borrow_mut();<br>    let next_node = anchor_borrow.next.clone();<br>    new_node.borrow_mut().prev = Some(anchor.clone());<br>    new_node.borrow_mut().next = next_node.clone();<br>    if let Some(next) = next_node {<br>        next.borrow_mut().prev = Some(new_node.clone());<br>    } else {<br>        self.tail = Some(new_node.clone());<br>    }<br>    anchor_borrow.next = Some(new_node);<br>}</pre><ul><li>The method starts by borrowing the anchor node mutably using anchor.borrow_mut(). This allows modifying the anchor node’s pointers.</li><li>The next node of the anchor is cloned using anchor_borrow.next.clone(). This provides a reference to the node that currently follows the anchor.</li><li>The new node’s previous pointer is set to the anchor (new_node.borrow_mut().prev = Some(anchor.clone())), and its next pointer is set to the next node (new_node.borrow_mut().next = next_node.clone()).</li><li>If a next node exists (if let Some(next) = next_node), its previous pointer is updated to point to the new node (next.borrow_mut().prev = Some(new_node.clone())). If there is no next node, the new node becomes the new tail of the list (self.tail = Some(new_node.clone())).</li><li>Finally, the anchor node’s next pointer is updated to point to the new node (anchor_borrow.next = Some(new_node)).</li></ul><h4>Pushing Nodes</h4><p>push_front and push_back add new nodes to the front or back of the list, respectively.</p><p>They use the insert method to handle the actual insertion logic. They utilize the Side enum to push After the tail for push_back and Before the head for push_front .</p><pre>pub fn push_front(&amp;mut self, data: T) {<br>    if let Some(head) = self.head.clone() {<br>        self.insert(Side::Before, data, head);<br>    } else {<br>        let new_node = Rc::new(RefCell::new(Node::new(data)));<br>        self.head = Some(new_node.clone());<br>        self.tail = Some(new_node);<br>    }<br>}<br><br>pub fn push_back(&amp;mut self, data: T) {<br>    if let Some(tail) = self.tail.clone() {<br>        self.insert(Side::After, data, tail);<br>    } else {<br>        let new_node = Rc::new(RefCell::new(Node::new(data)));<br>        self.head = Some(new_node.clone());<br>        self.tail = Some(new_node);<br>    }<br>}</pre><h3>Removing Nodes</h3><p>The remove method removes a node from the list and returns its data. Here’s how it works:</p><pre>pub fn remove(&amp;mut self, node: Rc&lt;RefCell&lt;Node&lt;T&gt;&gt;&gt;) -&gt; Option&lt;T&gt; {<br>    let node_borrow = node.borrow();<br>    let (_prev, next) = (node_borrow.prev.clone(), node_borrow.next.clone());<br>    if let Some(prev) = _prev.clone() {<br>        prev.borrow_mut().next = next.clone();<br>    } else {<br>        self.head = next.clone();<br>    }<br>    if let Some(next) = next {<br>        next.borrow_mut().prev = _prev.clone();<br>    } else {<br>        self.tail = _prev.clone();<br>    }<br>    drop(node_borrow);<br><br>    Some(Rc::try_unwrap(node).ok().expect(&quot;More than one strong reference exists&quot;).into_inner().data)<br>}</pre><ul><li>The method starts by borrowing the node mutably using node.borrow(). This allows access to the node’s pointers.</li><li>The previous and next nodes are cloned using node_borrow.prev.clone() and node_borrow.next.clone(), respectively. This provides references to the nodes that precede and follow the node being removed.</li><li>If a previous node exists (if let Some(prev) = _prev.clone()), its next pointer is updated to point to the next node (prev.borrow_mut().next = next.clone()). If there is no previous node, the head of the list is updated to the next node (self.head = next.clone()).</li><li>If a next node exists (if let Some(next) = next), its previous pointer is updated to point to the previous node (next.borrow_mut().prev = _prev.clone()). If there is no next node, the tail of the list is updated to the previous node (self.tail = _prev.clone()).</li><li>The borrow on the node is explicitly dropped using drop(node_borrow) to avoid borrowing issues during node removal.</li><li>The method returns the data contained in the node being removed using Some(Rc::try_unwrap(node).ok().expect(&quot;More than one strong reference exists&quot;).into_inner().data). Rc::try_unwrap attempts to unwrap the Rc and take ownership of the node if there are no other strong references. If successful, it returns the inner RefCell, which is then converted to the inner node to extract the data.</li></ul><h3>pop_front and Method</h3><p>Now, let’s look at the pop_front method and see how map,closures, and flatten are used together.</p><pre>pub fn pop_front(&amp;mut self) -&gt; Option&lt;T&gt; {<br>    return self.head.clone().map(|head| self.remove(head)).flatten();<br>}</pre><p>The pop_front method removes and returns the front (head) element of the doubly linked list. Here&#39;s a breakdown of how it works:</p><ul><li>self.head is an Option&lt;Rc&lt;RefCell&lt;Node&lt;T&gt;&gt;&gt;&gt;. Cloning it allows working with the head node without modifying the original reference in self.head.</li><li>Cloning an Option&lt;Rc&lt;RefCell&lt;Node&lt;T&gt;&gt;&gt;&gt; creates a new Option with a cloned Rc, which means it increments the reference count but doesn&#39;t duplicate the actual node.</li><li>The map method is called on the Option. If the Option is Some, it applies the closure |head| self.remove(head) to the contained value (which is the head node).</li><li>The closure |head| self.remove(head) takes the cloned head node, passes it to the remove method, and returns the result of remove.</li><li>The remove method returns an Option&lt;T&gt;. Therefore, after the map, what is returned is anOption&lt;Option&lt;T&gt;&gt;.</li><li>flatten is used to transform Option&lt;Option&lt;T&gt;&gt; into Option&lt;T&gt;. If the outer Option is Some, it extracts the inner Option&lt;T&gt;.</li></ul><h3>pop_back Method</h3><p>The pop_back method works similarly to pop_front, but it operates on the tail of the list instead of the head.</p><h3>Reference Cycles</h3><p>Without a proper Drop implementation, the doubly linked list could create reference cycles, where nodes reference each other in a cycle. This would prevent Rust’s automatic memory management from deallocating the nodes, leading to memory leaks.</p><p>During the testing phase of this implementation, I experienced that memory leak first-hand. Read about how I found it here: <a href="https://www.linkedin.com/pulse/unexpected-memory-leak-pasan-gimhana-itx8c/">An Unexpected Memory Leak</a></p><h3>Implementing Drop</h3><p>The Drop trait ensures that when a DoublyLinkedList goes out of scope, all its nodes are correctly deallocated.</p><pre>impl&lt;T&gt; Drop for DoublyLinkedList&lt;T&gt; {<br>    fn drop(&amp;mut self) {<br>        while self.pop_back().is_some() {}<br>    }<br>}</pre><p>By calling pop_back repeatedly until the list is empty, it ensures that all nodes are removed and their memory is freed, breaking any potential reference cycles.</p><h3>Performance Enhancement with a Node Pool</h3><p>A significant performance enhancement was achieved by incorporating a node pool into the DoublyLinkedList. This addition helps reduce the overhead of frequent memory allocations and deallocations by reusing nodes from a pre-allocated pool. Here’s an explanation of the concept behind the node pool and a highlight of the differences from the standard implementation:</p><h4>Concept of Node Pool</h4><p>The NodePool struct is designed to manage a pool of reusable nodes. Instead of creating a new node every time an insertion is performed, the node pool provides a pre-existing node. When a node is removed, it is returned to the pool for future use. This helps in reducing the number of memory allocations and deallocations, which can significantly enhance performance, especially in scenarios with frequent insertions and deletions.</p><h4>NodePool Struct</h4><pre>pub struct NodePool&lt;T&gt; {<br>    pool: Vec&lt;Rc&lt;RefCell&lt;Node&lt;T&gt;&gt;&gt;&gt;,<br>}</pre><ul><li>Pool Vector: The pool is a vector that stores nodes wrapped in Rc&lt;RefCell&lt;Node&lt;T&gt;&gt;&gt;, allowing shared and mutable access to nodes.</li></ul><h4>NodePool Methods</h4><ul><li>new : Initializes an empty node pool.</li></ul><pre>pub fn new() -&gt; Self {     NodePool { pool: Vec::new() } }</pre><ul><li>populate: Populates the pool with a specified number of nodes initialized with a default value.</li></ul><pre>pub fn populate(&amp;mut self, size: usize, default_value: T) {<br>        for _ in 0..size {<br>            self.pool<br>                .push(Rc::new(RefCell::new(Node::new(default_value.clone()))));<br>        }<br>    }</pre><ul><li>get_node: Retrieves a node from the pool if available, or creates a new one if the pool is empty.</li></ul><pre>    pub fn get_node(&amp;mut self, data: T) -&gt; Rc&lt;RefCell&lt;Node&lt;T&gt;&gt;&gt; {<br>        if let Some(node) = self.pool.pop() {<br>            node.borrow_mut().data = data;<br>            node.borrow_mut().next = None;<br>            node.borrow_mut().prev = None;<br>            node<br>        } else {<br>            Rc::new(RefCell::new(Node::new(data)))<br>        }<br>    }</pre><ul><li>return_node: Returns a node to the pool, resetting its pointers.</li></ul><pre>    pub fn return_node(&amp;mut self, node: Rc&lt;RefCell&lt;Node&lt;T&gt;&gt;&gt;) {<br>        node.borrow_mut().next = None;<br>        node.borrow_mut().prev = None;<br>        self.pool.push(node);<br>    }</pre><h4>Differences in DoublyLinkedList</h4><p>The DoublyLinkedList now includes a NodePool and utilizes it for node management.</p><ul><li>The DoublyLinkedList is initialized with an empty node pool.</li></ul><pre>    pub fn new() -&gt; Self {<br>        DoublyLinkedList {<br>            head: None,<br>            tail: None,<br>            pool: NodePool::new(),<br>        }<br>    }</pre><ul><li>A new init method is added to prepopulate the node pool.</li></ul><pre>    pub fn init(&amp;mut self, size: usize, default_value: T) {<br>        self.pool.populate(size, default_value);<br>    }</pre><ul><li>Using Node Pool in Insert: The insert method uses pool.get_node(data) to retrieve nodes from the pool instead of creating new ones.</li></ul><pre>let new_node = self.pool.get_node(data);</pre><ul><li>Returning Nodes to Pool: When a node is removed, it is returned to the pool for reuse.</li></ul><pre>self.pool.return_node(node);</pre><h3>Performance Testing of Doubly Linked List Implementations</h3><p>This performance testing assesses the efficiency of the DoublyLinkedList implementations using various data types. It was done 3 times for each implementation, standard list, custom list, custom list with node pool.</p><p>Here&#39;s a concise overview:</p><h4>Tests Conducted:</h4><ol><li>Integer Test (i32): Measures insertion time for 1million i32 values.</li><li>Floating-Point Test (f64): Evaluate performance with 1 million f64 values.</li><li>Complex Number Test: Inserts 1 million custom Complex struct instances.</li><li>User Struct Test: Inserts 1 million User struct instances.</li></ol><h4>Execution:</h4><ul><li>Each test inserts 20 million elements into a new DoublyLinkedList.</li><li>The time taken for each insertion is recorded using SystemTime.</li><li>Tests are run 10 times for consistency.</li></ul><h4>Data Collection:</h4><ul><li>Results from each test run are stored in separate vectors.</li><li>Results are written to a CSV file named doubly_linked_list.csv for analysis.</li></ul><h4>Test Results</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0pcRMykzWfQS_pkkyza21Q.png" /></figure><ul><li>Standard Library Doubly Linked List emerged as the best-performing implementation across all tests. This can be attributed to the low-level implementation.</li><li>Our custom implementations utilize the RefCell which brings the runtime overhead of the runtime borrow checker thus giving almost 2x performance loss for both custom implementations.</li><li>Custom Doubly Linked List with a Node Pool slightly outperformed the custom doubly linked list without a node pool. The incorporation of a node pool provided modest performance improvements, particularly noticeable with larger datasets.</li></ul><h3>Conclusion</h3><p>This journey of implementing the linked list has been a rollercoaster ride filled with challenges and learning experiences. While the Rust language offers powerful features and performance benefits, it’s undeniable that it can be frustrating to work with at times, especially for those accustomed to more traditional programming paradigms.</p><p>But this exploration won’t be limited to linked lists alone. From package management to concurrency, from string manipulation to object-oriented programming in Rust, I have so much more to learn.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45fd6a4745ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Rust Memory Management]]></title>
            <link>https://medium.com/@pasangimhanaofficial/understanding-rust-memory-management-93681f202eb1?source=rss-8358f868af8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/93681f202eb1</guid>
            <category><![CDATA[smart-pointer]]></category>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <dc:creator><![CDATA[Pasan Gimhana]]></dc:creator>
            <pubDate>Sun, 26 May 2024 10:20:44 GMT</pubDate>
            <atom:updated>2024-05-26T10:40:25.680Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-5ob8tedGgFQmX3kQVtyLw.jpeg" /></figure><p>Rust’s memory management model is one of its defining features, setting it apart from other systems programming languages like C and C++. Rust’s ownership system enforces rules at compile time, ensuring memory safety and preventing data races. This article will delve into the essential components of Rust’s memory management, explaining how they work together to provide a safe and efficient programming environment.</p><h3>Mutability Rules</h3><p>Rust enforces strict rules about mutability to ensure memory safety:</p><ul><li>Immutable by Default: All variables in Rust are immutable by default. Once a value is bound to a name, it cannot be changed unless explicitly stated otherwise.</li><li>Mut Keyword: To make a variable mutable, you need to use the mut keyword. This allows the variable&#39;s value to be changed.</li></ul><pre>let x = 5; // immutable by default<br>let mut y = 10; // mutable variable<br>y = 15; // valid because y is mutable</pre><p>These rules prevent unintended changes to data, reducing bugs related to state changes.</p><h3>Stack vs. Heap Allocation</h3><p>In Rust, as in many other programming languages, memory is managed through stack and heap allocation.</p><h3>Stack</h3><p>The stack is a region of memory that operates on a Last In, First Out (LIFO) basis. Variables allocated on the stack have a known, fixed size and are pushed and popped from the stack in a predictable manner.</p><h3>Heap</h3><p>The heap, on the other hand, is used for data that needs to live beyond the scope of a function call or for data whose size is not known at compile time. Allocating memory on the heap is more complex and involves a performance cost due to dynamic allocation and deallocation.</p><h3>C++ Example for Comparison</h3><p>In C++, you can explicitly manage memory allocation using new and delete.</p><pre>int* p = new int; // heap allocation<br>*p = 10;<br>delete p; // deallocation</pre><p>In Rust, explicit memory management and deallocation like this is not necessary due to its ownership model.</p><h3>References and Borrowing</h3><p>Rust’s references and borrowing system allows you to access data without taking ownership of it.</p><h3>References</h3><p>A reference is a way of referring to some other value without owning it. References are either mutable or immutable.</p><pre>let s1 = String::from(&quot;hello&quot;);<br>let s2 = &amp;s1; // immutable reference</pre><h3>Borrowing</h3><p>Borrowing refers to the action of creating references. Rust enforces borrowing rules to ensure safety:</p><ul><li>Immutable References: Multiple immutable references are allowed simultaneously.</li><li>Mutable References: Only one mutable reference is allowed at a time, preventing data races.</li></ul><pre>let s = String::from(&quot;hello&quot;);<br>let r1 = &amp;s; // immutable borrow<br>let r2 = &amp;s; // another immutable borrow<br>let mut s = String::from(&quot;hello&quot;);<br>let r3 = &amp;mut s; // mutable borrow</pre><h3>Dereferencing</h3><p>Dereferencing is accessing the value behind a reference using the * operator.</p><pre>let x = 5;<br>let y = &amp;x;<br>println!(&quot;{}&quot;, *y); // dereference to access the value of x</pre><h3>Smart Pointers</h3><p>Smart pointers are data structures that act like pointers but come with additional capabilities, such as automatic memory management.</p><h3>Box</h3><p>Box is the simplest smart pointer in Rust, used for allocating values on the heap.</p><pre>let b = Box::new(5);<br>println!(&quot;{}&quot;, *b); // dereference to access the value</pre><h4>Disadvantage of Box</h4><p>While Box is useful for heap allocation, it has limitations:</p><ul><li>Single Ownership: A Box can only have one owner at a time, limiting its use in scenarios where shared ownership is required.</li><li>Performance Overhead: There is a slight performance overhead due to heap allocation and deallocation.</li></ul><p>In many programming scenarios, a need for multiple parts of a program to access and modify the same piece of data simultaneously can occur. This requires shared ownership, where multiple references to a single resource must coexist without causing conflicts or memory safety issues.</p><p>Rust addresses this need through its reference counting mechanisms, allowing safe and efficient shared ownership while preventing common pitfalls like data races and memory leaks.</p><h3>Reference Counting</h3><p>For scenarios requiring shared ownership, Rust provides reference-counted pointers.</p><h3>Rc and Weak</h3><p>In Rust, shared ownership is managed using the Rc (Reference Counted) smart pointer. Rc allows multiple parts of a program to own the same data. The reference count is tracked, and the data is only deallocated when the count drops to zero, ensuring memory safety and preventing premature deallocation.</p><pre>use std::rc::Rc;<br>let a = Rc::new(5);<br>let b = Rc::clone(&amp;a);<br>println!(&quot;{}&quot;, Rc::strong_count(&amp;a)); // prints 2</pre><p>In the above example, a and b both own the value 5. The reference count is incremented when b is created and decremented when b goes out of scope. The data is deallocated only when the reference count is zero.</p><h4>Limitations of Rc</h4><ol><li>Single-threaded Use Only: Rc is not thread-safe. For multi-threaded scenarios, Arc (Atomic Reference Counted) should be used.</li><li>Reference Cycles: If two Rc pointers reference each other, they create a reference cycle, causing a memory leak because the reference count will never reach zero. This is what we encountered in our Doubly Linked List implementation with Strong References for both directions.</li></ol><h3>Weak References</h3><p>To prevent reference cycles, Rust provides Weak references. Weak references do not contribute to the reference count and therefore do not prevent the data from being deallocated.</p><pre>use std::rc::{Rc, Weak};<br>let a = Rc::new(5);<br>let b: Weak&lt;_&gt; = Rc::downgrade(&amp;a);<br>println!(&quot;{}&quot;, Rc::strong_count(&amp;a)); // prints 1<br>println!(&quot;{}&quot;, Rc::weak_count(&amp;a));   // prints 1</pre><p>In this example, b is a Weak reference to a. The strong count remains 1 because Weak references do not increment it. The weak count tracks the number of Weak references.</p><h4>Rules and Usage of Rc and Weak</h4><ul><li>Creating Rc: Use Rc::new(data) to create an Rc instance.</li><li>Cloning Rc: Use Rc::clone(&amp;original) to create a new Rc pointer to the same data, incrementing the reference count.</li><li>Downgrading to Weak: Use Rc::downgrade(&amp;rc) to create a Weak reference from an Rc pointer.</li><li>Upgrading Weak: Use weak.upgrade() to attempt to convert a Weak reference back to an Rc. This returns None if the data has been deallocated.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ojX63l3TR9_-nOUlzVpSuQ.jpeg" /></figure><pre>if let Some(strong) = b.upgrade() {<br>    println!(&quot;Value: {}&quot;, strong);<br>} else {<br>    println!(&quot;Value has been deallocated&quot;);<br>}</pre><p>The reason, I initially explored Rust memory management was to build a doubly linked list. For that, Rc was not enough.</p><h4>The Problem with Multiple Mutable Rcs</h4><p>When using Rc to enable shared ownership of nodes in a linked list, Rust&#39;s borrowing rules prevent having multiple mutable references to the same node. This limitation makes it difficult to mutate nodes through shared references, which is often needed in linked list operations.</p><h4>Cell and RefCell</h4><p>To address this problem, Rust provides Cell and RefCell, types that allow for interior mutability. <strong>Interior mutability</strong> is a design pattern that allows you to mutate data even when there are immutable references to that data.</p><ul><li>Cell: Used for types that implement the Copy trait. It allows for interior mutability without runtime borrow checking.</li></ul><pre>use std::cell::Cell;<br>let x = Cell::new(5);<br>x.set(10);<br>println!(&quot;{}&quot;, x.get()); // prints 10</pre><ul><li>In the example above, Cell allows the value to be changed even though x is not mutable.</li><li>RefCell: Used for types that do not implement the Copy trait. It enables interior mutability with runtime borrow checking. RefCell ensures at runtime that the borrowing rules are followed: only one mutable borrow or multiple immutable borrows at any time.</li></ul><pre>use std::cell::RefCell;<br>let x = RefCell::new(5);<br>*x.borrow_mut() = 10;<br>println!(&quot;{}&quot;, *x.borrow()); // prints 10</pre><ul><li>In the example above, RefCell allows mutable access to x&#39;s value even though x itself is not mutable. The borrow_mut method provides a mutable reference, and borrow provides an immutable reference, with runtime checks to enforce borrowing rules.</li></ul><h3>Combining Rc with RefCell</h3><p>To create a linked list that allows interior mutability, we combine Rc and RefCell. This combination provides shared ownership with the flexibility to mutate the shared data.</p><pre>use std::cell::RefCell;<br>use std::rc::Rc;<br><br>struct Node {<br>    value: i32,<br>    next: Option&lt;Rc&lt;RefCell&lt;Node&gt;&gt;&gt;,<br>}<br><br>fn main() {<br>    let node1 = Rc::new(RefCell::new(Node { value: 1, next: None }));<br>    let node2 = Rc::new(RefCell::new(Node { value: 2, next: None }));<br>    <br>    node1.borrow_mut().next = Some(Rc::clone(&amp;node2));<br>    <br>    println!(&quot;{}&quot;, node1.borrow().next.as_ref().unwrap().borrow().value); // prints 2<br>}</pre><p>In this example, Rc&lt;RefCell&lt;Node&gt;&gt; allows multiple parts of the program to share ownership of nodes and mutate them as needed. Rc handles the reference counting, while RefCell allows interior mutability with runtime borrow checking.</p><h3>Conclusion</h3><p>Rust’s memory management model, with its ownership system, borrowing rules, and smart pointers, offers a robust framework for ensuring memory safety. How we implemented the full linked list utilizing these memory management principles, is a topic for another blog.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93681f202eb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[yt-dlp : The Ultimate YouTube Downloader.]]></title>
            <link>https://medium.com/@pasangimhanaofficial/yt-dlp-the-ultimate-youtube-downloader-9f061a60c8f1?source=rss-8358f868af8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f061a60c8f1</guid>
            <category><![CDATA[youtube]]></category>
            <category><![CDATA[youtube-downloader]]></category>
            <category><![CDATA[yt-dlp]]></category>
            <category><![CDATA[command-line-tools]]></category>
            <dc:creator><![CDATA[Pasan Gimhana]]></dc:creator>
            <pubDate>Thu, 13 Jul 2023 08:57:31 GMT</pubDate>
            <atom:updated>2023-07-14T02:38:38.759Z</atom:updated>
            <content:encoded><![CDATA[<h3>yt-dlp : The Ultimate YouTube Downloader.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4pNTXuHldnbdwcIaNJVtBA.jpeg" /></figure><p>Some of the YouTube tutorials I followed were in playlists. When I wanted to download those playlists, I relied on a software called <a href="https://www.freedownloadmanager.org/">Free Download Manager</a> (FDM), which allowed me to download entire YouTube playlists effortlessly. After an update, that feature was removed from FDM and I was left without a dependable way to download YouTube videos or playlists. I combed the internet in quest of a new saviour because I was desperate to discover a solution.</p><p>I found a ton of websites that offered YouTube downloading, but to my disappointment, most of them only supported 720p resolution, but didn’t support downloading playlists so I had to download each video individually. My patience was worn thin by the tedious and annoying process because I was used to the convenience. But in the midst of my utter hopelessness, I found a GitHub repository called <a href="https://github.com/yt-dlp/yt-dlp">yt-dlp</a>.</p><p><a href="https://github.com/yt-dlp/yt-dlp">yt-dlp</a> is a powerful command line tool for downloading videos, playlists, and other content from YouTube and several other supported websites. It is a successor to youtube-dl, offering additional features and improvements. With yt-dlp, you can effortlessly save videos, extract audio, and download entire playlists for offline viewing or listening.</p><p>To begin my journey with yt-dlp, I needed to install it on my computer. The installation process varied depending on the operating system.</p><p>If you have Python installed on your computer you can install the <a href="https://pypi.org/project/yt-dlp">PyPI package</a> with python3 -m pip install -U yt-dlp</p><p>On some systems, you may need to use py or python instead of python3</p><p>As I am using<strong> Windows,</strong> and didn’t have Python installed at the time, I downloaded the yt-dlp.exe Windows executable file and created a folder called “yt-dlp” on my c:/ drive and placed the yt-dlp executable inside. Then, I added the folder path c:/yt-dlp/ to my user path variable, which allowed me to access yt-dlp from any command prompt window.</p><p>Installing yt-dlp on <strong>Unix (Linux/BSD)</strong> systems requires using platform-independent binary files. After downloading the appropriate binary, you can follow the provided instructions to install and configure yt-dlp.</p><p>On a <strong>macOS</strong> computer, you can either obtain the universal standalone executable called “yt-dlp_macos” and install it following the provided instructions. This allowed you to use yt-dlp it smoothly on your macOS system. Be sure to use a bash terminal because some terminals can’t correctly parse youtube links.</p><p>You can find extensive and clear documentation about the installation and setup <a href="https://github.com/yt-dlp/yt-dlp#installation">here</a>.</p><p>Note: For the video to mp3 conversion feature, make sure you have ffmpeg installed. ffmpeg enables merging separate video and audio files and various post-processing tasks. If you used the pip command to install yt-dlp, ffmpeg is also installed automatically. Unless, follow the documentation on the <a href="https://ffmpeg.org/documentation.html">ffmpeg</a> page for installation guidelines.</p><p>Here are some commands I use most of the time to download YouTube playlists in video or audio formats.</p><pre>// Download a YouTube video/playlist as mp3 or any audio format<br><br>// Single File<br>yt-dlp --no-part -x --audio-format mp3 -o &quot;%(title)s.%(ext)s&quot; https://youtu.be/dQw4w9WgXcQ<br>// Playlist<br>yt-dlp --no-part -x --yes-playlist --audio-format mp3 -o &quot;%(title)s.%(ext)s&quot; https://www.youtube.com/playlist?list=PLu4wnki9NI_8VmJ7Qz_byhKwCquXcy6u9<br><br><br>// Download a YouTube video/playlist as a video file.<br><br>// Single File<br>yt-dlp -S &quot;height:1080&quot; https://youtu.be/dQw4w9WgXcQ<br>// Playlist<br>yt-dlp --no-part -S &quot;height:1080&quot; --yes-playlist --playlist-items 1-100 --output &quot;%(playlist_index)s-%(title)s.%(ext)s&quot; https://www.youtube.com/playlist?list=PLu4wnki9NI_8VmJ7Qz_byhKwCquXcy6u9</pre><p>It might seem like random syntax, but hold on.</p><p>--no-part: This option ensures that the video or audio file is not downloaded in parts. It downloads the complete file instead.</p><p>-x: This option instructs yt-dlp to extract the audio from the video file and save it as a separate audio file. It enables the conversion of video files to audio formats like MP3.</p><p>--audio-format mp3: This parameter specifies the desired audio format for the extracted file. In the given example, the format is set to MP3. You can replace &quot;mp3&quot; with other supported audio formats like &quot;aac&quot; or &quot;ogg&quot;.</p><p>-o &quot;%(title)s.%(ext)s&quot;: This option specifies the output format of the downloaded file. In this case, it uses the title of the video as the file name and the extension of the original file. For example, if the video is titled &quot;MyVideo&quot; and the file format is MP3, the output file will be named &quot;MyVideo.mp3&quot;.</p><p>-S &quot;height:1080&quot;: This parameter is used to specify the desired resolution for downloading video files. In the given example, the height is set to 1080 pixels. You can adjust the resolution by changing the value to &quot;720&quot; or &quot;480&quot; as needed.</p><p>--yes-playlist: This option enables the downloading of entire playlists instead of just individual videos. It ensures that all videos in the playlist are included in the download.</p><p>--playlist-items 1-100: This parameter allows you to specify a range of items from a playlist to download. In the given example, it downloads items 1 to 100 from the playlist. You can modify the range as per your requirements.</p><p>yt-dlp offers a wide range of options and features, which can be overwhelming to learn all at once. My suggestion is to focus on mastering the necessary commands that serve your specific needs. Maintaining a collection of commands you can refer to when you are downloading something is helpful.</p><figure><img alt="Me using yt-dlp to download a really important YouTube video." src="https://cdn-images-1.medium.com/max/1024/1*bY97Q5dl6alL-g0dazCLCQ.png" /><figcaption>Using yt-dlp for the greater good of humanity.</figcaption></figure><p>To all those seeking to save valuable YouTube playlists, fear not! Embrace, install it on your preferred operating system, and utilize its simple commands to embark on your own adventure.</p><p>Thousands of YouTube downloaders will come and go but, yt-dlp is, <a href="https://youtu.be/dQw4w9WgXcQ">Never gonna give you up!!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f061a60c8f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Taming the flex-bison with Pacman]]></title>
            <link>https://medium.com/@pasangimhanaofficial/taming-the-flex-bison-with-pacman-51fd79ba463b?source=rss-8358f868af8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/51fd79ba463b</guid>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[flex]]></category>
            <category><![CDATA[compiler-design]]></category>
            <category><![CDATA[bison]]></category>
            <dc:creator><![CDATA[Pasan Gimhana]]></dc:creator>
            <pubDate>Sun, 09 Jul 2023 07:59:05 GMT</pubDate>
            <atom:updated>2023-07-09T08:04:58.681Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D6UNbc6K8CvBAxO707vvBg.png" /></figure><p>Once upon a time, in the land of Windows, I embarked on a journey to install Flex and Bison on my computer. I had no idea that this seemingly straightforward mission would lead me through a confusing maze of barriers and detours.</p><p>My initial choice was to use WSL2 (Windows Subsystem for Linux) along with the good old VSCode. Suprisingly WSL2 came with a significant performance hit, as I discovered after installing it and configuring everything. I was unable to find the smoothness I was looking for, so I knew I had to look elsewhere.</p><p>I searched the internet in search of a solution. I found myself installing not one, not two, but three different C and C++ compilers on my laptop after turning to tutorials for guidance. On my system, MinGW64, Codeblocks MinGW, and Dev CPP all settled in, bringing with them the expectation that Flex and Bison will at last work together.</p><p>Flex and Bison eventually worked and I was relieved. But alas, my happiness was short-lived. After compiling a flex file, I confidently ran the</p><pre>gcc lex.yy.c -lfl</pre><p>command to compile the resulting1ex.yy.c file. Compiling C files were a normal thing using gcc. But this time it started to malfunction. You see, the path variables clashed in a jumble of confusion, each folder containing the same gcc.exe files.</p><p>As my frustration reached a breaking point, I said goodbye to the three compilers and cleaned up the path variables. Finding a new ally was necessary to put an end to this chaotic symphony of diverging roads. And that’s when I came across MSYS2, a glimmer of optimism.</p><p><a href="https://www.msys2.org/">https://www.msys2.org/</a></p><p>I installed with MSYS2 and had the powerful pacman package manager at my disposal. Surprisingly, the installation went without a hitch, as if the universe had decided to atone for the difficulties in the past. I added C:\msys64\usr\bin to the System Path variable and I was good to go.</p><p>Victorious, I released a happy sigh of relief and amusement. It was like that time when I fearlessly popped in a video game DVD, generously gifted by my buddies, almost giving my poor PC a meltdown in the process.</p><p>So, fellow coders, keep my story in mind if you ever find yourself installing the Flex and Bison on a Windows PC.</p><p>As a token of my journey, here are the pacman commands that granted me success:</p><pre>pacman -S gcc<br>pacman -S flex<br>pacman -S bison<br>pacman -S make</pre><p>May pacman be with you. Happy coding, my friends!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51fd79ba463b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>