From 096193f7ab65f1f128547a354acb6764734b4a11 Mon Sep 17 00:00:00 2001
From: Sebastien Bourdeauducq <sb@m-labs.hk>
Date: Sun, 9 Jan 2022 10:51:10 +0800
Subject: [PATCH] demo: rewrite in Rust

---
 nac3standalone/demo/demo.c      | 30 ------------------------------
 nac3standalone/demo/demo.rs     | 29 +++++++++++++++++++++++++++++
 nac3standalone/demo/run_demo.sh |  2 +-
 3 files changed, 30 insertions(+), 31 deletions(-)
 delete mode 100644 nac3standalone/demo/demo.c
 create mode 100644 nac3standalone/demo/demo.rs

diff --git a/nac3standalone/demo/demo.c b/nac3standalone/demo/demo.c
deleted file mode 100644
index ad19ee1eb..000000000
--- a/nac3standalone/demo/demo.c
+++ /dev/null
@@ -1,30 +0,0 @@
-#include <stdio.h>
-#include <string.h>
-
-void output_int32(int x) {
-    printf("%d\n", x);
-}
-
-void output_int64(long x) {
-    printf("%ld\n", x);
-}
-
-void output_asciiart(int x) {
-    static char chars[] = " .,-:;i+hHM$*#@  ";
-    if(x < 0) {
-        putchar('\n');
-    } else {
-        if(x < strlen(chars)) {
-            putchar(chars[x]);
-        } else {
-            printf("ERROR\n");
-        }
-    }
-}
-
-extern int run();
-
-int main() {
-    run();
-    return 0;
-}
diff --git a/nac3standalone/demo/demo.rs b/nac3standalone/demo/demo.rs
new file mode 100644
index 000000000..a2794c9c4
--- /dev/null
+++ b/nac3standalone/demo/demo.rs
@@ -0,0 +1,29 @@
+#[no_mangle]
+pub extern "C" fn output_int32(x: i32) {
+    println!("{}", x);
+}
+
+#[no_mangle]
+pub extern "C" fn output_int64(x: i64) {
+    println!("{}", x);
+}
+
+#[no_mangle]
+pub extern "C" fn output_asciiart(x: i32) {
+    let chars = " .,-:;i+hHM$*#@  ";
+    if x < 0 {
+        println!("");
+    } else {
+        print!("{}", chars.chars().nth(x as usize).unwrap());
+    }
+}
+
+extern "C" {
+    fn run() -> i32;
+}
+
+fn main() {
+    unsafe {
+        run();
+    }
+}
diff --git a/nac3standalone/demo/run_demo.sh b/nac3standalone/demo/run_demo.sh
index f4185e74b..f60dc10ba 100755
--- a/nac3standalone/demo/run_demo.sh
+++ b/nac3standalone/demo/run_demo.sh
@@ -9,5 +9,5 @@ fi
 
 rm -f *.o
 ../../target/release/nac3standalone $1
-clang -Wall -O2 -o $1.elf demo.c module.o -lm
+rustc -o $1.elf demo.rs -Clink-arg=./module.o
 ./$1.elf