Adding File I/O to the SHA256 Hash Algorithm Implemented in WebAssembly Text
Prerequisites
Before diving into this blog, please check that the following prerequisites have been met.
-
Are you comfortable writing directly in WebAssembly Text? (Be honest)
If the answer is “No”, then please read my Introduction to WebAssembly Text
-
Install
wasmtime
. This is an Open Source project by the Bytecode Alliance that provides both the WebAssembly development tools we will be using, and the WebAssembly System Interface (WASI) that will be the focus of our attention in this blog. -
In order to understand how to code against the WASI interface, it is very helpful to look at the Rust source code that implements the WASI functions you will be calling from your WebAssembly Text program.
This code can be found in the
wasmtime
GitHub repo https://github.com/bytecodealliance/wasmtime. The specific file to look in iscrates/wasi-preview1-component-adapter/src/lib.rs
Explanation of Update
The original version of this program focused only on implementation the core the SHA256 algorithm. This was a good starting point, but it meant that the JavaScript wrapper used to invoke the WASM module had to read the file from disk, then write it to memory in the special format required by the SHA256 algorithm.
The purpose of this update therefore is to significantly reduce the degree of coupling between the JavaScript wrapper and the underlying WASM module by moving all the file IO into WebAssembly.
Overview of Steps
- Getting Started
- Start WASI
- Import WASI Functions into WebAssembly
- Count the Command Line Arguments
- Extract the filename from the command line arguments
- Open the file
- Read the File Size
- Do We Have Enough Memory?
- Read the file into memory
- Close the file