<?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 Aryan Alikhani on Medium]]></title>
        <description><![CDATA[Stories by Aryan Alikhani on Medium]]></description>
        <link>https://medium.com/@learn_aryan?source=rss-86b1f3224d4b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mTLzpzFn0j6H0sKbR0Kj6w.jpeg</url>
            <title>Stories by Aryan Alikhani on Medium</title>
            <link>https://medium.com/@learn_aryan?source=rss-86b1f3224d4b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 14:03:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@learn_aryan/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[Squeezing Real-Time Processing into a 16KB Microcontroller]]></title>
            <link>https://medium.com/@learn_aryan/squeezing-real-time-processing-into-a-16kb-microcontroller-6f55569a973e?source=rss-86b1f3224d4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f55569a973e</guid>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[electronics]]></category>
            <category><![CDATA[microcontrollers]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[c-programming]]></category>
            <dc:creator><![CDATA[Aryan Alikhani]]></dc:creator>
            <pubDate>Mon, 04 Aug 2025 09:05:59 GMT</pubDate>
            <atom:updated>2025-08-04T09:09:15.992Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I built a custom task scheduler to overcome the limits of a budget STM32 processor</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GSWK9i9U-TEI7JFhI-YQiw.jpeg" /></figure><p>Imagine trying to process real-time sensor data and talk to a server using a chip with less memory than a single email. That’s the challenge I faced when I started a project with the STM32, a microcontroller used in everything from drones to IoT devices. To keep costs low, I chose its most basic model with just 16KB of programmable memory. The question was: should I wrestle with messy spaghetti code or rely on an expensive Real-Time Operating System (RTOS) for cleaner code? Neither felt right, so I rolled up my sleeves and built a minimalist task scheduling framework with as few lines of code as possible.</p><h3>The Problem</h3><p>My goal was to create a system to schedule tasks and functions within a specific context and time range essentially, a lightweight event loop that waits for the perfect moment to execute each task. A key requirement was preventing duplicate tasks, so every time a task is added to the system, it must be unique and carefully managed to avoid conflicts.</p><p>This setup had to handle practical scenarios like:</p><ul><li>Regularly checking sensor data.</li><li>Repeatedly verifying a network connection.</li><li>Monitoring for failures and re-establishing connections.</li><li>Running internal state diagnostics.</li><li>Managing server communication routines.</li><li>Keeping processes alive with minimal overhead.</li></ul><h3>My Solution: A Lean Task Scheduler with a Heap</h3><p>To bring my task scheduler to life, I first needed a structure to hold information about the functions to be executed. I defined a task_t structure in C to store each task’s details:</p><pre>#pragma once<br><br>typedef uint32_t (*task_func_t)();<br>typedef struct {<br>  uint32_t id;        // Unique task identifier (power of 2)<br>  task_func_t func;   // Function to execute<br>  uint32_t due;       // When the task should run<br>} task_t;</pre><p>The goal was to execute tasks at their scheduled times. My initial approach was to store tasks in a simple list and, within the main event loop, find the task with the closest due time:</p><pre>while(true) {<br>  task_t* closest = find_closest_linear();<br>  if(now &gt;= closest-&gt;due) {<br>    handle_task(closest);<br>    remove_task(closest);<br>  }<br>}</pre><p>This worked, but it had significant drawbacks. Searching linearly through the list to find the closest task and removing tasks from the list were computationally expensive, especially in an infinite loop. For a 16KB STM32, these operations could quickly become a bottleneck. I needed a solution with O(1) access time to pop the closest task and perform operations efficiently.</p><p>Since the heap data structure a perfect fit for storing sorted tasks and accessing the earliest one in O(1) time. A min-heap ensures the task with the smallest due time is always at the root, making retrieval fast and efficient. Below is my template heap implementation in C, designed to be lightweight and tailored for the STM32’s constraints:</p><pre>// fastheap.h<br><br>#pragma once<br><br>#define __fastheap_type(t_name) Fastheap_##t_name<br><br>#define __fast_swap(data, i, j)  \<br>  typeof(data[0]) tmp = data[i]; \<br>  data[i] = data[j];             \<br>  data[j] = tmp;<br><br>#define MAKE_FASTHEAP(t_name, t_key, t_cap, t_compare)                                            \<br>  typedef struct                                                                                  \<br>  {                                                                                               \<br>    volatile size_t length;                                                                       \<br>    volatile t_key vector[t_cap];                                                                 \<br>  } __fastheap_type(t_name);                                                                      \<br>  static void __fastheap_##t_name##_sortup(__fastheap_type(t_name) * self, size_t index)   \<br>  {                                                                                               \<br>    while (index &gt; 1)                                                                             \<br>    {                                                                                             \<br>      size_t parent = index / 2;                                                                  \<br>      int cmp = t_compare(self-&gt;vector[parent - 1], self-&gt;vector[index - 1]);                     \<br>      if (cmp &gt; 0)                                                                                \<br>        return;                                                                                   \<br>      __fast_swap(self-&gt;vector, index - 1, parent - 1);                                           \<br>      index = parent;                                                                             \<br>    }                                                                                             \<br>    return;                                                                                       \<br>  }                                                                                               \<br>  static void __fastheap_##t_name##_sortdown(__fastheap_type(t_name) * self, size_t index) \<br>  {                                                                                               \<br>    while (index &lt;= self-&gt;length)                                                                 \<br>    {                                                                                             \<br>      size_t leftIndex = index * 2;                                                               \<br>      size_t rightIndex = index * 2 + 1;                                                          \<br>      if (leftIndex &gt; self-&gt;length)                                                               \<br>        return;                                                                                   \<br>      size_t next = leftIndex;                                                                    \<br>      int cmp = t_compare(self-&gt;vector[rightIndex - 1], self-&gt;vector[leftIndex - 1]);             \<br>      if (rightIndex &lt;= self-&gt;length &amp;&amp; cmp &gt; 0)                                                  \<br>      {                                                                                           \<br>        next = rightIndex;                                                                        \<br>      }                                                                                           \<br>      cmp = t_compare(self-&gt;vector[index - 1], self-&gt;vector[next - 1]);                           \<br>      if (cmp &gt; 0)                                                                                \<br>        return;                                                                                   \<br>      __fast_swap(self-&gt;vector, index - 1, next - 1);                                             \<br>      index = next;                                                                               \<br>    }                                                                                             \<br>  }                                                                                               \<br>  static void fastheap_##t_name##_push(__fastheap_type(t_name) * self, t_key value)        \<br>  {                                                                                               \<br>    self-&gt;vector[self-&gt;length++] = value;                                                         \<br>    __fastheap_##t_name##_sortup(self, self-&gt;length);                                             \<br>  }                                                                                               \<br>  static t_key fastheap_##t_name##_pop(__fastheap_type(t_name) * self)                     \<br>  {                                                                                               \<br>    t_key root = self-&gt;vector[0];                                                                 \<br>    self-&gt;vector[0] = self-&gt;vector[--self-&gt;length];                                               \<br>    __fastheap_##t_name##_sortdown(self, 1);                                                      \<br>    return root;                                                                                  \<br>  }                                                                                               \<br>  static t_key fastheap_##t_name##_remove(__fastheap_type(t_name) * self, size_t index)    \<br>  {                                                                                               \<br>    t_key root = self-&gt;vector[index];                                                             \<br>    self-&gt;vector[index] = self-&gt;vector[--self-&gt;length];                                           \<br>    __fastheap_##t_name##_sortdown(self, index + 1);                                              \<br>    return root;                                                                                  \<br>  }</pre><p>This macro-based implementation is flexible and reusable, allowing me to create a heap for any data type (in this case, task_t) with a specified capacity and comparison function. For my scheduler, I used it to create a heap for tasks, sorted by their due time. Here’s how I set it up:</p><pre>#include &quot;task.h&quot;<br>#include &quot;fastheap.h&quot;<br><br>#define compare_tasks(a, b) (b.due - a.due)<br>MAKE_FASTHEAP(task, task_t, 32, compare_tasks);<br>static Fastheap_task timers = {0};<br><br><br>// Example usage<br>task_t tsk;<br>tsk.id = 2;<br>tsk.due = 10;<br>fastheap_task_push(&amp;timers, tsk);<br><br><br>task_t tsk2;<br>tsk2.id = 4;<br>tsk2.due = 6;<br>fastheap_task_push(&amp;timers, tsk2);<br>task_t t = fastheap_task_pop(&amp;timers);<br>// The task with due=6 is popped first, as it&#39;s the earliest</pre><p>In this example, I push two tasks with different due times onto the heap. The heap ensures the task with the earliest due time (6) is popped first, maintaining efficient scheduling. This approach kept my scheduler lean, using minimal memory while achieving near O(1) access for task retrieval, perfectly suited for the STM32’s 16KB constraints.</p><h3>Implementation: Building the Task Scheduler</h3><p>With a heap data structure in place, it was time to define the core functionalities of my task scheduler. I started by setting up the necessary interfaces in task.h:</p><pre>// task.h<br>#pragma once<br><br>#include &lt;stdint.h&gt;<br><br>// The returned value informs the scheduler when to execute the task next,<br>// enabling looping tasks<br>typedef uint32_t (*task_func_t)();<br><br>// Returns the current system time (e.g., HAL_GetTick() on STM32)<br>extern uint32_t get_system_time();<br><br>// Ensures a task is scheduled at a given time<br>void task_ensure(uint32_t id, uint32_t ms, task_func_t func);<br><br>// Runs the scheduler in the main loop<br>void task_scheduler();</pre><p>Next, I defined the task structure and heap integration in task.c:</p><pre>#include &quot;task.h&quot;<br>#include &quot;fastheap.h&quot;<br><br>#define compare_tasks(a, b) (b.due - a.due)<br><br>typedef struct {<br>  uint32_t id;        // Unique task identifier<br>  task_func_t func;   // Function to execute<br>  uint32_t due;       // When the task should run<br>} task_t;<br><br>MAKE_FASTHEAP(task, task_t, 32, compare_tasks);<br><br>static Fastheap_task timers = {0}; // Heap to store tasks<br>static volatile uint32_t running_tasks = 0; // Tracks active tasks</pre><p>With the heap data structure and core interfaces set up, I was ready to implement the key functions of my task scheduler: task_ensure and task_scheduler. These functions bring the scheduler to life, ensuring tasks are added efficiently and executed at the right time within the STM32’s 16KB memory constraints.</p><h4>The task_ensure Function</h4><p>The task_ensure function schedules a task to run at a specified time. To prevent duplicates, it first checks if the task is already running using a clever trick: task IDs are powers of two (e.g., 1, 2, 4, 8), allowing a fast bitwise check against a running_tasks bitmask. If the task isn’t already scheduled, it’s added to the heap with its execution time.</p><p>Here’s the implementation:</p><pre>void task_ensure(uint32_t id, uint32_t ms, task_func_t func)<br>{<br>  // Fast check: if task ID is in running_tasks bitmask, skip<br>  if (running_tasks &amp; id)<br>      return;<br><br>  task_t t;<br>  t.due = get_system_time() + ms; // Set execution time<br>  t.func = func;                  // Set task function<br>  t.id = id;                      // Set unique ID<br><br>  // Mark task as running and push to heap<br>  running_tasks |= id;<br>  fastheap_task_push(&amp;timers, t);<br>}</pre><p>This approach is lightweight and efficient, using bitwise operations to avoid costly searches, which is critical for the STM32’s limited resources.</p><h4>The task_scheduler Function</h4><p>The task_scheduler function runs in the main loop, checking if the earliest task (at the heap’s root) is due. If it is, the task is popped, executed, and either rescheduled (for recurring tasks) or removed, keeping the system non-blocking and responsive.</p><p>Here’s how it works:</p><pre>void task_scheduler()<br>{<br>  if (!timers.length) // If heap is empty, exit<br>    return;<br><br>  // Check if the earliest task is due<br>  if (get_system_time() &gt;= timers.vector[0].due)<br>  {<br>    // Pop the task from the heap<br>    task_t t = fastheap_task_pop(&amp;timers);<br><br>    // Execute the task function<br>    uint32_t ms = t.func();<br><br>    // Reschedule if the task returns a non-zero ms<br>    if (ms &gt; 0)<br>    {<br>      running_tasks |= t.id; // Mark as running<br>      t.due = get_system_time() + ms; // Set new execution time<br>      fastheap_task_push(&amp;timers, t); // Push back to heap<br>    }<br>    else<br>    {<br>      // Remove from running tasks<br>      running_tasks &amp;= ~t.id;<br>    }<br>  }<br>}</pre><p>This keeps the scheduler lean, with the heap ensuring O(1) access to the earliest task and O(log n) for insertions, perfect for real-time performance.</p><h4>Putting It All Together</h4><p>To see the scheduler in action, I created a simple example in main.c with two tasks: one recurring every 2 seconds and another that runs once after 5 seconds.</p><pre>#include &quot;task.h&quot;<br>#include &quot;time.h&quot;<br><br>#define TASK_1 (1 &lt;&lt; 0) // ID: 1<br>#define TASK_2 (1 &lt;&lt; 1) // ID: 2<br><br>// Implement system time function<br>uint32_t get_system_time() {<br>  return time();<br>}<br><br>uint32_t task1() {<br>  // Recurring task, every 2 seconds<br>  printf(&quot;hello world!\n&quot;);<br>  return 2000; // Reschedule after 2s<br>}<br><br>uint32_t task2() {<br>  // One-time task<br>  printf(&quot;just once!\n&quot;);<br>  return 0; // No rescheduling<br>}<br><br>int main(void) {<br><br>  // Schedule task1 for 2s from now<br>  task_ensure(TASK_1, 2000, task1);<br>  // Schedule task2 for 5s from now<br>  task_ensure(TASK_2, 5000, task2);<br><br>  while (true) {<br>    // Non-blocking scheduler<br>    task_scheduler();<br>    // Other main loop tasks can go here<br>  }<br>}</pre><p>The output shows the scheduler in action:</p><pre>waits 2s<br>&gt;&gt; &quot;hello world!&quot;<br>waits 2s<br>&gt;&gt; &quot;hello world!&quot;<br>waits 1s (total of 5s)<br>&gt;&gt; &quot;just once!&quot;<br>waits 1s<br>&gt;&gt; &quot;hello world!&quot;<br>every 2s<br>&gt;&gt; &quot;hello world!&quot;</pre><p>This demonstrates the scheduler’s ability to handle both recurring and one-time tasks efficiently, all while staying within the STM32’s tight memory limits. I hope this walk through makes the mission clear</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f55569a973e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pool Memory Allocator in C (Embedded Systems)]]></title>
            <link>https://medium.com/@learn_aryan/pool-memory-allocator-in-c-embedded-systems-22e9f1d0026e?source=rss-86b1f3224d4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/22e9f1d0026e</guid>
            <category><![CDATA[c-language]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Aryan Alikhani]]></dc:creator>
            <pubDate>Wed, 15 Jan 2025 07:09:21 GMT</pubDate>
            <atom:updated>2025-01-15T07:09:21.942Z</atom:updated>
            <content:encoded><![CDATA[<p>In some scenarios, you don’t have the luxury of using malloc or other sophisticated memory allocators. Instead, you’re working with <strong>limited resources</strong>—perhaps only a few kilobytes of RAM—and must allocate and release memory <strong>during runtime</strong> while staying within strict CPU cycle constraints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*kiy8BkL1Z1B4wIJYNxvMiA.png" /></figure><p>There are many categories of memory allocation techniques, and I’ll cover them in detail in future posts. Today, however, I want to focus on the <strong>pool memory allocator</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*yO_ZVulnyt5NdwdonScWNg.png" /><figcaption>program memory structure</figcaption></figure><p>A pool allocator is extremely fast, offering <strong>O(1)</strong> complexity for both allocation and release. It’s particularly well-suited for scenarios where allocations are of a fixed size.</p><p>For instance, imagine working with network packets. These packets are small, typically only a few bytes, and you know they won’t exceed a certain size. In such a case, a pool allocator is a feasible solution. Each time you call allocate, it provides you with a fixed block of memory. When you’re done with the memory, you can release it back to the pool with minimal overhead—often requiring just a few CPU cycles.</p><p>The only downside is that in a <strong>32-bit system architecture</strong>, you waste <strong>4 bytes</strong> per chunk, while in a <strong>64-bit system</strong>, the waste increases to <strong>8 bytes</strong> per chunk.</p><p>This overhead is caused by the need to store metadata, such as pointers or bookkeeping information, to manage the chunks. The size of this metadata is directly tied to the system’s pointer size — <strong>4 bytes</strong> for 32-bit systems and <strong>8 bytes</strong> for 64-bit systems.</p><p>While this overhead might seem negligible for large chunks, it can become significant when managing a large number of small, fixed-size allocations.</p><h3>Pointers &amp;</h3><p>You’ve probably heard many stories about pointers and watched numerous tutorials explaining “internal pointer variables”!<br>Let’s focus on the aspect that interests us most: <strong>memory addresses</strong>.</p><p>In C, <strong>pointers</strong> are essentially memory addresses. The type of data only determines how much memory will be read after the pointer’s address. The compiler handles this automatically based on the pointer’s type.</p><p>For example:</p><pre>// on 32-bit system:<br>void hello() {<br>  // &#39;a&#39; is initialized on the stack at address 0x00000100<br>  uint32_t a = 2;<br>  // Since &#39;a&#39; is of type &#39;int&#39; <br>  // it occupies 4 consecutive memory addresses:  <br>  // 0x00000100, 0x00000101, 0x00000102, 0x00000103<br>  printf(&quot;%x&quot;, &amp;a);<br>}</pre><p>In C, using the <strong>&amp;</strong> operator on a variable allows you to obtain its <strong>memory address</strong>. This gives you a pointer to the variable, which can be used for direct memory manipulation.</p><p>Once you have a <strong>memory address</strong>, you can convert it to a specific type later by dereferencing it with the <strong>*</strong> operator. This tells the compiler to treat the memory at that address as the specified type, allowing you to access or modify the value stored there.</p><p>For example:</p><pre>uint32_t val = 23;<br><br>// get memory address of the variable<br>// ex: 0x00000010<br>size_t address = (size_t)(&amp;val);<br><br>// convert the variable to a byte array<br>// ex: {0x17, 0x00, 0x00, 0x00}<br>uint8_t* bytes = (uint8_t*)(address); <br><br>// get the first byte of the variable<br>// ex: 0x17<br>uint8_t first_byte = *bytes;<br><br>// get the second byte of the variable<br>// ex: 0x00<br>uint8_t second_byte = *(bytes+1);<br></pre><p>In C, strings are essentially pointers to a memory address where the characters are stored consecutively. Unlike some higher-level languages, C does not store the string length explicitly. Instead, strings are terminated by a <strong>null character</strong> (&#39;\0&#39;), which marks the end of the string.</p><p>Functions like strlen work by <strong>manually scanning the string</strong> character by character until they encounter the null terminator. The number of characters scanned (excluding the null terminator) gives the length of the string.</p><p>For example:</p><pre>const char* text = &quot;hello world!&quot;;</pre><p>In this example, the pointer text points to the memory address where the string &quot;hello world!&quot; is stored. If the pointer text is at memory address 0x00000100, then the next 12 bytes will contain the characters &quot;hello world!&quot;, and the <strong>13th byte</strong> will be the <strong>null terminator</strong> (&#39;\0&#39;), which marks the end of the string.</p><p>Since each character typically occupies <strong>1 byte</strong>, we can conclude that the string &quot;hello world!&quot; occupies <strong>13 bytes</strong> in memory. This includes the 12 characters in the string and the null terminator at the end.</p><ul><li>0x00000100 -&gt; &#39;h&#39;</li><li>0x00000101 -&gt; &#39;e&#39;</li><li>0x00000102 -&gt; &#39;l&#39;</li><li>0x00000103 -&gt; &#39;l&#39;</li><li>0x00000104 -&gt; &#39;o&#39;</li><li>0x00000105 -&gt; &#39; &#39;</li><li>0x00000106 -&gt; &#39;w&#39;</li><li>0x00000107 -&gt; &#39;o&#39;</li><li>0x00000108 -&gt; &#39;r&#39;</li><li>0x00000109 -&gt; &#39;l&#39;</li><li>0x0000010A -&gt; &#39;d&#39;</li><li>0x0000010B -&gt; &#39;!&#39;</li><li>0x0000010C -&gt; &#39;\0&#39; (null terminator)</li></ul><h3>Pool Allocator Basics</h3><p>A <strong>pool allocator</strong> is a memory management structure that operates as a <strong>stack that implemented using a linked list</strong>. It works by dividing a pre-allocated block of memory into fixed-size chunks, which can be efficiently managed during runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y-Ran6DEGEVPm_8IMmzkSA.png" /></figure><p>The <strong>pool allocator</strong> itself occupies the first bytes of the given memory space. It primarily consists of a <strong>head</strong>, which is a pointer to the next available chunk. This head acts as the entry point for managing the free list.</p><pre>// pool.h<br>#pragma once<br><br>#include &lt;stdint.h&gt;<br><br>typedef struct pool_t {<br>    struct pool_t *next;<br>} pool_t;<br><br>// given a memory space, create and initialize a memory pool<br>pool_t *pool_create(void *memory_space, uint16_t size, uint8_t object_size);<br><br>// allocate and return the memory address to the user<br>void *pool_alloc(pool_t *self);<br><br>// free the memory, and release it to the pool<br>void pool_free(pool_t *self, void *ptr);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZTsvh4AyTsLiRhkjPRoNIg.png" /></figure><p>Each chunk in the pool follows the same structure:</p><ul><li><strong>Header</strong>: Contains a pointer to the next available chunk in the free list.</li><li><strong>Data Section</strong>: The remaining bytes in the chunk are allocated to the user when the alloc function is called.</li></ul><h4>Create</h4><p>When the pool allocator is created, all chunks are pre-initialized and added to the pool’s free list.</p><pre>// pool.c<br><br>#include &quot;pool.h&quot;<br>#include &lt;stddef.h&gt;<br><br>// simply works as adding an item to a stack<br>void __pool_push(pool_t *self, pool_t *node)<br>{<br>  node-&gt;next = self-&gt;next;<br>  self-&gt;next = node;<br>}<br><br>// create a pool using <br>pool_t *pool_create(void *memory_space, uint16_t size, uint8_t object_size)<br>{<br>  // initialize the first bytes to the pool instance itself<br>  pool_t *self = (pool_t *)(memory_space);<br>  self-&gt;next = NULL;<br><br>  // get the address of the memory space<br>  size_t address = (size_t)memory_space;<br><br>  // initialize a cursor to calculate chunk addresses<br>  size_t cursor = sizeof(pool_t);<br><br>  // actual chunk size, which is the<br>  // block(object) size + the size of its header<br>  size_t chunk_size = object_size + sizeof(pool_t);<br><br>  while (1)<br>  {<br>    // if the next chunk cannot fit into the memory space<br>    // break the loop, that&#39;s enough partitioning for today!<br>    if (cursor + chunk_size &gt; size)<br>      break;<br><br>    // extend the pool chunks with current memory address<br>    __pool_push(self, (pool_t *)(address + cursor));<br><br>    // move the cursor<br>    cursor += chunk_size;<br>  }<br>  return self;<br>}</pre><h4>ALLOC</h4><p>When the alloc function is called, the next available chunk is removed from the pool and passed to the user.</p><pre>// pool.c<br><br>...<br><br><br>// just like you pop an item from a stack<br>// pool pop is a helper function that will do that for you<br>pool_t *__pool_pop(pool_t *self)<br>{<br>  pool_t *node = self-&gt;next;<br>  if (!node)<br>    return NULL;<br>  self-&gt;next = node-&gt;next;<br>  return node;<br>}<br><br><br>// allocate memory and return the reference to the user<br>void *pool_alloc(pool_t *self)<br>{<br>  // pop a chunk from the stack<br>  pool_t *node = __pool_pop(self);<br>  // if it&#39;s null, we&#39;re probably out of memory!<br>  if (!node)<br>    return NULL;<br><br>  // return a valid reference to the data section<br>  return (void *)((size_t)node + sizeof(pool_t));<br>}</pre><p>The tricky part of implementing a pool allocator is passing the reference to the user while ensuring the metadata remains protected.</p><p>The metadata, which is stored in the earliest bytes of each chunk, is essential for managing the pool and must not be overwritten by the user. To prevent this, we ensure that when a reference is passed to the user, it is shifted by the size of the pool header.</p><pre>return (void *)((size_t)node + sizeof(pool_t));</pre><p>This means the pointer provided to the user points directly to the usable memory space, bypassing the metadata.</p><h4>FREE</h4><p>When the free function is called, the chunk is returned to the pool by adding it back to the free list.</p><pre>// pool.c<br><br>...<br><br>// free the allocated memory and return it back to the pool<br>void pool_free(pool_t *self, void *ptr)<br>{<br>  if (!ptr)<br>    return;<br>  // as you remember, we did shift the pointer when alloc function is called<br>  // so we need to shift it back, to access the pool header<br>  pool_t *node = (pool_t *)(ptr - sizeof(pool_t));<br>  // extend the pool with this new available<br>  __pool_push(self, node);<br>}</pre><h3>Caution</h3><p>As you can see, this implementation is <strong>not completely safe</strong>. To prioritize performance and reduce overhead, I intentionally removed many error-handling mechanisms, making it lightweight and suitable for use on microcontrollers with limited resources.</p><p>However, this comes with trade-offs:</p><ul><li><strong>Manual Memory Management</strong>: You need to keep track of all allocated memory and ensure that each allocation is properly deallocated.</li><li><strong>Risk of Memory Leaks</strong>: Any memory not properly deallocated during runtime will result in memory leaks. In the constrained environment of a microcontroller, losing even a few bytes can have catastrophic consequences, potentially causing your application to fail without any way to recover</li></ul><h3>Key Considerations:</h3><ol><li><strong>Careful Deallocation</strong>: Always ensure memory chunks are freed back to the pool as soon as they are no longer needed.</li><li><strong>Error Handling</strong>: If adapting this for a critical system, consider adding basic error-handling mechanisms to track invalid allocations or double frees.</li><li><strong>Testing</strong>: Rigorously test the implementation under various scenarios to ensure stability and reliability, especially in long-running systems.</li></ol><p>This lightweight implementation is ideal for highly constrained environments, but it demands extra caution from developers to avoid runtime issues. In such systems, a disciplined approach to memory management is crucial.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22e9f1d0026e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generics in C]]></title>
            <link>https://medium.com/@learn_aryan/generics-in-c-4e8a0f861a60?source=rss-86b1f3224d4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e8a0f861a60</guid>
            <dc:creator><![CDATA[Aryan Alikhani]]></dc:creator>
            <pubDate>Tue, 14 Jan 2025 18:48:42 GMT</pubDate>
            <atom:updated>2025-01-19T13:49:01.201Z</atom:updated>
            <content:encoded><![CDATA[<p>Generics are a powerful feature in programming languages. They enable developers to write reusable and efficient code without having to duplicate data structures or logic for different types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QjecS3X-QTfGGx2eCNq7CA.jpeg" /></figure><p>Unfortunately, some languages, such as C, lack built-in support for generics. However, this doesn’t mean generic functionality is impossible in C.<br>C is a highly capable language, designed with flexibility and power in mind,</p><h4>Problem</h4><p>In modern programming, generics are almost a necessity. They allow developers to write type-safe and reusable code without sacrificing performance. Without generics, developers are often forced to re-implement the same logic multiple times for different data types, which leads to redundancy and increases the risk of bugs.</p><h4>How C++ compiles templates</h4><p>In C++, the compiler generates specific code for each unique set of template parameters used in a template class instantiation. For example, consider the following template class:</p><pre>template &lt;typename tType, int tCapacity, typename tCompareFunc&gt;<br>class Heap_t<br>{<br>public:<br>  void push(const T&amp; item) {}<br>  T pop() {}<br>  int size() {}<br>private:<br>  tType vector[tCapacity];<br>  int length;<br>};</pre><p>When the template class is instantiated with specific parameters, such as:</p><pre>#define compare_int(a, b) (a-b)<br>Heap_t&lt;int, 32, compare_int&gt; heapInt;<br><br>#define compare_movement(a, b) (a.rank - b.rank)<br>Heap_t&lt;Movement_t, 64, compare_movement&gt; heapDouble;</pre><p>The compiler generates separate versions of the class tailored to the provided types and constants. For instance, it might produce the following equivalent link-able classes for each instantiation:</p><pre>// int implementation<br>class Heap<br>{<br>public:<br>  void push(const int&amp; item) {}<br>  int pop() {}<br>  int size() {}<br>private:<br>  int vector[32];<br>  int length;<br>};<br><br>// Movement implementation<br>class Heap<br>{<br>public:<br>  void push(const Movement_t&amp; item) {}<br>  Movement_t pop() {}<br>  int size() {}<br>private:<br>  Movement_t vector[64];<br>  int length;<br>};</pre><h4>How to implement templates in C</h4><p>Unlike C++, C does not provide a built-in syntax for defining generic classes or templates. However, you can achieve similar functionality using the#define preprocessors. By leveraging the preprocessor, you can define type-specific implementations at compile time, mimicking the behavior of templates.</p><pre>#define __heap_type(t_name) heap_##t_name##_t<br><br>#define MAKE_HEAP(t_name, t_type, t_capacity, t_compare) \<br>  typedef struct {                                       \<br>    t_type vector[t_capacity];                           \<br>    uint16_t length;                                     \<br>  } __heap_type(t_name);<br></pre><p>The process works similarly to C++ template compilation. First, you use the preprocessor to define or “instantiate” the desired type-specific implementation. This approach forces the compiler to generate the corresponding linkable code for the given type.</p><pre>#define compare_int(a, b) (a - b)<br>MAKE_HEAP(maxint, int, 32, compare_int);<br><br><br>heap_maxint_t m_heap;</pre><p>While it lacks the syntactic elegance of C++ templates, it is a powerful workaround for achieving generic programming in C.</p><h4>Implementation of heap DSA in C</h4><pre>#pragma once<br>#include &lt;stdint.h&gt;<br><br>#define __heap_type(t_name) heap_##t_name##_t<br><br>#define __swap(data, i, j)       \<br>  typeof(data[0]) tmp = data[i]; \<br>  data[i] = data[j];             \<br>  data[j] = tmp;<br><br>#define MAKE_HEAP(t_name, t_key, t_cap, t_compare)                                          \<br>  typedef struct                                                                            \<br>  {                                                                                         \<br>    volatile uint16_t length;                                                               \<br>    volatile t_key vector[t_cap];                                                           \<br>  } __heap_type(t_name);                                                                    \<br>  inline static void __heap_##t_name##_sortup(__heap_type(t_name) * self, uint16_t index)   \<br>  {                                                                                         \<br>    while (index &gt; 1)                                                                       \<br>    {                                                                                       \<br>      uint16_t parent = index / 2;                                                          \<br>      int cmp = t_compare(self-&gt;vector[parent - 1], self-&gt;vector[index - 1]);               \<br>      if (cmp &gt; 0)                                                                          \<br>        return;                                                                             \<br>      __swap(self-&gt;vector, index - 1, parent - 1);                                          \<br>      index = parent;                                                                       \<br>    }                                                                                       \<br>    return;                                                                                 \<br>  }                                                                                         \<br>  inline static void __heap_##t_name##_sortdown(__heap_type(t_name) * self, uint16_t index) \<br>  {                                                                                         \<br>    while (index &lt;= self-&gt;length)                                                           \<br>    {                                                                                       \<br>      uint16_t leftIndex = index * 2;                                                       \<br>      uint16_t rightIndex = index * 2 + 1;                                                  \<br>      if (leftIndex &gt; self-&gt;length)                                                         \<br>        return;                                                                             \<br>      uint16_t next = leftIndex;                                                            \<br>      int cmp = t_compare(self-&gt;vector[rightIndex - 1], self-&gt;vector[leftIndex - 1]);       \<br>      if (rightIndex &lt;= self-&gt;length &amp;&amp; cmp &gt; 0)                                            \<br>      {                                                                                     \<br>        next = rightIndex;                                                                  \<br>      }                                                                                     \<br>      cmp = t_compare(self-&gt;vector[index - 1], self-&gt;vector[next - 1]);                     \<br>      if (cmp &gt; 0)                                                                          \<br>        return;                                                                             \<br>      __swap(self-&gt;vector, index - 1, next - 1);                                            \<br>      index = next;                                                                         \<br>    }                                                                                       \<br>  }                                                                                         \<br>  inline static void heap_##t_name##_push(__heap_type(t_name) * self, t_key value)          \<br>  {                                                                                         \<br>    self-&gt;vector[self-&gt;length++] = value;                                                   \<br>    __heap_##t_name##_sortup(self, self-&gt;length);                                           \<br>  }                                                                                         \<br>  inline static t_key heap_##t_name##_pop(__heap_type(t_name) * self)                       \<br>  {                                                                                         \<br>    t_key root = self-&gt;vector[0];                                                           \<br>    self-&gt;vector[0] = self-&gt;vector[--self-&gt;length];                                         \<br>    __heap_##t_name##_sortdown(self, 1);                                                    \<br>    return root;                                                                            \<br>  }                                                                                         \<br>  inline static t_key heap_##t_name##_remove(__heap_type(t_name) * self, uint16_t index)    \<br>  {                                                                                         \<br>    t_key root = self-&gt;vector[index];                                                       \<br>    self-&gt;vector[index] = self-&gt;vector[--self-&gt;length];                                     \<br>    __heap_##t_name##_sortdown(self, index + 1);                                            \<br>    return root;                                                                            \<br>  }</pre><p>example usage:</p><pre>#include &quot;heap.h&quot;<br><br>#define comp(a, b) (a - b)<br>MAKE_HEAP(hello, int, 32, ccomp);<br><br>int main(void)<br>{<br>  heap_hello_t heap = {0};<br>  heap_hello_push(&amp;heap, 123);<br>  heap_hello_push(&amp;heap, 1);<br>  heap_hello_push(&amp;heap, 8);<br>  int a = heap_hello_pop(&amp;heap);<br>  // a is 123<br>}</pre><p>#c #embedded</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e8a0f861a60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Validation in GO made easy]]></title>
            <link>https://medium.com/@learn_aryan/validation-in-go-made-easy-2ade1416f9ca?source=rss-86b1f3224d4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ade1416f9ca</guid>
            <category><![CDATA[web]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Aryan Alikhani]]></dc:creator>
            <pubDate>Tue, 29 Oct 2019 22:41:09 GMT</pubDate>
            <atom:updated>2019-10-29T22:41:09.671Z</atom:updated>
            <content:encoded><![CDATA[<p>This year may be the roughest year I’ve ever had in my entire life, after weeks of developing services and APIs I&#39;ve got time to share some cool stuff with you, this is one of the tools I&#39;ve been used during request validation and messaging in my APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Crdfx0oezFuySqey_4vjtQ.png" /></figure><p>first of all, in every API we develop, we must consider validating user requests in a proper way, not to only validate on frontend but most importantly on backends where actual data going to evaluate.</p><p>I&#39;ve tried many different ways to validate my structs and requests, many of them failed me because of an improper interface or hard way to use, I needed something more flexible and more convenient for a web developer, I do not like to hardcode many lines of code in each API, so I decided to write “vstruct”, this library you see, does all the magic parts for validating a request, so you just need to implement some extra tags beside your JSON tag in your struct, here is a simple example of “v” usage in your structs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb8931b41b3cc7094a7ab46db50e937b/href">https://medium.com/media/bb8931b41b3cc7094a7ab46db50e937b/href</a></iframe><p>as you see, there is no difference between this library and others but this one provides you more than just validating and translate messages for you in a very delightful way! here is the output of validating the above example giving no input to its implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65ba8132307d135134165fd529de2535/href">https://medium.com/media/65ba8132307d135134165fd529de2535/href</a></iframe><p>see, you don&#39;t need to generate error messages yourself, vstruct will generate them for you, here is the code you need:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9d00e53c00c38b498f4188964a80c2a/href">https://medium.com/media/c9d00e53c00c38b498f4188964a80c2a/href</a></iframe><p>just like built-in functions, you can register your own validation rules, and translations, vstruct core supports adding multiple localization and validation rules, you can read more at:</p><p><a href="https://github.com/xeuus/vstruct">xeuus/vstruct</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ade1416f9ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Save and Restore current directory inside Shell]]></title>
            <link>https://medium.com/@learn_aryan/save-and-restore-current-directory-inside-shell-7de1473819c0?source=rss-86b1f3224d4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7de1473819c0</guid>
            <category><![CDATA[mac]]></category>
            <category><![CDATA[shell]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Aryan Alikhani]]></dc:creator>
            <pubDate>Tue, 30 Jul 2019 11:52:35 GMT</pubDate>
            <atom:updated>2019-07-30T11:52:35.695Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*EVOqwyUQ1OuJxXCUmkjcGg.png" /></figure><p>With this simple shell script, you are allowed to save and restore your current directory path.</p><p>every time you open a new terminal it will start from the last directory you left terminal.</p><p>just copy these lines of code into your .bashrc</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a6854e759db22c8af872b0c237c56a5/href">https://medium.com/media/3a6854e759db22c8af872b0c237c56a5/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7de1473819c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native File System — From Scratch]]></title>
            <link>https://medium.com/@learn_aryan/react-native-storage-io-do-we-really-have-to-use-asyncstorage-write-your-own-io-bridge-bb14a86b0418?source=rss-86b1f3224d4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb14a86b0418</guid>
            <category><![CDATA[files]]></category>
            <category><![CDATA[modules]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[storage]]></category>
            <dc:creator><![CDATA[Aryan Alikhani]]></dc:creator>
            <pubDate>Tue, 27 Mar 2018 19:16:25 GMT</pubDate>
            <atom:updated>2018-03-28T14:12:39.245Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YIe9wSDXWlwXgjLK8jUDtw.jpeg" /></figure><blockquote>Do we really have to use AsyncStorage? Write your own FileIO Bridge</blockquote><p>In this tutorial you will learn how to create native modules for ReactNative, how to download a file and how to store it on device, and how to send and store images in gallery on both IOS and Android, although this is not a very detailed tutorial on Java or ObjectiveC but i will try to explain anything when it’s possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xSZAZfFUwPsK3PV5Hv5Yng.jpeg" /></figure><p>My first experience with ReactNative was like, what the heck? what am I supposed to do with this thing, this thing gonna wrap me up, will cuff my hands, and keep me from being free to do anything i like to do, like writing api specific codes or other thing, well you might wonder why do i actually use ReactNative, that’s interesting but we get on to that later, but for this problem I found that I could write native codes to connect my application to outside world (yeah it’s actually like that), well it’s simple, you write native modules on both side on some standards, native modules are like interfaces, you should be careful to write modules on both side with the same function names and same variables to make them available on both IOS and android, it’s not that complicated that i’m saying it is, it is actually so so simple.</p><p>First of all, let me explain something to you, we are going to use “<strong>Base64</strong>” encryption everywhere in our IO streams and data communication between React and our Native Modules, also we are going to use it to display some image on some view.</p><p>In Javascript world we would be very happy to use Base64 strings, the good approach is to download a file as an ArrayBuffer, then convert it to Base64 string, then we could pass it to either Native Modules or to do other things with it. here is an example how:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86a43ad420f4ed65808fba319f0a845c/href">https://medium.com/media/86a43ad420f4ed65808fba319f0a845c/href</a></iframe><h3>[ Part One I ] React Native Application</h3><p>In this part we are going to create a fresh codebase using React Native CLI, let’s initialize a blank React application</p><p>You will need Node, Watchman, the React Native command line interface, and Xcode (on Mac), and I assume you know how to do this on Linux or Windows, but the purpose of this tutorial is to make modules available to both IOS and Android, and since you could only compile ObjectiveC code on MacOS (Jesus, sounds so selfish to me) i decided to explain it, only on mac, so excuse me for this :)</p><pre>brew install node<br>brew install watchman</pre><p>Let me tell you a secret, i use Yarn :) [f**k npm, don’t ask, join the campain]</p><pre>npm install -g yarn</pre><p>And then:</p><pre>yarn global add react-native-cli</pre><p>Then we create project using command line:</p><pre>react-native init iosBridgeModule<br>cd iosBridgeModule &amp;&amp; react-native run-ios</pre><p>Don’t forget to add dependencies:</p><pre>yarn add axios buffer</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XF9DQyvO8frw9rGdZmHdKg.png" /><figcaption>project should be like this :)</figcaption></figure><p>Now lets add some functionality to our app, like when user hit a Button, download task starts and after that, we save downloaded file to phone.</p><p>Edit App.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bebefc34844ff91a11a75fbc11976ee2/href">https://medium.com/media/bebefc34844ff91a11a75fbc11976ee2/href</a></iframe><p>And run it :)</p><pre>react-native run-ios <strong>or </strong>react-native run-android</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*thxZ14mxkn5g6Hns3rmfTA.png" /><figcaption>result should be like this :) and indicator shown up on click while performing download</figcaption></figure><h3>[ Part Two II ] IOS Module</h3><p>Now we’re going to add IOS module, go to [project directory]/ios/ and open ioBridgeModule.xcodeproj using XCode then:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uyy00EwV4mbHGn0HT4mU_w.png" /><figcaption>Objective-C class creation instruction</figcaption></figure><ol><li>right click on the project and create a Group named MyModules then &gt;</li><li>add a new Cocoa Touch Class named FileIO and click next.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*drDAs2fF5T-s3QPxfLHP6g.png" /><figcaption>result should be like this :)</figcaption></figure><p>Now that we have created our classes let’s add it to React Modules, and add a function to determine where to store our files, in IOS there’s a local Documents folder, were gonna use that to store our data:</p><p>inside FileIO.h:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ed89e600fd1ad74d052439ed93e7a6d/href">https://medium.com/media/2ed89e600fd1ad74d052439ed93e7a6d/href</a></iframe><p>and in FileIO.m:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72085e26a44d3861b07fc60bd51de6a9/href">https://medium.com/media/72085e26a44d3861b07fc60bd51de6a9/href</a></iframe><p>Now we want to pass data from Javasrcript to NativeModule, we have to use a special type of functions to do this, unlike resolvePath that we have written before there are other types of methods in ReactNative that allows us to expose native functionality to our application, we use ReactNative predefined macros to do this.</p><p>First approach is to use synchronous methods, they declared using RCT_EXPORT_METHOD and they allow us to send data to module at time, no callback, and no return, like a one way street:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/449a3f9773147d8c2bd624804ec20498/href">https://medium.com/media/449a3f9773147d8c2bd624804ec20498/href</a></iframe><p>and in javascript:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fd1c4b85985538795d7579cc81396e6/href">https://medium.com/media/2fd1c4b85985538795d7579cc81396e6/href</a></iframe><p>Second approach is to use callbacks, we declare them using RCT_EXPORT_METHOD with RCTResponseSenderBlock as argument, in javascript we send a callback function as an argument to function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3dd61e22ef470d635ee4bbbf5ac0aeb/href">https://medium.com/media/d3dd61e22ef470d635ee4bbbf5ac0aeb/href</a></iframe><p>and in javascript:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1606c9c5b6e6dd8879c96dad1434b9a/href">https://medium.com/media/e1606c9c5b6e6dd8879c96dad1434b9a/href</a></iframe><p>Third approach is to use Promise like interface to call our native function, we declare them using RCT_REMAP_METHOD:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b64b81bfc13cf704c447706ac823c112/href">https://medium.com/media/b64b81bfc13cf704c447706ac823c112/href</a></iframe><p>and in javascript:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67d069c2150679c093c628f5e7819ba5/href">https://medium.com/media/67d069c2150679c093c628f5e7819ba5/href</a></iframe><p><strong>[save method]</strong> Now that we understand how bridge methods works, let’s add a save method to store a file to device.</p><p>open FileIO.mand add these lines, saving file to device doesn’t need to be asynchronous unless we want to see if file stored successfully or find out if any error occurred.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7dfe8ae05eb1addc5697519f38763afd/href">https://medium.com/media/7dfe8ae05eb1addc5697519f38763afd/href</a></iframe><p>or synchronously:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf4696d19a0a1874255ddb3a1ff9563e/href">https://medium.com/media/bf4696d19a0a1874255ddb3a1ff9563e/href</a></iframe><p>Now let’s go back to our App.js and use this function to save downloaded file to device:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6220cf043c0d8f2587d8f739a90c9a3/href">https://medium.com/media/b6220cf043c0d8f2587d8f739a90c9a3/href</a></iframe><p>then run it using command line react-native run-ios , then click on “Download” button. you should see “Download Finished!” on the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*nYFMGzodQDzkPtsJMm-PFw.png" /></figure><p>Now lets check if file stored correctly in device storage, Simulator files are located at somewhere on ~/Library/Developer/CoreSimulator/.../Documents/</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vqmmlZe451fzfTSOQGJ5dg.png" /><figcaption>you can see that it’s correctly stored on device :)</figcaption></figure><p>now let’s add some other methods before we get to AndroidModule Instalation. here is full FileIO.h and FileIO.m :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c258d8bcd89165b6fa3ba20e2890106/href">https://medium.com/media/0c258d8bcd89165b6fa3ba20e2890106/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95438edd300287246303f5625771b572/href">https://medium.com/media/95438edd300287246303f5625771b572/href</a></iframe><p>Now we could use these functions too</p><pre>// Sync Functions<br>FileIO.delete(path); // delete file<br>FileIO.saveSync(path, base64); // store Base64 stream</pre><pre>// Async Functions<br>await FileIO.exists(path); // check if file exists<br>await FileIO.path(to); // absolute path to file<br>await FileIO.read(path); // read Base64 file<br>await FileIO.save(path, base64); // store Base64 stream async</pre><h3>[ Part Two III ] Android Module</h3><p>Well it’s time to give our chance to android, we are going to write exact functions on android too, with the same interface like mentioned above.</p><p>First of all open [project directory]/android/ inside AndroidStudio and if you don’t have it, it’s not a problem, you could add Java Classes and gradle will build it for you.</p><p>Now inside /app/src/main/java/com/iobridgemodule/ add two Java Class, one named StorageModule.java and another StoragePackage.java</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*osTbAT0Yc3FFo25j-02dyQ.png" /></figure><p>in StoragePackage.java:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0dae3e6dfde26bf82d337074befb284/href">https://medium.com/media/a0dae3e6dfde26bf82d337074befb284/href</a></iframe><p>and in StorageModule.java:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fa84d83cba80a32228f9d82a0f710b1/href">https://medium.com/media/5fa84d83cba80a32228f9d82a0f710b1/href</a></iframe><p>and one another step, you have to add your Package to Application, now inside MainApplication.java add StoragePackage where getPackages functions declared:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rOi97JH5p0WYh3saPXYgHw.png" /></figure><p>almost done, now you can test your application,</p><p>first run an emulator then cmd react-native run-android :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*rmsCKkLtKEMIRTv3jAMg5A.png" /></figure><h3>[ PART IV ] Load and view information</h3><p>Now what if we wanted to view the information, consider a scenario where you downloaded a picture, you wanted to store it and use it later for offline use, first of all ReactNative is fully capable of showing Base64 images, see example bellow :</p><p>try to make these changes to App.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2575b704464dbb7074864502a44fb8b/href">https://medium.com/media/d2575b704464dbb7074864502a44fb8b/href</a></iframe><h3>Lets see the result :)))))</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wqyYpdfsn6oO1sxdQkczPw.png" /><figcaption>Isn’t this cooool :)</figcaption></figure><h3>[ PART V ] Save Images to Gallery</h3><p>in this part we are going to create some wrapper in both Android and IOS to do such action for us, let’s start with ObjectiveC.</p><p>open FileIO.hand include UIKit.h header, we are going to need it to store images.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80b5102d501bbea7b55b7e7bfc9ce963/href">https://medium.com/media/80b5102d501bbea7b55b7e7bfc9ce963/href</a></iframe><p>then open FileIO.mand add these two functions :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2367e86af0eef153e26d5d78ca0a0c5/href">https://medium.com/media/c2367e86af0eef153e26d5d78ca0a0c5/href</a></iframe><p>now open Info.plistand add these two lines:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9436ac43c257acb827395c4fab4f39a8/href">https://medium.com/media/9436ac43c257acb827395c4fab4f39a8/href</a></iframe><p>or follow these instruction &gt; open Info.plist in Xcode &gt; then add a new key inside “Information Property List” &gt; Search for “Privacy — Photo Library Additions Usage Description” &gt; then were done</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jaOSumR6kBICpZLv7Ii04w.png" /></figure><p>compile application and we done :) hooof</p><p>we’re gonna change App.js again. (don’t kill me) to add a save button, i tried my best to cover everything including this :D</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a562515cb9267b0f4af91f4a89f62ac/href">https://medium.com/media/7a562515cb9267b0f4af91f4a89f62ac/href</a></iframe><p>Now if you run the application and press on “Save” button you see that it get stored on gallery.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ign0tiXdXo5M5A4EHRffw.jpeg" /></figure><p>Now let’s do the same on <strong>android</strong>:</p><p>open StorageModule.java and add these a few lines:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/137dc35877197a160152f9003f7400e2/href">https://medium.com/media/137dc35877197a160152f9003f7400e2/href</a></iframe><p>and don’t forget to give needed permissions to AndroidManifest.xml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b95bc7e375c3163f27484cfa137e9f5/href">https://medium.com/media/0b95bc7e375c3163f27484cfa137e9f5/href</a></iframe><p>Now we’re done, let’s test it :) haha it works, and here’s the screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*3lRWWwIH9XCx6dgg9v7t8w.png" /></figure><p>I think we’re done here, and i have to tell you this was the first Story of mine on Medium, please give me feedback, i do really love to prepare more tutorial for you. and if there are any grammar mistakes please tell me :) my english is awful (kidding)</p><p>here is my GitHub, if you mind to visit:</p><p><a href="https://github.com/xeuus">https://github.com/xeuus</a></p><p>and here is full source code of this tutorial, don’t forget to Star:</p><p><a href="https://github.com/xeuus/native-io-bridge-react-native">https://github.com/xeuus/native-io-bridge-react-native</a></p><p>hahaha, and i love you, see you next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb14a86b0418" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>