WebAssembly – Validation ”; Previous Next In this chapter, we are going to discuss the webassembly.validate() function that will validate the .wasm output. The .wasm is available when we compile C, C++ or rust code. You can make use of the following tools to get the wasm code. Wasm Fiddler,which is available at https://wasmfiddle.com/ WebAssembly Explorer, which is available at https://mbebenita.github.io/WasmExplorer/. Syntax The syntax is as given below − WebAssembly.validate(bufferSource); Parameters bufferSource − The bufferSource has the binary code that comes from either C, C++ or Rust program. It is in the form of typedarray or ArrayBuffer. Return Value The function will return true if the .wasm code is valid and false if not. Let us try one example. Go to Wasm fiddler, which is available at https://wasmfiddle.com/, enter C code of your choice and down the wasm code. The block marked in red is the C code. Click on the Build button at the center to execute the code. Click on the Wasm , button to download the .wasm code. Save the .wasm at your end and let us use the same for validating. Example For Example: validate.html <!doctype html> <html> <head> <meta charset=”utf-8″> <title>Testing WASM validate()</title> </head> <body> <script> fetch(”program.wasm”).then(res => res.arrayBuffer() ).then(function(testbytes) { var valid = WebAssembly.validate(testbytes); if (valid) { console.log(“Valid Wasm Bytes!”); } else { console.log(“Invalid Wasm Code!”); } }); </script> </body> </html> I have hosted the above .html file in wamp server along with the download .wasm file. Here, is the output when you test it in the browser. Output The output is the mentioned below − Print Page Previous Next Advertisements ”;
Category: Computer Programming
WebAssembly – Introduction
WebAssembly – Introduction ”; Previous Next WebAssembly is also called WASM which was first introduced in the year 2017. The big technology companies behind the origin of WebAssembly are Google, Apple, Microsoft, Mozilla and W3C. The buzz is that WebAssembly is going to replace Javascript because of its faster execution, but that is not the case. WebAssembly and Javascript are meant to work together towards solving the complex issues. Need for WebAssembly So far, we have only Javascript that can work successfully inside the browser. There are very heavy tasks that are difficult to carry out in the browsers using javascript. To name a few they are Image recognition, Computer-Aided Design (CAD) applications, Live video augmentation, VR and augmented reality, Music applications, Scientific visualization and simulation, Games, Image / video editing etc. WebAssembly is a new language with binary instruction that can load and execute faster. The task stated above, can be easily done in high level languages like C, C++, Rust etc. We need a way that, the code we have in C, C++, Rust can be compiled and can use it in web browsers. The same is achievable using WebAssembly. When the WebAssembly code is loaded inside the browser. Then, the browser takes care of converting into machine format that can be understood by the processors. For javascript the code has to be downloaded, parsed and converted to machine format. A lot of time goes into it and for heavy tasks like, we mentioned earlier can be very slow. Working of WebAssembly High level languages like C, C++ and Rust are compiled into binary format, that is, .wasm and text format .wat. The source code written in C, C++ and Rust is compiled to .wasm using a compiler. You can make use of the Emscripten SDK for compiling C/C++ to .wasm. The flow is as follows − C/C++ code can be compiled to .wasm using Emscripten SDK. Later, the .wasm code can be used with the help of javascript in your html file to display the output. Key Concepts of WebAssembly The Key concepts are as explained below − Module A module is an object that is compiled by the browser to executable machine code. A module is said to be stateless and it can be shared between windows and web workers. Memory Memory in WebAssembly, is an arraybuffer that holds the data. You can allocate memory by using the Javascript api WebAssembly.memory(). Table Table in WebAssembly is a typed array that is, outside WebAssembly memory and mostly has a reference to functions. It stores the memory address of the functions. Instance Instance is an object that will have, all the exported functions that can be called from javascript to execute inside the browser. Print Page Previous Next Advertisements ”;
WebAssembly – Javascript API
WebAssembly – JavaScript API ”; Previous Next In this chapter, we will understand how to load the wasm code and execute them in the browser using the help of javascript webassembly API. Here are some important API”s, we are going to make use throughout the tutorial to execute wasm code. fetch() Browser API WebAssembly.compile WebAssembly.instance WebAssembly.instantiate WebAssembly.instantiateStreaming Before we discuss the WebAssembly javascript API”s, to test the API and the output we are going to use the following C program and the .wasm code generated from the c program using wasm explorer. An example for C Program is as follows − #include<stdio.h> int square(int n) { return n*n; } We will make use of WASM explorer, to get the wasm code − Download WASM code and use it to test the API”s. fetch() Browser API fetch() API is meant to load .wasm network resource. <script> var result = fetch(“findsquare.wasm”); console.log(result); </script> It returns a promise as shown below − You can also make use of XMLHttpRequest method to fetch the wasm network resource. WebAssembly.compile() The api responsibility is to compile the module details that are fetched from .wasm. Syntax The syntax is as given below − WebAssembly.compile(buffer); Parameters Buffer − This code from .wasm has to be converted to a typed array or arraybuffer, before giving as input to compile. Return value It will return a promise that will have the compiled module. Example Let us see one example, that gives the output as a compiled module using webAssembly.compile(). <script> fetch(“findsquare.wasm”) .then(bytes => bytes.arrayBuffer()) .then(mod => { var compiledmod = WebAssembly.compile(mod); compiledmod.then(test=> { console.log(test); }) }) </script> Output The console.log, when checked in the browser, will give you the compiled module details − The module has a constructor object with imports, exports, and customSections. Let us see the next API, to get more details of the compiled module. WebAssembly.instance Using the WebAssembly.instance, API will give you the executable instance of the compiled module that can be further executed to get the output. Syntax The syntax is as given below − new WebAssembly.Instance(compiled module) Return value The return value will be an object with the array of exports function that can be executed. Example <script> fetch(“findsquare.wasm”) .then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)).then(module => { let instance = new WebAssembly.Instance(module); console.log(instance); }) </script> Output The output will give us an array of exports function as shown below − You can see the square function, that we got from the C code that is compiled. To execute the square function, you can do the following − <script> fetch(“findsquare.wasm”) .then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) .then(module => { let instance = new WebAssembly.Instance(module); console.log(instance.exports.square(15)); }) </script> The output will be − 225 WebAssembly.instantiate This API takes care of compiling and instantiating the module together. Syntax The syntax is as follows − WebAssembly.instantiate(arraybuffer, importObject) Parameters arraybuffer − The code from .wasm has to be converted to typed array or arraybuffer before giving as input to instantiate. importObject − The import object has to have details of the memory, imported functions to be used inside the module. It can be an empty module object, in case, there is nothing to be shared. Return value It will return a promise, that will have module and instance details. Example <script type=”text/javascript”> const importObj = { module: {} }; fetch(“findsquare.wasm”) .then(bytes => bytes.arrayBuffer()) .then(module => WebAssembly.instantiate(module, importObj)) .then(finalcode => { console.log(finalcode); console.log(finalcode.instance.exports.square(25)); }); </script> Output When you execute the code, you will get the below mentioned output. WebAssembly.instantiateStreaming This API takes care of compiling as well as instantiating the WebAssembly module from the .wasm code given. Syntax The syntax is as given below − WebAssembly.instantiateStreaming(wasmcode, importObject); Parameters wasmcode − Response from fetch or any other API that gives the wasm code and returns a promise. importObject − The import object has to have details of the memory, imported functions to be used inside the module. It can be an empty module object in case there is nothing to be shared. Return Value It will return a promise, that will have module and instance details. Example An example is discussed below − <script type=”text/javascript”> const importObj = { module: {} }; WebAssembly.instantiateStreaming(fetch(“findsquare.wasm”), importObj).then(obj => { console.log(obj); }); </script> When you test it in the browser, you will see an error − To make it work at your server end, you will have to add the mime type application/wasm or else make use of WebAssembly.instantiate(arraybuffer, importObject). Print Page Previous Next Advertisements ”;
WebAssembly – Program Structure ”; Previous Next WebAssembly, also called WASM, is binary format low level code developed to be executed inside browsers in the most efficient way. WebAssembly code is structured with following concepts − Values Types Instructions Let us learn them in detail now. Values Values in WebAssembly are meant to store complex data such as text, strings and vectors. WebAssembly supports the following − Bytes Integers Floating point Names Bytes Bytes is the simplest form of values supported in WebAssembly. The value is in hexadecimal format. For example Bytes represented as b, can also take natural numbers n, where n <256. byte ::= 0x00| …. |0xFF Integers In WebAssembly, integers supported are as given below − i32: 32-bit integer i64: 64-bit integer Floating Point In WebAssembly floating point numbers supported are as follows − f32: 32-bit floating point f64: 64-bit floating point Names Names are sequence of character, with scalar values defined by Unicode, which is available at the link http://www.unicode.org/versions/Unicode12.1.0/ given herewith. Types The entities in WebAssembly are classified as types. The types supported are as stated below − Value Types Result Types Function Types Limits Memory Types Table Types Global Types External Types Let us study them one by one. Value Types The values type supported by WebAssembly are as mentioned below − i32: 32-bit integer i64: 64-bit integer f32: 32-bit floating point f64: 64-bit floating point valtype ::= i32|i64|f32|f64 Result Types The values written inside brackets are executed and stored inside result types. The result type is the output of the execution of a block of code made up of values. resulttype::=[valtype?] Function Types A function type will take in vector of parameters returns a vector of results. functype::=[vec(valtype)]–> [vec(valtype)] Limits Limits are the storage range linked with memory and table types. limits ::= {min u32, max u32} Memory Types Memory types deal with linear memories and the size range. memtype ::= limits Table Types Table Types are classified by the element type assigned to it. tabletype ::= limits elemtype elemtype ::= funcref Table type is dependent on the limit for the minimum and maximum size assigned to it. Global Types Global Type holds the global variables that have the value, that can change or remain the same. globaltype ::= mut valtype mut ::= const|var External Types External Types deals with imports and external values. externtype ::= func functype | table tabletype | mem memtype | global globaltype Instructions WebAssembly code is a sequence of instructions that follows a stack machine model. As WebAssembly follows a stack machine model, the instructions are pushed on the stack. The argument values for a function, for example, are popped from stack and the result is pushed back on the stack. In the end, there will be only one value in the stack and that is the result. Some of the commonly used Instructions are as follows − Numeric Instructions Variable Instructions Numeric Instructions Numeric Instructions are operations, which are performed on numeric value. For example nn, mm ::= 32|64 ibinop ::= add|sub|mul|div_sx|rem_sx|and|or|xor irelop ::= eq | ne | lt_sx | gt_sx | le_sx | ge_sx frelop ::= eq | ne | lt | gt | le | ge Variable Instructions Variable instructions are about accessing the local and global variables. For example To access local variables − get_local $a get_local $b To set local variables − set_local $a set_local $b To access global variables − get_global $a get_global $b To set global variables − set_global $a set_global $b Print Page Previous Next Advertisements ”;
WebAssembly – Javascript
WebAssembly – JavaScript ”; Previous Next This chapter will list out the comparison between WebAssembly and Javascript. Javascript is a language, that we have used a lot inside the browser. Now, with WebAssembly release, we can also use WebAssembly inside the browser. The reason for WebAssembly to come into existence is not to replace javascript, but to take care of certain things, that are difficult to handle with javascript. For example It is difficult to get the tasks such as Image recognition, CAD applications, Live video augmentation, VR and augmented reality, Music applications, Scientific visualization and simulation, Games, Image / video editing etc. to be done with javascript. Using high level languages like C/C++, Rust, which now can be compiled to WebAssembly, it is easy to get the task mentioned above to be done. WebAssembly generates a binary code that is easy to execute inside the browser. So here, is the list of comparison done between Javascript and WebAssembly. Parameters Javascript WebAssembly Coding You can easily write code in Javascript. The code written is human readable and saved as .js. When used inside the browser you need to use a <script> tag. The code can be written in text format in WebAssembly and it is saved as .wat. It is difficult to write the code in .wat format. It is best to compile the code from some other high level language instead of writing from start in .wat. You cannot execute the .wat file inside the browser and has to convert to .wasm using the compilers or online tools available. Execution The code written in javascript when used inside the browser has to be downloaded, parsed, compiled and optimized. We have WebAssembly code in .wasm already compiled and in binary format. Memory Management Javascript assigns memory when, variables are created and the memory is released when not used and are added to garbage collection. Memory in WebAssembly is an arraybuffer that holds the data. You can allocate memory by using the Javascript API WebAssembly.memory(). WebAssembly memory is stored in an array format i.e. a flat memory model that is easy to understand and perform the execution. The disadvantage of memory model in WebAssembly is − Complex calculation takes time. Webassembly does not support garbage collection that does not allow reuse of the memory and the memory is wasted. Load Time & Performance In case of javascript, when called inside the browser, the javascript file has to be downloaded, and parsed. Later, the parser converts the source code to bytecode that the javascript engine executes the code in the browser. The Javascript engine is very powerful and hence, the load time and performance of javascript is very fast in comparison to WebAssembly. A most important goal of WebAssembly is to be faster than JavaScript.Wasm code generated from high-level languages is smaller in size and hence, the load time is faster. But, languages like GO, when compiled to wasm produce a big file size for a small piece of code. WebAssembly is designed in such a way that it is faster in compilation, and can run across all the major browsers. WebAssembly still has to add lots of improvements in terms of performance in comparison to javascript. Debugging Javascript is human-readable and can be debugged easily. Adding breakpoints to your javascript code inside the browser allows you to easily debug the code. WebAssembly provides the code in text format, that is readable but, still very difficult to debug. Firefox does allow you to view the wasm code in .wat format inside the browser. You cannot add breakpoints in .wat and that is something that will be available in the future. Browser Support Javascript works well in all browsers. All major web browsers have support for WebAssembly. Print Page Previous Next Advertisements ”;
Scala Collections – ListSet
Scala Collections – ListSet ”; Previous Next Scala Set is a collection of pairwise different elements of the same type. In other words, a Set is a collection that contains no duplicate elements. ListSet implements immutable sets and uses list structure. Elements insertion order is preserved while storing the elements. Declaring ListSet Variables The following is the syntax for declaring an ListSet variable. Syntax var z : ListSet[String] = ListSet(“Zara”,”Nuha”,”Ayan”) Here, z is declared as an list-set of Strings which has three members. Values can be added by using commands like the following − Command var myList1: ListSet[String] = myList + “Naira”; Processing ListSet Below is an example program of showing how to create, initialize and process ListSet − Example import scala.collection.immutable.ListSet object Demo { def main(args: Array[String]) = { var myList: ListSet[String] = ListSet(“Zara”,”Nuha”,”Ayan”); // Add an element var myList1: ListSet[String] = myList + “Naira”; // Remove an element var myList2: ListSet[String] = myList – “Nuha”; // Create empty set var myList3: ListSet[String] = ListSet.empty[String]; println(myList); println(myList1); println(myList2); println(myList3); } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output ListSet(Zara, Nuha, Ayan) ListSet(Zara, Nuha, Ayan, Naira) ListSet(Zara, Ayan) ListSet() Print Page Previous Next Advertisements ”;
WebAssembly – Debugging WASM in Firefox ”; Previous Next WebAssembly support is added to all the latest browsers available with you today like Chrome, Firefox. The Firefox version 54+ onwards gives you a special feature to debug your wasm code. To do that, execute your code inside Firefox browsers that call wasm. For example, consider following C code that finds the square of the number. An example for the C Program is as follows − #include<stdio.h> int square(int n) { return n*n; } We will make use of WASM explorer to get the wasm code − Download WASM code and use it to see the output in the browser. The html file that loads the wasm is as follows − !doctype html> <html> <head> <meta charset=”utf-8″> <title>WebAssembly Square function</title> <style> div { font-size : 30px; text-align : center; color:orange; } </style> </head> <body> <div id=”textcontent”></div> <script> let square; fetch(“findsquare.wasm”).then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) .then(module => {return new WebAssembly.Instance(module) }) .then(instance => { square = instance.exports.square(13); console.log(“The square of 13 = ” +square); document.getElementById(“textcontent”).innerHTML = “The square of 13 = ” +square; }); </script> </body> </html> Open your Firefox browser and load the above html file and open the debugger tool. You should see wasm:// entry in the debugger tool. Click on wasm:// and it shows the wasm code converted to .wat format as shown above. You can take a look at the code of the exported function and can debug the code, if any issue comes up. Firefox also intends to add breakpoints, so that you can debug the code and check the execution flow. Print Page Previous Next Advertisements ”;
WebAssembly – Overview
WebAssembly – Overview ”; Previous Next WebAssembly is a new computer programming language for the web. WebAssembly code is a low level binary format, that is compatible with the web and can easily run in modern web browsers. The file size generated is small and it loads and executes faster. You can now compile languages like C, C++, Rust, etc. to binary format and it can run on the web just like javascript. Definition of WebAssembly As per the official website of WebAssembly, which is available at https://webassembly.org/, it is defined as WebAssembly (abbreviated as Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable target for compilation of high-level languages like C/C++/Rust, enabling deployment on the web for client and server applications. Web Assembly is not something that a developer will have to write, but the code is written in languages like C, C++, Rust and can be compiled to WebAssembly (wasm). The same code can be run inside the web browsers. Web Assembly is a new language, the code is low-level assembly language, but with its text format feature, the code is readable and debugging is possible, if necessary. Goals of WebAssembly The open standards for WebAssembly are developed in a W3C Community Group that includes representatives from all major browsers as well as a W3C Working Group. The main goals of WebAssembly are mentioned below − Faster, Efficient and Portable − WebAssembly code is meant to run faster on different platforms taking advantage of the hardware available. Easy to read and debug − WebAssembly, being a low level assembly language, has text format support, that allows you to debug the code for any issues and also to rewrite the code, if necessary. Security − WebAssembly is safe to run on the web browsers, as it takes care of permissions and same-origin policies. Advantages of WebAssembly The following are the advantages of WebAssembly − Run is Modern Browsers − WebAssembly is able to execute without any issues on the modern web browsers which are available. Multiple Language support − Languages like C, C++, Rust, Go can now compile the code to WebAssembly and run the same in web browsers. So, the languages which were not able to run in a browser will now be able to do so. Faster, Efficient and Portable − Due to the small size of the code, it loads and executes faster. Easy to understand − Developers don’t have to do much stress in understanding WebAssembly coding, as they don’t have to write the code in WebAssembly. Instead compile the code in WebAssembly and execute the same on the web. Easy to Debug − Though the final code is in low level assembly language, you can also get it in text format, that is easy to read and debug. Disadvantages of WebAssembly The following are the disadvantages of WebAssembly − WebAssembly is still being worked on and it is too early to decide the future of it. WebAssembly is dependent on javascript to interact with the Document Object Model (DOM). Print Page Previous Next Advertisements ”;
WebAssembly – Home
WebAssembly Tutorial PDF Version Quick Guide Resources Job Search Discussion WebAssembly is a new programming language for the web. WebAssembly code is low level binary format, that is compatible with the web and can easily run in modern web browsers. The file size generated is small and it loads and executes faster. You can now compile languages like C, C++, Rust, etc. to binary format and it can run on the web just like javascript. Audience This tutorial is designed for software programmers who want to learn the basics of WebAssembly and its programming concepts in simple and easy ways. It will give you enough understanding on various functionalities of Requests library with suitable examples. Prerequisites Before proceeding with this tutorial, you should have a basic understanding of Javascript, and any one of the high level language like C, C++, Rust and Go. Print Page Previous Next Advertisements ”;
Rust – Variables
Rust – Variables ”; Previous Next A variable is a named storage that programs can manipulate. Simply put, a variable helps programs to store values. Variables in Rust are associated with a specific data type. The data type determines the size and layout of the variable”s memory, the range of values that can be stored within that memory and the set of operations that can be performed on the variable. Rules for Naming a Variable In this section, we will learn about the different rules for naming a variable. The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Rust is case-sensitive. Syntax The data type is optional while declaring a variable in Rust. The data type is inferred from the value assigned to the variable. The syntax for declaring a variable is given below. let variable_name = value; // no type specified let variable_name:dataType = value; //type specified Illustration fn main() { let fees = 25_000; let salary:f64 = 35_000.00; println!(“fees is {} and salary is {}”,fees,salary); } The output of the above code will be fees is 25000 and salary is 35000. Immutable By default, variables are immutable − read only in Rust. In other words, the variable”s value cannot be changed once a value is bound to a variable name. Let us understand this with an example. fn main() { let fees = 25_000; println!(“fees is {} “,fees); fees = 35_000; println!(“fees changed is {}”,fees); } The output will be as shown below − error[E0384]: re-assignment of immutable variable `fees` –> main.rs:6:3 | 3 | let fees = 25_000; | —- first assignment to `fees` … 6 | fees=35_000; | ^^^^^^^^^^^ re-assignment of immutable variable error: aborting due to previous error(s) The error message indicates the cause of the error – you cannot assign values twice to immutable variable fees. This is one of the many ways Rust allows programmers to write code and takes advantage of the safety and easy concurrency. Mutable Variables are immutable by default. Prefix the variable name with mut keyword to make it mutable. The value of a mutable variable can be changed. The syntax for declaring a mutable variable is as shown below − let mut variable_name = value; let mut variable_name:dataType = value; Let us understand this with an example fn main() { let mut fees:i32 = 25_000; println!(“fees is {} “,fees); fees = 35_000; println!(“fees changed is {}”,fees); } The output of the snippet is given below − fees is 25000 fees changed is 35000 Print Page Previous Next Advertisements ”;