Blue Steel: Demo for The New Subzero Rust Codebase

What is this?

subZero is a standalone, extensible web server that turns your database directly into a REST/GraphQL api.

This repository is a showcases of it's functionality.

You can use it for free as a docker image where the constraints and permissions in the database determine the api endpoints and operations.

Alternatively, you can use it as a library dependence in your Rust code to bootstrap 90% of your backend and extend it with your custom routes and functionality.

Strengths

Complete CRUD and Auth out of the box

  • Just by defining your tables and views in your database you get a powerful CRUD api out of the box that will cover 90%+ of your needs. Throw in some database grants and constraints and you've got yourself an authentication/authorization functionality also.

Extensible (use it as a library)

  • The majority of the alternatives are available only as standalone services and to add custom functionality you have to use a combination between a proxy, messaging server and lambda functions (in addition to your database). This, as you imagine, massively complicates your production infrastructure and deployment procedure and of course you need extensive devops knowledge and resources. By using subzero as a library, you side step all that needles complication and deploy your custom application as a single binary/container.

Rust codebase

  • Rust is consistently voted the most loved language by developers and in heavy use at AWS, Google, Microsoft. This ensures that besides it's raw speed you also get a big pool of highly competent developers that are ready (and will enjoy) work on the codebase.

Speed

  • It's already cliche to use words like blazing, lightning, impressive to describe the performance of your product and we are running out of adjectives. How do you describe a product that is up to 8 times faster then the alternatives? We would like to assume credit for that though at this stage, this speed can mostly be attributed to Rust, that is to say, we haven't really optimized the code for performance yet, so expect even more impressive numbers.

Roadmap

  •  Core functions/types
  •  PostgreSQL backend
  •  SQLite backend
  •  REST frontend (PostgREST compatible)
  •  Production ready code
  •  Stable library interface
  •  Clickhouse backend

Try it

Bring up the docker services

docker-compose up -d

You can interact with the database at the following endpoints

  • Interact with the PostgreSQL database (subzero-postgresql) - http://localhost:8000/
  • Interact with the SQLite database (subzero-sqlite) - http://localhost:9000/

The REST API uses PostgREST dialect with additional support for analitical queries (GROUP BY, aggregate functions, window functions).

PostgreSQL backend sample request.

curl -i "http://localhost:8000/projects?select=id,name,tasks(name)&id=gt.1"

SQLite backend sample request.

curl -i "http://localhost:9000/projects?select=id,name,tasks(name)&id=gt.1"

License

A general overview of the standard commercial license is:

You can

  • Use the binary distribution for commercial or non-commercial purposes without charge
  • Use the source distribution to develop a SaaS product (subject to charges)
  • Use the source distribution to develop software that is distributed to clients in binary form (subject to charges).

You can not

  • Distribute/publish the source code
  • Develop services/software that directly competes with subzero
  • Study the code to create competing products

Download Details:

Author: subzerocloud
Source Code: https://github.com/subzerocloud/blue-steel

License: View license

#rust 

What is GEEK

Buddha Community

Blue Steel: Demo for The New Subzero Rust Codebase

Serde Rust: Serialization Framework for Rust

Serde

*Serde is a framework for serializing and deserializing Rust data structures efficiently and generically.*

You may be looking for:

Serde in action

Click to show Cargo.toml. Run this code in the playground.

[dependencies]

# The core APIs, including the Serialize and Deserialize traits. Always
# required when using Serde. The "derive" feature is only required when
# using #[derive(Serialize, Deserialize)] to make Serde work with structs
# and enums defined in your crate.
serde = { version = "1.0", features = ["derive"] }

# Each data format lives in its own crate; the sample code below uses JSON
# but you may be using a different one.
serde_json = "1.0"

 

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let point = Point { x: 1, y: 2 };

    // Convert the Point to a JSON string.
    let serialized = serde_json::to_string(&point).unwrap();

    // Prints serialized = {"x":1,"y":2}
    println!("serialized = {}", serialized);

    // Convert the JSON string back to a Point.
    let deserialized: Point = serde_json::from_str(&serialized).unwrap();

    // Prints deserialized = Point { x: 1, y: 2 }
    println!("deserialized = {:?}", deserialized);
}

Getting help

Serde is one of the most widely used Rust libraries so any place that Rustaceans congregate will be able to help you out. For chat, consider trying the #rust-questions or #rust-beginners channels of the unofficial community Discord (invite: https://discord.gg/rust-lang-community), the #rust-usage or #beginners channels of the official Rust Project Discord (invite: https://discord.gg/rust-lang), or the #general stream in Zulip. For asynchronous, consider the [rust] tag on StackOverflow, the /r/rust subreddit which has a pinned weekly easy questions post, or the Rust Discourse forum. It's acceptable to file a support issue in this repo but they tend not to get as many eyes as any of the above and may get closed without a response after some time.

Download Details:
Author: serde-rs
Source Code: https://github.com/serde-rs/serde
License: View license

#rust  #rustlang 

Blue Steel: Demo for The New Subzero Rust Codebase

What is this?

subZero is a standalone, extensible web server that turns your database directly into a REST/GraphQL api.

This repository is a showcases of it's functionality.

You can use it for free as a docker image where the constraints and permissions in the database determine the api endpoints and operations.

Alternatively, you can use it as a library dependence in your Rust code to bootstrap 90% of your backend and extend it with your custom routes and functionality.

Strengths

Complete CRUD and Auth out of the box

  • Just by defining your tables and views in your database you get a powerful CRUD api out of the box that will cover 90%+ of your needs. Throw in some database grants and constraints and you've got yourself an authentication/authorization functionality also.

Extensible (use it as a library)

  • The majority of the alternatives are available only as standalone services and to add custom functionality you have to use a combination between a proxy, messaging server and lambda functions (in addition to your database). This, as you imagine, massively complicates your production infrastructure and deployment procedure and of course you need extensive devops knowledge and resources. By using subzero as a library, you side step all that needles complication and deploy your custom application as a single binary/container.

Rust codebase

  • Rust is consistently voted the most loved language by developers and in heavy use at AWS, Google, Microsoft. This ensures that besides it's raw speed you also get a big pool of highly competent developers that are ready (and will enjoy) work on the codebase.

Speed

  • It's already cliche to use words like blazing, lightning, impressive to describe the performance of your product and we are running out of adjectives. How do you describe a product that is up to 8 times faster then the alternatives? We would like to assume credit for that though at this stage, this speed can mostly be attributed to Rust, that is to say, we haven't really optimized the code for performance yet, so expect even more impressive numbers.

Roadmap

  •  Core functions/types
  •  PostgreSQL backend
  •  SQLite backend
  •  REST frontend (PostgREST compatible)
  •  Production ready code
  •  Stable library interface
  •  Clickhouse backend

Try it

Bring up the docker services

docker-compose up -d

You can interact with the database at the following endpoints

  • Interact with the PostgreSQL database (subzero-postgresql) - http://localhost:8000/
  • Interact with the SQLite database (subzero-sqlite) - http://localhost:9000/

The REST API uses PostgREST dialect with additional support for analitical queries (GROUP BY, aggregate functions, window functions).

PostgreSQL backend sample request.

curl -i "http://localhost:8000/projects?select=id,name,tasks(name)&id=gt.1"

SQLite backend sample request.

curl -i "http://localhost:9000/projects?select=id,name,tasks(name)&id=gt.1"

License

A general overview of the standard commercial license is:

You can

  • Use the binary distribution for commercial or non-commercial purposes without charge
  • Use the source distribution to develop a SaaS product (subject to charges)
  • Use the source distribution to develop software that is distributed to clients in binary form (subject to charges).

You can not

  • Distribute/publish the source code
  • Develop services/software that directly competes with subzero
  • Study the code to create competing products

Download Details:

Author: subzerocloud
Source Code: https://github.com/subzerocloud/blue-steel

License: View license

#rust 

Awesome  Rust

Awesome Rust

1654894080

Serde JSON: JSON Support for Serde Framework

Serde JSON

Serde is a framework for serializing and deserializing Rust data structures efficiently and generically.

[dependencies]
serde_json = "1.0"

You may be looking for:

JSON is a ubiquitous open-standard format that uses human-readable text to transmit data objects consisting of key-value pairs.

{
    "name": "John Doe",
    "age": 43,
    "address": {
        "street": "10 Downing Street",
        "city": "London"
    },
    "phones": [
        "+44 1234567",
        "+44 2345678"
    ]
}

There are three common ways that you might find yourself needing to work with JSON data in Rust.

  • As text data. An unprocessed string of JSON data that you receive on an HTTP endpoint, read from a file, or prepare to send to a remote server.
  • As an untyped or loosely typed representation. Maybe you want to check that some JSON data is valid before passing it on, but without knowing the structure of what it contains. Or you want to do very basic manipulations like insert a key in a particular spot.
  • As a strongly typed Rust data structure. When you expect all or most of your data to conform to a particular structure and want to get real work done without JSON's loosey-goosey nature tripping you up.

Serde JSON provides efficient, flexible, safe ways of converting data between each of these representations.

Operating on untyped JSON values

Any valid JSON data can be manipulated in the following recursive enum representation. This data structure is serde_json::Value.

enum Value {
    Null,
    Bool(bool),
    Number(Number),
    String(String),
    Array(Vec<Value>),
    Object(Map<String, Value>),
}

A string of JSON data can be parsed into a serde_json::Value by the serde_json::from_str function. There is also from_slice for parsing from a byte slice &[u8] and from_reader for parsing from any io::Read like a File or a TCP stream.

use serde_json::{Result, Value};

fn untyped_example() -> Result<()> {
    // Some JSON input data as a &str. Maybe this comes from the user.
    let data = r#"
        {
            "name": "John Doe",
            "age": 43,
            "phones": [
                "+44 1234567",
                "+44 2345678"
            ]
        }"#;

    // Parse the string of data into serde_json::Value.
    let v: Value = serde_json::from_str(data)?;

    // Access parts of the data by indexing with square brackets.
    println!("Please call {} at the number {}", v["name"], v["phones"][0]);

    Ok(())
}

The result of square bracket indexing like v["name"] is a borrow of the data at that index, so the type is &Value. A JSON map can be indexed with string keys, while a JSON array can be indexed with integer keys. If the type of the data is not right for the type with which it is being indexed, or if a map does not contain the key being indexed, or if the index into a vector is out of bounds, the returned element is Value::Null.

When a Value is printed, it is printed as a JSON string. So in the code above, the output looks like Please call "John Doe" at the number "+44 1234567". The quotation marks appear because v["name"] is a &Value containing a JSON string and its JSON representation is "John Doe". Printing as a plain string without quotation marks involves converting from a JSON string to a Rust string with as_str() or avoiding the use of Value as described in the following section.

The Value representation is sufficient for very basic tasks but can be tedious to work with for anything more significant. Error handling is verbose to implement correctly, for example imagine trying to detect the presence of unrecognized fields in the input data. The compiler is powerless to help you when you make a mistake, for example imagine typoing v["name"] as v["nmae"] in one of the dozens of places it is used in your code.

Parsing JSON as strongly typed data structures

Serde provides a powerful way of mapping JSON data into Rust data structures largely automatically.

use serde::{Deserialize, Serialize};
use serde_json::Result;

#[derive(Serialize, Deserialize)]
struct Person {
    name: String,
    age: u8,
    phones: Vec<String>,
}

fn typed_example() -> Result<()> {
    // Some JSON input data as a &str. Maybe this comes from the user.
    let data = r#"
        {
            "name": "John Doe",
            "age": 43,
            "phones": [
                "+44 1234567",
                "+44 2345678"
            ]
        }"#;

    // Parse the string of data into a Person object. This is exactly the
    // same function as the one that produced serde_json::Value above, but
    // now we are asking it for a Person as output.
    let p: Person = serde_json::from_str(data)?;

    // Do things just like with any other Rust data structure.
    println!("Please call {} at the number {}", p.name, p.phones[0]);

    Ok(())
}

This is the same serde_json::from_str function as before, but this time we assign the return value to a variable of type Person so Serde will automatically interpret the input data as a Person and produce informative error messages if the layout does not conform to what a Person is expected to look like.

Any type that implements Serde's Deserialize trait can be deserialized this way. This includes built-in Rust standard library types like Vec<T> and HashMap<K, V>, as well as any structs or enums annotated with #[derive(Deserialize)].

Once we have p of type Person, our IDE and the Rust compiler can help us use it correctly like they do for any other Rust code. The IDE can autocomplete field names to prevent typos, which was impossible in the serde_json::Value representation. And the Rust compiler can check that when we write p.phones[0], then p.phones is guaranteed to be a Vec<String> so indexing into it makes sense and produces a String.

The necessary setup for using Serde's derive macros is explained on the Using derive page of the Serde site.

Constructing JSON values

Serde JSON provides a json! macro to build serde_json::Value objects with very natural JSON syntax.

use serde_json::json;

fn main() {
    // The type of `john` is `serde_json::Value`
    let john = json!({
        "name": "John Doe",
        "age": 43,
        "phones": [
            "+44 1234567",
            "+44 2345678"
        ]
    });

    println!("first phone number: {}", john["phones"][0]);

    // Convert to a string of JSON and print it out
    println!("{}", john.to_string());
}

The Value::to_string() function converts a serde_json::Value into a String of JSON text.

One neat thing about the json! macro is that variables and expressions can be interpolated directly into the JSON value as you are building it. Serde will check at compile time that the value you are interpolating is able to be represented as JSON.

let full_name = "John Doe";
let age_last_year = 42;

// The type of `john` is `serde_json::Value`
let john = json!({
    "name": full_name,
    "age": age_last_year + 1,
    "phones": [
        format!("+44 {}", random_phone())
    ]
});

This is amazingly convenient, but we have the problem we had before with Value: the IDE and Rust compiler cannot help us if we get it wrong. Serde JSON provides a better way of serializing strongly-typed data structures into JSON text.

Creating JSON by serializing data structures

A data structure can be converted to a JSON string by serde_json::to_string. There is also serde_json::to_vec which serializes to a Vec<u8> and serde_json::to_writer which serializes to any io::Write such as a File or a TCP stream.

use serde::{Deserialize, Serialize};
use serde_json::Result;

#[derive(Serialize, Deserialize)]
struct Address {
    street: String,
    city: String,
}

fn print_an_address() -> Result<()> {
    // Some data structure.
    let address = Address {
        street: "10 Downing Street".to_owned(),
        city: "London".to_owned(),
    };

    // Serialize it to a JSON string.
    let j = serde_json::to_string(&address)?;

    // Print, write to a file, or send to an HTTP server.
    println!("{}", j);

    Ok(())
}

Any type that implements Serde's Serialize trait can be serialized this way. This includes built-in Rust standard library types like Vec<T> and HashMap<K, V>, as well as any structs or enums annotated with #[derive(Serialize)].

Performance

It is fast. You should expect in the ballpark of 500 to 1000 megabytes per second deserialization and 600 to 900 megabytes per second serialization, depending on the characteristics of your data. This is competitive with the fastest C and C++ JSON libraries or even 30% faster for many use cases. Benchmarks live in the serde-rs/json-benchmark repo.

Getting help

Serde is one of the most widely used Rust libraries, so any place that Rustaceans congregate will be able to help you out. For chat, consider trying the #rust-questions or #rust-beginners channels of the unofficial community Discord (invite: https://discord.gg/rust-lang-community), the #rust-usage or #beginners channels of the official Rust Project Discord (invite: https://discord.gg/rust-lang), or the #general stream in Zulip. For asynchronous, consider the [rust] tag on StackOverflow, the /r/rust subreddit which has a pinned weekly easy questions post, or the Rust Discourse forum. It's acceptable to file a support issue in this repo, but they tend not to get as many eyes as any of the above and may get closed without a response after some time.

No-std support

As long as there is a memory allocator, it is possible to use serde_json without the rest of the Rust standard library. This is supported on Rust 1.36+. Disable the default "std" feature and enable the "alloc" feature:

[dependencies]
serde_json = { version = "1.0", default-features = false, features = ["alloc"] }

For JSON support in Serde without a memory allocator, please see the serde-json-core crate.

Link: https://crates.io/crates/serde_json

#rust  #rustlang  #encode   #json 

Justen  Hintz

Justen Hintz

1663559281

To-do List App with HTML, CSS and JavaScript

Learn how to create a to-do list app with local storage using HTML, CSS and JavaScript. Build a Todo list application with HTML, CSS and JavaScript. Learn the basics to JavaScript along with some more advanced features such as LocalStorage for saving data to the browser.

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>To Do List With Local Storage</title>
    <!-- Font Awesome Icons -->
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css"
    />
    <!-- Google Fonts -->
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500&display=swap"
      rel="stylesheet"
    />
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <div id="new-task">
        <input type="text" placeholder="Enter The Task Here..." />
        <button id="push">Add</button>
      </div>
      <div id="tasks"></div>
    </div>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>

CSS:

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
body {
  background-color: #0b87ff;
}
.container {
  width: 90%;
  max-width: 34em;
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
}
#new-task {
  position: relative;
  background-color: #ffffff;
  padding: 1.8em 1.25em;
  border-radius: 0.3em;
  box-shadow: 0 1.25em 1.8em rgba(1, 24, 48, 0.15);
  display: grid;
  grid-template-columns: 9fr 3fr;
  gap: 1em;
}
#new-task input {
  font-family: "Poppins", sans-serif;
  font-size: 1em;
  border: none;
  border-bottom: 2px solid #d1d3d4;
  padding: 0.8em 0.5em;
  color: #111111;
  font-weight: 500;
}
#new-task input:focus {
  outline: none;
  border-color: #0b87ff;
}
#new-task button {
  font-family: "Poppins", sans-serif;
  font-weight: 500;
  font-size: 1em;
  background-color: #0b87ff;
  color: #ffffff;
  outline: none;
  border: none;
  border-radius: 0.3em;
  cursor: pointer;
}
#tasks {
  background-color: #ffffff;
  position: relative;
  padding: 1.8em 1.25em;
  margin-top: 3.8em;
  width: 100%;
  box-shadow: 0 1.25em 1.8em rgba(1, 24, 48, 0.15);
  border-radius: 0.6em;
}
.task {
  background-color: #ffffff;
  padding: 0.3em 0.6em;
  margin-top: 0.6em;
  display: flex;
  align-items: center;
  border-bottom: 2px solid #d1d3d4;
  cursor: pointer;
}
.task span {
  font-family: "Poppins", sans-serif;
  font-size: 0.9em;
  font-weight: 400;
}
.task button {
  color: #ffffff;
  padding: 0.8em 0;
  width: 2.8em;
  border-radius: 0.3em;
  border: none;
  outline: none;
  cursor: pointer;
}
.delete {
  background-color: #fb3b3b;
}
.edit {
  background-color: #0b87ff;
  margin-left: auto;
  margin-right: 3em;
}
.completed {
  text-decoration: line-through;
}

Javascript:

//Initial References
const newTaskInput = document.querySelector("#new-task input");
const tasksDiv = document.querySelector("#tasks");
let deleteTasks, editTasks, tasks;
let updateNote = "";
let count;

//Function on window load
window.onload = () => {
  updateNote = "";
  count = Object.keys(localStorage).length;
  displayTasks();
};

//Function to Display The Tasks
const displayTasks = () => {
  if (Object.keys(localStorage).length > 0) {
    tasksDiv.style.display = "inline-block";
  } else {
    tasksDiv.style.display = "none";
  }

  //Clear the tasks
  tasksDiv.innerHTML = "";

  //Fetch All The Keys in local storage
  let tasks = Object.keys(localStorage);
  tasks = tasks.sort();

  for (let key of tasks) {
    let classValue = "";

    //Get all values
    let value = localStorage.getItem(key);
    let taskInnerDiv = document.createElement("div");
    taskInnerDiv.classList.add("task");
    taskInnerDiv.setAttribute("id", key);
    taskInnerDiv.innerHTML = `<span id="taskname">${key.split("_")[1]}</span>`;
    //localstorage would store boolean as string so we parse it to boolean back
    let editButton = document.createElement("button");
    editButton.classList.add("edit");
    editButton.innerHTML = `<i class="fa-solid fa-pen-to-square"></i>`;
    if (!JSON.parse(value)) {
      editButton.style.visibility = "visible";
    } else {
      editButton.style.visibility = "hidden";
      taskInnerDiv.classList.add("completed");
    }
    taskInnerDiv.appendChild(editButton);
    taskInnerDiv.innerHTML += `<button class="delete"><i class="fa-solid fa-trash"></i></button>`;
    tasksDiv.appendChild(taskInnerDiv);
  }

  //tasks completed
  tasks = document.querySelectorAll(".task");
  tasks.forEach((element, index) => {
    element.onclick = () => {
      //local storage update
      if (element.classList.contains("completed")) {
        updateStorage(element.id.split("_")[0], element.innerText, false);
      } else {
        updateStorage(element.id.split("_")[0], element.innerText, true);
      }
    };
  });

  //Edit Tasks
  editTasks = document.getElementsByClassName("edit");
  Array.from(editTasks).forEach((element, index) => {
    element.addEventListener("click", (e) => {
      //Stop propogation to outer elements (if removed when we click delete eventually rhw click will move to parent)
      e.stopPropagation();
      //disable other edit buttons when one task is being edited
      disableButtons(true);
      //update input value and remove div
      let parent = element.parentElement;
      newTaskInput.value = parent.querySelector("#taskname").innerText;
      //set updateNote to the task that is being edited
      updateNote = parent.id;
      //remove task
      parent.remove();
    });
  });

  //Delete Tasks
  deleteTasks = document.getElementsByClassName("delete");
  Array.from(deleteTasks).forEach((element, index) => {
    element.addEventListener("click", (e) => {
      e.stopPropagation();
      //Delete from local storage and remove div
      let parent = element.parentElement;
      removeTask(parent.id);
      parent.remove();
      count -= 1;
    });
  });
};

//Disable Edit Button
const disableButtons = (bool) => {
  let editButtons = document.getElementsByClassName("edit");
  Array.from(editButtons).forEach((element) => {
    element.disabled = bool;
  });
};

//Remove Task from local storage
const removeTask = (taskValue) => {
  localStorage.removeItem(taskValue);
  displayTasks();
};

//Add tasks to local storage
const updateStorage = (index, taskValue, completed) => {
  localStorage.setItem(`${index}_${taskValue}`, completed);
  displayTasks();
};

//Function To Add New Task
document.querySelector("#push").addEventListener("click", () => {
  //Enable the edit button
  disableButtons(false);
  if (newTaskInput.value.length == 0) {
    alert("Please Enter A Task");
  } else {
    //Store locally and display from local storage
    if (updateNote == "") {
      //new task
      updateStorage(count, newTaskInput.value, false);
    } else {
      //update task
      let existingCount = updateNote.split("_")[0];
      removeTask(updateNote);
      updateStorage(existingCount, newTaskInput.value, false);
      updateNote = "";
    }
    count += 1;
    newTaskInput.value = "";
  }
});

Related Videos

Build a Todo list app in HTML, CSS & JavaScript | JavaScript for Beginners tutorial

Build a Todo List App in HTML, CSS & JavaScript with LocalStorage | JavaScript for Beginners

To Do List using HTML CSS JavaScript | To Do List JavaScript

Create A Todo List App in HTML CSS & JavaScript | Todo App in JavaScript

#html #css #javascript

Comparing Rust scripting languages in game development

Rust has been something of a rockstar language in recent times as it continues to grow in popularity, thanks to its numerous benefits; like being very close to C/C++ in terms of performance and its ability to compile to WebAssembly.

The current state of gaming industry has primarily focused on programming languages such as C/C++, Java, and C# for both development and for game engines.

That was until the rise of Rust, which came with a different approach insofar as creating suitable programming languages that are flexible enough for games with respect to high performance, interfacing with other languages, and much more.

Terms to know

  • Scripting language: A scripting language is a language for a runtime system mostly used for automating the execution of tasks — in other words, scripting languages have fast execution because they are interpreted at runtime
  • Game engine: A game engine is a software framework developed with large support libraries for game development; it solves the problems of building game components from scratch which could be time consuming
  • WebAssembly: WebAssembly (abbreviated Wasm) is a concept of interfacing software built with languages such as Rust and Go with the output of a portable binary code format to a different environment, such as browser via JavaScript
  • Lua: Lua is a scripting language which is used in game development for fast execution, its short learning curve, and its ability to easily embed into an existing system
  • Lisp: (Game Oriented Assembly Lisp (GOAL)): This is a dialect of Lisp, which is also used for game development. In addition, Lisp as a language can be embedded in other languages to improve their performance

I will walk you through eight scripting languages developed for gaming in Rust which are categorized based on the following:

  • Community growth based on the GitHub stars
  • Stability based on release
  • Major features

GameLisp

GameLisp is a scripting language that has a unique garbage collector designed to run once per frame without causing latency spikes.

It works by loading the glsp file with the .glsp extension in Rust code. GameLisp is used for building 2D games as it also comes with common features available in modern languages.

Features include the following:

No garbage collection pauses

GameLisp was developed to handle garbage collection; this way it’s able to collect or gain memory back which has been allocated to objects.

Ease of Rust API integration

GameLisp is a Rust crate that can be installed and instantiated in a Rust program by loading the GameLisp file — this process makes it easy for GameLisp to be integrated in Rust code.

Memory-safe

GameLisp doesn’t implement unsafe code since the core logic of GameLisp is entirely written in Rust with few dependencies.

Easy entity scripting

The other benefit of GameLisp is the object system that is built around mixins and state machines specifically for game development entities.

  • Community: small
  • Stable: No

Example of GameLisp:

# GameLisp
(let fibs (arr 0 1))

(while (< (len fibs) 31)
  (push! fibs (+ \[fibs -1\] [fibs -2])))

(prn [fibs -1]) ; // Rust
use glsp::prelude::*;

fn main() {
    let app = Runtime::new();
    app.run(|| {
        glsp::load("external.glsp")?;
        Ok(())
    });
}

Throne

Throne is a scripting language for game prototyping and story logic; in other words, Throne is used to create syntax rules for a game which can be embedded in other engines.

It is developed to interface with JavaScript via WebAssembly. Throne can be used for storytelling and prototyping the concept of a game. It has the file extension .throne.

Its features includes:

Prototyping

Throne prototyping uses a variety of contexts, including semantics, syntax, etc., to express and evaluate the precision of game development analysis.

Story logic

Logic in storytelling is based on a narrative, character’s actions, events, etc., of a user’s point of view for a particular game.

  • Community: Small
  • Stability: No

Example of Throne:

// Throne file
// initialize state
fall-time 5 . default-fall-time 5 . block-id 0 . gravity-shape-id 0 . max-width 10 . max-height 20

#update . !shape _X _Y _BLOCKS . gravity-shape-id ID . + ID 1 ID' = gravity-shape-id ID' . #new-shape

#new-shape . $max-height H = new-shape 4 H ((block -1 0) ((block 0 0) ((block 1 0) ((block 0 1) (cons))))) . #shape-to-blocks (#input-lr)// Rust
#[cfg(not(target_arch = "wasm32"))]
fn main() {
  let mut context = throne::ContextBuilder::new()
  .text(include_str!("blocks.throne"))
  .build()
  .unwrap_or_else(|e| panic!("{}", e));
}

Wgpu

Wgpu is a cross-platform Rust graphics WebGPU standard API that runs on Vulkan, Metal, D3D12, D3D11, and OpenGLES — and likewise on WebGPU via WebAssembly (wasm).

It is built to allow web code access to GPU functionality in a safe and reliable paradigm, which also has binding support for languages via wgpu-native.

The features include:

Internal WebGPU implementation

Wgpu comes with WebGL as its core standard API, which is also used for rendering graphics such as 2D and 3D on a web browser without external plugins.

Internal GPU API abstraction layer

The performance of Wgpu solely relies on a GPU (graphics processing unit) abstract layer designed to augment the rendering process of graphics.

  • Community: Rising
  • Stability: Yes

Example of Wgpu:

// wgsl file
@vertex
fn main_vs(
  @location(0) particle_pos: vec2<f32>,
) -> @builtin(position) vec4<f32> {
  let angle = -atan2(particle_vel.x, particle_vel.y);
  let pos = vec2<f32>(
  position.x * cos(angle) - position.y * sin(angle),
  position.x * sin(angle) + position.y * cos(angle)
);
return vec4<f32>(pos + particle_pos, 0.0, 1.0);
}
@fragment
fn main_fs() -> @location(0) vec4<f32> {
  return vec4<f32>(1.0, 1.0, 1.0, 1.0);
}


fn main() {
  let draw = device.create_shader_module(&wgpu::ShaderModuleDescriptor {
            label: None,
            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("draw.wgsl"))),
        });
}

Mlua

Mlua is a high-level binding for the Lua language to provide a safe and flexible API. It has the following features:

Multiple Lua version support

This allows other Lua versions API modules to be accessed in Rust as well as Lua in a standalone environment.

Async/await support

It enables async/await support in which executors like Tokio and asyn-std can be used.

Serialization

Support for serialization and deserialization that support mlua types with Serde.

Standalone mode

The standalone mode is the declaration of Lua’s code directly in the Rust program, without the need for external import.

  • Community: Small
  • Production-ready: No

Example of Mlua:

fn main() {
    let mut lua = hlua::Lua::new();

    lua.execute_from_reader::<()>(File::open(&Path::new("script.lua")).unwrap())

    lua.set("add", hlua::function2(add));
    lua.execute::<()>("local c = add(2, 4)");   // calls the `add` function above
    let c: i32 = lua.get("c").unwrap(); 
    //standalone mode
    lua.set("a", 12);
    let val: i32 = lua.execute(r#"return a * 5;"#).unwrap();

}

Dyon

Dyon is a dynamically-typed language designed for game engines and interactive applications with the extension .dyon.

It is designed to work around limited memory model because it lacks a garbage collector. It has the following features:

Built-in support for 4D vectors; HTML hex colors

This allows more flexibility with types which can be used in Rust.

Go-like coroutines

This is a multi-threaded concept but with Go-like style which specifies go before the function name.

Macros

It also comes set of macros which makes embedding code with Rust much easier.

  • Community: Rising
  • Stability: Yes

Example of Dyon:

fn main() {
    shape := unwrap(load("src/shape.dyon"))
    game := unwrap(load(source: "src/game.dyon", imports: [spape]))
    call(game, "main", [])
}

Ketos

Ketos is a scripting language developed to provide an interface for accessing Lisp APIs. It is compiled into bytecode and interpreted by Rust code. It has the .ket extension. with the following features:

Compiles expression into bytecode objects

Ketos supports the compilation of .ket files to bytecode, which improves performance during runtime.

Provides a helper macro

It provides macro support for extracting arguments from Ketos values and value conversion from Rust.

Implements encoding and decoding

It also provides support for modification of bytecode instructions by dissecting data into opcodes.

  • Community: small
  • Stability: No

Example of Ketos:

//ket
(define (range a :optional b (step 1))
  (cond
    ((null b)   (range 0 a))
    ((> step 0) (range-pos a b step ()))
    ((< step 0) (range-neg a b step ()))
    (else       (panic "`range` got 0 step"))))// Rust
fn main() {
    let interp = Interpreter::new();
    interp.run_code(r#"
        (define (factorial n)
          (cond
            ((< n 0) (panic "factorial got negative integer"))
            ((<= n 1) 1)
            (else (* n (factorial (- n 1))))))
        "#, None).unwrap();
}

Mun

Mun is an innovation of Lua JIT designed for productivity and speed. It is built to easily detect errors during compiling ahead of time (AOT), as opposed to being interpreted or compiled with JIT (just in time) in mind.

It has the .munlib extension with the following features:

Ahead of time compilation

It is compiled ahead of time (AOT) by detecting errors in the code during this process; with this, developers can easily debug runtime errors on their IDEs (integrated development environment).

Statically typed

It resolves type check at compilation time instead of runtime which results in instant feedback for correction when not properly specified.

Performance

Ahead of time (AOT) with static typing and LLVM (low-level virtual machine) for optimization enforces Mun to be compiled to machine code and be executed cross-platform for optimal runtime performance.

IDE integration

It has support for IDE integrations for code completion and refactoring tools, which makes life easier for developers.

Cross compilation

Mun offers support for compiling to all targeted platforms from any supported compiler.

  • Community: rising
  • Stability: No

Example of Mun:

// munlib
extern fn random() -> i64;

pub fn random_bool() -> bool {
    random() % 2 == 0
}// Rust
fn main() {
    let app = RuntimeBuilder::new("main.munlib")
        .spawn()
        .expect("Failed to spawn Runtime");

    let app_ref = app.borrow();
    let result: bool = invoke_fn!(app_ref, "random_bool").unwrap();
    println!("random bool: {}", result);
}

LuaJIT RS

LuaJIT is developed to interface Lua code from Rust by easily accessing the functions that correspond directly to the underlying Lua C native-code API. It has the following features:

Cross platform

It supports other languages via native binding, since the native API is written in C.

Macro

LuaJIT also provides support for macro to easily communicate/interface directly with C.

  • Community: small
  • Stability: Yes

Example of LuaJIT:

pub fn main() {
    let mut state = State::new();
    state.open_libs();
    state.do_string(r#"print("Hello world!")"#);

    state.push(lua_fn!(return_42));
    state.set_global("return_42");
    state.do_string(r#"print(return_42())"#);
}

Conclusion

We’ve been able to look at several scripting languages for gaming in Rust, most of which are still in their infancy.

The most significant and popular one on this list is Wgpu, because it serves as the core of the WebGPU integration in Firefox, Servo, and Deno.

Elsewhere, Dyon serves as a dynamic language built with support for 4D vectors data type to augment 2D and 3D programming, mathematical iterations and Unicode symbols to improve readability and so much more. Others are built for interfacing with other platforms for performance optimization and more.

What Rust scripting language do you use for your game projects and why do you use it? I’d love to know in the comments section. Gracias! ☺️

Source: https://blog.logrocket.com/comparing-rust-scripting-language-game-development/

#rust #programming