Skip to content

Commit

Permalink
added pkg for now
Browse files Browse the repository at this point in the history
  • Loading branch information
dprosper committed Oct 25, 2024
1 parent 398550c commit a6cdfb3
Show file tree
Hide file tree
Showing 8 changed files with 400 additions and 9 deletions.
18 changes: 9 additions & 9 deletions .github/workflows/nextjs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,15 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install wasm-pack
run: |
curl https://crates.io/api/v1/crates/wasm-pack/0.10.2/download | tar xvf -
chmod +x wasm-pack-0.10.2/wasm-pack
sudo mv wasm-pack-0.10.2/wasm-pack /usr/local/bin/
- name: Build WASM
working-directory: frontend-wasm
run: |
wasm-pack build --target web
# - name: Install wasm-pack
# run: |
# curl https://crates.io/api/v1/crates/wasm-pack/0.10.2/download | tar xvf -
# chmod +x wasm-pack-0.10.2/wasm-pack
# sudo mv wasm-pack-0.10.2/wasm-pack /usr/local/bin/
# - name: Build WASM
# working-directory: frontend-wasm
# run: |
# wasm-pack build --target web
- name: Detect package manager
id: detect-package-manager
run: |
Expand Down
1 change: 1 addition & 0 deletions frontend-wasm/pkg/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# *
72 changes: 72 additions & 0 deletions frontend-wasm/pkg/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
This is based on an example from: https://towardsdev.com/rust-and-react-a-guide-to-webassembly-0cf4e751da99

# Step 1: Install wasm-pack
```sh
cargo install wasm-pack
```

# Step 2: Add WebAssembly Target
```sh
rustup target add wasm32-unknown-unknown
```

# Step 3: Create a Library Crate
```sh
cargo new --lib frontend-wasm
```

# Step 4: Configure Cargo.toml
Add to `Cargo.toml`

```sh
[lib]
crate-type = ["cdylib", "rlib"]

[dependencies]
wasm-bindgen = "0.2"
```

# Step 5: Write Rust Code
Update `lib.rs`

```sh
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn compare_cidr_networks(left_cidr: &str, right_cidr: &str) -> bool {
....
}
```

# Step 6: Compile to WebAssembly
```sh
wasm-pack build --target web
```

# Step 7: In React App, Install the WebAssembly Package
```sh
npm install ../frontend-wasm/pkg
```

# Step 8: Add to React App

- Module import
```sh
import init from 'frontend-wasm';
import { compare_cidr_networks, get_cidr_details } from 'frontend-wasm';
```
- Initialize the wasm module and use the function imported.
```sh
useEffect(() => {
// Initialize the wasm module
init().then(() => console.log('WASM loaded'));
}, []);
```
# Step 9: Start app
```sh
npm start
```
45 changes: 45 additions & 0 deletions frontend-wasm/pkg/frontend_wasm.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/* tslint:disable */
/* eslint-disable */
/**
* @param {string} left_cidr
* @param {string} right_cidr
* @returns {boolean}
*/
export function compare_cidr_networks(left_cidr: string, right_cidr: string): boolean;
/**
* @param {string} cidr
* @returns {any}
*/
export function get_cidr_details(cidr: string): any;

export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;

export interface InitOutput {
readonly memory: WebAssembly.Memory;
readonly compare_cidr_networks: (a: number, b: number, c: number, d: number) => number;
readonly get_cidr_details: (a: number, b: number) => number;
readonly __wbindgen_malloc: (a: number, b: number) => number;
readonly __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
readonly __wbindgen_exn_store: (a: number) => void;
}

export type SyncInitInput = BufferSource | WebAssembly.Module;
/**
* Instantiates the given `module`, which can either be bytes or
* a precompiled `WebAssembly.Module`.
*
* @param {{ module: SyncInitInput }} module - Passing `SyncInitInput` directly is deprecated.
*
* @returns {InitOutput}
*/
export function initSync(module: { module: SyncInitInput } | SyncInitInput): InitOutput;

/**
* If `module_or_path` is {RequestInfo} or {URL}, makes a request and
* for everything else, calls `WebAssembly.instantiate` directly.
*
* @param {{ module_or_path: InitInput | Promise<InitInput> }} module_or_path - Passing `InitInput` directly is deprecated.
*
* @returns {Promise<InitOutput>}
*/
export default function __wbg_init (module_or_path?: { module_or_path: InitInput | Promise<InitInput> } | InitInput | Promise<InitInput>): Promise<InitOutput>;
250 changes: 250 additions & 0 deletions frontend-wasm/pkg/frontend_wasm.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,250 @@
let wasm;

const cachedTextDecoder = (typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }) : { decode: () => { throw Error('TextDecoder not available') } } );

if (typeof TextDecoder !== 'undefined') { cachedTextDecoder.decode(); };

let cachedUint8ArrayMemory0 = null;

function getUint8ArrayMemory0() {
if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
}
return cachedUint8ArrayMemory0;
}

function getStringFromWasm0(ptr, len) {
ptr = ptr >>> 0;
return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
}

let WASM_VECTOR_LEN = 0;

const cachedTextEncoder = (typeof TextEncoder !== 'undefined' ? new TextEncoder('utf-8') : { encode: () => { throw Error('TextEncoder not available') } } );

const encodeString = (typeof cachedTextEncoder.encodeInto === 'function'
? function (arg, view) {
return cachedTextEncoder.encodeInto(arg, view);
}
: function (arg, view) {
const buf = cachedTextEncoder.encode(arg);
view.set(buf);
return {
read: arg.length,
written: buf.length
};
});

function passStringToWasm0(arg, malloc, realloc) {

if (realloc === undefined) {
const buf = cachedTextEncoder.encode(arg);
const ptr = malloc(buf.length, 1) >>> 0;
getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
WASM_VECTOR_LEN = buf.length;
return ptr;
}

let len = arg.length;
let ptr = malloc(len, 1) >>> 0;

const mem = getUint8ArrayMemory0();

let offset = 0;

for (; offset < len; offset++) {
const code = arg.charCodeAt(offset);
if (code > 0x7F) break;
mem[ptr + offset] = code;
}

if (offset !== len) {
if (offset !== 0) {
arg = arg.slice(offset);
}
ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
const ret = encodeString(arg, view);

offset += ret.written;
ptr = realloc(ptr, len, offset, 1) >>> 0;
}

WASM_VECTOR_LEN = offset;
return ptr;
}
/**
* @param {string} left_cidr
* @param {string} right_cidr
* @returns {boolean}
*/
export function compare_cidr_networks(left_cidr, right_cidr) {
const ptr0 = passStringToWasm0(left_cidr, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len0 = WASM_VECTOR_LEN;
const ptr1 = passStringToWasm0(right_cidr, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len1 = WASM_VECTOR_LEN;
const ret = wasm.compare_cidr_networks(ptr0, len0, ptr1, len1);
return ret !== 0;
}

const heap = new Array(128).fill(undefined);

heap.push(undefined, null, true, false);

function getObject(idx) { return heap[idx]; }

let heap_next = heap.length;

function dropObject(idx) {
if (idx < 132) return;
heap[idx] = heap_next;
heap_next = idx;
}

function takeObject(idx) {
const ret = getObject(idx);
dropObject(idx);
return ret;
}
/**
* @param {string} cidr
* @returns {any}
*/
export function get_cidr_details(cidr) {
const ptr0 = passStringToWasm0(cidr, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len0 = WASM_VECTOR_LEN;
const ret = wasm.get_cidr_details(ptr0, len0);
return takeObject(ret);
}

function addHeapObject(obj) {
if (heap_next === heap.length) heap.push(heap.length + 1);
const idx = heap_next;
heap_next = heap[idx];

heap[idx] = obj;
return idx;
}

function handleError(f, args) {
try {
return f.apply(this, args);
} catch (e) {
wasm.__wbindgen_exn_store(addHeapObject(e));
}
}

async function __wbg_load(module, imports) {
if (typeof Response === 'function' && module instanceof Response) {
if (typeof WebAssembly.instantiateStreaming === 'function') {
try {
return await WebAssembly.instantiateStreaming(module, imports);

} catch (e) {
if (module.headers.get('Content-Type') != 'application/wasm') {
console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);

} else {
throw e;
}
}
}

const bytes = await module.arrayBuffer();
return await WebAssembly.instantiate(bytes, imports);

} else {
const instance = await WebAssembly.instantiate(module, imports);

if (instance instanceof WebAssembly.Instance) {
return { instance, module };

} else {
return instance;
}
}
}

function __wbg_get_imports() {
const imports = {};
imports.wbg = {};
imports.wbg.__wbg_parse_51ee5409072379d3 = function() { return handleError(function (arg0, arg1) {
const ret = JSON.parse(getStringFromWasm0(arg0, arg1));
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbindgen_throw = function(arg0, arg1) {
throw new Error(getStringFromWasm0(arg0, arg1));
};

return imports;
}

function __wbg_init_memory(imports, memory) {

}

function __wbg_finalize_init(instance, module) {
wasm = instance.exports;
__wbg_init.__wbindgen_wasm_module = module;
cachedUint8ArrayMemory0 = null;



return wasm;
}

function initSync(module) {
if (wasm !== undefined) return wasm;


if (typeof module !== 'undefined') {
if (Object.getPrototypeOf(module) === Object.prototype) {
({module} = module)
} else {
console.warn('using deprecated parameters for `initSync()`; pass a single object instead')
}
}

const imports = __wbg_get_imports();

__wbg_init_memory(imports);

if (!(module instanceof WebAssembly.Module)) {
module = new WebAssembly.Module(module);
}

const instance = new WebAssembly.Instance(module, imports);

return __wbg_finalize_init(instance, module);
}

async function __wbg_init(module_or_path) {
if (wasm !== undefined) return wasm;


if (typeof module_or_path !== 'undefined') {
if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
({module_or_path} = module_or_path)
} else {
console.warn('using deprecated parameters for the initialization function; pass a single object instead')
}
}

if (typeof module_or_path === 'undefined') {
module_or_path = new URL('frontend_wasm_bg.wasm', import.meta.url);
}
const imports = __wbg_get_imports();

if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {
module_or_path = fetch(module_or_path);
}

__wbg_init_memory(imports);

const { instance, module } = await __wbg_load(await module_or_path, imports);

return __wbg_finalize_init(instance, module);
}

export { initSync };
export default __wbg_init;
Binary file added frontend-wasm/pkg/frontend_wasm_bg.wasm
Binary file not shown.
Loading

0 comments on commit a6cdfb3

Please sign in to comment.