<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Igor Proskurin</title>
    <description>The latest articles on DEV Community by Igor Proskurin (@iprosk).</description>
    <link>https://dev.to/iprosk</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1086206%2Fe1a34328-b853-466d-8be3-d769ff59c7b7.jpg</url>
      <title>DEV Community: Igor Proskurin</title>
      <link>https://dev.to/iprosk</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/iprosk"/>
    <language>en</language>
    <item>
      <title>Using GNU toolchain for Windows kernel-mode drivers</title>
      <dc:creator>Igor Proskurin</dc:creator>
      <pubDate>Mon, 03 Nov 2025 05:00:36 +0000</pubDate>
      <link>https://dev.to/iprosk/using-gnu-toolchain-for-windows-kernel-mode-drivers-5cfd</link>
      <guid>https://dev.to/iprosk/using-gnu-toolchain-for-windows-kernel-mode-drivers-5cfd</guid>
      <description>&lt;p&gt;For a long time, I was curious about using GNU toolchain on Windows platforms, especially when it boils down to kernel-mode driver development. I like GNU toolchain (binutils, gcc, libstdc++). I use it for embedded development, but compiling, and especially linking binaries with GNU ld linker, has always been tricky. Why is it important? Microsoft Visual Studio is an excellent tool, but it is kind of obscure what is happening behind the scenes. Having free and open-source software toolchain even on a proprietary platform is a good thing (and avoid all the bloat from Visual Studio).&lt;/p&gt;

&lt;p&gt;This time, it took me a while to figure out how to link a trivial kernel-mode driver, and this brief post is to document these findings.&lt;/p&gt;

&lt;p&gt;Compiling GCC from sources for the mingw-w64 target is a topic for a different post (binutils is easy, though). So for these experiments I just used &lt;a href="https://www.msys2.org/" rel="noopener noreferrer"&gt;MSYS2&lt;/a&gt; with UCRT64 environment. This painlessly bring you startup libraries (CRT), C standard library (mingw-w64), and compiler support libraries (libgcc and friends) together with libstdc++ if you use C++.&lt;/p&gt;

&lt;p&gt;Running kernel-mode drivers on Windows requires a bunch of tricks (disabling secure boot, enabling test signing, and installing &lt;a href="https://learn.microsoft.com/en-us/sysinternals/downloads/sysinternals-suite" rel="noopener noreferrer"&gt;sysinternals&lt;/a&gt;). If you are not familiar with it, read a few introductory chapters from &lt;a href="https://www.amazon.ca/Windows-Kernel-Programming-Pavel-Yosifovich/dp/B0BW2X91L2" rel="noopener noreferrer"&gt;Windows Kernel Programming&lt;/a&gt;, or message me in the comments, and I will update this post with some details.&lt;/p&gt;

&lt;h1&gt;
  
  
  Driver Hello World
&lt;/h1&gt;

&lt;p&gt;This is a typical "Hello World!" example for Windows kernel-mode drivers:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight c"&gt;&lt;code&gt;&lt;span class="cp"&gt;#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;ntddk.h&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
&lt;/span&gt;
&lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;test_driver_unload&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;PDRIVER_OBJECT&lt;/span&gt; &lt;span class="n"&gt;driverObject&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="n"&gt;NTSTATUS&lt;/span&gt; 
&lt;span class="nf"&gt;DriverEntry&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;PDRIVER_OBJECT&lt;/span&gt; &lt;span class="n"&gt;driverObject&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;PUNICODE_STRING&lt;/span&gt; &lt;span class="n"&gt;registryPath&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;UNREFERENCED_PARAMETER&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;registryPath&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="n"&gt;DbgPrint&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Sample driver initialized successfully&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="n"&gt;driverObject&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;DriverUnload&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;test_driver_unload&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;STATUS_SUCCESS&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kt"&gt;void&lt;/span&gt;
&lt;span class="nf"&gt;test_driver_unload&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;PDRIVER_OBJECT&lt;/span&gt; &lt;span class="n"&gt;driverObject&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;UNREFERENCED_PARAMETER&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;driverObject&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="n"&gt;DbgPrint&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Driver unload called&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For tracing purposes, &lt;code&gt;DbgPrint&lt;/code&gt; is provided by &lt;code&gt;ntoskrnl.exe&lt;/code&gt;. &lt;code&gt;DriverEntry&lt;/code&gt; is our entry point to the driver that is called by the kernel. &lt;code&gt;test_driver_unload&lt;/code&gt; is our custom callback that should be called when the module is unloaded.&lt;/p&gt;

&lt;h1&gt;
  
  
  Using GNU ld for linking
&lt;/h1&gt;

&lt;p&gt;Compiling into object code is easy, but linking is tricky. For reference of possible options, I used an example from &lt;a href="https://reactos.org/" rel="noopener noreferrer"&gt;ReactOS&lt;/a&gt; project. ReactOS is the only working (sort of) full reverse-engineered NT operating system kernel. It is a cool project. ReactOS &lt;a href="https://github.com/reactos/reactos/tree/master/drivers" rel="noopener noreferrer"&gt;GitHub repo&lt;/a&gt; has a collection of build options for kernel-mode drivers that can be carved out of CMake files.&lt;/p&gt;

&lt;p&gt;Unfortunately, with options from ReactOs, I could not make my example fully working 64-bit Windows 11 -- driver loaded but refused to unload. The next repo that helped me with a list of options was &lt;a href="https://github.com/utoni/mingw-w64-dpp/" rel="noopener noreferrer"&gt;Mingw64 Driver Plus Plus&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Finally, this combination of options provided a loadable and unloadable image:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;gcc -std=gnu99 -Wall -Wextra -pedantic -shared -fPIC\
   -O0 -municode -nostartfiles -nostdlib -nodefaultlibs\
   -I/ucrt64/include/ddk -Wl,-subsystem,native \
   -Wl,--exclude-all-symbols,-file-alignment=0x200,-section-alignment=0x1000 \
   -Wl,-entry,DriverEntry -Wl,-image-base,0x140000000\
   -Wl,--dynamicbase -Wl,--nxcompat -Wl,--gc-sections\
   -Wl,--stack,0x100000\
   -o test_driver.sys test_driver.c -lntoskrnl
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First time, I was also using &lt;code&gt;-Wl,--wdmdriver&lt;/code&gt; options, but it was not helping. This mess can be organized in a Makefile:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;TARGET = test_driver
OPT = -O0
CSTANDARD = -std=gnu99
DDK_INCLUDE_PATH = /ucrt64/include/ddk

CC = gcc
LD = ld
RM = rm -f
STRIP = strip
OBJDUMP = objdump -x

CFLAGS += -Wall
CFLAGS += -Wextra
CFLAGS += -pedantic
CFLAGS += -municode
CFLAGS += $(CTANDARD)
CFLAGS += $(OPT)

# Do not link startup, compiler support
# or C standard libraries.
CFLAGS += -nostartfiles
CFLAGS += -nostdlib
CFLAGS += -nodefaultlibs

CFLAGS += -fPIC
CFLAGS += -shared

# Include path to ntddk.h or wdm.h.
CFLAGS += -I$(DDK_INCLUDE_PATH)

LDFLAGS  = --exclude-all-symbols
LDFLAGS += --gc-sections
LDFLAGS += --dynamicbase
LDFLAGS += --nxcompat

LDFLAGS += -subsystem=native
LDFLAGS += -file-alignment=0x200
LDFLAGS += -section-alignment=0x1000
LDFLAGS += -image-base=0x140000000
LDFLAGS += --stack=0x100000

LDFLAGS +=-entry=DriverEntry

SRC = $(TARGET).c

OBJ = $(SRC:%.c=%.o)

LIBS  = -lntoskrnl
LIBS += -lhal

all: sys strip dump

dump: strip
    $(OBJDUMP) $(TARGET).sys

strip: sys
    $(STRIP) $(TARGET).sys

sys: $(TARGET).sys

.SECONDARY: $(TARGET).sys
.PRECIOUS: $(OBJ)

$(TARGET).sys: $(OBJ) 
    $(LD) $(LDFLAGS) -o $@ $(OBJ) $(LIBS)

%.o: %.c
    $(CC) $(CFLAGS) -c $&amp;lt; -o $@

clean:
    $(RM) $(TARGET).sys
    $(RM) $(SRC:%.c=%.o)

.PHONY: all sys clean strip dump
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This Makefile can be found in my GitHub repo &lt;a href="https://github.com/sciprosk/kmd_mingw32" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h1&gt;
  
  
  Loading and unloading
&lt;/h1&gt;

&lt;p&gt;On Windows 11, the driver also requires signing (using a Visual Studio tool). This is easy:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;PS C:\Users\Igor&amp;gt; signtool sign /v /fd sha256 /n WDKTestCert test_driver.sys
The following certificate was selected:
    Issued to: WDKTestCert Igor,133660689149334675
    Issued by: WDKTestCert Igor,133660689149334675
    Expires:   Thu Jul 20 16:00:00 2034
    SHA1 hash: E76CFF2C68E75A85631906D4BC2F55A6D7B32597

Done Adding Additional Store
Successfully signed: test_driver.sys

Number of files successfully Signed: 1
Number of warnings: 0
Number of errors: 0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After that, we can use Service Control utility (it is also easy to write a custom loader based on Service Manager API):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sc create test_driver type= kernel binPath= C:\Users\Igor\test_driver.sys
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Which creates a record in &lt;code&gt;\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\test_driver&lt;/code&gt;. After that, the driver can be started and stopped (and deleted if necessary):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;PS C:\Users\Igor&amp;gt; sc start test_driver

SERVICE_NAME: test_driver
        TYPE               : 1  KERNEL_DRIVER
        STATE              : 4  RUNNING
                                (STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN)
        WIN32_EXIT_CODE    : 0  (0x0)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x0
        PID                : 0
        FLAGS              :

PS C:\Users\Igor&amp;gt; sc stop test_driver

SERVICE_NAME: test_driver
        TYPE               : 1  KERNEL_DRIVER
        STATE              : 1  STOPPED
        WIN32_EXIT_CODE    : 0  (0x0)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The debug output (has to be enabled in the registry) shows tracing messages.&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Feccyfsqudcxhe7oxslnc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Feccyfsqudcxhe7oxslnc.png" alt=" " width="594" height="128"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Summary
&lt;/h1&gt;

&lt;p&gt;It is possible to link a simple Windows kernel-mode driver using GNU toolchain (mingw32-w64). For reference, source code for this example can be found in my GitHub repo &lt;a href="https://github.com/sciprosk/kmd_mingw32" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>microsoft</category>
      <category>tutorial</category>
      <category>c</category>
      <category>opensource</category>
    </item>
    <item>
      <title>Generics in Rust: murky waters of implementing foreign traits on foreign types</title>
      <dc:creator>Igor Proskurin</dc:creator>
      <pubDate>Tue, 04 Jun 2024 03:11:12 +0000</pubDate>
      <link>https://dev.to/iprosk/generics-in-rust-murky-waters-of-implementing-foreign-traits-on-foreign-types-584n</link>
      <guid>https://dev.to/iprosk/generics-in-rust-murky-waters-of-implementing-foreign-traits-on-foreign-types-584n</guid>
      <description>&lt;p&gt;This post is about what bothered me for a while in generic Rust before I could clarify what's going on (sort of), namely, implementing &lt;em&gt;foreign trait on foreign types&lt;/em&gt;, especially, in the context of Rust's way of "operator overloading".&lt;/p&gt;

&lt;h2&gt;
  
  
  We can't do it, or can we?
&lt;/h2&gt;

&lt;p&gt;First, there is no mystery, right? &lt;a href="https://doc.rust-lang.org/book/ch10-02-traits.html" rel="noopener noreferrer"&gt;The Rust Book&lt;/a&gt; is pretty clear on this matter.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;But we can’t implement external traits on external types. For example, we can’t implement the Display trait on &lt;code&gt;Vec&amp;lt;T&amp;gt;&lt;/code&gt; within our aggregator crate, because Display and &lt;code&gt;Vec&amp;lt;T&amp;gt;&lt;/code&gt; are both defined in the standard library and aren’t local to our &lt;code&gt;aggregator&lt;/code&gt; crate. This restriction is part of a property called coherence, and more specifically the orphan rule, so named because the parent type is not present.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;So if we try to write something like this in the Playground:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;impl From&amp;lt;usize&amp;gt; for f64 {
    // -- snippet --
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;the compiler immediately reminds us about this &lt;em&gt;orphan rule&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;error[E0117]: only traits defined in the current crate can be implemented for primitive types
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Nice and clear! Now, if we replace these lines with generics, the compiler error is different (and in a "slight" logical contradiction with the first error message), which hint that something is not so simple as advertised&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;impl&amp;lt;T, U&amp;gt; From&amp;lt;T&amp;gt; for U {
    // -- snippet --
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;error[E0210]: type parameter `U` must be used as the type parameter for some local type (e.g., `MyStruct&amp;lt;U&amp;gt;`)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When we look into a detailed explanation of &lt;code&gt;error[E0210]&lt;/code&gt;, we find our intuition was right:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;When implementing a foreign trait for a foreign type, the trait must have one or more type parameters. A type local to your crate must appear before any use of any type parameters.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;So we can do it in Rust, can't we? But what about &lt;a href="https://doc.rust-lang.org/book/ch10-02-traits.html" rel="noopener noreferrer"&gt;The Book&lt;/a&gt;? &lt;/p&gt;

&lt;h2&gt;
  
  
  How can &lt;code&gt;nalgebra&lt;/code&gt; do it?
&lt;/h2&gt;

&lt;p&gt;Looking into reputable library crates such &lt;code&gt;nalgebra&lt;/code&gt; also raises questions. Let's try, for example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use nalgebra::Vector3;

fn main() {
   let v = Vector3::new(1.0, 2.0, 3.0);
   println!("{:?}", v * 3.0);
   println!("{:?}", 3.0 * v);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It compiles and produces what's expected, and everything look alight. But how is that possible?&lt;/p&gt;

&lt;p&gt;The first expression is, of course, pretty standard: &lt;code&gt;v * 3.0&lt;/code&gt; requires implementing &lt;code&gt;std::ops::Mul&amp;lt;f64&amp;gt;&lt;/code&gt; trait with &lt;code&gt;Output = Vector3&lt;/code&gt; on &lt;code&gt;Vector3&lt;/code&gt;. However, &lt;code&gt;3.0 * v&lt;/code&gt; requires &lt;code&gt;std::ops::Mul&amp;lt;Vector3&amp;gt;&lt;/code&gt; on the build-in type &lt;code&gt;f64&lt;/code&gt;, which is nothing but &lt;em&gt;implementing a foreign trait on a foreign type&lt;/em&gt; in direct violation of the &lt;a href="https://doc.rust-lang.org/book/ch10-02-traits.html" rel="noopener noreferrer"&gt;The Book&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Looking into the &lt;a href="https://github.com/dimforge/nalgebra/blob/dev/src/base/ops.rs" rel="noopener noreferrer"&gt;&lt;code&gt;nalgebra&lt;/code&gt; source code&lt;/a&gt;, we find that the first expression  is implemented using generics&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;macro_rules! componentwise_scalarop_impl(
    ($Trait: ident, $method: ident, $bound: ident;
     $TraitAssign: ident, $method_assign: ident) =&amp;gt; {
        impl&amp;lt;T, R: Dim, C: Dim, S&amp;gt; $Trait&amp;lt;T&amp;gt; for Matrix&amp;lt;T, R, C, S&amp;gt;
            where T: Scalar + $bound,
                  S: Storage&amp;lt;T, R, C&amp;gt;,
                  DefaultAllocator: Allocator&amp;lt;T, R, C&amp;gt; {
                //
                // -- snippet --
                //
            }
        }  
    }
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The macro declaration is not so important in this case. More important is that right-multiplication by a scalar is generic, and all metavariables in the macro pattern simply bind to identifies. &lt;/p&gt;

&lt;p&gt;Left multiplication by a scalar is completely different. It is not generic, macro pattern matcher binds to types with repletion patterns&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;macro_rules! left_scalar_mul_impl(
    ($($T: ty),* $(,)*) =&amp;gt; {$(
        impl&amp;lt;R: Dim, C: Dim, S: Storage&amp;lt;$T, R, C&amp;gt;&amp;gt; Mul&amp;lt;Matrix&amp;lt;$T, R, C, S&amp;gt;&amp;gt; for $T
            // -- snippet --
    )*}
);

left_scalar_mul_impl!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize, f32, f64);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The last line explicitly instantiates implementations for built-in types.&lt;/p&gt;

&lt;p&gt;So why is it different?&lt;/p&gt;

&lt;h2&gt;
  
  
  We can do what we can't
&lt;/h2&gt;

&lt;p&gt;Finally, I found the answer in the &lt;a href="https://rust-lang.github.io/rfcs/" rel="noopener noreferrer"&gt;RFC Book&lt;/a&gt; (RFC stands for Request For Comments). &lt;br&gt;
&lt;a href="https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html" rel="noopener noreferrer"&gt;RFC 2451&lt;/a&gt; from 2018-05-30 that starts with the following lines:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;For better or worse, we allow implementing foreign traits for foreign types.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;That's it! That's the answer. &lt;/p&gt;

&lt;p&gt;Then it becomes more interesting:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;This change isn’t something that would end up in a guide, and is mostly communicated through error messages. The most common one seen is E0210. The text of that error will be changed to approximate the following:&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Then follows the details of E0210 that I have already mentioned above. Together  with &lt;a href="https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html" rel="noopener noreferrer"&gt;RFC 2451&lt;/a&gt; it clarifies a little bit when we can implement foreign traits for foreign types and when we cannon. One more details from these documents:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;When implementing a foreign trait for a foreign type, the trait must have one or more type parameters. A type local to your crate must appear before any use of any type parameters. This means that impl ForeignTrait, T&amp;gt; for ForeignType is valid, but impl ForeignTrait&amp;gt; for ForeignType is not.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This works in the following example for left-scalar multiplication from my little library of generic Bezier curves that I used for illustration in &lt;a href="https://dev.to/iprosk/generics-in-rust-visualizing-bezier-curves-in-a-jupyter-notebook-part-3-565n"&gt;previous posts&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;impl&amp;lt;T, const N: usize&amp;gt; Mul&amp;lt;Bernstein&amp;lt;T, f64, {N}&amp;gt;&amp;gt; for f64 where
            T: Copy + Mul&amp;lt;f64, Output = T&amp;gt;,
            [(); N]:
{
    // -- snippet --
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example a foreign trait &lt;code&gt;std::ops::Mul&amp;lt;T&amp;gt;&lt;/code&gt; specialized on a local generic type &lt;code&gt;Bernstein&amp;lt;T, U, N&amp;gt;&lt;/code&gt; is implemented for a foreign type &lt;code&gt;f64&lt;/code&gt; similar to example above with &lt;code&gt;left_scalar_mul_impl&lt;/code&gt; from &lt;code&gt;nalgebra&lt;/code&gt; crate. Purely generic variant of this implementation&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;impl&amp;lt;T, U, const N: usize&amp;gt; Mul&amp;lt;Bernstein&amp;lt;T, U, {N}&amp;gt;&amp;gt; for U where
            T: Copy + Mul&amp;lt;U, Output = T&amp;gt;,
            U: Copy,
            [(); N]:
{
    type Output = Bernstein&amp;lt;T, U, {N}&amp;gt;;

    fn mul(self, rhs: Bernstein&amp;lt;T, U, {N}&amp;gt;) -&amp;gt; Self::Output {
        // -- snippet --
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;gives already familiar compiler error &lt;a href="https://doc.rust-lang.org/error_codes/E0210.html" rel="noopener noreferrer"&gt;E0210&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;We can implement foreign traits on foreign types in Rust with caveats. However, this behavior is not in &lt;a href="https://doc.rust-lang.org/book/ch10-02-traits.html" rel="noopener noreferrer"&gt;The Rust Book&lt;/a&gt; yet, and is communicated mostly through &lt;a href="https://doc.rust-lang.org/error_codes/E0210.html" rel="noopener noreferrer"&gt;E0210&lt;/a&gt; and &lt;a href="https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html" rel="noopener noreferrer"&gt;RFCs&lt;/a&gt;. Pure generics do not work, which, according to &lt;a href="https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html" rel="noopener noreferrer"&gt;RFC 2451&lt;/a&gt;, looks like a technical difficulty that may be revised in the future.&lt;/p&gt;

</description>
      <category>rust</category>
      <category>generics</category>
      <category>numeric</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Generics in Rust: visualizing Bezier curves in a Jupyter notebook -- Part 3</title>
      <dc:creator>Igor Proskurin</dc:creator>
      <pubDate>Fri, 31 May 2024 04:48:27 +0000</pubDate>
      <link>https://dev.to/iprosk/generics-in-rust-visualizing-bezier-curves-in-a-jupyter-notebook-part-3-565n</link>
      <guid>https://dev.to/iprosk/generics-in-rust-visualizing-bezier-curves-in-a-jupyter-notebook-part-3-565n</guid>
      <description>&lt;p&gt;I decided to write a series posts about my experience with generic Rust, basically just to leave a trace of bread crumbs in my scattered studies. As a small practical problem, I chose to implement a library for manipulating generic Bezier curves that would work with different types and would wrap around primitive stack allocated arrays without dynamic binding and heap allocations. Here, there are some artefacts:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://dev.to/iprosk/experimenting-with-generics-in-rust-little-library-for-bezier-curves-part-1-4093"&gt;Experimenting with generics in Rust: little library for Bezier curves - part 1&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://dev.to/iprosk/generics-in-rust-little-library-for-bezier-curves-part-2-2cpi"&gt;Generics in Rust: little library for Bezier curves -- Part 2&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;and &lt;a href="https://github.com/sciprosk/bernstein" rel="noopener noreferrer"&gt;GitHub repository&lt;/a&gt; with source code and some examples.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In this post, I would briefly outline steps to visualize Bezier curves from my library by using Rust from a Jupyter notebook with Plotters. &lt;/p&gt;

&lt;p&gt;Jupyter notebooks really &lt;a href="https://www.nature.com/articles/d41586-018-07196-1" rel="noopener noreferrer"&gt;revolutionized&lt;/a&gt; not only data science but scientific computing in general. Conceived originally for REPL (read-eval-print-loop) languages such as Julia, Python, and R, Jupyter notebooks are &lt;a href="https://github.com/jupyter-xeus/xeus-cling" rel="noopener noreferrer"&gt;available now even for C++11&lt;/a&gt;, and, of course, Rust is not an exception.&lt;/p&gt;

&lt;h2&gt;
  
  
  First comes REPL - evxvr
&lt;/h2&gt;

&lt;p&gt;A project for Rust REPL environment is a combination of letter &lt;code&gt;evxvr&lt;/code&gt; (Evaluation Context for Rust). It contains &lt;a href="https://github.com/evcxr/evcxr/blob/main/evcxr_jupyter/README.md" rel="noopener noreferrer"&gt;Evcxr Jupyter kernel&lt;/a&gt;. I chose to follow the documentation and compile Jupyter kernel from Rust sources (which takes about 6 min on my laptop), and simply run in Microsoft Windows PowerShell&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cargo install --locked evcxr_jupyter
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This compiles the binary that can be found in &lt;code&gt;$HOME\.cargo\bin&lt;/code&gt;. I already have Jupyter server installed as part of my &lt;a href="https://www.anaconda.com/" rel="noopener noreferrer"&gt;Anaconda&lt;/a&gt; Python bundle. So after that, simply run&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;evcxr_jupyter --install
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And that's all. Now, when I start Jupyter Server, I can choose Rust kernel, and use it from an interactive environment.&lt;/p&gt;

&lt;p&gt;My overall impression from Rust notebooks is that they feel less smooth than, for example, Python notebooks (not surprising), but its pretty usable. Some extra work should be done to implement &lt;a href="https://github.com/evcxr/evcxr/tree/main/evcxr_jupyter#custom-output" rel="noopener noreferrer"&gt;custom output&lt;/a&gt; for user-defined types.&lt;/p&gt;

&lt;h2&gt;
  
  
  Adding external dependencies
&lt;/h2&gt;

&lt;p&gt;It is easy to add external dependencies directly to the Jupyter notebook. I just add the following lines to a notebook cell&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;:dep plotters = { version = "^0.3.0", default_features = false, features = ["evcxr", "all_series"] }
:dep num = {version = "0.4.3"}
:dep bernstein = { git = "https://github.com/sciprosk/bernstein.git" }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and then run it. It takes some visible time to run it for the first time, but after that it is fast. The last line adds my little library for Bezier curves directly from GitHub repo. Then I can put the following code into the next cell, and it works.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use bernstein::Bernstein;
use num::Complex;
use num::FromPrimitive;
use std::array;

// Create 2D Bezier control polygon in the complex plane
let p0 = Complex::new(0.0, 0.0);
let p1 = Complex::new(2.5, 1.0);
let p2 = Complex::new(-0.5, 1.0);
let p3 = Complex::new(2.0, 0.0);

// 2D Bezier curve in the complex plane parameterized with f32
let c: Bernstein&amp;lt;Complex&amp;lt;f32&amp;gt;, f32, 4&amp;gt; = Bernstein::new([p0, p1, p2, p3]);

// Just sample some points on the curve into array
let cs:[_; 11] = array::from_fn(
    |x| -&amp;gt; Complex&amp;lt;f32&amp;gt; {
        c.eval(f32::from_usize(x).unwrap() / 10.0)
    }
);

println!("{:?}", cs);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Plotting with Plotters
&lt;/h2&gt;

&lt;p&gt;One of the crates that integrates evcxr is Plotters, which is used for ...  well, &lt;a href="https://en.wikipedia.org/wiki/Lapalissade" rel="noopener noreferrer"&gt;you already know it&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Plotters can use different backends, and one them is &lt;code&gt;evcxr_figure&lt;/code&gt; that allows to draw directly to the Jupyter notebook cells. The syntax is mostly self-explanatory.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use plotters::prelude::*;

let figure = evcxr_figure((800, 640), |root| {
    root.fill(&amp;amp;WHITE)?;
    let mut chart = ChartBuilder::on(&amp;amp;root)
        .caption("Cubic Bezier", ("Arial", 30).into_font())
        .margin(5)
        .x_label_area_size(30)
        .y_label_area_size(30)
        .build_cartesian_2d(-0.2f32..2.1f32, -0.8f32..0.8f32)?;

    chart.configure_mesh().draw()?;

    // Cubic Bezier curve
    chart.draw_series(LineSeries::new(
        // Sample 20_000 points
        (0..=20000).map(|x| x as f32 / 20000.0).map(|x| (c.eval(x).re, c.eval(x).im)),
        &amp;amp;RED,
    )).unwrap()
        .label("Cubic Bezier")
        .legend(|(x,y)| PathElement::new(vec![(x,y), (x + 20,y)], &amp;amp;RED));

    // Derivative, scaled down
    chart.draw_series(LineSeries::new(
        // Sample 20_000 points
        (0..=20000).map(|x| x as f32 / 20000.0).map(|x| (0.2 * c.diff().eval(x).re, 0.2 * c.diff().eval(x).im)),
        &amp;amp;BLUE,
    )).unwrap()
        .label("Derivative")
        .legend(|(x,y)| PathElement::new(vec![(x,y), (x + 20,y)], &amp;amp;BLUE));

    chart.configure_series_labels()
        .background_style(&amp;amp;WHITE.mix(0.8))
        .border_style(&amp;amp;BLACK)
        .draw()?;
    Ok(())
});
figure
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This creates a 800x600 figure, fills it with white, sets the ranges to &lt;code&gt;-0.2f32..2.1f32&lt;/code&gt; along the horizontal axis, and to &lt;code&gt;-0.8f32..0.8f32&lt;/code&gt; along the vertical axis, and finally samples 20000 points of the cubic Bezier curve and its parametric derivative (which is a quadratic Bezier curve -- scaled down to fit).&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fo5ypbuv3wg1a63yyn5ea.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fo5ypbuv3wg1a63yyn5ea.png" alt=" " width="800" height="579"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;Interactive Rust is easy to install and straightforward to use. It requires more typing (sometimes struggling) than when using REPL in &lt;a href="https://en.wikipedia.org/wiki/Duck_typing" rel="noopener noreferrer"&gt;duck typed&lt;/a&gt; languages, which is a price of strong (and strict) type system. However, it is a cool tool for data visualization directly from Rust.&lt;/p&gt;

</description>
      <category>rust</category>
      <category>beginners</category>
      <category>jupyter</category>
      <category>numeric</category>
    </item>
    <item>
      <title>Generics in Rust: little library for Bezier curves -- Part 2</title>
      <dc:creator>Igor Proskurin</dc:creator>
      <pubDate>Mon, 27 May 2024 14:10:20 +0000</pubDate>
      <link>https://dev.to/iprosk/generics-in-rust-little-library-for-bezier-curves-part-2-2cpi</link>
      <guid>https://dev.to/iprosk/generics-in-rust-little-library-for-bezier-curves-part-2-2cpi</guid>
      <description>&lt;p&gt;Some time ago, I decided to write a couple of posts about my experience with &lt;a href="https://en.wikipedia.org/wiki/Generic_programming" rel="noopener noreferrer"&gt;generic programming&lt;/a&gt; in Rust. For me, when someone says generics, &lt;a href="https://en.cppreference.com/w/cpp/language/template_metaprogramming" rel="noopener noreferrer"&gt;C++ template metaprogramming&lt;/a&gt; and &lt;a href="https://en.wikipedia.org/wiki/Alexander_Stepanov" rel="noopener noreferrer"&gt;Alexander Stepanov&lt;/a&gt; immediately pop in my mind. Rust is different. So it was interesting to see what's going on out there, which motivated my original interest.&lt;/p&gt;

&lt;p&gt;Learning by doing is the best for quick hands-on, so I decided to write a little generic numeric library for manipulating &lt;a href="https://en.wikipedia.org/wiki/B%C3%A9zier_curve" rel="noopener noreferrer"&gt;Bezier curves&lt;/a&gt; (polynomials in the &lt;a href="https://en.wikipedia.org/wiki/Bernstein_polynomial" rel="noopener noreferrer"&gt;Bernstein basis&lt;/a&gt;) that is (i) uses static dispatch (and no heap allocation calls), and (ii) can be used with different types for specifying Bezier control polygon: reals, rationals, complex, and, in general, something that implements standard vector-space operations.&lt;/p&gt;

&lt;p&gt;What I &lt;a href="https://dev.to/iprosk/experimenting-with-generics-in-rust-little-library-for-bezier-curves-part-1-4093"&gt;learned&lt;/a&gt; is that writing generic libraries in Rust is not a piece of cake. There are two major facts that contribute into this: (i) Rust's explicit safety-oriented type system, and (ii) the absence of decent support of generic constant expressions in stable Rust. So what I am writing about here is based on Rust Nightly.&lt;/p&gt;

&lt;p&gt;So before we take of, there is a couple of previous posts&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://dev.to/iprosk/generic-constant-expressions-a-future-bright-side-of-nightly-rust-3bp7"&gt;Generic constant expressions: a future bright side of nightly Rust&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://dev.to/iprosk/experimenting-with-generics-in-rust-little-library-for-bezier-curves-part-1-4093"&gt;Experimenting with generics in Rust: little library for Bezier curves - part 1&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;And the &lt;a href="https://github.com/sciprosk/bernstein" rel="noopener noreferrer"&gt;Github repo&lt;/a&gt; that contains examples from these posts, some tests, and maybe even some demos, if I will manage to add them in nearby future.&lt;/p&gt;

&lt;h2&gt;
  
  
  First steps
&lt;/h2&gt;

&lt;p&gt;First, make sure we use the unstable rust build. I will just set it up for all repositories with &lt;code&gt;rustup default nightly&lt;/code&gt;, but it is possible to apply it to a folder with &lt;code&gt;rustup override set nightly&lt;/code&gt;. After that:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;PS &amp;gt; rustc --version
rustc 1.80.0-nightly (1ba35e9bb 2024-05-25)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and we also make sure that we include the following lines in our crate&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#![allow(incomplete_features)]
#![feature(generic_const_exprs)]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As I briefly outlined &lt;a href="https://dev.to/iprosk/generic-constant-expressions-a-future-bright-side-of-nightly-rust-3bp7"&gt;here&lt;/a&gt;, Rust currently does not support generic constant expression in its type system. It is not that something is wrong with it in general, it is just not implemented due to &lt;a href="https://hackmd.io/OZG_XiLFRs2Xmw5s39jRzA" rel="noopener noreferrer"&gt;technical difficulties&lt;/a&gt;. This is considered to be an unstable feature.&lt;/p&gt;

&lt;p&gt;To describe a generic Bezier curve &lt;code&gt;c(u) = (x(u), y(u), z(u), ...)&lt;/code&gt;, I basically wrap a primitive array type &lt;code&gt;[T; N]&lt;/code&gt; into a struct&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pub struct Bernstein&amp;lt;T, U, const N: usize&amp;gt; {
    coef: [T; N],
    segm: (U, U),
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;that contains a generic type parameter &lt;code&gt;T&lt;/code&gt; for Bezier control polygon,  type parameter &lt;code&gt;U&lt;/code&gt; for curve parametrization, and a generic constexpression parameter &lt;code&gt;N&lt;/code&gt; for the number of basis polynomials (or just the size of the Bezier control polygon). For example, a cubic Bezier curve should have four points in its control polygon, i. e. &lt;code&gt;N = 4&lt;/code&gt;. The curve is always parameterized on &lt;code&gt;0 &amp;lt;= u &amp;lt;= 1&lt;/code&gt;, so right now &lt;code&gt;segm&lt;/code&gt; is defaulted to &lt;code&gt;(0, 1)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Some more details can be found in my &lt;a href="https://dev.to/iprosk/experimenting-with-generics-in-rust-little-library-for-bezier-curves-part-1-4093"&gt;previous post&lt;/a&gt;. In this post, I would like to discuss how implement generic methods on this type that would leverage generic constant expressions on the size of the control polygon &lt;code&gt;N&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Implementing eval-method
&lt;/h2&gt;

&lt;p&gt;The first method to do is, of course, to implement &lt;code&gt;eval()&lt;/code&gt; method to find a point on the curve at some value of the parameter &lt;code&gt;u&lt;/code&gt;, so that we can  write something like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let p0 = Complex::new(0.0, 0.0);
let p1 = Complex::new(2.5, 1.0);
let p2 = Complex::new(-0.5, 1.0);
let p3 = Complex::new(2.0, 0.0);

// Define cubic Bezier curve in the complex plane.
let c: Bernstein&amp;lt;Complex&amp;lt;f32&amp;gt;, f32, 4&amp;gt; = Bernstein::new([p0, p1, p2, p3]);

let p = c.eval(0.5); // point on a curve of type Complex&amp;lt;f32&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This part is easy, and can be done even in stable Rust. I just use the De &lt;a href="https://en.wikipedia.org/wiki/De_Casteljau%27s_algorithm" rel="noopener noreferrer"&gt;Casteljau's algorithm&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;impl&amp;lt;T, U, const N: usize&amp;gt; Bernstein&amp;lt;T, U, N&amp;gt; where
    T: Copy + Add&amp;lt;T, Output = T&amp;gt; + Sub&amp;lt;T, Output = T&amp;gt; + Mul&amp;lt;U, Output = T&amp;gt;,
    U: Copy + Num,
{
    pub fn eval(&amp;amp;self, u: U) -&amp;gt; T {
        // -- snippet --
        // De Casteljau's algorithm
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Trait bounds on types are quite transparent. I require &lt;code&gt;Copy&lt;/code&gt; trait to make my life easier when manipulating mathematical expressions, type &lt;code&gt;U&lt;/code&gt; should be a number, which is required by &lt;a href="https://docs.rs/num/latest/num/trait.Num.html" rel="noopener noreferrer"&gt;&lt;code&gt;num::Num&lt;/code&gt;&lt;/a&gt; trait. This is especially useful because &lt;code&gt;Num&lt;/code&gt; trait requires generic &lt;code&gt;One&lt;/code&gt; and &lt;code&gt;Zero&lt;/code&gt; traits, which provide methods such as &lt;code&gt;U::zero()&lt;/code&gt; and &lt;code&gt;U::one()&lt;/code&gt;. Type &lt;code&gt;T&lt;/code&gt; is required to implement vector space operations of addition, subtraction, and right-hand-side multiplication by a variable of type &lt;code&gt;U&lt;/code&gt; with the result of being of type &lt;code&gt;T&lt;/code&gt; (&lt;code&gt;Mul&amp;lt;U, Output = T&amp;gt;&lt;/code&gt;).&lt;/p&gt;

&lt;h2&gt;
  
  
  Implementing diff and integ methods
&lt;/h2&gt;

&lt;p&gt;The next step is to implement generic &lt;code&gt;diff()&lt;/code&gt; and &lt;code&gt;integ()&lt;/code&gt; methods to find the parametric derivative of the Bezier curve &lt;code&gt;dc(u)/du&lt;/code&gt;, and the integral with respect to parameter &lt;code&gt;u&lt;/code&gt;. That's where generic constant expression come into play. &lt;/p&gt;

&lt;p&gt;The problem is that our methods should take an array of control points &lt;code&gt;[T; N]&lt;/code&gt; of size &lt;code&gt;N&lt;/code&gt; as an input, and return an array of size &lt;code&gt;N - 1&lt;/code&gt; for &lt;code&gt;diff()&lt;/code&gt; or &lt;code&gt;N + 1&lt;/code&gt; for &lt;code&gt;integ()&lt;/code&gt; as output nicely wrapped into our custom &lt;code&gt;Bernstein&lt;/code&gt; type so that the signatures of the functions should be like these:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn diff(&amp;amp;self) -&amp;gt; Bernstein&amp;lt;T, U, {N - 1}&amp;gt; {}

// c: T -- is the initial point to fix the constant of integration.
fn integ(&amp;amp;self, c: T) -&amp;gt; Bernstein&amp;lt;T, U, {N + 1}&amp;gt; {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And stable Rust does not allow us to do that. Using &lt;code&gt;generic_const_exprs&lt;/code&gt; feature, it becomes possible, as we shall see shortly.&lt;/p&gt;

&lt;p&gt;Another difficulty is related to Rust's explicit type system. In these methods, the size of the array &lt;code&gt;N&lt;/code&gt; becomes a part of mathematical expressions in the &lt;code&gt;diff()&lt;/code&gt; and &lt;code&gt;integ()&lt;/code&gt; algorithms. Rust requires the size of the array to be of a machine-dependent pointer size &lt;code&gt;usize&lt;/code&gt; (which totally make sense but it is not generic). Converting from &lt;code&gt;usize&lt;/code&gt; to other type is not considered to be a safe operation so I have to rely on third party traits for that purpose, such as &lt;code&gt;num::FromPrimitive&lt;/code&gt; trait that is implemented for &lt;code&gt;usize&lt;/code&gt; in the &lt;code&gt;num&lt;/code&gt; crate. Otherwise, multiplying and expression of type, let's say, &lt;code&gt;f64&lt;/code&gt;, by &lt;code&gt;N&lt;/code&gt; is not defined.&lt;/p&gt;

&lt;p&gt;Having this in mind, let's discuss &lt;code&gt;diff()&lt;/code&gt; method (implementing &lt;code&gt;integ()&lt;/code&gt; is similar and may be found in the &lt;a href="https://github.com/sciprosk/bernstein" rel="noopener noreferrer"&gt;repo&lt;/a&gt;):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;impl&amp;lt;T, U, const N: usize&amp;gt; Bernstein&amp;lt;T, U, N&amp;gt; where
    T: Copy + Add&amp;lt;T, Output = T&amp;gt; + Sub&amp;lt;T, Output = T&amp;gt; + Mul&amp;lt;U, Output = T&amp;gt;,
    U: Copy + Num + FromPrimitive,
{
    pub fn diff(&amp;amp;self) -&amp;gt; Bernstein&amp;lt;T, U, {N - 1}&amp;gt; where
        [(); N - 1]:
    {
        let coef: [T; N - 1] = array::from_fn(
            |i| -&amp;gt; T {
                (self.coef[i + 1] - self.coef[i]) *
                (U::from_usize(N - 1).unwrap() / (self.segm.1 - self.segm.0))
            }
        );

        Bernstein {
            segm: self.segm,
            coef: coef,
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, there is a couple of new details. First, I require type &lt;code&gt;U&lt;/code&gt; to be bounded by &lt;code&gt;FromPrimitive&lt;/code&gt; trait that allows to convert from &lt;code&gt;usize&lt;/code&gt; to &lt;code&gt;U&lt;/code&gt; in a generic environment by calling &lt;code&gt;U::from_usize(N - 1).unwrap()&lt;/code&gt;. Second is that there is new bound &lt;code&gt;[(); N - 1]:&lt;/code&gt; which is &lt;a href="https://hackmd.io/OZG_XiLFRs2Xmw5s39jRzA" rel="noopener noreferrer"&gt;required by &lt;code&gt;generic_const_exprs&lt;/code&gt; feature&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;We currently use where [(); expr]: as a way to add additional const wf bounds. Once we have started experimenting with this it is probably worth it to add a more intuitive way to add const wf bounds.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The bounds on &lt;code&gt;T&lt;/code&gt; type is basically the same as in the &lt;code&gt;eval()&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;Now, we can find a derivative type from a basic type, by using for example the following&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Define cubic Bezier curve in the complex plane.
let c: Bernstein&amp;lt;Complex&amp;lt;f32&amp;gt;, f32, 4&amp;gt; = Bernstein::new([p0, p1, p2, p3]);

// Get the derivative, or hodograph curve at u = 0.2.
let d = c.diff().eval(0.2); // `d` is of type Complex&amp;lt;f32&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Generic product of two polynomials
&lt;/h2&gt;

&lt;p&gt;The next example is a product of two polynomials of order &lt;code&gt;N - 1&lt;/code&gt; and &lt;code&gt;M -  1&lt;/code&gt; (the size of arrays of coefficients is &lt;code&gt;N&lt;/code&gt; and &lt;code&gt;M&lt;/code&gt; respectively). This is a little bit more involved since it has to take the array &lt;code&gt;[T; N]&lt;/code&gt; as an input, multiply it by &lt;code&gt;[T; M]&lt;/code&gt; and the type of output should be &lt;code&gt;[T; M + N - 1]&lt;/code&gt;. For example, multiplying a polynomial of the third order (&lt;code&gt;N = 4&lt;/code&gt;) by a second-order polynomial (&lt;code&gt;N = 3&lt;/code&gt;) should give a quintic polynomial (&lt;code&gt;N = 6&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;The implementation may looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;impl&amp;lt;T, U, const N: usize, const M: usize&amp;gt;
Mul&amp;lt;Bernstein&amp;lt;T, U, {M}&amp;gt;&amp;gt; for Bernstein&amp;lt;T, U, {N}&amp;gt; where
    T: Copy + Add&amp;lt;Output = T&amp;gt; + Sub&amp;lt;Output = T&amp;gt; + Mul&amp;lt;Output = T&amp;gt; + Mul&amp;lt;U, Output = T&amp;gt;,
    U: Num + FromPrimitive,
    [(); N]:,
    [(); M]:,
    [(); N + M - 1]:
{
    type Output = Bernstein&amp;lt;T, U, {N + M - 1}&amp;gt;;

    fn mul(self, rhs: Bernstein&amp;lt;T, U, {M}&amp;gt;) -&amp;gt; Self::Output {
        let mut coef = [self.coef[0] - self.coef[0]; N + M - 1];

        // -- snippet --
        // actual algorithm

        Bernstein {
            coef: coef,
            segm: self.segm,
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The required operation is specified by &lt;code&gt;Mul&amp;lt;Bernstein&amp;lt;T, U, {M}&amp;gt;&amp;gt;&lt;/code&gt; in the &lt;code&gt;impl&lt;/code&gt;, and the resulting type should be &lt;code&gt;type Output = Bernstein&amp;lt;T, U, {N + M - 1}&amp;gt;&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Another subtle moment is that I have to initialize the array in the body of the function &lt;code&gt;mul()&lt;/code&gt; because Rust does not allow to use uninitialized variables (remember old plain C89? -- who cared about initializing all the variables). One way to do it is to put a trait bound on &lt;code&gt;T&lt;/code&gt; to implement &lt;code&gt;T::zero()&lt;/code&gt; that can be used as an initial value. In this case, I chose a workaround instead (may change it later) which is to require subtraction &lt;code&gt;Sub&amp;lt;Output = T&amp;gt;&lt;/code&gt; and use &lt;code&gt;self.coef[0] - self.coef[0]&lt;/code&gt; as a kind of generic zero.&lt;/p&gt;

&lt;p&gt;Note that &lt;code&gt;generic-const-exprs&lt;/code&gt; require additional trait bounds to be imposed for each of the array types we use &lt;code&gt;[(); N]:&lt;/code&gt;, &lt;code&gt;[(); M]:&lt;/code&gt;, &lt;code&gt;[(); N + M - 1]:&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now, it possible to write&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let p: Bernstein&amp;lt;f64, f64, 3&amp;gt; = Bernstein::new([0.0, 2.0, 1.0]);
let q: Bernstein&amp;lt;f64, f64, 4&amp;gt; = Bernstein::new([1.0, 2.0, 0.0, 0.0]);

// Quintic polynomial with real coefficient 
let c = p * q;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;Generic constant expressions in Rust give the flexibility of implementing generic types which size is known at compile time. So far, using an unstable Rust nightly 1.80, I didn't notice any issues with using &lt;code&gt;generic-const-exprs&lt;/code&gt; feature.&lt;/p&gt;

</description>
      <category>rust</category>
      <category>generic</category>
      <category>beginners</category>
      <category>numeric</category>
    </item>
    <item>
      <title>Experimenting with generics in Rust: little library for Bezier curves - part 1</title>
      <dc:creator>Igor Proskurin</dc:creator>
      <pubDate>Mon, 20 May 2024 20:17:57 +0000</pubDate>
      <link>https://dev.to/iprosk/experimenting-with-generics-in-rust-little-library-for-bezier-curves-part-1-4093</link>
      <guid>https://dev.to/iprosk/experimenting-with-generics-in-rust-little-library-for-bezier-curves-part-1-4093</guid>
      <description>&lt;p&gt;&lt;a href="https://dev.to/iprosk/generic-constant-expressions-a-future-bright-side-of-nightly-rust-3bp7"&gt;Not so long time ago&lt;/a&gt;, I decided to look into one aspect of Rust programming language that is of a certain personal interest for me --- &lt;a href="https://en.wikipedia.org/wiki/Generic_programming" rel="noopener noreferrer"&gt;generic programming&lt;/a&gt;. Generic (or template) programming is one of my favorite paradigms in modern C++, and it was certainly worth trying how it is currently supported in a shiny "new" language such as Rust. I actually liked what I found out there. After struggling a little with Rust's strict type system, I even started to appreciate its philosophy of being explicit.&lt;/p&gt;

&lt;p&gt;This post is an attempt to document some of my experiments with generics in Rust. As time goes by, I found that it is quite handy to leave some traces and artefacts so that there is a place go back after some time. This post is basically written to my future self and maybe for someone who finds it useful.&lt;/p&gt;

&lt;p&gt;Code, examples, tests, and some other documentation for this post can be in the &lt;a href="https://github.com/sciprosk/bernstein" rel="noopener noreferrer"&gt;repo&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Tiny generic numeric library: requirements
&lt;/h2&gt;

&lt;p&gt;The best way of learning is by doing, and there is no other way... So let's try write a tiny numeric library which nevertheless can be helpful elsewhere. The truth is that I have a similar library in C++ which I used quite a lot, so this would be a good test for Rust.&lt;/p&gt;

&lt;p&gt;The requirements are as follows: write a library to manipulate a generic &lt;a href="https://en.wikipedia.org/wiki/B%C3%A9zier_curve" rel="noopener noreferrer"&gt;Bezier curve&lt;/a&gt; (or a polynomial in the &lt;a href="https://en.wikipedia.org/wiki/Bernstein_polynomial" rel="noopener noreferrer"&gt;Bernstein basis&lt;/a&gt; if you prefer it this way). &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The control polygon of the Bezier curve should be of a generic type &lt;code&gt;T&lt;/code&gt; which supports usual vector-space operations: it should support &lt;code&gt;f32/f64&lt;/code&gt;, complex numbers, and vectors (in linear algebra sense).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The curve should be parameterized with a parameter of a generic type &lt;code&gt;U&lt;/code&gt;, which should support &lt;code&gt;f32/f64&lt;/code&gt;, rationals, and maybe arbitrary-precision floats.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The library should use &lt;em&gt;stack memory allocation&lt;/em&gt; (no memory allocations on the heap), which means that the size of the control polygon is a compile-time constant &lt;code&gt;N&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The library should implement usual vector space operations on the control polygon, &lt;code&gt;eval(u)&lt;/code&gt; method to get the point on the curve of type &lt;code&gt;T&lt;/code&gt; at the parameter value u of type &lt;code&gt;U&lt;/code&gt;, &lt;code&gt;diff()/integ()&lt;/code&gt; method to get new instance of the curve which is the derivative/integral of the current curve at every point, and multiplication of two polynomials of different degrees. The last three methods are especially problematic because they should return an instance of a different size: &lt;code&gt;N-1&lt;/code&gt;, &lt;code&gt;N + 1&lt;/code&gt;, or &lt;code&gt;N + M&lt;/code&gt; in general.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So these are all the requirement for now. Let's try it...&lt;/p&gt;

&lt;h2&gt;
  
  
  Generic Bezier curves: design considerations
&lt;/h2&gt;

&lt;p&gt;The first thing I stumbled upon while tying to implement these requirements was the &lt;em&gt;lack of support for generic constant expressions&lt;/em&gt; in Rust, which I briefly summarized in my &lt;a href="https://dev.to/iprosk/generic-constant-expressions-a-future-bright-side-of-nightly-rust-3bp7"&gt;previous post&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;In general, it is a known problem, and since I don't expect this example to ever reach a productionable stage, I decided to go with Rust nightly and use a highly experimental &lt;code&gt;generic_const_exprs&lt;/code&gt; feature.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#![allow(incomplete_features)]
#![feature(generic_const_exprs)]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And I compile it with &lt;code&gt;rustc 1.80.0-nightly (d84b90375 2024-05-19)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Second difficulty for designing generics is Rust's explicit type system, which does very little for you if you want automatic type promotions and conversions. This is actually a feature not a bug, and part of Rust's philosophy of being explicit. It helps to ensure that the program is correct, but makes life harder...&lt;/p&gt;

&lt;p&gt;For example, I want to store coefficients internally in the array of type &lt;code&gt;[T; N]&lt;/code&gt;, where &lt;code&gt;N&lt;/code&gt; is constant type parameter. In Rust, &lt;code&gt;N&lt;/code&gt; must be of the platform-dependent pointer-size type &lt;code&gt;usize&lt;/code&gt;, and there is a little you can do to convert &lt;code&gt;usize&lt;/code&gt; to other types using core language. This is of course for safety reasons, but in a generic environment, in conjunction with direct prohibition for implementing external traits for standard types, I either have to implement conversion manually, or rely on third party crates such as &lt;code&gt;conv&lt;/code&gt; for example. &lt;/p&gt;

&lt;p&gt;There is also an interesting crate &lt;code&gt;generic-array&lt;/code&gt; but we are not going this path here.&lt;/p&gt;

&lt;p&gt;After experimenting a little bit with different dependencies, I decided to depend on &lt;code&gt;num&lt;/code&gt; crate, that exposes some new types for e.g. rationals and complex numbers, and also has extended type conversions in &lt;code&gt;num::cast&lt;/code&gt; including handy &lt;code&gt;FromPrimitive&lt;/code&gt; trait.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[dependencies]
num = "0.4.3"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, let me introduce our type for a generic Bezier curve.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pub struct Bernstein&amp;lt;T, U, const N: usize&amp;gt; {
    coef: [T; N],
    segm: (U, U),
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have two generic types: &lt;code&gt;T&lt;/code&gt; for control polygon, and &lt;code&gt;U&lt;/code&gt; for the curve parameter (which I decided to make a part of the type), and one constant generic parameter for the size of the control polygon (the order of the curve is &lt;code&gt;N - 1&lt;/code&gt;, i.e. a cubic Bezier has &lt;code&gt;N = 4&lt;/code&gt; control points).&lt;/p&gt;

&lt;p&gt;The fields are private because the interval where Bezier curve is defined will be defaulted to (0, 1). Reason? It is hard to introduces anything that includes testing for equality or ordering in a numeric generic environment, because when it boils down to floating point math... &lt;a href="http://www.altdevblogaday.com/2012/02/22/comparing-floating-point-numbers-2012-edition/" rel="noopener noreferrer"&gt;well, you know&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Let's provide a simple accessors to get-set our type, and I leave it at this primitive level for now. Here, the type &lt;code&gt;U&lt;/code&gt; is bounded by &lt;code&gt;num::Num&lt;/code&gt; trait which includes convenient &lt;code&gt;U::one()&lt;/code&gt; and &lt;code&gt;U::zero()&lt;/code&gt; to set the default interval.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;impl&amp;lt;T, U, const N: usize&amp;gt; Bernstein&amp;lt;T, U, N&amp;gt; where
    U: Num,
{

    /// Create new instance of a Bernstein polynomial from an array of
    /// coefficients in the Bernstein basis over the default interval (0, 1).
    pub fn new(coef: [T; N]) -&amp;gt; Bernstein&amp;lt;T, U, N&amp;gt; {
        Bernstein {
            coef: coef,
            segm: (U::zero(), U::one()),
        }
    }

    /// Return an array of coefficients for a polynomial in the Bernstein basis.
    pub fn coef(&amp;amp;self) -&amp;gt; &amp;amp;[T; N] {
        &amp;amp;self.coef
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, I have all the prerequisites for the next steps. It is possible to create an instance of the Bezier curve like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let p0 = Rational64::new(1, 5);
let p1 = Rational64::new(-3, 7);
let p2 = Rational64::new(4, 13);
let p3 = Rational64::new(-11, 17);

let c: Bernstein&amp;lt;Rational64, Rational64, 4&amp;gt; = Bernstein::new([p0, p1, p2, p3]);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, I specify the control polygon that has four rational control points, and rationals are also used for the curve parameterization on the interval (0, 1). The syntax is quite terse for my taste because the type is not automatically deduced from &lt;code&gt;::new()&lt;/code&gt;, and I have to spell out it explicitly in &lt;code&gt;Bernstein&amp;lt;Rational64, Rational64, 4&amp;gt;&lt;/code&gt; but it's okay.&lt;/p&gt;

&lt;h3&gt;
  
  
  Next steps...
&lt;/h3&gt;

&lt;p&gt;The next will be to implement a bunch of methods to evaluate the curve at a given point, generic differentiation and integration. The last two require &lt;code&gt;generic_const_exprs&lt;/code&gt;, and that is where experimental features kick in.&lt;/p&gt;

</description>
      <category>rust</category>
      <category>generic</category>
      <category>numeric</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Generic constant expressions: a future bright side of nightly Rust</title>
      <dc:creator>Igor Proskurin</dc:creator>
      <pubDate>Fri, 17 May 2024 02:49:35 +0000</pubDate>
      <link>https://dev.to/iprosk/generic-constant-expressions-a-future-bright-side-of-nightly-rust-3bp7</link>
      <guid>https://dev.to/iprosk/generic-constant-expressions-a-future-bright-side-of-nightly-rust-3bp7</guid>
      <description>&lt;p&gt;When I just started looking into generic programming in Rust, I was quite annoyed that something that is trivially done with C++ templates, cannot be done in Rust. You just can't... Generic traits are pretty cool, and certainly you can use &lt;code&gt;const&lt;/code&gt; parameters in generics but if you just try&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn f&amp;lt;const N: usize&amp;gt;() -&amp;gt; [i32; 2 * N] {
    [2; 2 * N]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or even&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct s&amp;lt;const N: usize&amp;gt; {
    value: [i32; N + 1]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;in both cases &lt;a href="https://www.rustacean.net/" rel="noopener noreferrer"&gt;Ferris&lt;/a&gt; would be upset and we get &lt;code&gt;error: generic parameters may not be used in const operations&lt;/code&gt;. So how can we implement something generic that is allocated on the stack or should we ask the operating system each time for memory on the heap?&lt;/p&gt;

&lt;h2&gt;
  
  
  Generic constant expression parameters
&lt;/h2&gt;

&lt;p&gt;Unfortunately, there is no way of doing it in stable Rust. And we have to opt to a nightly build. Let's try it! I will use the latest &lt;code&gt;nightly-x86_64-pc-windows-msvc&lt;/code&gt;. However, this feature seems to be here for while, and this may compile in other versions as well. Or maybe not... It looks like support of generic constant expressions is still highly experimental.&lt;/p&gt;

&lt;p&gt;First look is into &lt;a href="https://doc.rust-lang.org/nightly/unstable-book/language-features/generic-const-exprs.html" rel="noopener noreferrer"&gt;The Unstable Book&lt;/a&gt;. Well, it does not look informative but gives us some background from the rust-lang Github &lt;a href="https://github.com/rust-lang/rust/issues/76560" rel="noopener noreferrer"&gt;project-const-generics&lt;/a&gt;. It says: &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The implementation is still far from ready but already available for experimentation.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Nice! That's exactly what we want...&lt;/p&gt;

&lt;p&gt;Also, some interesting discussions and difficulties with implementing safe generic constant expressions can be found &lt;a href="https://hackmd.io/OZG_XiLFRs2Xmw5s39jRzA?view" rel="noopener noreferrer"&gt;here&lt;/a&gt; and &lt;a href="https://hackmd.io/z7LKv6WKRkiw2WC7KDkvYw" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Constant expression generic parameters in functions
&lt;/h3&gt;

&lt;p&gt;Gear up and embrace for impact: &lt;code&gt;rustup override set nightly&lt;/code&gt;, and we are in uncharted waters of experimental Rust.&lt;br&gt;
Let's try again:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#![feature(generic_const_exprs)]
#![allow(incomplete_features)]
fn f&amp;lt;const N: usize&amp;gt;() -&amp;gt; [i32; 2 * N] {
    [2; 2 * N]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now it compiles and &lt;code&gt;let v = f::&amp;lt;2&amp;gt;()&lt;/code&gt; produces what we asked for &lt;code&gt;[2, 2, 2, 2]&lt;/code&gt;. &lt;/p&gt;

&lt;h3&gt;
  
  
  Constant expression generic parameters in types
&lt;/h3&gt;

&lt;p&gt;Let's try a generic struct that wraps an array of a size known at compile time that is a constant expression.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#[derive(Debug)]
struct s&amp;lt;const N: usize&amp;gt; 
//where [i32; 2* N + 1]:
{
    value: [i32; 2 * N + 1]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Oops, this does not compile:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;error: unconstrained generic constant
  --&amp;gt; src/main.rs:11:12
   |
11 |     value: [i32; 2 * N + 1]
   |            ^^^^^^^^^^^^^^^^
   |
help: try adding a `where` bound
   |
8  | struct s&amp;lt;const N: usize&amp;gt; where [(); 2 * N + 1]: 
   |                          ++++++++++++++++++++++
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The problem here, as far as I understand from the &lt;a href="https://hackmd.io/OZG_XiLFRs2Xmw5s39jRzA?view" rel="noopener noreferrer"&gt;discussion&lt;/a&gt;, is with the const-well-formdness. That is having a constant parameter &lt;code&gt;N&lt;/code&gt;, how to verify that &lt;code&gt;2 * N + 1&lt;/code&gt; is well-formed and won't, for example, overflow? So we need to add a bound.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;a href="https://hackmd.io/OZG_XiLFRs2Xmw5s39jRzA" rel="noopener noreferrer"&gt;We currently&lt;/a&gt; use where [(); expr]: as a way to add additional const wf bounds. Once we have started experimenting with this it is probably worth it to add a more intuitive way to add const wf bounds.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Adding this bound certainly helps, and now this compiles:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#![feature(generic_const_exprs)]
#![allow(incomplete_features)]

#[derive(Debug)]
struct s&amp;lt;const N: usize&amp;gt; 
where [(); 2 * N + 1]:
{
    value: [i32; 2 * N + 1]
}

fn main() {
    let v: s::&amp;lt;2&amp;gt; = s {value: [1, 2, 3, 4, 5]};
    println!("{:?}", v);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and gives &lt;code&gt;s { value: [1, 2, 3, 4, 5] }&lt;/code&gt;. And if we replace this declaration with a wrong one &lt;code&gt;let v: s::&amp;lt;3&amp;gt; = s {value: [1, 2, 3, 4, 5]}&lt;/code&gt;, it errors out with a meaningful error message&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;error[E0308]: mismatched types
  --&amp;gt; src/main.rs:12:31
   |
12 |     let v: s::&amp;lt;3&amp;gt; = s {value: [1, 2, 3, 4, 5]};
   |                               ^^^^^^^^^^^^^^^ expected `7`, found `5`
   |
   = note: expected constant `7`
              found constant `5`
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Good!&lt;/p&gt;

&lt;h3&gt;
  
  
  What does not work...
&lt;/h3&gt;

&lt;p&gt;It is not possible to define a recursive invocation of a function with a constant expression parameter like this (which is again trivial in C++ &lt;a href="https://en.wikipedia.org/wiki/Template_metaprogramming" rel="noopener noreferrer"&gt;template metaprogramming&lt;/a&gt;):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn factorial&amp;lt;const N: usize&amp;gt;() -&amp;gt; usize 
where [(); N - 1] {
    // ???
    factorial::&amp;lt;{N-1}&amp;gt;()
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The problems is (1) how to stop the recursion, and (2) how to impose recursive generic-parameter bounds that the compiler asks us for.&lt;/p&gt;

&lt;p&gt;Declaring internal constant expression parameters does not work either:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn f&amp;lt;const N: usize&amp;gt;() -&amp;gt; [i32; 2 * N] {
    const M: usize = 2 * N;
    [2; 2 * N]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;error[E0401]: can't use generic parameters from outer item
  --&amp;gt; src/main.rs:10:26
   |
9  | fn f&amp;lt;const N: usize&amp;gt;() -&amp;gt; [i32; 2 * N] {
   |            - const parameter from outer item
10 |     const M: usize = 2 * N;
   |                          ^ use of generic parameter from outer item
   |
   = note: a `const` is a separate item from the item that contains it
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Summary
&lt;/h3&gt;

&lt;p&gt;Let's hope that generic constant expressions will find their way in future safe and stable Rust. It will certainly help the expressiveness of the language when it comes to implementing generic libraries with static-sized aggregate types known at compile time.&lt;/p&gt;

</description>
      <category>rust</category>
      <category>nightlyrust</category>
      <category>generic</category>
      <category>beginners</category>
    </item>
    <item>
      <title>WebAssembly: Building GUI for C++ libraries with Embind</title>
      <dc:creator>Igor Proskurin</dc:creator>
      <pubDate>Sun, 17 Sep 2023 04:47:42 +0000</pubDate>
      <link>https://dev.to/iprosk/webassembly-building-gui-for-c-libraries-with-embind-53cc</link>
      <guid>https://dev.to/iprosk/webassembly-building-gui-for-c-libraries-with-embind-53cc</guid>
      <description>&lt;p&gt;This post will probably not be very long of full of technical details. Instead, I would like to share some thought about using &lt;a href="https://emscripten.org/docs/porting/connecting_cpp_and_javascript/embind.html" rel="noopener noreferrer"&gt;Embind&lt;/a&gt; -- a WebAssembly tool for binding high-level C++ code to JavaScript, and an example of an open-source project (that is of personal interest to me) that uses Embind to make GUI for its main product -- a numeric motion planning library. So if you are a C/C++ software/library developer, and you are looking for new tools to visualize, advertise or present you work, WebAssembly is something to thing about...&lt;/p&gt;

&lt;p&gt;If you are new to WebAssembly, it is a relatively new web-technology that allows to compile code in languages such as C, C++ and Rust into a low-level assembly language that can be executed in a virtual stack-based machine inside a browser with reasonable productivity (compared to pure JavaSript). There are several resources that provide a good dive into WebAssembly basics:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;MDN Web Docs: &lt;a href="https://developer.mozilla.org/en-US/docs/WebAssembly" rel="noopener noreferrer"&gt;WebAssembly&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://webassembly.org/" rel="noopener noreferrer"&gt;WebAssembly.org&lt;/a&gt;: nice collection of resouces.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://emscripten.org" rel="noopener noreferrer"&gt;Emscipten&lt;/a&gt; C/C++ to WebAssembly compiler.&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  What should I use it for?
&lt;/h1&gt;

&lt;p&gt;What are benefits of using WebAssebmly with compiled languages like C/C++ or Rust? &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You can run computationally intensive stuff client-side in browser, and have it on a web page. Think about fractal rendering, 3D graphics, or some physics simulations.&lt;/li&gt;
&lt;li&gt;If you have library already written in C++ or C, it can be (in most cases) recompiled into WebAssembly bytecode with moderate efforts.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Of course, with benefits come limitations (&lt;a href="https://en.wikipedia.org/wiki/Dialectic" rel="noopener noreferrer"&gt;Dialectics&lt;/a&gt;, eh?).&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;There are some &lt;a href="https://emscripten.org/docs/porting/guidelines/portability_guidelines.html" rel="noopener noreferrer"&gt;limitations&lt;/a&gt; with &lt;em&gt;what&lt;/em&gt; you can port to WebAssembly. Exceptions? Threads? Fancy memory layout?&lt;/li&gt;
&lt;li&gt;To use it in a web browser, the code should be compiled with a dedicated compiler (e.g. &lt;code&gt;emcc&lt;/code&gt;). It not possible to grab a production &lt;code&gt;library.a&lt;/code&gt; compiled for x86-64 and just use it (would be nice, eh?).&lt;/li&gt;
&lt;li&gt;Some work has to be done to bind data from web application to WebAssembly (read C/C++). Low-level memory management is clumsy, and tools like Embind are real help.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;One possible application of WebAssembly is to provide a web access to a (low-level) numeric library API, so that users may turn the knobs in the browser and see what goes on without deploying this library to a hardware of making it a part of larger project. And in this post I will provide and example of a cool project in robotics that uses this approach. Of course, there is always an option to bind such code to Python or Julia which might make more sense in most cases, but sometimes a web app might be an interesting option.&lt;/p&gt;

&lt;h1&gt;
  
  
  A little bit about Embind
&lt;/h1&gt;

&lt;p&gt;If you would like to jump start with C/C++ in WebAssembly, just install &lt;a href="https://emscripten.org/" rel="noopener noreferrer"&gt;Emscipten&lt;/a&gt; SDK. It will install the &lt;code&gt;emcc&lt;/code&gt; compiler and some basic environment. If you don't have XTerm/Bash at hand, don't worry -- it works in Windows PowerShell out of the box. Compiling C/C++ with &lt;code&gt;emcc&lt;/code&gt; produces &lt;code&gt;*.wasm&lt;/code&gt; binary file and optionally JavaScript module to embed &lt;code&gt;*.wasm&lt;/code&gt; into a web application. Making it work in React may require a &lt;a href="https://dev.to/iprosk/cc-code-in-react-using-webassembly-7ka"&gt;little bit more work&lt;/a&gt;. But that's pretty much it.&lt;/p&gt;

&lt;p&gt;The problem is how to get something into WebAssembly internal memory space, and how to get stuff out of there. There is always low-level API at our disposal, but this is &lt;a href="https://dev.to/iprosk/playing-with-low-level-memory-in-webassembly-257i"&gt;tedious and error prone&lt;/a&gt;, and that's where our today's hero comes in.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://emscripten.org/docs/porting/connecting_cpp_and_javascript/embind.html" rel="noopener noreferrer"&gt;Embind&lt;/a&gt;. I will not write much about it here, because the official documentation is quite comprehensive to get hands on. Just one remark from the official docs to make this discussion complete. Binding class methods and properties with &lt;code&gt;EMSCRIPTEN_BINDINGS(my_class_example) {class_&amp;lt;MyClass&amp;gt;("MyClass") /* ... */}&lt;/code&gt; allows to use it from JavaScript in a "normal" way without worrying about how this works at low level.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var instance = new Module.MyClass(10, "hello");
instance.incrementX();
instance.x; // 11
instance.x = 20; // 20
Module.MyClass.getStringFromInstance(instance); // "hello"
instance.delete();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's now look at the example from some real-world project...&lt;/p&gt;

&lt;h1&gt;
  
  
  Example: GUI for a motion planning library
&lt;/h1&gt;

&lt;p&gt;There is an open-source project which is of personal interest for me -- a robotic motion planning library which is called &lt;a href="https://ruckig.com/" rel="noopener noreferrer"&gt;&lt;em&gt;Ruckig&lt;/em&gt;&lt;/a&gt;. It is a relatively small C++17 tool which &lt;a href="https://en.wikipedia.org/wiki/Unix_philosophy" rel="noopener noreferrer"&gt;does one thing and does it well&lt;/a&gt; -- it plans kinematically-optimal multi-degrees-of-freedom trajectories for robotics controllers. Doesn't matter what it really means. It is a software library that is supposed to be a part of another software tools or libraries. It has Python bindings (of course), and can be used from a Jupyter notebook. Well, as I found recently, it now has WebAssembly bindings too to provide a simple &lt;a href="https://gui.ruckig.com/" rel="noopener noreferrer"&gt;web GUI&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;For it is a good chance to peek inside and learn something by example...&lt;/p&gt;

&lt;h2&gt;
  
  
  Install it for local development and peek inside
&lt;/h2&gt;

&lt;p&gt;Let us quickly look inside &lt;em&gt;Ruckig&lt;/em&gt; project. Jump into the &lt;a href="https://github.com/pantor/ruckig" rel="noopener noreferrer"&gt;GitHub repository&lt;/a&gt; of the community version (MIT license) and clone it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git clone https://github.com/pantor/ruckig
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We don't have to build it with CMake, so don't worry about right building tools. It can just live in a Windows folder for now if it is your platform. &lt;/p&gt;

&lt;p&gt;If we go to &lt;code&gt;src/ruckig&lt;/code&gt;, we will find a file &lt;code&gt;wasm.cpp&lt;/code&gt; which contains all the  Embind bindings for the &lt;a href="https://gui.ruckig.com/" rel="noopener noreferrer"&gt;web GUI&lt;/a&gt;, which allows to seamlessly bind input/output into underlying C++ library.&lt;/p&gt;

&lt;p&gt;The web GUI itself is in &lt;code&gt;doc/web-gui&lt;/code&gt;. To build it, we need to compile the C++ library to the &lt;code&gt;ruckig.wasm&lt;/code&gt; binary first. This can be done by running &lt;code&gt;doc/web-gui/make_wasm.sh&lt;/code&gt; in Bash, or if you are in Windows PowerShell, just run the following command in the terminal or put it in a &lt;code&gt;*.bat&lt;/code&gt; file (this implies that Emscipten SDK is &lt;a href="https://emscripten.org/docs/getting_started/downloads.html" rel="noopener noreferrer"&gt;installed and activated&lt;/a&gt; and the environmental variables are already sources into current shell)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;emcc src/ruckig/wasm.cpp src/ruckig/brake.cpp src/ruckig/position_first_step1.cpp src/ruckig/position_first_step2.cpp src/ruckig/position_second_step1.cpp src/ruckig/position_second_step2.cpp src/ruckig/position_third_step1.cpp src/ruckig/position_third_step2.cpp src/ruckig/velocity_second_step1.cpp src/ruckig/velocity_second_step2.cpp src/ruckig/velocity_third_step1.cpp src/ruckig/velocity_third_step2.cpp -Iinclude -Ithird_party -std=c++17 -lembind -Os -s MODULARIZE -s EXPORT_ES6 -s EXPORT_NAME='RuckigModule' -s ENVIRONMENT='web' -s EXPORTED_RUNTIME_METHODS=ccall,cwrap -o doc/web-gui/src/ruckig.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This gives us two files &lt;code&gt;ruckig.wasm&lt;/code&gt; binary, and &lt;code&gt;ruckig.js&lt;/code&gt; glue code to load this binary into a browser session and interface with a Plotly.js React component, which shows fancy plots on the web page.&lt;/p&gt;

&lt;p&gt;If you have resent version of Node.js, you can quickly build you local copy of &lt;a href="https://gui.ruckig.com/" rel="noopener noreferrer"&gt;web GUI&lt;/a&gt; by running the &lt;a href="https://github.com/pantor/ruckig/tree/master/doc/web-gui" rel="noopener noreferrer"&gt;following commands&lt;/a&gt; in the root directory of the project.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install
npm run start
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will serve the page at &lt;code&gt;localhost:1234&lt;/code&gt;. Now, make a cup of coffee (if it is still morning) and just look inside the &lt;code&gt;doc/web-gui/&lt;/code&gt; at &lt;code&gt;index.html&lt;/code&gt; and &lt;code&gt;gui.js&lt;/code&gt;. That's it.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>C/C++ code in React using WebAssembly</title>
      <dc:creator>Igor Proskurin</dc:creator>
      <pubDate>Wed, 13 Sep 2023 04:54:14 +0000</pubDate>
      <link>https://dev.to/iprosk/cc-code-in-react-using-webassembly-7ka</link>
      <guid>https://dev.to/iprosk/cc-code-in-react-using-webassembly-7ka</guid>
      <description>&lt;p&gt;I started looking into WebAssembly (WASM) recently having a small project in mind. The project is to make a web interface for an open-source numeric C++17 library. I was thinking about a web application using a popular framework such as React. So here we go. This post is about my first experience with using C code compiled to WebAssembly in React.&lt;/p&gt;

&lt;p&gt;While it was relatively easy to compile and call C-code from JavaScript which I described in the &lt;a href="https://dev.to/iprosk/my-first-take-on-webassembly-213h"&gt;first&lt;/a&gt; and &lt;a href="https://dev.to/iprosk/playing-with-low-level-memory-in-webassembly-257i"&gt;second&lt;/a&gt; posts, making it work with React required much more time and patience. I did my homework, and I knew about difficulty with loading WASM modules. I read about solutions based on &lt;code&gt;wasm-loader&lt;/code&gt; with&lt;code&gt;react-app-rewired&lt;/code&gt; as discussed &lt;a href="https://www.telerik.com/blogs/using-webassembly-with-react" rel="noopener noreferrer"&gt;here&lt;/a&gt;.  And I tried &lt;code&gt;fetch&lt;/code&gt; WASM directly as described in &lt;a href="https://developer.mozilla.org/en-US/docs/WebAssembly/Loading_and_running" rel="noopener noreferrer"&gt;MDN Docs&lt;/a&gt;. But each time the result was the same -- my WASM module refused to load at runtime complaining about "incorrect MIME types" or something like that.&lt;/p&gt;

&lt;p&gt;Finally, the only solution that really worked for me was to compile C code in &lt;a href="https://emscripten.org/" rel="noopener noreferrer"&gt;Emscripten&lt;/a&gt; with &lt;code&gt;-sSINGLE_FILE=1&lt;/code&gt;. What it does? It embeds WebAssembly binary directly into JavaScript glue code, which is then used to call byte code at runtime.  This solved my problems with loading WASM modules.&lt;/p&gt;

&lt;p&gt;Here is what I did step by step...&lt;/p&gt;

&lt;h1&gt;
  
  
  Setting up a React App
&lt;/h1&gt;

&lt;p&gt;If you are new to React (like myself), there is a good introduction at &lt;a href="https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started" rel="noopener noreferrer"&gt;MDN Docs&lt;/a&gt;. I used Node.js v16.20.0, which is bundled with Emscripten compiler. Just type in the terminal (I used PowerShell this time)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$npx create-react-app  react-wasm
$cd react-wasm
$npm start
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And we have a demo React project in the directory &lt;code&gt;react-wasm&lt;/code&gt; up and running at &lt;code&gt;localhost:3000&lt;/code&gt;. We will need to install some more stuff for our demo, but it can be done later. There is no rush...&lt;/p&gt;

&lt;h1&gt;
  
  
  Preparing a toy C library
&lt;/h1&gt;

&lt;p&gt;I am going a prepare a toy C library. One function will be only for side effects, and another one will be a "numeric algorithm" -- it will take data from an input buffer, transform it, and put it into an output buffer. The input buffer will be filled in from JavaScript and the output data should be rendered by some React component (I will just use &lt;code&gt;react-plotly.js&lt;/code&gt; to make some visuals). So here is our C file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// hello_react.c

#include &amp;lt;assert.h&amp;gt;
#include &amp;lt;stdio.h&amp;gt;

void hello_react() {
    printf("Hello, React!\n");
}

void process_data(double* input, double* output, int size) {
    int i;

    assert(size &amp;gt; 0 &amp;amp;&amp;amp; "size must be positive");
    assert(input &amp;amp;&amp;amp; output &amp;amp;&amp;amp; "must be valid pointers");

    for (i = 0; i &amp;lt; size; i++) {
        output[i] = input[i] * input[i];
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you like to compile this file as C++, just wrap the function into &lt;code&gt;extern "C" {}&lt;/code&gt; to prevent function names being &lt;a href="https://en.wikipedia.org/wiki/Name_mangling" rel="noopener noreferrer"&gt;mangled&lt;/a&gt; (in a WASM binary our functions will be translated into symbols &lt;code&gt;_hello_react&lt;/code&gt; and &lt;code&gt;_process_data&lt;/code&gt;). I saved this file as &lt;code&gt;react-wasm/src/hello_react.c&lt;/code&gt; into &lt;code&gt;src&lt;/code&gt; folder of the React project.&lt;/p&gt;

&lt;p&gt;The next step is to compile this file into WASM binary and JavaScript glue code to interface it with React. I use &lt;a href="https://emscripten.org/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.html" rel="noopener noreferrer"&gt;Emscripten&lt;/a&gt; compiler that wraps around LLVM. There are two compiler options that make our life easier. One is &lt;code&gt;-sMODULARIZE&lt;/code&gt; that helps to run WASM code in Node.js. Another one is &lt;code&gt;-sSINGLE_FILE=1&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;As I mentioned above, without &lt;code&gt;-sSINGLE_FILE=1&lt;/code&gt; the &lt;code&gt;emcc&lt;/code&gt; compiler produces a separate &lt;code&gt;*.wasm&lt;/code&gt; file that has to be loaded into browser at runtime. In my case (I mostly followed a method described &lt;a href="https://www.telerik.com/blogs/using-webassembly-with-react" rel="noopener noreferrer"&gt;here&lt;/a&gt; with some variations), whenever I used a separate file, it refused to load, despite the fact that I could build a package with &lt;code&gt;npm&lt;/code&gt;. According to &lt;a href="https://emscripten.org/docs/getting_started/FAQ.html?highlight=single_file" rel="noopener noreferrer"&gt;Emscripten FAQ&lt;/a&gt;: "another option than a local webserver is to bundle everything into a single file, using -sSINGLE_FILE (as then no XHRs will be made to file:// URLs)." This worked for me.&lt;/p&gt;

&lt;p&gt;Okay, the final command to compile out toy C "library" with Emscripten looks like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$emcc hello_react.c -o hello_react.js -sMODULARIZE -sSINGLE_FILE=1 -sEXPORTED_FUNCTIONS=_hello_react,_process_data,_malloc,_free,getValue -sEXPORTED_RUNTIME_METHODS=ccall
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, we have &lt;code&gt;hello_react.js&lt;/code&gt; that contains JavaScript glue code and embedded WASM code (and we &lt;em&gt;don't have&lt;/em&gt; a separate &lt;code&gt;hello_react.wasm&lt;/code&gt;). We also asked the compiler to export some functions for us including &lt;code&gt;_hello_react&lt;/code&gt; and &lt;code&gt;_process_data&lt;/code&gt;.&lt;/p&gt;

&lt;h1&gt;
  
  
  Interfacing with React components
&lt;/h1&gt;

&lt;p&gt;Now comes the fun stuff. How can we integrate our compiled file &lt;code&gt;hello_react.js&lt;/code&gt; into a React component? Let's move step by step...&lt;/p&gt;

&lt;p&gt;To call a JavaScript module with WASM code, I will mostly follow the method for interoperability with Node.js from &lt;a href="https://emscripten.org/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.html#interacting-with-code" rel="noopener noreferrer"&gt;Emscripten Docs&lt;/a&gt;. The basics idea is to to call &lt;code&gt;require('./hello_wasm.js')&lt;/code&gt; which returns a promise.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var factory = require('./hello_react.js');

factory().then((instance) =&amp;gt; {
  instance._hello_react(); // direct calling
  instance.ccall("hello_react", null, null, null);
  // more code...
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we can call our C function directly via the exported symbol &lt;code&gt;_hello_react&lt;/code&gt; or using a runtime method &lt;code&gt;ccall&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now &lt;code&gt;index.js&lt;/code&gt; inside my &lt;code&gt;src&lt;/code&gt; folder looks like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';

var factory = require('./hello_react.js');

factory().then((instance) =&amp;gt; {
  instance._hello_react(); // direct calling
  instance.ccall("hello_react", null, null, null);
});

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  &amp;lt;React.StrictMode&amp;gt;
    &amp;lt;App /&amp;gt;
  &amp;lt;/React.StrictMode&amp;gt;
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At this point, we can run our project with &lt;code&gt;npm start&lt;/code&gt;... And see that it doesn't work.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxelqjtsa1vt78ct8y4pi.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxelqjtsa1vt78ct8y4pi.png" alt=" " width="800" height="367"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The first problem is specific to webpack, and there is a &lt;a href="https://stackoverflow.com/questions/70591567/module-not-found-error-cant-resolve-fs-in-react" rel="noopener noreferrer"&gt;standard workaround&lt;/a&gt;, which is called &lt;code&gt;react-app-rewired&lt;/code&gt;. So our next step is to install this package.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$npm install react-app-rewired
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And set up &lt;code&gt;config-overrides.js&lt;/code&gt; in the root directory of the project with the following content.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;module.exports = function override(config, env) {
  config.resolve.fallback = {
    fs: false
  };
  return config;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After that I just modify the &lt;code&gt;script&lt;/code&gt; section of the &lt;code&gt;package.json&lt;/code&gt; to call &lt;code&gt;react-app-rewired&lt;/code&gt; at startup.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-app-rewired eject"
  },
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next step is &lt;code&gt;npm install path&lt;/code&gt; so we can silence the following.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Module not found: Error: Can't resolve 'path' in 'C:\Users\Igor\Devel\react-wasm\src'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This almost works. The only remaining thing is the annoying &lt;code&gt;eslint&lt;/code&gt; complaints, which I silenced using a temporary solution simply by adding the following lines on top of &lt;code&gt;hello_react.js&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/* eslint-disable no-undef */
/* eslint-disable  no-restricted-globals */
/* eslint-disable import/no-amd */
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, we open the console, and see that our function has been called.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4cvxpqex5i51uyzis3ey.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4cvxpqex5i51uyzis3ey.png" alt=" " width="554" height="126"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Okay, this part works. We can even built package with &lt;code&gt;npm run build&lt;/code&gt; at this point. Now let's go a little bit further and try to connect WASM code with a React component.&lt;/p&gt;

&lt;h1&gt;
  
  
  Mocking interface between C code and a React component
&lt;/h1&gt;

&lt;p&gt;I will use &lt;a href="https://plotly.com/javascript/react/" rel="noopener noreferrer"&gt;Plotly.js&lt;/a&gt; as a simple graphical react component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$npm install plotly-react.js plotly.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since I am using low-level C code here, I will need to make an input buffer using &lt;code&gt;_malloc&lt;/code&gt; to pass data to the WASM module. We already exported it when compiled our C file with &lt;code&gt;emcc&lt;/code&gt;. And I will use a separate output buffer to get data out. Let me skip some little steps here. More details can be found in my &lt;a href="https://dev.to/iprosk/playing-with-low-level-memory-in-webassembly-257i"&gt;previous post&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Out &lt;code&gt;index.js&lt;/code&gt; now looks like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';

var factory = require('./hello_react.js');

factory().then((instance) =&amp;gt; {
  const inputArr = new Float64Array([0, 1, 2, 3, 5]);
  const inputBuff = instance._malloc(inputArr.length * inputArr.BYTES_PER_ELEMENT);
  instance.HEAPF64.set(inputArr, inputBuff / inputArr.BYTES_PER_ELEMENT);

  let outputArr = new Float64Array(inputArr.length);
  const outputBuff = instance._malloc(inputArr.length * inputArr.BYTES_PER_ELEMENT);

  instance.ccall('process_data', 'number', ['number', 'number', 'number'], [inputBuff, outputBuff, inputArr.length]);

  for (let i = 0; i &amp;lt; outputArr.length; i++) {
      outputArr[i] = instance.getValue(outputBuff + i * outputArr.BYTES_PER_ELEMENT, 'double');
  }

  console.log(inputArr);
  console.log(outputArr);

  instance._free(outputBuff);
  instance._free(inputBuff);

  const root = ReactDOM.createRoot(document.getElementById('root'));

  root.render(
    &amp;lt;React.StrictMode&amp;gt;
      &amp;lt;App /&amp;gt;
    &amp;lt;/React.StrictMode&amp;gt;
  );

});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To get data out of the output buffer, I used a low-level operation &lt;code&gt;getValue&lt;/code&gt; (there is no &lt;code&gt;HEAPF64.get&lt;/code&gt; in the API).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for (let i = 0; i &amp;lt; outputArr.length; i++) {
      outputArr[i] = instance.getValue(outputBuff + i * outputArr.BYTES_PER_ELEMENT, 'double');
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's check console logs and find correct input and output array values.&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5w0018fez2emnqt8ii3l.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5w0018fez2emnqt8ii3l.png" alt=" " width="554" height="188"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let's now use this data somewhere...&lt;/p&gt;
&lt;h1&gt;
  
  
  Let's visualize what we get
&lt;/h1&gt;

&lt;p&gt;We can add a simple script into &lt;code&gt;src&lt;/code&gt; folder to plot input and output using a Plotly.js component &lt;code&gt;&amp;lt;Plot /&amp;gt;&lt;/code&gt; (sprinkle it with some CSS if you like).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// MyPlot.js
import React from 'react';
import Plot from 'react-plotly.js';
import './MyPlot.css'

function MyPlot(props) {

    const xs = props.xs;
    const ys = props.ys;

    const plots = [{
        x: xs, 
        y: ys, 
        type: 'scatter', 
        mode: 'lines+markers', 
        marker: {color: 'red'}
    }];

    return (
        &amp;lt;div className='MyPlot'&amp;gt;
            &amp;lt;Plot
              data={ plots }
              layout={ {width: 640, height: 480, title: 'Plotly React'} }
            /&amp;gt;
        &amp;lt;/div&amp;gt;
    );
}

export default MyPlot;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now the component is ready to use from &lt;code&gt;index.js&lt;/code&gt;. Just add &lt;code&gt;import MyPlot from './MyPlot'&lt;/code&gt; and update the rendering&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;root.render(
    &amp;lt;React.StrictMode&amp;gt;
      &amp;lt;App /&amp;gt;
      &amp;lt;MyPlot xs={inputArr} ys={outputArr} /&amp;gt;
    &amp;lt;/React.StrictMode&amp;gt;
  );
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Voila!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Floi49j6nc7019c1n5grb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Floi49j6nc7019c1n5grb.png" alt=" " width="800" height="425"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>cpp</category>
      <category>webassembly</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Playing with low-level memory allocation in WebAssembly</title>
      <dc:creator>Igor Proskurin</dc:creator>
      <pubDate>Wed, 06 Sep 2023 03:58:19 +0000</pubDate>
      <link>https://dev.to/iprosk/playing-with-low-level-memory-in-webassembly-257i</link>
      <guid>https://dev.to/iprosk/playing-with-low-level-memory-in-webassembly-257i</guid>
      <description>&lt;p&gt;I wrote a &lt;a href="https://dev.to/iprosk/my-first-take-on-webassembly-213h"&gt;blog post&lt;/a&gt; about my first experience with WebAssembly (WASM) recently. And in that post, I touched a little bit how to set up an SDK for writing code in C/C++, and how to compile a simple C++ function that can takes couple of numeric values from JavaScript, run WASM binary in a browser, and return a value.&lt;/p&gt;

&lt;p&gt;For those who just jumped in, WebAssembly is cool cross-platform binary format, assembly language, and a Virtual Machine to run this binary in a browser. What can it do? Well, it &lt;a href="https://www.zdnet.com/article/half-of-the-websites-using-webassembly-use-it-for-malicious-purposes/" rel="noopener noreferrer"&gt;can mine crypto currency&lt;/a&gt; silently in background while you go through your favorite webpages. And guess who pays for the electricity?&lt;/p&gt;

&lt;p&gt;Well, besides crypto-currency abuse, it is an interesting technology to run heavy stuff client-side with reasonable performance.&lt;/p&gt;

&lt;h1&gt;
  
  
  Where to start
&lt;/h1&gt;

&lt;p&gt;In this post, I am playing around with &lt;a href="https://emscripten.org" rel="noopener noreferrer"&gt;Emscipten&lt;/a&gt;. It is a WASM compiler which wraps around &lt;code&gt;clang&lt;/code&gt; to compile C/C++ source code in a binary &lt;code&gt;.wasm&lt;/code&gt; format. It  also provides some glue-code API to embed this WASM binary into JavaScript. Just look into &lt;a href="https://developer.mozilla.org/en-US/docs/WebAssembly" rel="noopener noreferrer"&gt;MDN Docs&lt;/a&gt; and &lt;a href="https://emscripten.org/docs/getting_started/index.html" rel="noopener noreferrer"&gt;Emscripten SDK&lt;/a&gt; to get started.&lt;/p&gt;

&lt;h1&gt;
  
  
  Managing memory with Emscripten
&lt;/h1&gt;

&lt;p&gt;Before, diving into high-level Emscripten stuff such as &lt;a href="https://emscripten.org/docs/porting/connecting_cpp_and_javascript/embind.html?highlight=embind" rel="noopener noreferrer"&gt;Embind&lt;/a&gt;, I decided to look into its low-level memory model.&lt;/p&gt;

&lt;p&gt;Here is a toy problem. We have a C-function that takes an array of &lt;code&gt;double&lt;/code&gt; precision values, do something with them and return a number. It may look as simple this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// malloc_testing.c

#include &amp;lt;assert.h&amp;gt;
#include &amp;lt;math.h&amp;gt;
#include &amp;lt;stdio.h&amp;gt;

double vector_norm(double* p, int n) {
    int i;
    double norm2 = 0;

    assert(n &amp;gt; 0 &amp;amp;&amp;amp; "number of elements must be positive");
    assert(p &amp;amp;&amp;amp; "must be a valid pointer");
    printf("received: n = %d\n", n);

    for (i = 0; i &amp;lt; n; i++) {
        printf("processed: p[%d] = %.3f\n", i, p[i]);
        norm2 += p[i] * p[i];
    }
    return sqrt(norm2);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the code, I sprinkled some asserts and old-fashioned print-outs for convenience. Don't forget to wrap it in &lt;code&gt;extern "C" {}&lt;/code&gt; if you are going to treat as C++ code.&lt;/p&gt;

&lt;p&gt;We &lt;a href="https://dev.to/iprosk/my-first-take-on-webassembly-213h"&gt;already know&lt;/a&gt; that this function can be called from JavaScript using &lt;code&gt;ccall()&lt;/code&gt; or &lt;code&gt;cwrap()&lt;/code&gt; methods, but how can we pass an array from JavaScript to our C-code?&lt;/p&gt;

&lt;p&gt;Let us compile this function into a binary using Emscripten &lt;code&gt;emcc&lt;/code&gt; compiler.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$emcc malloc_testing.c -o malloc_testing.js -O0 -sASSERTIONS=2 -sEXPORTED_FUNCTIONS=_vector_norm,_malloc,_free,setValue -sEXPORTED_RUNTIME_METHODS=cwrap,ccall
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, I tell the compiler to keep the assertions by setting low optimization level &lt;code&gt;-O0&lt;/code&gt;, and export some useful stuff like &lt;code&gt;_malloc&lt;/code&gt;, &lt;code&gt;_free&lt;/code&gt;, and &lt;code&gt;setValue&lt;/code&gt;, and our C-function of course &lt;code&gt;_vector_norm&lt;/code&gt; (note the leading underscore).&lt;/p&gt;

&lt;p&gt;Now we have a couple of files: &lt;code&gt;malloc_testing.wasm&lt;/code&gt; that contains a binary, and &lt;code&gt;malloc_testing.js&lt;/code&gt; which is JavaScript glue code that allows us to use it from a web page. You can also run in Node.js, but in this case it should be compiled with &lt;code&gt;-sMODULARIZE&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Allocating memory from JavaScript
&lt;/h2&gt;

&lt;p&gt;How does memory model of the WASM VM look like? Well, for C/C++ code it look pretty normal: code, heap, stack. We can allocate stuff on the heap and pass pointers around. Luckily for us, we also asked &lt;code&gt;emcc&lt;/code&gt; to export memory allocation, &lt;code&gt;_malloc&lt;/code&gt;, in to the JavaScript glue code, so now we can allocate memory on the heap in WASM from JavaScript.&lt;/p&gt;

&lt;p&gt;In theory, the whole process looks easy: allocate memory on the heap and get pointer into JavaScript code, write something into this memory, and pass this pointer to the C-function. Something like that:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftm7756tb38s1cc82vtli.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftm7756tb38s1cc82vtli.png" alt=" " width="696" height="361"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let's try it. I will use a simple web page set up to run our C-function inside the browser by pressing a button.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
&amp;lt;body&amp;gt;

&amp;lt;button id="mybutton"&amp;gt;Run&amp;lt;/button&amp;gt;

&amp;lt;script&amp;gt;
    document.getElementById("mybutton").addEventListener("click", ()=&amp;gt;{

        const vectorNorm = Module.cwrap(
                               'vector_norm', // no underscore
                                'number',  // return type 
                                ['number', 'number']); // param types;

        const myTypedArray = new Float64Array([0, 1, 2, 3, 5]);

        // allocate empty buffer
        let buf = Module._malloc(myTypedArray.length * myTypedArray.BYTES_PER_ELEMENT);

        // fill  this buffer with our stuff
        Module.HEAPF64.set(myTypedArray, buf / myTypedArray.BYTES_PER_ELEMENT);

        // call our function and pass pointer to buffer
        const result = vectorNorm(buf, myTypedeArray.length);

        console.log(`result = ${result}`);

        Module._free(buf);  // no leaks!
    });
&amp;lt;/script&amp;gt;

&amp;lt;script src="malloc_testing.js"&amp;gt;&amp;lt;/script&amp;gt;

&amp;lt;/body&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, I first create a JavaScript typed array with &lt;code&gt;float64&lt;/code&gt; continuous view of memory. &lt;/p&gt;

&lt;p&gt;After that, I create an empty buffer on the heap inside WASM memory by calling to &lt;code&gt;_malloc&lt;/code&gt; that we exported when we compiled our C-file. It returns a pointer &lt;code&gt;buf&lt;/code&gt; to the allocated segment of memory, which in JavaScript code is treated simply as a &lt;code&gt;number&lt;/code&gt; (very "safe", eh?). &lt;/p&gt;

&lt;p&gt;Next step is to fill allocated memory with something. I use &lt;code&gt;Module.HEAPF64.set(myTypedArray, buf / myTypedArray.BYTES_PER_ELEMENT)&lt;/code&gt; that takes two arguments: my array, and a pointer to the buffer. Note the alignment! The pointer must count by 8-bytes. It actually took me more than an hour to figure it out since Empscipten API docs are quite, hm, &lt;em&gt;emscryptic&lt;/em&gt; on this point. Thanks to ChatGPT and &lt;a href="https://stackoverflow.com/questions/70050802/where-is-the-documentation-for-webassembly-heapf64-set" rel="noopener noreferrer"&gt;this post&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;To see how it works, we can replace the call to &lt;code&gt;HEAPF64.set&lt;/code&gt; by manual allocation. I came up with something like this (don't do it anywhere near production!):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function setMemoryManually(myArray, ptr) {
    for (const x of myArray) {
        Module.setValue(ptr, x, 'double');
        ptr += myArray.BYTES_PER_ELEMENT;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It looks ugly, but works. Low-level function &lt;code&gt;Module.setValue(ptr, value, 'double')&lt;/code&gt; can be used to manually set a &lt;code&gt;value&lt;/code&gt; at the address pointed by &lt;code&gt;ptr&lt;/code&gt;. In this case, no tricks. The pointer is incremented by &lt;code&gt;BYTES_PER_ELEMENT = 8&lt;/code&gt; for &lt;code&gt;double&lt;/code&gt;. So now I can write something like &lt;code&gt;setMemoryManually(myTypedArray, buf)&lt;/code&gt; in my JavaScript code, and it will fill the buffer with the content of &lt;code&gt;myTypedArray&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;When all memory is set, we can call our C-function from JavaScript. I prefer to wrap it up first.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const vectorNorm = Module.cwrap('vector_norm', // no underscore
                                'number',  // return type 
                                ['number', 'number']); // param types;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We tell &lt;code&gt;cwrap&lt;/code&gt; that we return a &lt;code&gt;number&lt;/code&gt;, and we pass a couple of &lt;code&gt;number&lt;/code&gt; values. Yes, the pointer to the buffer of the allocated memory is passed as a &lt;code&gt;number&lt;/code&gt; (looks very "safe" and "portable", eh?). So we can just call &lt;code&gt;vectorNorm&lt;/code&gt; from our script.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const result = vectorNorm(buf, myTypedArray.length);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Last step. Open a browser, serve our http-web page from a local host (I just run &lt;code&gt;python -m http.server&lt;/code&gt;)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;http://localhost:8000/wasm_testing/malloc_testing.html
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;hard reload, press &lt;code&gt;Run&lt;/code&gt;, and here we go&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;received: n = 5
p[0] = 0.000
p[1] = 1.000
p[2] = 2.000
p[3] = 3.000
p[4] = 5.000
result = 6.244997998398398
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  In summary...
&lt;/h1&gt;

&lt;p&gt;Playing with low-level stuff is fun, but I won't use it anywhere in  productionable code. Well, at least without considerable experience and understanding of the &lt;a href="https://github.com/emscripten-core/emscripten" rel="noopener noreferrer"&gt;Emscripten code base&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>cpp</category>
      <category>webassembly</category>
      <category>beginners</category>
    </item>
    <item>
      <title>My first take on WebAssembly</title>
      <dc:creator>Igor Proskurin</dc:creator>
      <pubDate>Mon, 04 Sep 2023 03:31:03 +0000</pubDate>
      <link>https://dev.to/iprosk/my-first-take-on-webassembly-213h</link>
      <guid>https://dev.to/iprosk/my-first-take-on-webassembly-213h</guid>
      <description>&lt;p&gt;Here we go, I decided to try WebAssembly having a project in mind, but before dedicating myself and take on coding, there is always fun of fooling around with some code.&lt;/p&gt;

&lt;p&gt;If you are new to WebAssembly, the first place to go after Wikipedia is probably &lt;a href="https://developer.mozilla.org/en-US/docs/WebAssembly" rel="noopener noreferrer"&gt;MDN Web Docs&lt;/a&gt; that gives a decent introductory background. It explains that WebAssembly is binary format and the corresponding assembly language that runs in a Virtual Machine built into all modern browsers. It sounds like a blasphemy if you are an acolyte of &lt;a href="https://en.wikipedia.org/wiki/Unix_philosophy" rel="noopener noreferrer"&gt;Unix Philosophy&lt;/a&gt;, but otherwise it is a cool client-side portable technology to deal with high-performance numeric computations (no, no, I am not talking about crypto mining).&lt;/p&gt;

&lt;p&gt;So where should we start?&lt;/p&gt;

&lt;h1&gt;
  
  
  First comes a compiler
&lt;/h1&gt;

&lt;p&gt;In order to use WebAssembly with our shiny cool numeric C/C++ libraries (you are not going to manually write assembly, aren't you?), we need a compiler that takes C/C++ source as an input and generates a &lt;code&gt;*.wasm&lt;/code&gt; binary file along with some JavaScript glue code, which is needed to call binary code from a web-page or Node.js. Well, MDN recommends to use &lt;a href="https://emscripten.org/" rel="noopener noreferrer"&gt;Emscipten&lt;/a&gt;, which wraps around LLVM &lt;code&gt;clang&lt;/code&gt; compiler, and I am not in a position to make a reasonable argument about other options...&lt;/p&gt;

&lt;p&gt;I will skip the details of how to install Emscripten SDK. &lt;a href="https://emscripten.org/docs/getting_started/downloads.html" rel="noopener noreferrer"&gt;It is pretty easy&lt;/a&gt;. Just note that the most reasonable and sane way to use &lt;code&gt;emcc&lt;/code&gt; compiler is, probably, from &lt;code&gt;bash&lt;/code&gt;. But I decided to give it a try from PowerShell first without additional abstractions like WSL, and it worked... Nice surprise.&lt;/p&gt;

&lt;h1&gt;
  
  
  Let's compile something
&lt;/h1&gt;

&lt;p&gt;Well, let me skip a &lt;a href="https://developer.mozilla.org/en-US/docs/WebAssembly/C_to_Wasm" rel="noopener noreferrer"&gt;hello world&lt;/a&gt; example, and start with some basic questions one needs to figure out before starting a project.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;How can I interface my C/C++ code with JavaScript? At minimum, I need to call some functions. It would be nice to have a full support of classes, threads, etc -- but maybe later, okay?&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;How can I pass anything from JavaScript to C/C++. Passing a couple of &lt;code&gt;double&lt;/code&gt;s would be nice, but I also need to pass &lt;code&gt;Float64&lt;/code&gt; arrays and aggregate data like &lt;code&gt;struct&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;How would my C/C++ library functions return anything meaningful rather than a single numeric value?&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let's move one step after another and take time to look around...&lt;/p&gt;

&lt;h2&gt;
  
  
  Calling C-functions using &lt;code&gt;ccall()&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;Let us prepare a very basic "numeric library".&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ccall_testing.cpp

#include &amp;lt;cmath&amp;gt;
#include &amp;lt;iostream&amp;gt;

#include &amp;lt;emscripten/emscripten.h&amp;gt;

extern "C" {

EMSCRIPTEN_KEEPALIVE double my_norm(double x, double y) {
    std::cout &amp;lt;&amp;lt; "my_norm is called\n";
    return std::sqrt(x * x + y * y);
}

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And yes, &lt;code&gt;ccall()&lt;/code&gt; is to call C-functions, so here is &lt;code&gt;extern "C"&lt;/code&gt; to deal with C++ &lt;a href="https://en.wikipedia.org/wiki/Name_mangling" rel="noopener noreferrer"&gt;name mangling&lt;/a&gt;. We also need &lt;code&gt;EMSCRIPTEN_KEEPALIVE&lt;/code&gt; to prevent this code to be optimized out as &lt;a href="https://emscripten.org/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.html" rel="noopener noreferrer"&gt;dead code&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Now, don't forget to source all the environmental variables from your shell of choice. There is a collection of shell scripts for doing it in your Emscripten SDK source directory. In PowerShell, I just run &lt;code&gt;./emcmdprompt.bat&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Then compile our source file using &lt;code&gt;emcc&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$emcc ccall_testing.cpp -o ccall_testing.js -sEXPORTED_RUNTIME_METHODS=ccall
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have two files. The first is WebAssembly binary &lt;code&gt;ccall_testing.wasm&lt;/code&gt; and the second is JavaScript glue code &lt;code&gt;ccall_testing.js&lt;/code&gt;. It is possible to use &lt;code&gt;html&lt;/code&gt; as the compiler's target, and it will generate a web-page, but I will stick to &lt;code&gt;*.js&lt;/code&gt; to remain in control.&lt;/p&gt;

&lt;p&gt;It is time to call our library function from a web page. Let's come up with something very basic:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
&amp;lt;head&amp;gt;
    &amp;lt;title&amp;gt;My WASM experiments&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;

&amp;lt;button id="mybutton"&amp;gt;Run&amp;lt;/button&amp;gt;

&amp;lt;script&amp;gt;
    document.getElementById("mybutton").addEventListener("click", ()=&amp;gt;{
        const result = Module.ccall("my_norm", // yes, that's our function
                            "number",               // return type
                           ["number", "number"],    // argument types
                           [3.0, 4.0]           // yeah, Pythagorean triple
                       );

        console.log(`result = ${result}`);
    });
&amp;lt;/script&amp;gt;

&amp;lt;script src="ccall_testing.js" type="text/javascript" async&amp;gt;&amp;lt;/script&amp;gt;

&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Save this as &lt;code&gt;ccall_testing.html&lt;/code&gt; and then run in the browther. Does not work? There is additional step. In order to load &lt;code&gt;*.wasm&lt;/code&gt; blob, we can serve the page from a simple http-server:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$python -m http.server
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;which will open a connection at &lt;code&gt;localhost:8000&lt;/code&gt;. Now just open &lt;code&gt;html&lt;/code&gt;-file in the directory of your choice:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;http://localhost:8000/wasm_testing/ccall_testing.html
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Press &lt;code&gt;Run&lt;/code&gt;, open a console &lt;code&gt;Ctrl-Shift-I&lt;/code&gt; and &lt;em&gt;Voila!&lt;/em&gt; (don't forget &lt;code&gt;Ctrl+R&lt;/code&gt; to reload cache):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_norm is called   ccall_testing.js:1559:16
result = 5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Prefer wraps instead of calls?
&lt;/h2&gt;

&lt;p&gt;No problem! It is possible to wrap C-function directly into JavaScript function using &lt;code&gt;cwrap()&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;In this case, we don't need &lt;code&gt;EMSCRIPTEN_KEEPALIVE&lt;/code&gt; any more because we will tell the compiler to export this function anyway so our &lt;code&gt;cpp&lt;/code&gt;-file becomes a bit cleaner&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// cwrap_testing.cpp

#include &amp;lt;cmath&amp;gt;
#include &amp;lt;iostream&amp;gt;

#include &amp;lt;emscripten/emscripten.h&amp;gt;

extern "C" {

double my_norm(double x, double y) {
    std::cout &amp;lt;&amp;lt; "my_norm is called\n";
    return std::sqrt(x * x + y * y);
}

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Call the compiler and add &lt;code&gt;-sEXPORTED_FUNCTIONS=_my_norm&lt;/code&gt; with an underscore in front of the function name (that's an assembly symbol, like &lt;code&gt;_start&lt;/code&gt;)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$emcc cwrap_testing.cpp -o cwrap_testing.js -sEXPORTED_FUNCTIONS=_my_norm -sEXPORTED_RUNTIME_METHODS=cwrap
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our &lt;code&gt;html&lt;/code&gt; file also becomes slightly different. Here, I introduce a new JavaScript function &lt;code&gt;myNorm&lt;/code&gt; that wraps around the C-library function call&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;button id="mybutton"&amp;gt;Run&amp;lt;/button&amp;gt;

&amp;lt;script&amp;gt;
    document.getElementById("mybutton").addEventListener("click", ()=&amp;gt;{
        const myNorm = Module.cwrap("my_norm", // no underscore
                                    'number',  // return type 
                                    ['number', 'number']); // param types;
        const result = myNorm(3.0, 4.0);
        console.log(`result = ${result}`);
    });
&amp;lt;/script&amp;gt;

&amp;lt;script src="cwrap_testing.js" type="text/javascript" async&amp;gt;&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The result is the same as for &lt;code&gt;ccall()&lt;/code&gt;. That's nice. But how can we pass something more meaningful? &lt;/p&gt;

&lt;h2&gt;
  
  
  But I need to pass an array of &lt;code&gt;Float64&lt;/code&gt;...
&lt;/h2&gt;

&lt;p&gt;The naive question would be: can we use &lt;code&gt;'array'&lt;/code&gt; instead of &lt;code&gt;'number'&lt;/code&gt; in the function call? So our code would look like: &lt;code&gt;Module.ccall("my_norm", "number", "array", [3.0, 4.0])&lt;/code&gt;?&lt;/p&gt;

&lt;p&gt;The answer is "not so simple"... The &lt;code&gt;array&lt;/code&gt; type here really means something like "raw byte buffer".&lt;/p&gt;

&lt;p&gt;According to the &lt;a href="https://emscripten.org/docs/api_reference/preamble.js.html#preamble-js" rel="noopener noreferrer"&gt;API documentation&lt;/a&gt;: " 'array' [is] for JavaScript arrays and typed arrays, containing 8-bit integer data - that is, the data is written into a C array of 8-bit integers". &lt;/p&gt;

&lt;p&gt;So if we need to pass an array of &lt;code&gt;double&lt;/code&gt;s, it is either a manual allocation and passing a pointer (as a &lt;code&gt;'number'&lt;/code&gt;) or &lt;a href="https://emscripten.org/docs/porting/connecting_cpp_and_javascript/embind.html" rel="noopener noreferrer"&gt;Embind&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Yeah, Embind is cool! Let's come back to that...&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>cpp</category>
      <category>webassembly</category>
      <category>beginners</category>
    </item>
  </channel>
</rss>
