Add debug info

This commit is contained in:
lights0123 2020-11-21 17:14:08 -05:00
parent 9c39ce1806
commit 500d2c0c65
No known key found for this signature in database
GPG key ID: 28F315322E37972F
53 changed files with 7730 additions and 1 deletions

View file

@ -154,7 +154,9 @@ export default class UsbCompat {
}
async processCmd(cmd: Cmd) {
console.log(cmd);
const msg = await this._processCmd(cmd);
console.log(msg);
const encoded = encoder.encode(msg);
if (encoded.length > this.arr.length - 4) {

View file

@ -6,7 +6,7 @@ import type { Calculator } from 'web-libnspire';
console.log('worker!');
const ctx: Worker = self as any;
const module = import('web-libnspire');
const module = import('@/web-libusb/web-libnspire/pkg');
let calc: Calculator | undefined;
const rpcProvider = new RpcProvider((message, transfer: any) =>
ctx.postMessage(message, transfer)
@ -17,12 +17,19 @@ type Path = { path: string };
type Data = { data: Uint8Array };
type SrcDest = { src: string; dest: string };
function log(...args: any) {
console.log('worker:', ...args);
}
rpcProvider.registerRpcHandler<{id: number, sab: SharedArrayBuffer, vid: number, pid: number}>('init', async ({ id, sab, vid, pid }) => {
if (calc) calc.free();
log('init');
calc = new (await module).Calculator(id, vid, pid, new Int32Array(sab));
log('init done');
});
rpcProvider.registerRpcHandler('updateDevice', async () => {
log('update');
return calc?.update();
});

View file

@ -0,0 +1,12 @@
# editorconfig.org
[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false

1
web/web-libusb/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
target

644
web/web-libusb/Cargo.lock generated Normal file
View file

@ -0,0 +1,644 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "aho-corasick"
version = "0.7.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "043164d8ba5c4c3035fec9bbee8647c0261d788f3474306f93bb65901cae0e86"
dependencies = [
"memchr",
]
[[package]]
name = "array_iterator"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "015eb97c25bb20230c9fdf1533b4cee74b27924cd462f74b0d6fc011aaf196de"
[[package]]
name = "autocfg"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"
[[package]]
name = "bstr"
version = "0.2.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "31accafdb70df7871592c058eca3985b71104e15ac32f64706022c58867da931"
dependencies = [
"memchr",
]
[[package]]
name = "bumpalo"
version = "3.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e8c087f005730276d1096a652e92a8bacee2e2472bcc9715a74d2bec38b5820"
[[package]]
name = "bytemuck"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41aa2ec95ca3b5c54cf73c91acf06d24f4495d5f1b1c12506ae3483d646177ac"
[[package]]
name = "byteorder"
version = "1.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08c48aae112d48ed9f069b33538ea9e3e90aa263cfa3d1c24309612b1f7472de"
[[package]]
name = "cc"
version = "1.0.60"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef611cc68ff783f18535d77ddd080185275713d852c4f5cbb6122c462a7a825c"
dependencies = [
"jobserver",
]
[[package]]
name = "cfg-if"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"
[[package]]
name = "console_error_panic_hook"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8d976903543e0c48546a91908f21588a680a8c8f984df9a5d69feccb2b2a211"
dependencies = [
"cfg-if",
"wasm-bindgen",
]
[[package]]
name = "crossbeam-utils"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3c7c73a2d1e9fc0886a08b93e98eb643461230d5f1925e4036204d5f2e261a8"
dependencies = [
"autocfg",
"cfg-if",
"lazy_static",
]
[[package]]
name = "displaydoc"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adc2ab4d5a16117f9029e9a6b5e4e79f4c67f6519bc134210d4d4a04ba31f41b"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "fnv"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "globset"
version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ad1da430bd7281dde2576f44c84cc3f0f7b475e7202cd503042dff01a8c8120"
dependencies = [
"aho-corasick",
"bstr",
"fnv",
"log",
"regex",
]
[[package]]
name = "globwalk"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9db17aec586697a93219b19726b5b68307eba92898c34b170857343fe67c99d"
dependencies = [
"ignore",
"walkdir",
]
[[package]]
name = "ignore"
version = "0.4.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22dcbf2a4a289528dbef21686354904e1c694ac642610a9bff9e7df730d9ec72"
dependencies = [
"crossbeam-utils",
"globset",
"lazy_static",
"log",
"memchr",
"regex",
"same-file",
"thread_local",
"walkdir",
"winapi-util",
]
[[package]]
name = "image"
version = "0.23.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985fc06b1304d19c28d5c562ed78ef5316183f2b0053b46763a0b94862373c34"
dependencies = [
"bytemuck",
"byteorder",
"num-iter",
"num-rational",
"num-traits",
]
[[package]]
name = "itoa"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc6f3ad7b9d11a0c00842ff8de1b60ee58661048eb8049ed33c73594f359d7e6"
[[package]]
name = "jobserver"
version = "0.1.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c71313ebb9439f74b00d9d2dcec36440beaf57a6aa0623068441dd7cd81a7f2"
dependencies = [
"libc 0.2.78",
]
[[package]]
name = "js-sys"
version = "0.3.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca059e81d9486668f12d455a4ea6daa600bd408134cd17e3d3fb5a32d1f016f8"
dependencies = [
"wasm-bindgen",
]
[[package]]
name = "lazy_static"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "libc"
version = "0.2.77"
source = "git+https://github.com/rust-lang/libc?tag=0.2.77#c2a184b255c2d7548e17b66f19f0330192ce6484"
[[package]]
name = "libc"
version = "0.2.78"
dependencies = [
"libc 0.2.77",
]
[[package]]
name = "libnspire"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6428b72ef81134d34d077748639ae280cf8b5b3314ae99fa8ff1e34cbc1d64b"
dependencies = [
"array_iterator",
"displaydoc",
"image",
"libnspire-sys",
"libusb1-sys",
"rusb",
"serde",
"thiserror",
]
[[package]]
name = "libnspire-sys"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "361969d82d11a723a53ba4814d3086a7562812bc4cec8bd8b332fd478dc9c722"
dependencies = [
"cc",
"globwalk",
"libusb1-sys",
]
[[package]]
name = "libusb1-sys"
version = "0.4.2"
dependencies = [
"js-sys",
"libc 0.2.78",
"rmp-serde",
"serde",
"serde-wasm-bindgen",
"serde_bytes",
"wasm-bindgen",
"web-sys",
]
[[package]]
name = "log"
version = "0.4.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fabed175da42fed1fa0746b0ea71f412aa9d35e76e95e59b192c64b9dc2bf8b"
dependencies = [
"cfg-if",
]
[[package]]
name = "memchr"
version = "2.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3728d817d99e5ac407411fa471ff9800a778d88a24685968b36824eaf4bee400"
[[package]]
name = "num-integer"
version = "0.1.43"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d59457e662d541ba17869cf51cf177c0b5f0cbf476c66bdc90bf1edac4f875b"
dependencies = [
"autocfg",
"num-traits",
]
[[package]]
name = "num-iter"
version = "0.1.41"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a6e6b7c748f995c4c29c5f5ae0248536e04a5739927c74ec0fa564805094b9f"
dependencies = [
"autocfg",
"num-integer",
"num-traits",
]
[[package]]
name = "num-rational"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5b4d7360f362cfb50dde8143501e6940b22f644be75a4cc90b2d81968908138"
dependencies = [
"autocfg",
"num-integer",
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac267bcc07f48ee5f8935ab0d24f316fb722d7a1292e2913f0cc196b29ffd611"
dependencies = [
"autocfg",
]
[[package]]
name = "proc-macro2"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71"
dependencies = [
"unicode-xid",
]
[[package]]
name = "quote"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa563d17ecb180e500da1cfd2b028310ac758de548efdd203e18f283af693f37"
dependencies = [
"proc-macro2",
]
[[package]]
name = "regex"
version = "1.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c3780fcf44b193bc4d09f36d2a3c87b251da4a046c87795a0d35f4f927ad8e6"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
"thread_local",
]
[[package]]
name = "regex-syntax"
version = "0.6.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26412eb97c6b088a6997e05f69403a802a92d520de2f8e63c2b65f9e0f47c4e8"
[[package]]
name = "rmp"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f10b46df14cf1ee1ac7baa4d2fbc2c52c0622a4b82fa8740e37bc452ac0184f"
dependencies = [
"byteorder",
"num-traits",
]
[[package]]
name = "rmp-serde"
version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ce7d70c926fe472aed493b902010bccc17fa9f7284145cb8772fd22fdb052d8"
dependencies = [
"byteorder",
"rmp",
"serde",
]
[[package]]
name = "rusb"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67fa037368ee577fca9ef237c5ec129084c18e7e3e5987cc611fb8b2d78cf84a"
dependencies = [
"libc 0.2.78",
"libusb1-sys",
]
[[package]]
name = "ryu"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e"
[[package]]
name = "same-file"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
dependencies = [
"winapi-util",
]
[[package]]
name = "scoped-tls"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea6a9290e3c9cf0f18145ef7ffa62d68ee0bf5fcd651017e586dc7fd5da448c2"
[[package]]
name = "serde"
version = "1.0.116"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96fe57af81d28386a513cbc6858332abc6117cfdb5999647c6444b8f43a370a5"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde-wasm-bindgen"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ee6f12f7ed0e7ad2e55200da37dbabc2cadeb942355c5b629aa3771f5ac5636"
dependencies = [
"fnv",
"js-sys",
"serde",
"wasm-bindgen",
]
[[package]]
name = "serde_bytes"
version = "0.11.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16ae07dd2f88a366f15bd0632ba725227018c69a1c8550a927324f8eb8368bb9"
dependencies = [
"serde",
]
[[package]]
name = "serde_derive"
version = "1.0.116"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f630a6370fd8e457873b4bd2ffdae75408bc291ba72be773772a4c2a065d9ae8"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.58"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a230ea9107ca2220eea9d46de97eddcb04cd00e92d13dda78e478dd33fa82bd4"
dependencies = [
"itoa",
"ryu",
"serde",
]
[[package]]
name = "syn"
version = "1.0.42"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c51d92969d209b54a98397e1b91c8ae82d8c87a7bb87df0b29aa2ad81454228"
dependencies = [
"proc-macro2",
"quote",
"unicode-xid",
]
[[package]]
name = "thiserror"
version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7dfdd070ccd8ccb78f4ad66bf1982dc37f620ef696c6b5028fe2ed83dd3d0d08"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd80fc12f73063ac132ac92aceea36734f04a1d93c1240c6944e23a3b8841793"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "thread_local"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d40c6d1b69745a6ec6fb1ca717914848da4b44ae29d9b3080cbee91d72a69b14"
dependencies = [
"lazy_static",
]
[[package]]
name = "unicode-xid"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564"
[[package]]
name = "walkdir"
version = "2.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "777182bc735b6424e1a57516d35ed72cb8019d85c8c9bf536dccb3445c1a2f7d"
dependencies = [
"same-file",
"winapi",
"winapi-util",
]
[[package]]
name = "wasm-bindgen"
version = "0.2.68"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ac64ead5ea5f05873d7c12b545865ca2b8d28adfc50a49b84770a3a97265d42"
dependencies = [
"cfg-if",
"serde",
"serde_json",
"wasm-bindgen-macro",
]
[[package]]
name = "wasm-bindgen-backend"
version = "0.2.68"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f22b422e2a757c35a73774860af8e112bff612ce6cb604224e8e47641a9e4f68"
dependencies = [
"bumpalo",
"lazy_static",
"log",
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-futures"
version = "0.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7866cab0aa01de1edf8b5d7936938a7e397ee50ce24119aef3e1eaa3b6171da"
dependencies = [
"cfg-if",
"js-sys",
"wasm-bindgen",
"web-sys",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.68"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b13312a745c08c469f0b292dd2fcd6411dba5f7160f593da6ef69b64e407038"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.68"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f249f06ef7ee334cc3b8ff031bfc11ec99d00f34d86da7498396dc1e3b1498fe"
dependencies = [
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.68"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d649a3145108d7d3fbcde896a468d1bd636791823c9921135218ad89be08307"
[[package]]
name = "wasm-bindgen-test"
version = "0.3.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34d1cdc8b98a557f24733d50a1199c4b0635e465eecba9c45b214544da197f64"
dependencies = [
"console_error_panic_hook",
"js-sys",
"scoped-tls",
"wasm-bindgen",
"wasm-bindgen-futures",
"wasm-bindgen-test-macro",
]
[[package]]
name = "wasm-bindgen-test-macro"
version = "0.3.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8fb9c67be7439ee8ab1b7db502a49c05e51e2835b66796c705134d9b8e1a585"
dependencies = [
"proc-macro2",
"quote",
]
[[package]]
name = "web-libnspire"
version = "0.1.3"
dependencies = [
"console_error_panic_hook",
"js-sys",
"libnspire",
"libnspire-sys",
"libusb1-sys",
"rmp-serde",
"rusb",
"serde",
"serde-wasm-bindgen",
"serde_bytes",
"wasm-bindgen",
"wasm-bindgen-test",
"web-sys",
]
[[package]]
name = "web-sys"
version = "0.3.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4bf6ef87ad7ae8008e15a355ce696bed26012b7caa21605188cfd8214ab51e2d"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-util"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178"
dependencies = [
"winapi",
]
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"

11
web/web-libusb/Cargo.toml Normal file
View file

@ -0,0 +1,11 @@
[workspace]
members = ["web-libusb", "web-libnspire", "wasm-libc"]
[profile.release]
# Tell `rustc` to optimize for small code size.
opt-level = "s"
lto = true
[patch.crates-io]
libusb1-sys = { path = "web-libusb" }
libc = { path = "wasm-libc" }

View file

@ -0,0 +1,10 @@
[package]
name = "libc"
version = "0.2.78"
authors = ["lights0123 <developer@lights0123.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
libc2 = { git = "https://github.com/rust-lang/libc", tag = "0.2.77", package = "libc" }

View file

@ -0,0 +1,16 @@
#[allow(non_camel_case_types)]
pub use libc2::*;
#[cfg(target_arch = "wasm32")]
pub use std::os::raw::*;
#[cfg(target_arch = "wasm32")]
pub type time_t = i64;
#[cfg(target_arch = "wasm32")]
pub type suseconds_t = i32;
#[cfg(target_arch = "wasm32")]
#[repr(C)]
pub struct timeval {
pub tv_sec: time_t,
pub tv_usec: suseconds_t,
}

View file

@ -0,0 +1,5 @@
/target
**/*.rs.bk
Cargo.lock
bin/
wasm-pack.log

View file

@ -0,0 +1,69 @@
language: rust
sudo: false
cache: cargo
matrix:
include:
# Builds with wasm-pack.
- rust: beta
env: RUST_BACKTRACE=1
addons:
firefox: latest
chrome: stable
before_script:
- (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update)
- (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate)
- cargo install-update -a
- curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh -s -- -f
script:
- cargo generate --git . --name testing
# Having a broken Cargo.toml (in that it has curlies in fields) anywhere
# in any of our parent dirs is problematic.
- mv Cargo.toml Cargo.toml.tmpl
- cd testing
- wasm-pack build
- wasm-pack test --chrome --firefox --headless
# Builds on nightly.
- rust: nightly
env: RUST_BACKTRACE=1
before_script:
- (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update)
- (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate)
- cargo install-update -a
- rustup target add wasm32-unknown-unknown
script:
- cargo generate --git . --name testing
- mv Cargo.toml Cargo.toml.tmpl
- cd testing
- cargo check
- cargo check --target wasm32-unknown-unknown
- cargo check --no-default-features
- cargo check --target wasm32-unknown-unknown --no-default-features
- cargo check --no-default-features --features console_error_panic_hook
- cargo check --target wasm32-unknown-unknown --no-default-features --features console_error_panic_hook
- cargo check --no-default-features --features "console_error_panic_hook wee_alloc"
- cargo check --target wasm32-unknown-unknown --no-default-features --features "console_error_panic_hook wee_alloc"
# Builds on beta.
- rust: beta
env: RUST_BACKTRACE=1
before_script:
- (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update)
- (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate)
- cargo install-update -a
- rustup target add wasm32-unknown-unknown
script:
- cargo generate --git . --name testing
- mv Cargo.toml Cargo.toml.tmpl
- cd testing
- cargo check
- cargo check --target wasm32-unknown-unknown
- cargo check --no-default-features
- cargo check --target wasm32-unknown-unknown --no-default-features
- cargo check --no-default-features --features console_error_panic_hook
- cargo check --target wasm32-unknown-unknown --no-default-features --features console_error_panic_hook
# Note: no enabling the `wee_alloc` feature here because it requires
# nightly for now.

View file

@ -0,0 +1,33 @@
[package]
name = "web-libnspire"
description = "libnspire with WASM"
repository = "https://github.com/lights0123/web-libusb"
license = "GPL-3.0"
version = "0.1.3"
authors = ["lights0123 <developer@lights0123.com>"]
edition = "2018"
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
js-sys = "0.3.45"
web-sys = { version = "0.3.45", features = ["DedicatedWorkerGlobalScope"] }
serde = { version = "1.0", features = ["derive"] }
wasm-bindgen = { version = "0.2", features = ["serde-serialize"] }
serde_bytes = "0.11"
serde-wasm-bindgen = "0.1.3"
rmp-serde = "0.14.4"
libusb1-sys = "0.4.2"
libnspire-sys = "0.3.2"
libnspire = "0.2.3"
rusb = "0.6.4"
# The `console_error_panic_hook` crate provides better debugging of panics by
# logging them with `console.error`. This is great for development, but requires
# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for
# code size when deploying.
console_error_panic_hook = { version = "0.1.6", optional = true }
[dev-dependencies]
wasm-bindgen-test = "0.3.13"

View file

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View file

@ -0,0 +1,16 @@
web-libnspire
### 🛠️ Build with `wasm-pack build`
```
wasm-pack build
```
### 🎁 Publish to NPM with `wasm-pack publish`
NOTE: you'll need to edit pkg/package.json to include `web_libnspire_bg.js` under `files`
```
wasm-pack publish
```

View file

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View file

@ -0,0 +1,16 @@
web-libnspire
### 🛠️ Build with `wasm-pack build`
```
wasm-pack build
```
### 🎁 Publish to NPM with `wasm-pack publish`
NOTE: you'll need to edit pkg/package.json to include `web_libnspire_bg.js` under `files`
```
wasm-pack publish
```

View file

@ -0,0 +1,21 @@
{
"name": "web-libnspire",
"collaborators": [
"lights0123 <developer@lights0123.com>"
],
"description": "libnspire with WASM",
"version": "0.1.3",
"license": "GPL-3.0",
"repository": {
"type": "git",
"url": "https://github.com/lights0123/web-libusb"
},
"files": [
"web_libnspire_bg.wasm",
"web_libnspire.js",
"web_libnspire.d.ts"
],
"module": "web_libnspire.js",
"types": "web_libnspire.d.ts",
"sideEffects": false
}

View file

@ -0,0 +1,63 @@
/* tslint:disable */
/* eslint-disable */
/**
*/
export function set_panic_hook(): void;
/**
*/
export class Calculator {
free(): void;
/**
* @param {number} id
* @param {number} vid
* @param {number} pid
* @param {Int32Array} comm
*/
constructor(id: number, vid: number, pid: number, comm: Int32Array);
/**
* @returns {Info}
*/
update(): Info;
/**
* @param {string} path
* @returns {FileInfos}
*/
list_dir(path: string): FileInfos;
/**
* @param {string} path
* @param {number} size
* @returns {Uint8Array}
*/
download_file(path: string, size: number): Uint8Array;
/**
* @param {string} path
* @param {Uint8Array} bytes
*/
upload_file(path: string, bytes: Uint8Array): void;
/**
* @param {Uint8Array} bytes
*/
upload_os(bytes: Uint8Array): void;
/**
* @param {string} path
*/
delete_file(path: string): void;
/**
* @param {string} path
*/
delete_dir(path: string): void;
/**
* @param {string} path
*/
create_dir(path: string): void;
/**
* @param {string} src
* @param {string} dest
*/
copy_file(src: string, dest: string): void;
/**
* @param {string} src
* @param {string} dest
*/
move_file(src: string, dest: string): void;
}

View file

@ -0,0 +1,3 @@
import * as wasm from "./web_libnspire_bg.wasm";
export * from "./web_libnspire_bg.js";
wasm.__wbindgen_start();

View file

@ -0,0 +1,488 @@
import * as wasm from './web_libnspire_bg.wasm';
const heap = new Array(32).fill(undefined);
heap.push(undefined, null, true, false);
function getObject(idx) { return heap[idx]; }
let heap_next = heap.length;
function dropObject(idx) {
if (idx < 36) return;
heap[idx] = heap_next;
heap_next = idx;
}
function takeObject(idx) {
const ret = getObject(idx);
dropObject(idx);
return 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;
}
const lTextDecoder = typeof TextDecoder === 'undefined' ? (0, module.require)('util').TextDecoder : TextDecoder;
let cachedTextDecoder = new lTextDecoder('utf-8', { ignoreBOM: true, fatal: true });
cachedTextDecoder.decode();
let cachegetUint8Memory0 = null;
function getUint8Memory0() {
if (cachegetUint8Memory0 === null || cachegetUint8Memory0.buffer !== wasm.memory.buffer) {
cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer);
}
return cachegetUint8Memory0;
}
function getStringFromWasm0(ptr, len) {
return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len));
}
function debugString(val) {
// primitive types
const type = typeof val;
if (type == 'number' || type == 'boolean' || val == null) {
return `${val}`;
}
if (type == 'string') {
return `"${val}"`;
}
if (type == 'symbol') {
const description = val.description;
if (description == null) {
return 'Symbol';
} else {
return `Symbol(${description})`;
}
}
if (type == 'function') {
const name = val.name;
if (typeof name == 'string' && name.length > 0) {
return `Function(${name})`;
} else {
return 'Function';
}
}
// objects
if (Array.isArray(val)) {
const length = val.length;
let debug = '[';
if (length > 0) {
debug += debugString(val[0]);
}
for(let i = 1; i < length; i++) {
debug += ', ' + debugString(val[i]);
}
debug += ']';
return debug;
}
// Test for built-in
const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val));
let className;
if (builtInMatches.length > 1) {
className = builtInMatches[1];
} else {
// Failed to match the standard '[object ClassName]'
return toString.call(val);
}
if (className == 'Object') {
// we're a user defined class or Object
// JSON.stringify avoids problems with cycles, and is generally much
// easier than looping through ownProperties of `val`.
try {
return 'Object(' + JSON.stringify(val) + ')';
} catch (_) {
return 'Object';
}
}
// errors
if (val instanceof Error) {
return `${val.name}: ${val.message}\n${val.stack}`;
}
// TODO we could test for more things here, like `Set`s and `Map`s.
return className;
}
let WASM_VECTOR_LEN = 0;
const lTextEncoder = typeof TextEncoder === 'undefined' ? (0, module.require)('util').TextEncoder : TextEncoder;
let cachedTextEncoder = new lTextEncoder('utf-8');
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);
getUint8Memory0().subarray(ptr, ptr + buf.length).set(buf);
WASM_VECTOR_LEN = buf.length;
return ptr;
}
let len = arg.length;
let ptr = malloc(len);
const mem = getUint8Memory0();
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);
const view = getUint8Memory0().subarray(ptr + offset, ptr + len);
const ret = encodeString(arg, view);
offset += ret.written;
}
WASM_VECTOR_LEN = offset;
return ptr;
}
let cachegetInt32Memory0 = null;
function getInt32Memory0() {
if (cachegetInt32Memory0 === null || cachegetInt32Memory0.buffer !== wasm.memory.buffer) {
cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer);
}
return cachegetInt32Memory0;
}
/**
*/
export function set_panic_hook() {
wasm.set_panic_hook();
}
function passArray8ToWasm0(arg, malloc) {
const ptr = malloc(arg.length * 1);
getUint8Memory0().set(arg, ptr / 1);
WASM_VECTOR_LEN = arg.length;
return ptr;
}
function handleError(f) {
return function () {
try {
return f.apply(this, arguments);
} catch (e) {
wasm.__wbindgen_exn_store(addHeapObject(e));
}
};
}
/**
*/
export class Calculator {
static __wrap(ptr) {
const obj = Object.create(Calculator.prototype);
obj.ptr = ptr;
return obj;
}
free() {
const ptr = this.ptr;
this.ptr = 0;
wasm.__wbg_calculator_free(ptr);
}
/**
* @param {number} id
* @param {number} vid
* @param {number} pid
* @param {Int32Array} comm
*/
constructor(id, vid, pid, comm) {
var ret = wasm.calculator_new(id, vid, pid, addHeapObject(comm));
return Calculator.__wrap(ret);
}
/**
* @returns {Info}
*/
update() {
var ret = wasm.calculator_update(this.ptr);
return takeObject(ret);
}
/**
* @param {string} path
* @returns {FileInfos}
*/
list_dir(path) {
var ptr0 = passStringToWasm0(path, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
var ret = wasm.calculator_list_dir(this.ptr, ptr0, len0);
return takeObject(ret);
}
/**
* @param {string} path
* @param {number} size
* @returns {Uint8Array}
*/
download_file(path, size) {
var ptr0 = passStringToWasm0(path, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
var ret = wasm.calculator_download_file(this.ptr, ptr0, len0, size);
return takeObject(ret);
}
/**
* @param {string} path
* @param {Uint8Array} bytes
*/
upload_file(path, bytes) {
var ptr0 = passStringToWasm0(path, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
var ptr1 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);
var len1 = WASM_VECTOR_LEN;
wasm.calculator_upload_file(this.ptr, ptr0, len0, ptr1, len1);
}
/**
* @param {Uint8Array} bytes
*/
upload_os(bytes) {
var ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);
var len0 = WASM_VECTOR_LEN;
wasm.calculator_upload_os(this.ptr, ptr0, len0);
}
/**
* @param {string} path
*/
delete_file(path) {
var ptr0 = passStringToWasm0(path, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.calculator_delete_file(this.ptr, ptr0, len0);
}
/**
* @param {string} path
*/
delete_dir(path) {
var ptr0 = passStringToWasm0(path, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.calculator_delete_dir(this.ptr, ptr0, len0);
}
/**
* @param {string} path
*/
create_dir(path) {
var ptr0 = passStringToWasm0(path, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.calculator_create_dir(this.ptr, ptr0, len0);
}
/**
* @param {string} src
* @param {string} dest
*/
copy_file(src, dest) {
var ptr0 = passStringToWasm0(src, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
var ptr1 = passStringToWasm0(dest, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len1 = WASM_VECTOR_LEN;
wasm.calculator_copy_file(this.ptr, ptr0, len0, ptr1, len1);
}
/**
* @param {string} src
* @param {string} dest
*/
move_file(src, dest) {
var ptr0 = passStringToWasm0(src, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
var ptr1 = passStringToWasm0(dest, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len1 = WASM_VECTOR_LEN;
wasm.calculator_move_file(this.ptr, ptr0, len0, ptr1, len1);
}
}
export const __wbindgen_object_drop_ref = function(arg0) {
takeObject(arg0);
};
export const __wbg_log_5c0c1b962d8de78f = function(arg0, arg1) {
console.log(getStringFromWasm0(arg0, arg1));
};
export const __wbg_log_ab4b9253afad956b = function(arg0, arg1) {
console.log(getStringFromWasm0(arg0, arg1));
};
export const __wbg_new_68adb0d58759a4ed = function() {
var ret = new Object();
return addHeapObject(ret);
};
export const __wbindgen_number_new = function(arg0) {
var ret = arg0;
return addHeapObject(ret);
};
export const __wbg_set_2e79e744454afade = function(arg0, arg1, arg2) {
getObject(arg0)[takeObject(arg1)] = takeObject(arg2);
};
export const __wbindgen_string_new = function(arg0, arg1) {
var ret = getStringFromWasm0(arg0, arg1);
return addHeapObject(ret);
};
export const __wbindgen_object_clone_ref = function(arg0) {
var ret = getObject(arg0);
return addHeapObject(ret);
};
export const __wbindgen_is_undefined = function(arg0) {
var ret = getObject(arg0) === undefined;
return ret;
};
export const __wbg_postMessage_048e2aa1055be67d = handleError(function(arg0, arg1) {
getObject(arg0).postMessage(getObject(arg1));
});
export const __wbg_new_e13110f81ae347cf = function() {
var ret = new Array();
return addHeapObject(ret);
};
export const __wbg_push_b46eeec52d2b03bb = function(arg0, arg1) {
var ret = getObject(arg0).push(getObject(arg1));
return ret;
};
export const __wbg_new_1192d65414040ad9 = function(arg0, arg1) {
var ret = new Error(getStringFromWasm0(arg0, arg1));
return addHeapObject(ret);
};
export const __wbg_newnoargs_f3b8a801d5d4b079 = function(arg0, arg1) {
var ret = new Function(getStringFromWasm0(arg0, arg1));
return addHeapObject(ret);
};
export const __wbg_call_8e95613cc6524977 = handleError(function(arg0, arg1) {
var ret = getObject(arg0).call(getObject(arg1));
return addHeapObject(ret);
});
export const __wbg_now_4de5b53a19e45567 = function() {
var ret = Date.now();
return ret;
};
export const __wbg_self_07b2f89e82ceb76d = handleError(function() {
var ret = self.self;
return addHeapObject(ret);
});
export const __wbg_window_ba85d88572adc0dc = handleError(function() {
var ret = window.window;
return addHeapObject(ret);
});
export const __wbg_globalThis_b9277fc37e201fe5 = handleError(function() {
var ret = globalThis.globalThis;
return addHeapObject(ret);
});
export const __wbg_global_e16303fe83e1d57f = handleError(function() {
var ret = global.global;
return addHeapObject(ret);
});
export const __wbg_buffer_49131c283a06686f = function(arg0) {
var ret = getObject(arg0).buffer;
return addHeapObject(ret);
};
export const __wbg_newwithbyteoffsetandlength_c0f38401daad5a22 = function(arg0, arg1, arg2) {
var ret = new Uint8Array(getObject(arg0), arg1 >>> 0, arg2 >>> 0);
return addHeapObject(ret);
};
export const __wbg_new_9b295d24cf1d706f = function(arg0) {
var ret = new Uint8Array(getObject(arg0));
return addHeapObject(ret);
};
export const __wbg_set_3bb960a9975f3cd2 = function(arg0, arg1, arg2) {
getObject(arg0).set(getObject(arg1), arg2 >>> 0);
};
export const __wbg_length_2b13641a9d906653 = function(arg0) {
var ret = getObject(arg0).length;
return ret;
};
export const __wbg_buffer_059acb3eca99e644 = function(arg0) {
var ret = getObject(arg0).buffer;
return addHeapObject(ret);
};
export const __wbg_getindex_e8f2294046c64658 = function(arg0, arg1) {
var ret = getObject(arg0)[arg1 >>> 0];
return ret;
};
export const __wbg_subarray_4eaeb3de00cf1955 = function(arg0, arg1, arg2) {
var ret = getObject(arg0).subarray(arg1 >>> 0, arg2 >>> 0);
return addHeapObject(ret);
};
export const __wbg_store_2ae1fa457ad837c7 = handleError(function(arg0, arg1, arg2) {
var ret = Atomics.store(getObject(arg0), arg1 >>> 0, arg2);
return ret;
});
export const __wbg_wait_92f745c042351c89 = handleError(function(arg0, arg1, arg2) {
var ret = Atomics.wait(getObject(arg0), arg1 >>> 0, arg2);
return addHeapObject(ret);
});
export const __wbindgen_debug_string = function(arg0, arg1) {
var ret = debugString(getObject(arg1));
var ptr0 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
getInt32Memory0()[arg0 / 4 + 1] = len0;
getInt32Memory0()[arg0 / 4 + 0] = ptr0;
};
export const __wbindgen_throw = function(arg0, arg1) {
throw new Error(getStringFromWasm0(arg0, arg1));
};
export const __wbindgen_rethrow = function(arg0) {
throw takeObject(arg0);
};
export const __wbindgen_memory = function() {
var ret = wasm.memory;
return addHeapObject(ret);
};

Binary file not shown.

View file

@ -0,0 +1,46 @@
/* tslint:disable */
/* eslint-disable */
export const memory: WebAssembly.Memory;
export function printf(a: number, b: number): number;
export function puts(a: number): number;
export function putchar(a: number): number;
export function gettimeofday(a: number, b: number): number;
export function set_panic_hook(): void;
export function __wbg_calculator_free(a: number): void;
export function libusb_get_device(a: number): number;
export function libusb_ref_device(a: number): number;
export function libusb_unref_device(a: number): void;
export function calculator_new(a: number, b: number, c: number, d: number): number;
export function calculator_update(a: number): number;
export function calculator_list_dir(a: number, b: number, c: number): number;
export function calculator_download_file(a: number, b: number, c: number, d: number): number;
export function calculator_upload_file(a: number, b: number, c: number, d: number, e: number): void;
export function calculator_upload_os(a: number, b: number, c: number): void;
export function calculator_delete_file(a: number, b: number, c: number): void;
export function calculator_delete_dir(a: number, b: number, c: number): void;
export function calculator_create_dir(a: number, b: number, c: number): void;
export function calculator_copy_file(a: number, b: number, c: number, d: number, e: number): void;
export function calculator_move_file(a: number, b: number, c: number, d: number, e: number): void;
export function libusb_release_interface(a: number, b: number): number;
export function libusb_close(a: number): void;
export function libusb_get_device_descriptor(a: number, b: number): number;
export function strncpy(a: number, b: number, c: number): number;
export function malloc(a: number): number;
export function realloc(a: number, b: number): number;
export function free(a: number): void;
export function memchr(a: number, b: number, c: number): number;
export function strlen(a: number): number;
export function libusb_init(a: number): number;
export function libusb_exit(a: number): void;
export function libusb_set_configuration(a: number, b: number): number;
export function libusb_reset_device(a: number): number;
export function libusb_claim_interface(a: number, b: number): number;
export function libusb_get_active_config_descriptor(a: number, b: number): number;
export function libusb_free_config_descriptor(a: number): void;
export function libusb_bulk_transfer(a: number, b: number, c: number, d: number, e: number, f: number): number;
export function libusb_get_version(): number;
export function libusb_has_capability(a: number): number;
export function __wbindgen_malloc(a: number): number;
export function __wbindgen_realloc(a: number, b: number, c: number): number;
export function __wbindgen_exn_store(a: number): void;
export function __wbindgen_start(): void;

View file

@ -0,0 +1,230 @@
#![feature(c_variadic)]
mod printf;
use std::os::raw::c_int;
use std::ptr::{null_mut, NonNull};
use std::cell::RefCell;
use js_sys::{JsString, Uint8Array};
use libnspire::dir::EntryType;
use libnspire::{Error, Handle};
use rusb::GlobalContext;
use serde::Serialize;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen::__rt::std::ffi::CStr;
use libusb1_sys::dbg;
use std::convert::TryFrom;
#[wasm_bindgen(start)]
pub fn set_panic_hook() {
// When the `console_error_panic_hook` feature is enabled, we can call the
// `set_panic_hook` function at least once during initialization, and then
// we will get better error messages if our code ever panics.
//
// For more details see
// https://github.com/rustwasm/console_error_panic_hook#readme
#[cfg(feature = "console_error_panic_hook")]
console_error_panic_hook::set_once();
}
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
}
thread_local! {
static PRINT_BUF: RefCell<String> = RefCell::new(String::new());
}
#[no_mangle]
pub unsafe extern "C" fn printf(format: *const u8, mut args: ...) -> c_int {
if let Ok(f) = CStr::from_ptr(format as _).to_str() {
if f == "%02x " {
PRINT_BUF.with(|b| {
let mut b = b.borrow_mut();
let b: &mut String = &mut b;
printf::func(format as _, args.as_va_list(), printf::to_write(b));
});
return 0;
}
}
let mut s = String::new();
printf::func(format as _, args.as_va_list(), printf::to_write(&mut s));
log(&s);
0
}
#[no_mangle]
pub unsafe extern "C" fn puts(s: *const u8) -> c_int {
log(&CStr::from_ptr(s as _).to_string_lossy());
0
}
#[no_mangle]
pub unsafe extern "C" fn putchar(s: c_int) -> c_int {
if s == b'\n' as c_int {
PRINT_BUF.with(|b| {
let mut b = b.borrow_mut();
let b: &mut String = &mut b;
log(&b);
b.clear();
});
}
if let Ok(c) = char::try_from(s as u32) {
let mut buf = [0; 4];
log(c.encode_utf8(&mut buf));
}
0
}
#[no_mangle]
pub unsafe extern "C" fn gettimeofday(tp: *mut libusb1_sys::timeval, tz: *mut c_int) -> c_int {
*tp = libusb1_sys::timeval {
tv_sec: (js_sys::Date::now() / 1000.) as _,
tv_usec: 0,
};
0
}
fn global() -> web_sys::DedicatedWorkerGlobalScope {
js_sys::global().unchecked_into()
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FileInfo {
pub path: String,
pub is_dir: bool,
pub date: u64,
pub size: u64,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProgressUpdate {
pub remaining: u32,
pub total: u32,
}
fn progress_sender(total: u32) -> impl FnMut(usize) {
let mut i = 0;
move |remaining| {
if i > 5 {
i = 0;
}
if i == 0 || remaining == 0 {
let update = ProgressUpdate {
remaining: remaining as u32,
total,
};
let value = serde_wasm_bindgen::to_value(&update).unwrap();
global().post_message(&value);
}
i += 1;
}
}
fn err<T, E: std::fmt::Display>(res: Result<T, E>) -> Result<T, JsValue> {
match res {
Ok(c) => Ok(c),
Err(e) => Err(JsString::from(dbg!(format!("{}", e).as_str())).into()),
}
}
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(typescript_type = "FileInfos")]
pub type FileInfos;
#[wasm_bindgen(typescript_type = "Info")]
pub type CalcInfo;
}
#[wasm_bindgen]
pub struct Calculator {
handle: libnspire::Handle<GlobalContext>,
}
#[wasm_bindgen]
impl Calculator {
#[wasm_bindgen(constructor)]
pub fn new(
id: u32,
vid: u16,
pid: u16,
comm: js_sys::Int32Array,
) -> Result<Calculator, JsValue> {
let dev = libusb1_sys::init(id, dbg!((vid, pid)), comm);
let dev = unsafe {
rusb::DeviceHandle::from_libusb(
rusb::GlobalContext::default(),
NonNull::new(dev).unwrap(),
)
};
dbg!(dev.device().device_descriptor().unwrap().product_id());
Ok(Calculator {
handle: err(libnspire::Handle::new(dev))?,
})
}
pub fn update(&self) -> Result<CalcInfo, JsValue> {
Ok(serde_wasm_bindgen::to_value(&dbg!(err(self.handle.info()))?)
.unwrap()
.into())
}
pub fn list_dir(&self, path: &str) -> Result<FileInfos, JsValue> {
let dir = err(self.handle.list_dir(path))?
.iter()
.map(|file| FileInfo {
path: file.name().to_string_lossy().to_string(),
is_dir: file.entry_type() == EntryType::Directory,
date: file.date(),
size: file.size(),
})
.collect::<Vec<_>>();
Ok(serde_wasm_bindgen::to_value(&dir).unwrap().into())
}
pub fn download_file(&self, path: &str, size: u32) -> Result<Uint8Array, JsValue> {
let mut buf = vec![0; size as usize];
let size = err(self
.handle
.read_file(path, &mut buf, &mut progress_sender(size)))?;
Ok((&buf[..size]).into())
}
pub fn upload_file(&self, path: &str, bytes: &[u8]) -> Result<(), JsValue> {
err(self
.handle
.write_file(path, bytes, &mut progress_sender(bytes.len() as u32)))
}
pub fn upload_os(&self, bytes: &[u8]) -> Result<(), JsValue> {
err(self
.handle
.send_os(bytes, &mut progress_sender(bytes.len() as u32)))
}
pub fn delete_file(&self, path: &str) -> Result<(), JsValue> {
err(self.handle.delete_file(path))
}
pub fn delete_dir(&self, path: &str) -> Result<(), JsValue> {
err(self.handle.delete_dir(path))
}
pub fn create_dir(&self, path: &str) -> Result<(), JsValue> {
err(self.handle.create_dir(path))
}
pub fn copy_file(&self, src: &str, dest: &str) -> Result<(), JsValue> {
err(self.handle.copy_file(src, dest))
}
pub fn move_file(&self, src: &str, dest: &str) -> Result<(), JsValue> {
err(self.handle.move_file(src, dest))
}
}

View file

@ -0,0 +1,108 @@
#![feature(c_variadic)]
use core::ffi::VaList;
use std::os::raw::*;
use std::ffi::CStr;
use libusb1_sys::{dbg, println};
use std::fmt;
#[derive(Debug)]
pub enum DoubleFormat {
Normal,
Standard,
Auto,
}
#[derive(Debug)]
pub enum Argument<'a> {
Extra(&'a [u8]),
Percent,
Int(c_int),
Uint(c_uint),
Double {
value: c_uint,
upper: bool,
format: DoubleFormat,
},
String(&'a CStr),
Char(u8),
Hex(u8, c_int),
Pointer(*const ()),
}
pub fn to_write<'a>(w: &'a mut impl fmt::Write) -> impl FnMut(Argument) + 'a {
move |arg| match arg {
Argument::Extra(d) => {w.write_str(&String::from_utf8_lossy(d));},
Argument::Hex(len, data) => {write!(w, "{:#0width$x}", data, width=len as usize);},
e => {dbg!(e);},
}
}
pub unsafe fn func(format: *const c_char, mut args: VaList, mut handler: impl FnMut(Argument)) -> c_int {
let str = CStr::from_ptr(format).to_bytes();
let mut iter = str.split(|&c| c == b'%');
if let Some(begin) = iter.next() {
handler(Argument::Extra(begin));
}
for mut sub in iter {
let prefix = if let Some(init) = sub.get(..2) {
std::str::from_utf8(init).ok().and_then(|s|s.parse().ok()).map(|a| {
sub = &sub[2..];
a
})
} else {
None
};
let ch = sub.get(0).unwrap_or(&0);
handler(match ch {
b'%' => {
Argument::Percent
}
b'd' | b'i' => {
Argument::Int(args.arg())
}
b'x' => {
Argument::Hex(prefix.unwrap_or(0), args.arg())
}
b'u' => {
Argument::Uint(args.arg())
}
b'f' | b'F' => {
Argument::Double {
value: args.arg(),
upper: ch.is_ascii_uppercase(),
format: DoubleFormat::Normal,
}
}
b'e' | b'E' => {
Argument::Double {
value: args.arg(),
upper: ch.is_ascii_uppercase(),
format: DoubleFormat::Standard,
}
}
b'g' | b'G' => {
Argument::Double {
value: args.arg(),
upper: ch.is_ascii_uppercase(),
format: DoubleFormat::Auto,
}
}
b's' => {
Argument::String(CStr::from_ptr(args.arg()))
}
b'c' => {
Argument::Char(args.arg())
}
b'p' => {
Argument::Pointer(args.arg())
}
x => {
dbg!("unrec {}", x);
return -1;
}
});
handler(Argument::Extra(sub.get(1..).unwrap_or(&[])));
}
0
}

6
web/web-libusb/web-libusb/.gitignore vendored Normal file
View file

@ -0,0 +1,6 @@
/target
**/*.rs.bk
Cargo.lock
bin/
pkg/
wasm-pack.log

View file

@ -0,0 +1,20 @@
[package]
name = "libusb1-sys"
version = "0.4.2"
authors = ["lights0123 <developer@lights0123.com>"]
edition = "2018"
build = "build.rs"
links = "usb-1.0" # Required for metadata passing to work
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
js-sys = "0.3.45"
web-sys = { version = "0.3.45", features = ["DedicatedWorkerGlobalScope", "console"] }
serde = { version = "1.0", features = ["derive"] }
wasm-bindgen = { version = "0.2", features = ["serde-serialize"] }
serde_bytes = "0.11"
serde-wasm-bindgen = "0.1.3"
rmp-serde = "0.14.4"
libc = "0.2.77"

View file

@ -0,0 +1,176 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

View file

@ -0,0 +1,25 @@
Copyright (c) 2018 lights0123 <developer@lights0123.com>
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1,69 @@
<div align="center">
<h1><code>wasm-pack-template</code></h1>
<strong>A template for kick starting a Rust and WebAssembly project using <a href="https://github.com/rustwasm/wasm-pack">wasm-pack</a>.</strong>
<p>
<a href="https://travis-ci.org/rustwasm/wasm-pack-template"><img src="https://img.shields.io/travis/rustwasm/wasm-pack-template.svg?style=flat-square" alt="Build Status" /></a>
</p>
<h3>
<a href="https://rustwasm.github.io/docs/wasm-pack/tutorials/npm-browser-packages/index.html">Tutorial</a>
<span> | </span>
<a href="https://discordapp.com/channels/442252698964721669/443151097398296587">Chat</a>
</h3>
<sub>Built with 🦀🕸 by <a href="https://rustwasm.github.io/">The Rust and WebAssembly Working Group</a></sub>
</div>
## About
[**📚 Read this template tutorial! 📚**][template-docs]
This template is designed for compiling Rust libraries into WebAssembly and
publishing the resulting package to NPM.
Be sure to check out [other `wasm-pack` tutorials online][tutorials] for other
templates and usages of `wasm-pack`.
[tutorials]: https://rustwasm.github.io/docs/wasm-pack/tutorials/index.html
[template-docs]: https://rustwasm.github.io/docs/wasm-pack/tutorials/npm-browser-packages/index.html
## 🚴 Usage
### 🐑 Use `cargo generate` to Clone this Template
[Learn more about `cargo generate` here.](https://github.com/ashleygwilliams/cargo-generate)
```
cargo generate --git https://github.com/rustwasm/wasm-pack-template.git --name my-project
cd my-project
```
### 🛠️ Build with `wasm-pack build`
```
wasm-pack build
```
### 🔬 Test in Headless Browsers with `wasm-pack test`
```
wasm-pack test --headless --firefox
```
### 🎁 Publish to NPM with `wasm-pack publish`
```
wasm-pack publish
```
## 🔋 Batteries Included
* [`wasm-bindgen`](https://github.com/rustwasm/wasm-bindgen) for communicating
between WebAssembly and JavaScript.
* [`console_error_panic_hook`](https://github.com/rustwasm/console_error_panic_hook)
for logging panic messages to the developer console.
* [`wee_alloc`](https://github.com/rustwasm/wee_alloc), an allocator optimized
for small code size.

View file

@ -0,0 +1,10 @@
use std::path::PathBuf;
fn main() {
println!(
"cargo:include={}",
PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap())
.join("include")
.display()
);
}

View file

@ -0,0 +1,6 @@
#pragma once
namespace std {
template <class T> const T& min (const T& a, const T& b) {
return !(b<a)?a:b; // or: return !comp(b,a)?a:b; for version (2)
}
};

View file

@ -0,0 +1,7 @@
#pragma once
// WASM is little-endian
#define htonl __builtin_bswap32
#define htons __builtin_bswap16
#define ntohl __builtin_bswap32
#define ntohs __builtin_bswap16

View file

@ -0,0 +1,421 @@
#define _Addr __PTRDIFF_TYPE__
#define _Int64 __INT64_TYPE__
#define _Reg __PTRDIFF_TYPE__
#if __GNUC__ >= 3
#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)
typedef __builtin_va_list va_list;
#define __DEFINED_va_list
#endif
#if defined(__NEED___isoc_va_list) && !defined(__DEFINED___isoc_va_list)
typedef __builtin_va_list __isoc_va_list;
#define __DEFINED___isoc_va_list
#endif
#else
#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)
typedef struct __va_list * va_list;
#define __DEFINED_va_list
#endif
#if defined(__NEED___isoc_va_list) && !defined(__DEFINED___isoc_va_list)
typedef struct __va_list * __isoc_va_list;
#define __DEFINED___isoc_va_list
#endif
#endif
#ifndef __cplusplus
#ifdef __WCHAR_TYPE__
#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)
typedef __WCHAR_TYPE__ wchar_t;
#define __DEFINED_wchar_t
#endif
#else
#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)
typedef long wchar_t;
#define __DEFINED_wchar_t
#endif
#endif
#endif
#if defined(__NEED_wint_t) && !defined(__DEFINED_wint_t)
typedef unsigned wint_t;
#define __DEFINED_wint_t
#endif
#if defined(__FLT_EVAL_METHOD__) && __FLT_EVAL_METHOD__ == 0
#if defined(__NEED_float_t) && !defined(__DEFINED_float_t)
typedef float float_t;
#define __DEFINED_float_t
#endif
#if defined(__NEED_double_t) && !defined(__DEFINED_double_t)
typedef double double_t;
#define __DEFINED_double_t
#endif
#else
#if defined(__NEED_float_t) && !defined(__DEFINED_float_t)
typedef long double float_t;
#define __DEFINED_float_t
#endif
#if defined(__NEED_double_t) && !defined(__DEFINED_double_t)
typedef long double double_t;
#define __DEFINED_double_t
#endif
#endif
#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)
typedef long time_t;
#define __DEFINED_time_t
#endif
#if defined(__NEED_suseconds_t) && !defined(__DEFINED_suseconds_t)
typedef long suseconds_t;
#define __DEFINED_suseconds_t
#endif
#if defined(__NEED_pthread_attr_t) && !defined(__DEFINED_pthread_attr_t)
#ifdef __EMSCRIPTEN__
// For canvas transfer implementation in Emscripten, use an extra 11th control field
// to pass a pointer to a string denoting the WebGL canvases to transfer.
typedef struct { union { int __i[11]; volatile int __vi[11]; unsigned __s[11]; } __u; } pthread_attr_t;
#else
typedef struct { union { int __i[10]; volatile int __vi[10]; unsigned __s[10]; } __u; } pthread_attr_t;
#endif
#define __DEFINED_pthread_attr_t
#endif
#if defined(__NEED_pthread_mutex_t) && !defined(__DEFINED_pthread_mutex_t)
typedef struct { union { int __i[7]; volatile int __vi[7]; volatile void *__p[7]; } __u; } pthread_mutex_t;
typedef pthread_mutex_t mtx_t;
#define __DEFINED_pthread_mutex_t
#endif
#if defined(__NEED_pthread_cond_t) && !defined(__DEFINED_pthread_cond_t)
typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12]; } __u; } pthread_cond_t;
typedef pthread_cond_t cnd_t;
#define __DEFINED_pthread_cond_t
#endif
#if defined(__NEED_pthread_rwlock_t) && !defined(__DEFINED_pthread_rwlock_t)
typedef struct { union { int __i[8]; volatile int __vi[8]; void *__p[8]; } __u; } pthread_rwlock_t;
#define __DEFINED_pthread_rwlock_t
#endif
#if defined(__NEED_pthread_barrier_t) && !defined(__DEFINED_pthread_barrier_t)
typedef struct { union { int __i[5]; volatile int __vi[5]; void *__p[5]; } __u; } pthread_barrier_t;
#define __DEFINED_pthread_barrier_t
#endif
#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)
typedef unsigned _Addr size_t;
#define __DEFINED_size_t
#endif
#if defined(__NEED_uintptr_t) && !defined(__DEFINED_uintptr_t)
typedef unsigned _Addr uintptr_t;
#define __DEFINED_uintptr_t
#endif
#if defined(__NEED_ptrdiff_t) && !defined(__DEFINED_ptrdiff_t)
typedef _Addr ptrdiff_t;
#define __DEFINED_ptrdiff_t
#endif
#if defined(__NEED_ssize_t) && !defined(__DEFINED_ssize_t)
typedef _Addr ssize_t;
#define __DEFINED_ssize_t
#endif
#if defined(__NEED_intptr_t) && !defined(__DEFINED_intptr_t)
typedef _Addr intptr_t;
#define __DEFINED_intptr_t
#endif
#if defined(__NEED_regoff_t) && !defined(__DEFINED_regoff_t)
typedef _Addr regoff_t;
#define __DEFINED_regoff_t
#endif
#if defined(__NEED_register_t) && !defined(__DEFINED_register_t)
typedef _Reg register_t;
#define __DEFINED_register_t
#endif
#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)
typedef signed char int8_t;
#define __DEFINED_int8_t
#endif
#if defined(__NEED_int16_t) && !defined(__DEFINED_int16_t)
typedef short int16_t;
#define __DEFINED_int16_t
#endif
#if defined(__NEED_int32_t) && !defined(__DEFINED_int32_t)
typedef int int32_t;
#define __DEFINED_int32_t
#endif
#if defined(__NEED_int64_t) && !defined(__DEFINED_int64_t)
typedef _Int64 int64_t;
#define __DEFINED_int64_t
#endif
#if defined(__NEED_intmax_t) && !defined(__DEFINED_intmax_t)
typedef _Int64 intmax_t;
#define __DEFINED_intmax_t
#endif
#if defined(__NEED_uint8_t) && !defined(__DEFINED_uint8_t)
typedef unsigned char uint8_t;
#define __DEFINED_uint8_t
#endif
#if defined(__NEED_uint16_t) && !defined(__DEFINED_uint16_t)
typedef unsigned short uint16_t;
#define __DEFINED_uint16_t
#endif
#if defined(__NEED_uint32_t) && !defined(__DEFINED_uint32_t)
typedef unsigned int uint32_t;
#define __DEFINED_uint32_t
#endif
#if defined(__NEED_uint64_t) && !defined(__DEFINED_uint64_t)
typedef unsigned _Int64 uint64_t;
#define __DEFINED_uint64_t
#endif
#if defined(__NEED_u_int64_t) && !defined(__DEFINED_u_int64_t)
typedef unsigned _Int64 u_int64_t;
#define __DEFINED_u_int64_t
#endif
#if defined(__NEED_uintmax_t) && !defined(__DEFINED_uintmax_t)
typedef unsigned _Int64 uintmax_t;
#define __DEFINED_uintmax_t
#endif
#if defined(__NEED_mode_t) && !defined(__DEFINED_mode_t)
typedef unsigned mode_t;
#define __DEFINED_mode_t
#endif
#if defined(__NEED_nlink_t) && !defined(__DEFINED_nlink_t)
typedef unsigned _Reg nlink_t;
#define __DEFINED_nlink_t
#endif
#if defined(__NEED_off_t) && !defined(__DEFINED_off_t)
typedef _Int64 off_t;
#define __DEFINED_off_t
#endif
#if defined(__NEED_ino_t) && !defined(__DEFINED_ino_t)
typedef unsigned _Int64 ino_t;
#define __DEFINED_ino_t
#endif
#if defined(__NEED_dev_t) && !defined(__DEFINED_dev_t)
typedef unsigned int dev_t;
#define __DEFINED_dev_t
#endif
#if defined(__NEED_blksize_t) && !defined(__DEFINED_blksize_t)
typedef long blksize_t;
#define __DEFINED_blksize_t
#endif
#if defined(__NEED_blkcnt_t) && !defined(__DEFINED_blkcnt_t)
typedef int blkcnt_t;
#define __DEFINED_blkcnt_t
#endif
#if defined(__NEED_fsblkcnt_t) && !defined(__DEFINED_fsblkcnt_t)
typedef unsigned int fsblkcnt_t;
#define __DEFINED_fsblkcnt_t
#endif
#if defined(__NEED_fsfilcnt_t) && !defined(__DEFINED_fsfilcnt_t)
typedef unsigned int fsfilcnt_t;
#define __DEFINED_fsfilcnt_t
#endif
#if defined(__NEED_wint_t) && !defined(__DEFINED_wint_t)
typedef unsigned wint_t;
#define __DEFINED_wint_t
#endif
#if defined(__NEED_wctype_t) && !defined(__DEFINED_wctype_t)
typedef unsigned long wctype_t;
#define __DEFINED_wctype_t
#endif
#if defined(__NEED_timer_t) && !defined(__DEFINED_timer_t)
typedef void * timer_t;
#define __DEFINED_timer_t
#endif
#if defined(__NEED_clockid_t) && !defined(__DEFINED_clockid_t)
typedef int clockid_t;
#define __DEFINED_clockid_t
#endif
#if defined(__NEED_clock_t) && !defined(__DEFINED_clock_t)
typedef long clock_t;
#define __DEFINED_clock_t
#endif
#if defined(__NEED_max_align_t) && !defined(__DEFINED_max_align_t)
typedef struct { long long __ll; long double __ld; } max_align_t;
#define __DEFINED_max_align_t
#endif
#if defined(__NEED_struct_timeval) && !defined(__DEFINED_struct_timeval)
struct timeval { time_t tv_sec; suseconds_t tv_usec; };
#define __DEFINED_struct_timeval
#endif
#if defined(__NEED_struct_timespec) && !defined(__DEFINED_struct_timespec)
struct timespec { time_t tv_sec; long tv_nsec; };
#define __DEFINED_struct_timespec
#endif
#if defined(__NEED_pid_t) && !defined(__DEFINED_pid_t)
typedef int pid_t;
#define __DEFINED_pid_t
#endif
#if defined(__NEED_id_t) && !defined(__DEFINED_id_t)
typedef unsigned id_t;
#define __DEFINED_id_t
#endif
#if defined(__NEED_uid_t) && !defined(__DEFINED_uid_t)
typedef unsigned uid_t;
#define __DEFINED_uid_t
#endif
#if defined(__NEED_gid_t) && !defined(__DEFINED_gid_t)
typedef unsigned gid_t;
#define __DEFINED_gid_t
#endif
#if defined(__NEED_key_t) && !defined(__DEFINED_key_t)
typedef int key_t;
#define __DEFINED_key_t
#endif
#if defined(__NEED_useconds_t) && !defined(__DEFINED_useconds_t)
typedef unsigned useconds_t;
#define __DEFINED_useconds_t
#endif
#ifdef __cplusplus
#if defined(__NEED_pthread_t) && !defined(__DEFINED_pthread_t)
typedef unsigned long pthread_t;
#define __DEFINED_pthread_t
#endif
#else
#if defined(__NEED_pthread_t) && !defined(__DEFINED_pthread_t)
typedef struct __pthread * pthread_t;
#define __DEFINED_pthread_t
#endif
#endif
#if defined(__NEED_pthread_once_t) && !defined(__DEFINED_pthread_once_t)
typedef int pthread_once_t;
#define __DEFINED_pthread_once_t
#endif
#if defined(__NEED_pthread_key_t) && !defined(__DEFINED_pthread_key_t)
typedef unsigned pthread_key_t;
#define __DEFINED_pthread_key_t
#endif
#if defined(__NEED_pthread_spinlock_t) && !defined(__DEFINED_pthread_spinlock_t)
typedef int pthread_spinlock_t;
#define __DEFINED_pthread_spinlock_t
#endif
#if defined(__NEED_pthread_mutexattr_t) && !defined(__DEFINED_pthread_mutexattr_t)
typedef struct { unsigned __attr; } pthread_mutexattr_t;
#define __DEFINED_pthread_mutexattr_t
#endif
#if defined(__NEED_pthread_condattr_t) && !defined(__DEFINED_pthread_condattr_t)
typedef struct { unsigned __attr; } pthread_condattr_t;
#define __DEFINED_pthread_condattr_t
#endif
#if defined(__NEED_pthread_barrierattr_t) && !defined(__DEFINED_pthread_barrierattr_t)
typedef struct { unsigned __attr; } pthread_barrierattr_t;
#define __DEFINED_pthread_barrierattr_t
#endif
#if defined(__NEED_pthread_rwlockattr_t) && !defined(__DEFINED_pthread_rwlockattr_t)
typedef struct { unsigned __attr[2]; } pthread_rwlockattr_t;
#define __DEFINED_pthread_rwlockattr_t
#endif
#if defined(__NEED_FILE) && !defined(__DEFINED_FILE)
typedef struct _IO_FILE FILE;
#define __DEFINED_FILE
#endif
#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)
typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;
#define __DEFINED_mbstate_t
#endif
#if defined(__NEED_locale_t) && !defined(__DEFINED_locale_t)
typedef struct __locale_struct * locale_t;
#define __DEFINED_locale_t
#endif
#if defined(__NEED_sigset_t) && !defined(__DEFINED_sigset_t)
typedef struct __sigset_t { unsigned long __bits[128/sizeof(long)]; } sigset_t;
#define __DEFINED_sigset_t
#endif
#if defined(__NEED_struct_iovec) && !defined(__DEFINED_struct_iovec)
struct iovec { void *iov_base; size_t iov_len; };
#define __DEFINED_struct_iovec
#endif
#if defined(__NEED_socklen_t) && !defined(__DEFINED_socklen_t)
typedef unsigned socklen_t;
#define __DEFINED_socklen_t
#endif
#if defined(__NEED_sa_family_t) && !defined(__DEFINED_sa_family_t)
typedef unsigned short sa_family_t;
#define __DEFINED_sa_family_t
#endif
#undef _Addr
#undef _Int64
#undef _Reg

View file

@ -0,0 +1,8 @@
#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
|| defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
#define PAGE_SIZE 16384
#define LONG_BIT 32
#endif
#define LONG_MAX 0x7fffffffL
#define LLONG_MAX 0x7fffffffffffffffLL

View file

@ -0,0 +1,20 @@
typedef int32_t int_fast16_t;
typedef int32_t int_fast32_t;
typedef uint32_t uint_fast16_t;
typedef uint32_t uint_fast32_t;
#define INT_FAST16_MIN INT32_MIN
#define INT_FAST32_MIN INT32_MIN
#define INT_FAST16_MAX INT32_MAX
#define INT_FAST32_MAX INT32_MAX
#define UINT_FAST16_MAX UINT32_MAX
#define UINT_FAST32_MAX UINT32_MAX
#define INTPTR_MIN INT32_MIN
#define INTPTR_MAX INT32_MAX
#define UINTPTR_MAX UINT32_MAX
#define PTRDIFF_MIN INT32_MIN
#define PTRDIFF_MAX INT32_MAX
#define SIZE_MAX UINT32_MAX

View file

@ -0,0 +1 @@
#include "stdint.h"

View file

@ -0,0 +1,3 @@
extern "C" {
int printf ( const char * format, ... );
}

View file

@ -0,0 +1,3 @@
extern "C" {
#include "stdlib.h"
}

View file

@ -0,0 +1,3 @@
extern "C" {
#include "string.h"
}

View file

@ -0,0 +1,39 @@
#ifndef _FEATURES_H
#define _FEATURES_H
#if defined(_ALL_SOURCE) && !defined(_GNU_SOURCE)
#define _GNU_SOURCE 1
#endif
#if defined(_DEFAULT_SOURCE) && !defined(_BSD_SOURCE)
#define _BSD_SOURCE 1
#endif
#if !defined(_POSIX_SOURCE) && !defined(_POSIX_C_SOURCE) \
&& !defined(_XOPEN_SOURCE) && !defined(_GNU_SOURCE) \
&& !defined(_BSD_SOURCE) && !defined(__STRICT_ANSI__)
#define _BSD_SOURCE 1
#define _XOPEN_SOURCE 700
#endif
#if __STDC_VERSION__ >= 199901L
#define __restrict restrict
#elif !defined(__GNUC__)
#define __restrict
#endif
#if __STDC_VERSION__ >= 199901L || defined(__cplusplus)
#define __inline inline
#endif
#if __STDC_VERSION__ >= 201112L
#elif defined(__GNUC__)
#define _Noreturn __attribute__((__noreturn__))
#else
#define _Noreturn
#endif
#define weak_alias(old, new) \
extern __typeof(old) new __attribute__((__weak__, __alias__(#old)))
#endif

View file

@ -0,0 +1,229 @@
#ifndef _INTTYPES_H
#define _INTTYPES_H
#ifdef __cplusplus
extern "C" {
#endif
#include <features.h>
#include <stdint.h>
#define __NEED_wchar_t
#include <bits/alltypes.h>
typedef struct { intmax_t quot, rem; } imaxdiv_t;
intmax_t imaxabs(intmax_t);
imaxdiv_t imaxdiv(intmax_t, intmax_t);
intmax_t strtoimax(const char *__restrict, char **__restrict, int);
uintmax_t strtoumax(const char *__restrict, char **__restrict, int);
intmax_t wcstoimax(const wchar_t *__restrict, wchar_t **__restrict, int);
uintmax_t wcstoumax(const wchar_t *__restrict, wchar_t **__restrict, int);
#if UINTPTR_MAX == UINT64_MAX
#define __PRI64 "l"
#define __PRIPTR "l"
#else
#define __PRI64 "ll"
#define __PRIPTR ""
#endif
#define PRId8 "d"
#define PRId16 "d"
#define PRId32 "d"
#define PRId64 __PRI64 "d"
#define PRIdLEAST8 "d"
#define PRIdLEAST16 "d"
#define PRIdLEAST32 "d"
#define PRIdLEAST64 __PRI64 "d"
#define PRIdFAST8 "d"
#define PRIdFAST16 "d"
#define PRIdFAST32 "d"
#define PRIdFAST64 __PRI64 "d"
#define PRIi8 "i"
#define PRIi16 "i"
#define PRIi32 "i"
#define PRIi64 __PRI64 "i"
#define PRIiLEAST8 "i"
#define PRIiLEAST16 "i"
#define PRIiLEAST32 "i"
#define PRIiLEAST64 __PRI64 "i"
#define PRIiFAST8 "i"
#define PRIiFAST16 "i"
#define PRIiFAST32 "i"
#define PRIiFAST64 __PRI64 "i"
#define PRIo8 "o"
#define PRIo16 "o"
#define PRIo32 "o"
#define PRIo64 __PRI64 "o"
#define PRIoLEAST8 "o"
#define PRIoLEAST16 "o"
#define PRIoLEAST32 "o"
#define PRIoLEAST64 __PRI64 "o"
#define PRIoFAST8 "o"
#define PRIoFAST16 "o"
#define PRIoFAST32 "o"
#define PRIoFAST64 __PRI64 "o"
#define PRIu8 "u"
#define PRIu16 "u"
#define PRIu32 "u"
#define PRIu64 __PRI64 "u"
#define PRIuLEAST8 "u"
#define PRIuLEAST16 "u"
#define PRIuLEAST32 "u"
#define PRIuLEAST64 __PRI64 "u"
#define PRIuFAST8 "u"
#define PRIuFAST16 "u"
#define PRIuFAST32 "u"
#define PRIuFAST64 __PRI64 "u"
#define PRIx8 "x"
#define PRIx16 "x"
#define PRIx32 "x"
#define PRIx64 __PRI64 "x"
#define PRIxLEAST8 "x"
#define PRIxLEAST16 "x"
#define PRIxLEAST32 "x"
#define PRIxLEAST64 __PRI64 "x"
#define PRIxFAST8 "x"
#define PRIxFAST16 "x"
#define PRIxFAST32 "x"
#define PRIxFAST64 __PRI64 "x"
#define PRIX8 "X"
#define PRIX16 "X"
#define PRIX32 "X"
#define PRIX64 __PRI64 "X"
#define PRIXLEAST8 "X"
#define PRIXLEAST16 "X"
#define PRIXLEAST32 "X"
#define PRIXLEAST64 __PRI64 "X"
#define PRIXFAST8 "X"
#define PRIXFAST16 "X"
#define PRIXFAST32 "X"
#define PRIXFAST64 __PRI64 "X"
#define PRIdMAX __PRI64 "d"
#define PRIiMAX __PRI64 "i"
#define PRIoMAX __PRI64 "o"
#define PRIuMAX __PRI64 "u"
#define PRIxMAX __PRI64 "x"
#define PRIXMAX __PRI64 "X"
#define PRIdPTR __PRIPTR "d"
#define PRIiPTR __PRIPTR "i"
#define PRIoPTR __PRIPTR "o"
#define PRIuPTR __PRIPTR "u"
#define PRIxPTR __PRIPTR "x"
#define PRIXPTR __PRIPTR "X"
#define SCNd8 "hhd"
#define SCNd16 "hd"
#define SCNd32 "d"
#define SCNd64 __PRI64 "d"
#define SCNdLEAST8 "hhd"
#define SCNdLEAST16 "hd"
#define SCNdLEAST32 "d"
#define SCNdLEAST64 __PRI64 "d"
#define SCNdFAST8 "hhd"
#define SCNdFAST16 "d"
#define SCNdFAST32 "d"
#define SCNdFAST64 __PRI64 "d"
#define SCNi8 "hhi"
#define SCNi16 "hi"
#define SCNi32 "i"
#define SCNi64 __PRI64 "i"
#define SCNiLEAST8 "hhi"
#define SCNiLEAST16 "hi"
#define SCNiLEAST32 "i"
#define SCNiLEAST64 __PRI64 "i"
#define SCNiFAST8 "hhi"
#define SCNiFAST16 "i"
#define SCNiFAST32 "i"
#define SCNiFAST64 __PRI64 "i"
#define SCNu8 "hhu"
#define SCNu16 "hu"
#define SCNu32 "u"
#define SCNu64 __PRI64 "u"
#define SCNuLEAST8 "hhu"
#define SCNuLEAST16 "hu"
#define SCNuLEAST32 "u"
#define SCNuLEAST64 __PRI64 "u"
#define SCNuFAST8 "hhu"
#define SCNuFAST16 "u"
#define SCNuFAST32 "u"
#define SCNuFAST64 __PRI64 "u"
#define SCNo8 "hho"
#define SCNo16 "ho"
#define SCNo32 "o"
#define SCNo64 __PRI64 "o"
#define SCNoLEAST8 "hho"
#define SCNoLEAST16 "ho"
#define SCNoLEAST32 "o"
#define SCNoLEAST64 __PRI64 "o"
#define SCNoFAST8 "hho"
#define SCNoFAST16 "o"
#define SCNoFAST32 "o"
#define SCNoFAST64 __PRI64 "o"
#define SCNx8 "hhx"
#define SCNx16 "hx"
#define SCNx32 "x"
#define SCNx64 __PRI64 "x"
#define SCNxLEAST8 "hhx"
#define SCNxLEAST16 "hx"
#define SCNxLEAST32 "x"
#define SCNxLEAST64 __PRI64 "x"
#define SCNxFAST8 "hhx"
#define SCNxFAST16 "x"
#define SCNxFAST32 "x"
#define SCNxFAST64 __PRI64 "x"
#define SCNdMAX __PRI64 "d"
#define SCNiMAX __PRI64 "i"
#define SCNoMAX __PRI64 "o"
#define SCNuMAX __PRI64 "u"
#define SCNxMAX __PRI64 "x"
#define SCNdPTR __PRIPTR "d"
#define SCNiPTR __PRIPTR "i"
#define SCNoPTR __PRIPTR "o"
#define SCNuPTR __PRIPTR "u"
#define SCNxPTR __PRIPTR "x"
#ifdef __cplusplus
}
#endif
#endif

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,154 @@
#ifndef _LIMITS_H
#define _LIMITS_H
#include <features.h>
/* Most limits are system-specific */
#include <bits/limits.h>
/* Support signed or unsigned plain-char */
#if '\0'-1 > 0
#define CHAR_MIN 0
#define CHAR_MAX 255
#else
#define CHAR_MIN (-128)
#define CHAR_MAX 127
#endif
/* Some universal constants... */
#define CHAR_BIT 8
#define SCHAR_MIN (-128)
#define SCHAR_MAX 127
#define UCHAR_MAX 255
#define SHRT_MIN (-1-0x7fff)
#define SHRT_MAX 0x7fff
#define USHRT_MAX 0xffff
#define INT_MIN (-1-0x7fffffff)
#define INT_MAX 0x7fffffff
#define UINT_MAX 0xffffffffU
#define LONG_MIN (-LONG_MAX-1)
#define ULONG_MAX (2UL*LONG_MAX+1)
#define LLONG_MIN (-LLONG_MAX-1)
#define ULLONG_MAX (2ULL*LLONG_MAX+1)
#define MB_LEN_MAX 4
#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
|| defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
#define PIPE_BUF 4096
#ifdef PAGE_SIZE
#define PAGESIZE PAGE_SIZE
#endif
#define FILESIZEBITS 64
#define NAME_MAX 255
#define SYMLINK_MAX 255
#define PATH_MAX 4096
#define NZERO 20
#define NGROUPS_MAX 32
#define ARG_MAX 131072
#define IOV_MAX 1024
#define SYMLOOP_MAX 40
#define WORD_BIT 32
#define SSIZE_MAX LONG_MAX
#define TZNAME_MAX 6
#define TTY_NAME_MAX 32
#define HOST_NAME_MAX 255
/* Implementation choices... */
#define PTHREAD_KEYS_MAX 128
#define PTHREAD_STACK_MIN 2048
#define PTHREAD_DESTRUCTOR_ITERATIONS 4
#define SEM_VALUE_MAX 0x7fffffff
#define SEM_NSEMS_MAX 256
#define DELAYTIMER_MAX 0x7fffffff
#define MQ_PRIO_MAX 32768
#define LOGIN_NAME_MAX 256
/* Arbitrary numbers... */
#define BC_BASE_MAX 99
#define BC_DIM_MAX 2048
#define BC_SCALE_MAX 99
#define BC_STRING_MAX 1000
#define CHARCLASS_NAME_MAX 14
#define COLL_WEIGHTS_MAX 2
#define EXPR_NEST_MAX 32
#define LINE_MAX 4096
#define RE_DUP_MAX 255
#define NL_ARGMAX 9
#define NL_LANGMAX 32
#define NL_MSGMAX 32767
#define NL_SETMAX 255
#define NL_TEXTMAX 2048
#endif
#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) \
|| (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE+0 < 700)
#define NL_NMAX 16
#endif
/* POSIX/SUS requirements follow. These numbers come directly
* from SUS and have nothing to do with the host system. */
#define _POSIX_AIO_LISTIO_MAX 2
#define _POSIX_AIO_MAX 1
#define _POSIX_ARG_MAX 4096
#define _POSIX_CHILD_MAX 25
#define _POSIX_CLOCKRES_MIN 20000000
#define _POSIX_DELAYTIMER_MAX 32
#define _POSIX_HOST_NAME_MAX 255
#define _POSIX_LINK_MAX 8
#define _POSIX_LOGIN_NAME_MAX 9
#define _POSIX_MAX_CANON 255
#define _POSIX_MAX_INPUT 255
#define _POSIX_MQ_OPEN_MAX 8
#define _POSIX_MQ_PRIO_MAX 32
#define _POSIX_NAME_MAX 14
#define _POSIX_NGROUPS_MAX 8
#define _POSIX_OPEN_MAX 20
#define _POSIX_PATH_MAX 256
#define _POSIX_PIPE_BUF 512
#define _POSIX_RE_DUP_MAX 255
#define _POSIX_RTSIG_MAX 8
#define _POSIX_SEM_NSEMS_MAX 256
#define _POSIX_SEM_VALUE_MAX 32767
#define _POSIX_SIGQUEUE_MAX 32
#define _POSIX_SSIZE_MAX 32767
#define _POSIX_STREAM_MAX 8
#define _POSIX_SS_REPL_MAX 4
#define _POSIX_SYMLINK_MAX 255
#define _POSIX_SYMLOOP_MAX 8
#define _POSIX_THREAD_DESTRUCTOR_ITERATIONS 4
#define _POSIX_THREAD_KEYS_MAX 128
#define _POSIX_THREAD_THREADS_MAX 64
#define _POSIX_TIMER_MAX 32
#define _POSIX_TRACE_EVENT_NAME_MAX 30
#define _POSIX_TRACE_NAME_MAX 8
#define _POSIX_TRACE_SYS_MAX 8
#define _POSIX_TRACE_USER_EVENT_MAX 32
#define _POSIX_TTY_NAME_MAX 9
#define _POSIX_TZNAME_MAX 6
#define _POSIX2_BC_BASE_MAX 99
#define _POSIX2_BC_DIM_MAX 2048
#define _POSIX2_BC_SCALE_MAX 99
#define _POSIX2_BC_STRING_MAX 1000
#define _POSIX2_CHARCLASS_NAME_MAX 14
#define _POSIX2_COLL_WEIGHTS_MAX 2
#define _POSIX2_EXPR_NEST_MAX 32
#define _POSIX2_LINE_MAX 2048
#define _POSIX2_RE_DUP_MAX 255
#define _XOPEN_IOV_MAX 16
#define _XOPEN_NAME_MAX 255
#define _XOPEN_PATH_MAX 1024
#endif

View file

@ -0,0 +1,124 @@
#define DEBUG
#ifndef _STDINT_H
#define _STDINT_H
#define __NEED_int8_t
#define __NEED_int16_t
#define __NEED_int32_t
#define __NEED_int64_t
#define __NEED_uint8_t
#define __NEED_uint16_t
#define __NEED_uint32_t
#define __NEED_uint64_t
#define __NEED_intptr_t
#define __NEED_uintptr_t
#define __NEED_intmax_t
#define __NEED_uintmax_t
#define __NEED_size_t
#define __NEED_ssize_t
#include <bits/alltypes.h>
typedef int8_t int_fast8_t;
typedef int64_t int_fast64_t;
typedef int8_t int_least8_t;
typedef int16_t int_least16_t;
typedef int32_t int_least32_t;
typedef int64_t int_least64_t;
typedef uint8_t uint_fast8_t;
typedef uint64_t uint_fast64_t;
typedef uint8_t uint_least8_t;
typedef uint16_t uint_least16_t;
typedef uint32_t uint_least32_t;
typedef uint64_t uint_least64_t;
#define INT8_MIN (-1-0x7f)
#define INT16_MIN (-1-0x7fff)
#define INT32_MIN (-1-0x7fffffff)
#define INT64_MIN (-1-0x7fffffffffffffff)
#define INT8_MAX (0x7f)
#define INT16_MAX (0x7fff)
#define INT32_MAX (0x7fffffff)
#define INT64_MAX (0x7fffffffffffffff)
#define UINT8_MAX (0xff)
#define UINT16_MAX (0xffff)
#define UINT32_MAX (0xffffffffu)
#define UINT64_MAX (0xffffffffffffffffu)
#define INT_FAST8_MIN INT8_MIN
#define INT_FAST64_MIN INT64_MIN
#define INT_LEAST8_MIN INT8_MIN
#define INT_LEAST16_MIN INT16_MIN
#define INT_LEAST32_MIN INT32_MIN
#define INT_LEAST64_MIN INT64_MIN
#define INT_FAST8_MAX INT8_MAX
#define INT_FAST64_MAX INT64_MAX
#define INT_LEAST8_MAX INT8_MAX
#define INT_LEAST16_MAX INT16_MAX
#define INT_LEAST32_MAX INT32_MAX
#define INT_LEAST64_MAX INT64_MAX
#define UINT_FAST8_MAX UINT8_MAX
#define UINT_FAST64_MAX UINT64_MAX
#define UINT_LEAST8_MAX UINT8_MAX
#define UINT_LEAST16_MAX UINT16_MAX
#define UINT_LEAST32_MAX UINT32_MAX
#define UINT_LEAST64_MAX UINT64_MAX
#define INTMAX_MIN INT64_MIN
#define INTMAX_MAX INT64_MAX
#define UINTMAX_MAX UINT64_MAX
#define WINT_MIN 0U
#define WINT_MAX UINT32_MAX
#if L'\0'-1 > 0
#define WCHAR_MAX (0xffffffffu+L'\0')
#define WCHAR_MIN (0+L'\0')
#else
#define WCHAR_MAX (0x7fffffff+L'\0')
#define WCHAR_MIN (-1-0x7fffffff+L'\0')
#endif
#define SIG_ATOMIC_MIN INT32_MIN
#define SIG_ATOMIC_MAX INT32_MAX
#include <bits/stdint.h>
#define INT8_C(c) c
#define INT16_C(c) c
#define INT32_C(c) c
#define UINT8_C(c) c
#define UINT16_C(c) c
#define UINT32_C(c) c ## U
#if UINTPTR_MAX == UINT64_MAX
#define INT64_C(c) c ## L
#define UINT64_C(c) c ## UL
#define INTMAX_C(c) c ## L
#define UINTMAX_C(c) c ## UL
#else
#define INT64_C(c) c ## LL
#define UINT64_C(c) c ## ULL
#define INTMAX_C(c) c ## LL
#define UINTMAX_C(c) c ## ULL
#endif
#define NULL 0
#endif

View file

@ -0,0 +1,3 @@
#pragma once
int printf ( const char * format, ... );

View file

@ -0,0 +1,6 @@
#pragma once
#include "stdint.h"
void* malloc (size_t size);
void free (void* ptr);
void* realloc (void* ptr, size_t size);

View file

@ -0,0 +1,10 @@
#pragma once
#include "stdint.h"
void * memcpy ( void * destination, const void * source, size_t num );
void * memset ( void * ptr, int value, size_t num );
void * memmove ( void * destination, const void * source, size_t num );
char * strncpy ( char * destination, const char * source, size_t num );
void * memchr ( const void *, int, size_t );
size_t strlen ( const char * str );
void * memset ( void * ptr, int value, size_t num );

View file

@ -0,0 +1,19 @@
#pragma once
#include "stdint.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef int64_t time_t;
typedef int32_t suseconds_t;
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
int gettimeofday(struct timeval *tv, void *tz);
#ifdef __cplusplus
}
#endif

View file

@ -0,0 +1,44 @@
use std::alloc;
use std::alloc::Layout;
use std::os::raw::c_void;
const ALIGN: usize = 8;
#[no_mangle]
pub unsafe extern "C" fn malloc(size: usize) -> *mut c_void {
let new_size = size + 8;
let ptr = alloc::alloc(Layout::from_size_align_unchecked(new_size, ALIGN)) as *mut c_void;
(ptr as *mut usize).write(new_size);
ptr.add(8)
}
#[no_mangle]
pub unsafe extern "C" fn free(p: *mut c_void) {
let ptr = p.sub(8);
let size = (ptr as *mut usize).read();
alloc::dealloc(
ptr as *mut u8,
Layout::from_size_align_unchecked(size, ALIGN),
)
}
#[no_mangle]
pub unsafe extern "C" fn realloc(p: *mut c_void, new_size: usize) -> *mut c_void {
if p.is_null() {
malloc(new_size)
} else {
let ptr = p.sub(8);
let old_size = (ptr as *mut usize).read();
let new_ptr = alloc::realloc(
ptr as *mut u8,
Layout::from_size_align_unchecked(old_size, ALIGN),
new_size + 8,
);
if new_ptr.is_null() {
new_ptr as *mut c_void
} else {
(ptr as *mut usize).write(new_size + 8);
new_ptr.add(8) as *mut c_void
}
}
}

View file

@ -0,0 +1,160 @@
#![allow(non_camel_case_types)]
#![allow(dead_code)]
use std::os::raw::c_int;
pub type libusb_hotplug_flag = c_int;
pub type libusb_hotplug_event = c_int;
pub type libusb_log_cb_mode = c_int;
// libusb_error
pub const LIBUSB_SUCCESS: c_int = 0;
pub const LIBUSB_ERROR_IO: c_int = -1;
pub const LIBUSB_ERROR_INVALID_PARAM: c_int = -2;
pub const LIBUSB_ERROR_ACCESS: c_int = -3;
pub const LIBUSB_ERROR_NO_DEVICE: c_int = -4;
pub const LIBUSB_ERROR_NOT_FOUND: c_int = -5;
pub const LIBUSB_ERROR_BUSY: c_int = -6;
pub const LIBUSB_ERROR_TIMEOUT: c_int = -7;
pub const LIBUSB_ERROR_OVERFLOW: c_int = -8;
pub const LIBUSB_ERROR_PIPE: c_int = -9;
pub const LIBUSB_ERROR_INTERRUPTED: c_int = -10;
pub const LIBUSB_ERROR_NO_MEM: c_int = -11;
pub const LIBUSB_ERROR_NOT_SUPPORTED: c_int = -12;
pub const LIBUSB_ERROR_OTHER: c_int = -99;
// libusb_transfer_status
pub const LIBUSB_TRANSFER_COMPLETED: c_int = 0;
pub const LIBUSB_TRANSFER_ERROR: c_int = 1;
pub const LIBUSB_TRANSFER_TIMED_OUT: c_int = 2;
pub const LIBUSB_TRANSFER_CANCELLED: c_int = 3;
pub const LIBUSB_TRANSFER_STALL: c_int = 4;
pub const LIBUSB_TRANSFER_NO_DEVICE: c_int = 5;
pub const LIBUSB_TRANSFER_OVERFLOW: c_int = 6;
pub const LIBUSB_TRANSFER_SHORT_NOT_OK: u8 = 1 << 0;
pub const LIBUSB_TRANSFER_FREE_BUFFER: u8 = 1 << 1;
pub const LIBUSB_TRANSFER_FREE_TRANSFER: u8 = 1 << 2;
pub const LIBUSB_TRANSFER_ADD_ZERO_PACKET: u8 = 1 << 3;
// libusb_capability
pub const LIBUSB_CAP_HAS_CAPABILITY: u32 = 0x0000;
pub const LIBUSB_CAP_HAS_HOTPLUG: u32 = 0x0001;
pub const LIBUSB_CAP_HAS_HID_ACCESS: u32 = 0x0100;
pub const LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER: u32 = 0x0101;
//// libusb_log_level
pub const LIBUSB_LOG_LEVEL_NONE: c_int = 0;
pub const LIBUSB_LOG_LEVEL_ERROR: c_int = 1;
pub const LIBUSB_LOG_LEVEL_WARNING: c_int = 2;
pub const LIBUSB_LOG_LEVEL_INFO: c_int = 3;
pub const LIBUSB_LOG_LEVEL_DEBUG: c_int = 4;
// libusb_class_code
pub const LIBUSB_CLASS_PER_INTERFACE: u8 = 0;
pub const LIBUSB_CLASS_AUDIO: u8 = 1;
pub const LIBUSB_CLASS_COMM: u8 = 2;
pub const LIBUSB_CLASS_HID: u8 = 3;
pub const LIBUSB_CLASS_PHYSICAL: u8 = 5;
pub const LIBUSB_CLASS_PRINTER: u8 = 7;
pub const LIBUSB_CLASS_IMAGE: u8 = 6;
pub const LIBUSB_CLASS_MASS_STORAGE: u8 = 8;
pub const LIBUSB_CLASS_HUB: u8 = 9;
pub const LIBUSB_CLASS_DATA: u8 = 10;
pub const LIBUSB_CLASS_SMART_CARD: u8 = 0x0B;
pub const LIBUSB_CLASS_CONTENT_SECURITY: u8 = 0x0D;
pub const LIBUSB_CLASS_VIDEO: u8 = 0x0E;
pub const LIBUSB_CLASS_PERSONAL_HEALTHCARE: u8 = 0x0F;
pub const LIBUSB_CLASS_DIAGNOSTIC_DEVICE: u8 = 0xDC;
pub const LIBUSB_CLASS_WIRELESS: u8 = 0xE0;
pub const LIBUSB_CLASS_APPLICATION: u8 = 0xFE;
pub const LIBUSB_CLASS_VENDOR_SPEC: u8 = 0xFF;
// libusb_speed
pub const LIBUSB_SPEED_UNKNOWN: c_int = 0;
pub const LIBUSB_SPEED_LOW: c_int = 1;
pub const LIBUSB_SPEED_FULL: c_int = 2;
pub const LIBUSB_SPEED_HIGH: c_int = 3;
pub const LIBUSB_SPEED_SUPER: c_int = 4;
// libusb_descriptor_type
pub const LIBUSB_DT_DEVICE: u8 = 0x01;
pub const LIBUSB_DT_CONFIG: u8 = 0x02;
pub const LIBUSB_DT_STRING: u8 = 0x03;
pub const LIBUSB_DT_INTERFACE: u8 = 0x04;
pub const LIBUSB_DT_ENDPOINT: u8 = 0x05;
pub const LIBUSB_DT_BOS: u8 = 0x0F;
pub const LIBUSB_DT_DEVICE_CAPABILITY: u8 = 0x10;
pub const LIBUSB_DT_HID: u8 = 0x21;
pub const LIBUSB_DT_REPORT: u8 = 0x22;
pub const LIBUSB_DT_PHYSICAL: u8 = 0x23;
pub const LIBUSB_DT_HUB: u8 = 0x29;
pub const LIBUSB_DT_SUPERSPEED_HUB: u8 = 0x2A;
pub const LIBUSB_DT_SS_ENDPOINT_COMPANION: u8 = 0x30;
// libusb_endpoint_direction
pub const LIBUSB_ENDPOINT_ADDRESS_MASK: u8 = 0x0F;
pub const LIBUSB_ENDPOINT_DIR_MASK: u8 = 0x80;
pub const LIBUSB_ENDPOINT_IN: u8 = 0x80;
pub const LIBUSB_ENDPOINT_OUT: u8 = 0x00;
// libusb_transfer_type
pub const LIBUSB_TRANSFER_TYPE_MASK: u8 = 0x03;
pub const LIBUSB_TRANSFER_TYPE_CONTROL: u8 = 0;
pub const LIBUSB_TRANSFER_TYPE_ISOCHRONOUS: u8 = 1;
pub const LIBUSB_TRANSFER_TYPE_BULK: u8 = 2;
pub const LIBUSB_TRANSFER_TYPE_INTERRUPT: u8 = 3;
pub const LIBUSB_TRANSFER_TYPE_BULK_STREAM: u8 = 4;
// libusb_iso_sync_type
pub const LIBUSB_ISO_SYNC_TYPE_MASK: u8 = 0x0C;
pub const LIBUSB_ISO_SYNC_TYPE_NONE: u8 = 0;
pub const LIBUSB_ISO_SYNC_TYPE_ASYNC: u8 = 1;
pub const LIBUSB_ISO_SYNC_TYPE_ADAPTIVE: u8 = 2;
pub const LIBUSB_ISO_SYNC_TYPE_SYNC: u8 = 3;
// libusb_iso_usage_type
pub const LIBUSB_ISO_USAGE_TYPE_MASK: u8 = 0x30;
pub const LIBUSB_ISO_USAGE_TYPE_DATA: u8 = 0;
pub const LIBUSB_ISO_USAGE_TYPE_FEEDBACK: u8 = 1;
pub const LIBUSB_ISO_USAGE_TYPE_IMPLICIT: u8 = 2;
// libusb_request_type
pub const LIBUSB_REQUEST_TYPE_STANDARD: u8 = 0x00 << 5;
pub const LIBUSB_REQUEST_TYPE_CLASS: u8 = 0x01 << 5;
pub const LIBUSB_REQUEST_TYPE_VENDOR: u8 = 0x02 << 5;
pub const LIBUSB_REQUEST_TYPE_RESERVED: u8 = 0x03 << 5;
// libusb_request_recipient
pub const LIBUSB_RECIPIENT_DEVICE: u8 = 0x00;
pub const LIBUSB_RECIPIENT_INTERFACE: u8 = 0x01;
pub const LIBUSB_RECIPIENT_ENDPOINT: u8 = 0x02;
pub const LIBUSB_RECIPIENT_OTHER: u8 = 0x03;
// libusb_standard_request
pub const LIBUSB_REQUEST_GET_STATUS: u8 = 0x00;
pub const LIBUSB_REQUEST_CLEAR_FEATURE: u8 = 0x01;
pub const LIBUSB_REQUEST_SET_FEATURE: u8 = 0x03;
pub const LIBUSB_REQUEST_SET_ADDRESS: u8 = 0x05;
pub const LIBUSB_REQUEST_GET_DESCRIPTOR: u8 = 0x06;
pub const LIBUSB_REQUEST_SET_DESCRIPTOR: u8 = 0x07;
pub const LIBUSB_REQUEST_GET_CONFIGURATION: u8 = 0x08;
pub const LIBUSB_REQUEST_SET_CONFIGURATION: u8 = 0x09;
pub const LIBUSB_REQUEST_GET_INTERFACE: u8 = 0x0A;
pub const LIBUSB_REQUEST_SET_INTERFACE: u8 = 0x0B;
pub const LIBUSB_REQUEST_SYNCH_FRAME: u8 = 0x0C;
pub const LIBUSB_REQUEST_SET_SEL: u8 = 0x30;
pub const LIBUSB_SET_ISOCH_DELAY: u8 = 0x31;
// libusb_hotplug
pub const LIBUSB_HOTPLUG_NO_FLAGS: libusb_hotplug_flag = 0;
pub const LIBUSB_HOTPLUG_ENUMERATE: libusb_hotplug_flag = 1 << 0;
pub const LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED: libusb_hotplug_event = 0x01;
pub const LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT: libusb_hotplug_event = 0x02;
pub const LIBUSB_HOTPLUG_MATCH_ANY: c_int = -1;
pub const LIBUSB_OPTION_LOG_LEVEL: u32 = 0x00;
pub const LIBUSB_OPTION_USE_USBDK: u32 = 0x01;
// libusb_log_cb_mode
pub const LIBUSB_LOG_CB_GLOBAL: libusb_log_cb_mode = 1 << 0;
pub const LIBUSB_LOG_CB_CONTEXT: libusb_log_cb_mode = 1 << 1;

View file

@ -0,0 +1,407 @@
#![feature(c_variadic)]
#![allow(non_camel_case_types)]
#![allow(improper_ctypes)]
use std::cell::RefCell;
use std::os::raw::{c_int, c_uint, c_void};
use std::ptr::null_mut;
use std::{mem, slice};
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use web_sys::DedicatedWorkerGlobalScope;
use crate::constants::*;
use crate::msgs::call;
use js_sys::Int32Array;
mod alloc;
pub mod constants;
mod misc;
mod msgs;
mod structs;
pub use libc::*;
pub use misc::*;
pub use structs::*;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
pub fn log(s: &str);
}
#[macro_export]
macro_rules! println {
() => (
$crate::log()
);
($($arg:tt)*) => (
$crate::log(&format!($($arg)*))
)
}
#[macro_export]
macro_rules! dbg {
() => {
$crate::println!("[{}:{}]", file!(), line!());
};
($val:expr) => {
// Use of `match` here is intentional because it affects the lifetimes
// of temporaries - https://stackoverflow.com/a/48732525/1063961
match $val {
tmp => {
$crate::println!("[{}:{}] {} = {:#?}",
file!(), line!(), stringify!($val), &tmp);
tmp
}
}
};
// Trailing comma with single argument is ignored
($val:expr,) => { dbg!($val) };
($($val:expr),+ $(,)?) => {
($($crate::dbg!($val)),+,)
};
}
thread_local! {
static REPLY_BUF: RefCell<Vec<u8>> = RefCell::new(vec![0; 10000]);
}
fn global() -> DedicatedWorkerGlobalScope {
js_sys::global().unchecked_into()
}
pub struct libusb_context {}
pub struct libusb_device_handle {
device: *mut libusb_device,
}
impl libusb_device_handle {
unsafe fn new(device: *mut libusb_device) -> *mut libusb_device_handle {
libusb_ref_device(device);
Box::into_raw(Box::new(libusb_device_handle { device }))
}
}
pub struct libusb_device {
id: u32,
usb_id: (u16, u16),
comm: Int32Array,
refs: usize,
}
pub fn init(id: u32, usb_id: (u16, u16), comm: Int32Array) -> *mut libusb_device_handle {
let device = Box::into_raw(Box::new(libusb_device {
id,
usb_id,
comm,
refs: 0,
}));
unsafe { libusb_device_handle::new(device) }
}
#[no_mangle]
pub unsafe extern "C" fn libusb_init(context: *mut *mut libusb_context) -> c_int {
*context = Box::into_raw(Box::new(libusb_context {}));
LIBUSB_SUCCESS
}
#[no_mangle]
pub unsafe extern "C" fn libusb_exit(context: *mut libusb_context) {
Box::from_raw(context);
}
#[no_mangle]
pub unsafe extern "C" fn libusb_close(dev_handle: *mut crate::libusb_device_handle) {
libusb_unref_device((*dev_handle).device);
Box::from_raw(dev_handle);
}
#[no_mangle]
pub unsafe extern "C" fn libusb_get_device_descriptor(
dev: *const libusb_device,
desc: *mut libusb_device_descriptor,
) -> c_int {
*desc = libusb_device_descriptor {
idVendor: (*dev).usb_id.0,
idProduct: (*dev).usb_id.1,
..Default::default()
};
LIBUSB_SUCCESS
}
#[no_mangle]
pub unsafe extern "C" fn libusb_ref_device(dev: *mut libusb_device) -> *mut libusb_device {
(*dev).refs += 1;
dev
}
#[no_mangle]
pub unsafe extern "C" fn libusb_unref_device(dev: *mut libusb_device) {
(*dev).refs -= 1;
if (*dev).refs == 0 {
Box::from_raw(dev);
}
}
#[no_mangle]
pub unsafe extern "C" fn libusb_get_device(
dev_handle: *mut libusb_device_handle,
) -> *mut libusb_device {
(*dev_handle).device
}
#[no_mangle]
pub unsafe extern "C" fn libusb_bulk_transfer(
handle: *mut libusb_device_handle,
endpoint: u8,
data: *mut u8,
length: c_int,
transferred: *mut c_int,
timeout: c_uint,
) -> c_int {
let device = (*(*handle).device).id;
if endpoint & LIBUSB_ENDPOINT_DIR_MASK == LIBUSB_ENDPOINT_OUT {
match REPLY_BUF.with(|buf| {
let mut buf = buf.borrow_mut();
call(
&(*(*handle).device).comm,
msgs::BulkTransferOut {
device,
endpoint,
data: slice::from_raw_parts(data, length as usize),
},
&mut buf,
)
}) {
Ok(reply) => match reply.0 {
Ok(size) => {
*transferred = size as c_int;
LIBUSB_SUCCESS
}
Err(e) => e.into(),
},
Err(_) => LIBUSB_ERROR_OTHER,
}
} else {
REPLY_BUF.with(|buf| {
let mut buf = buf.borrow_mut();
match call(
&(*(*handle).device).comm,
msgs::BulkTransferIn {
device,
endpoint,
length: length as usize,
},
&mut buf,
) {
Ok(reply) => match reply.0 {
Ok(buf) => {
slice::from_raw_parts_mut(data, (buf.0).len().min(length as usize))
.copy_from_slice(buf.0);
LIBUSB_SUCCESS
}
Err(e) => e.into(),
},
Err(_) => LIBUSB_ERROR_OTHER,
}
})
}
}
#[no_mangle]
pub unsafe extern "C" fn libusb_set_configuration(
handle: *mut libusb_device_handle,
config: c_int,
) -> c_int {
let device = (*(*handle).device).id;
match REPLY_BUF.with(|buf| {
let mut buf = buf.borrow_mut();
call(
&(*(*handle).device).comm,
msgs::SelectConfiguration {
device,
config: config as u8,
},
&mut buf,
)
}) {
Ok(reply) => match reply.0 {
Ok(()) => LIBUSB_SUCCESS,
Err(e) => e.into(),
},
Err(_) => LIBUSB_ERROR_OTHER,
}
}
#[no_mangle]
pub unsafe extern "C" fn libusb_claim_interface(
handle: *mut libusb_device_handle,
interface_number: c_int,
) -> c_int {
let device = (*(*handle).device).id;
match REPLY_BUF.with(|buf| {
let mut buf = buf.borrow_mut();
call(
&(*(*handle).device).comm,
msgs::ClaimInterface {
device,
number: interface_number as u8,
},
&mut buf,
)
}) {
Ok(reply) => match reply.0 {
Ok(()) => LIBUSB_SUCCESS,
Err(e) => e.into(),
},
Err(_) => LIBUSB_ERROR_OTHER,
}
}
#[no_mangle]
pub unsafe extern "C" fn libusb_release_interface(
handle: *mut libusb_device_handle,
interface_number: c_int,
) -> c_int {
let device = (*(*handle).device).id;
match REPLY_BUF.with(|buf| {
let mut buf = buf.borrow_mut();
call(
&(*(*handle).device).comm,
msgs::ReleaseInterface {
device,
number: interface_number as u8,
},
&mut buf,
)
}) {
Ok(reply) => match reply.0 {
Ok(()) => LIBUSB_SUCCESS,
Err(e) => e.into(),
},
Err(_) => LIBUSB_ERROR_OTHER,
}
}
#[no_mangle]
pub unsafe extern "C" fn libusb_reset_device(handle: *mut libusb_device_handle) -> c_int {
let device = (*(*handle).device).id;
match REPLY_BUF.with(|buf| {
let mut buf = buf.borrow_mut();
call(
&(*(*handle).device).comm,
msgs::ResetDevice { device },
&mut buf,
)
}) {
Ok(reply) => match reply.0 {
Ok(()) => LIBUSB_SUCCESS,
Err(e) => e.into(),
},
Err(_) => LIBUSB_ERROR_OTHER,
}
}
#[no_mangle]
pub unsafe extern "C" fn libusb_get_active_config_descriptor(
handle: *const libusb_device,
config_ptr: *mut *const libusb_config_descriptor,
) -> c_int {
let device = (*handle).id;
match REPLY_BUF.with(|buf| {
let mut buf = buf.borrow_mut();
call(
&(*handle).comm,
msgs::ActiveConfigDescriptor { device },
&mut buf,
)
}) {
Ok(reply) => match reply.0 {
Ok(msg) => {
let mut config: Box<libusb_config_descriptor> = Box::new(mem::zeroed());
config.bConfigurationValue = msg.configuration_value;
let interfaces: Vec<_> = msg
.interfaces
.into_iter()
.map(|interface| {
let settings: Vec<_> = interface
.into_iter()
.map(|setting| {
let endpoints: Vec<_> = setting
.endpoints
.into_iter()
.map(|endpoint| libusb_endpoint_descriptor {
bLength: 0,
bDescriptorType: 0,
bEndpointAddress: endpoint.address,
bmAttributes: 0,
wMaxPacketSize: endpoint.packet_size,
bInterval: 0,
bRefresh: 0,
bSynchAddress: 0,
extra: null_mut(),
extra_length: 0,
})
.collect();
let endpoints = Box::into_raw(endpoints.into_boxed_slice());
libusb_interface_descriptor {
bLength: 0,
bDescriptorType: 0,
bInterfaceNumber: 0,
bAlternateSetting: setting.alternate_setting,
bNumEndpoints: (*endpoints).len() as u8,
bInterfaceClass: setting.interface_class,
bInterfaceSubClass: setting.interface_subclass,
bInterfaceProtocol: setting.interface_protocol,
iInterface: 0,
endpoint: (*endpoints).as_ptr(),
extra: null_mut(),
extra_length: 0,
}
})
.collect();
let settings = Box::into_raw(settings.into_boxed_slice());
libusb_interface {
altsetting: (*settings).as_ptr(),
num_altsetting: (*settings).len() as c_int,
}
})
.collect();
let interfaces = Box::into_raw(interfaces.into_boxed_slice());
config.interface = (*interfaces).as_ptr();
config.bNumInterfaces = (*interfaces).len() as u8;
*config_ptr = Box::into_raw(config);
LIBUSB_SUCCESS
}
Err(e) => e.into(),
},
Err(_) => LIBUSB_ERROR_OTHER,
}
}
#[no_mangle]
pub unsafe extern "C" fn libusb_free_config_descriptor(
config_ptr: *const libusb_config_descriptor,
) {
let config: Box<libusb_config_descriptor> = Box::from_raw(config_ptr as *mut _);
let interfaces = Box::from_raw(&mut slice::from_raw_parts(
config.interface,
config.bNumInterfaces as usize,
));
for interface in interfaces.iter() {
let settings = Box::from_raw(&mut slice::from_raw_parts(
interface.altsetting,
interface.num_altsetting as usize,
));
for setting in settings.iter() {
Box::from_raw(&mut slice::from_raw_parts(
setting.endpoint,
setting.bNumEndpoints as usize,
));
}
}
}

View file

@ -0,0 +1,201 @@
use std::os::raw::{c_char, c_int, c_uchar, c_uint, c_void};
use std::ptr::null_mut;
pub type libusb_hotplug_callback_handle = c_int;
pub type libusb_hotplug_callback_fn = extern "system" fn(
ctx: *mut crate::libusb_context,
device: *mut crate::libusb_device,
event: crate::libusb_hotplug_event,
user_data: *mut c_void,
) -> c_int;
#[repr(C)]
pub struct libusb_version {
pub major: u16,
pub minor: u16,
pub micro: u16,
pub nano: u16,
pub rc: *const c_char,
pub describe: *const c_char,
}
unsafe impl Send for libusb_version {}
unsafe impl Sync for libusb_version {}
#[no_mangle]
pub unsafe extern "C" fn libusb_get_version() -> *const libusb_version {
static LIBUSB_VERSION: libusb_version = libusb_version {
major: 0,
minor: 0,
micro: 0,
nano: 0,
rc: b"\0".as_ptr() as _,
describe: b"\0".as_ptr() as _,
};
&LIBUSB_VERSION
}
#[no_mangle]
pub unsafe extern "C" fn libusb_has_capability(capability: u32) -> c_int {
match capability {
crate::constants::LIBUSB_CAP_HAS_CAPABILITY => 1,
_ => 0,
}
}
extern "C" {
pub fn libusb_set_option(ctx: *mut crate::libusb_context, option: u32, ...) -> c_int;
pub fn libusb_open(
dev: *const crate::libusb_device,
handle: *mut *mut crate::libusb_device_handle,
) -> c_int;
pub fn libusb_open_device_with_vid_pid(
context: *mut crate::libusb_context,
vendor_id: u16,
product_id: u16,
) -> *mut crate::libusb_device_handle;
pub fn libusb_set_debug(context: *mut crate::libusb_context, level: c_int);
pub fn libusb_hotplug_register_callback(
ctx: *mut crate::libusb_context,
events: crate::libusb_hotplug_event,
flags: crate::libusb_hotplug_flag,
vendor_id: c_int,
product_id: c_int,
dev_class: c_int,
cb_fn: libusb_hotplug_callback_fn,
user_data: *mut crate::c_void,
callback_handle: *mut libusb_hotplug_callback_handle,
) -> c_int;
pub fn libusb_hotplug_deregister_callback(
ctx: *mut crate::libusb_context,
callback_handle: libusb_hotplug_callback_handle,
);
pub fn libusb_handle_events_timeout_completed(
context: *mut crate::libusb_context,
tv: *const libc::timeval,
completed: *mut c_int,
) -> c_int;
pub fn libusb_handle_events_completed(
context: *mut crate::libusb_context,
completed: *mut c_int,
) -> c_int;
pub fn libusb_get_device_descriptor(
dev: *const crate::libusb_device,
desc: *mut crate::libusb_device_descriptor,
) -> c_int;
pub fn libusb_get_config_descriptor(
dev: *const crate::libusb_device,
index: u8,
config: *mut *const crate::libusb_config_descriptor,
) -> c_int;
pub fn libusb_get_bus_number(dev: *const crate::libusb_device) -> u8;
pub fn libusb_get_port_number(dev: *mut crate::libusb_device) -> u8;
pub fn libusb_get_port_numbers(
dev: *mut crate::libusb_device,
port_numbers: *mut u8,
port_numbers_len: c_int,
) -> c_int;
pub fn libusb_get_device_address(dev: *const crate::libusb_device) -> u8;
pub fn libusb_get_device_speed(dev: *const crate::libusb_device) -> c_int;
pub fn libusb_get_max_packet_size(dev: *const crate::libusb_device, endpoint: c_uchar)
-> c_int;
pub fn libusb_get_max_iso_packet_size(
dev: *const crate::libusb_device,
endpoint: c_uchar,
) -> c_int;
pub fn libusb_get_configuration(
dev_handle: *mut crate::libusb_device_handle,
config: *mut c_int,
) -> c_int;
pub fn libusb_interrupt_transfer(
dev_handle: *mut crate::libusb_device_handle,
endpoint: c_uchar,
data: *mut c_uchar,
length: c_int,
transferred: *mut c_int,
timeout: c_uint,
) -> c_int;
pub fn libusb_control_transfer(
dev_handle: *mut crate::libusb_device_handle,
request_type: u8,
request: u8,
value: u16,
index: u16,
data: *mut c_uchar,
length: u16,
timeout: c_uint,
) -> c_int;
pub fn libusb_clear_halt(
dev_handle: *mut crate::libusb_device_handle,
endpoint: c_uchar,
) -> c_int;
pub fn libusb_set_auto_detach_kernel_driver(
dev_handle: *mut crate::libusb_device_handle,
enable: c_int,
) -> c_int;
pub fn libusb_kernel_driver_active(
dev_handle: *mut crate::libusb_device_handle,
interface_number: c_int,
) -> c_int;
pub fn libusb_detach_kernel_driver(
dev_handle: *mut crate::libusb_device_handle,
interface_number: c_int,
) -> c_int;
pub fn libusb_attach_kernel_driver(
dev_handle: *mut crate::libusb_device_handle,
interface_number: c_int,
) -> c_int;
pub fn libusb_set_interface_alt_setting(
dev_handle: *mut crate::libusb_device_handle,
interface_number: c_int,
alternate_setting: c_int,
) -> c_int;
pub fn libusb_get_string_descriptor_ascii(
dev_handle: *mut crate::libusb_device_handle,
desc_index: u8,
data: *mut c_uchar,
length: c_int,
) -> c_int;
pub fn libusb_get_device_list(
context: *mut crate::libusb_context,
list: *mut *const *mut crate::libusb_device,
) -> isize;
pub fn libusb_free_device_list(list: *const *mut crate::libusb_device, unref_devices: c_int);
}
#[no_mangle]
pub unsafe extern "C" fn memchr(mut ptr: *const c_void, value: c_int, num: usize) -> *mut c_void {
for _ in 0..num {
if *(ptr as *const u8) == value as u8 {
return ptr as *mut c_void;
}
ptr = ptr.add(1);
}
null_mut()
}
#[no_mangle]
pub unsafe extern "C" fn strncpy(
mut dst: *mut c_char,
mut src: *const c_char,
n: usize,
) -> *mut c_char {
let mut i = 0;
while i < n && *src.add(i) != 0 {
*dst.add(i) = *src.add(i);
i += 1;
}
while i < n {
*dst.add(i) = 0;
i += 1;
}
dst
}
#[no_mangle]
pub unsafe extern "C" fn strlen(mut cs: *const c_char) -> usize {
let mut i = 0;
while *cs != 0 {
i += 1;
cs = cs.add(1);
}
i
}

View file

@ -0,0 +1,233 @@
use crate::global;
use js_sys::{Atomics, Int32Array, Uint8Array};
use serde::{Deserialize, Serialize};
use std::os::raw::c_int;
use wasm_bindgen::prelude::*;
use std::fmt::Debug;
use crate::dbg;
#[derive(Debug, Deserialize)]
pub enum Error {
NotFound,
Security,
Network,
Abort,
InvalidState,
InvalidAccess,
Unknown,
}
impl From<Error> for c_int {
fn from(_: Error) -> Self {
unimplemented!()
}
}
#[derive(Debug, Serialize)]
#[serde(tag = "usbCmd", rename_all = "camelCase")]
pub enum Cmd<'a> {
BulkTransferOut(BulkTransferOut<'a>),
BulkTransferIn(BulkTransferIn),
SelectConfiguration(SelectConfiguration),
ClaimInterface(ClaimInterface),
ReleaseInterface(ReleaseInterface),
ResetDevice(ResetDevice),
ActiveConfigDescriptor(ActiveConfigDescriptor),
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NullReply(pub Result<(), Error>);
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BulkTransferOut<'a> {
pub device: u32,
pub endpoint: u8,
#[serde(with = "serde_bytes")]
pub data: &'a [u8],
}
impl<'a> From<BulkTransferOut<'a>> for Cmd<'a> {
fn from(c: BulkTransferOut<'a>) -> Self {
Cmd::BulkTransferOut(c)
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BulkTransferOutReply(pub Result<usize, Error>);
impl<'reply, 'cmd> Message<'reply, 'cmd> for BulkTransferOut<'cmd> {
type Reply = BulkTransferOutReply;
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BulkTransferIn {
pub device: u32,
pub endpoint: u8,
pub length: usize,
}
impl<'a> From<BulkTransferIn> for Cmd<'a> {
fn from(c: BulkTransferIn) -> Self {
Cmd::BulkTransferIn(c)
}
}
#[derive(Debug, Deserialize)]
#[serde(bound(deserialize = "'de: 'a"))]
pub struct Data<'a>(#[serde(with = "serde_bytes")] pub &'a [u8]);
#[derive(Debug, Deserialize)]
#[serde(bound(deserialize = "'de: 'a"))]
#[serde(rename_all = "camelCase")]
pub struct BulkTransferInReply<'a>(pub Result<Data<'a>, Error>);
impl<'reply, 'cmd> Message<'reply, 'cmd> for BulkTransferIn {
type Reply = BulkTransferInReply<'reply>;
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SelectConfiguration {
pub device: u32,
pub config: u8,
}
impl<'a> From<SelectConfiguration> for Cmd<'a> {
fn from(c: SelectConfiguration) -> Self {
Cmd::SelectConfiguration(c)
}
}
impl<'reply, 'cmd> Message<'reply, 'cmd> for SelectConfiguration {
type Reply = NullReply;
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClaimInterface {
pub device: u32,
pub number: u8,
}
impl<'a> From<ClaimInterface> for Cmd<'a> {
fn from(c: ClaimInterface) -> Self {
Cmd::ClaimInterface(c)
}
}
impl<'reply, 'cmd> Message<'reply, 'cmd> for ClaimInterface {
type Reply = NullReply;
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReleaseInterface {
pub device: u32,
pub number: u8,
}
impl<'a> From<ReleaseInterface> for Cmd<'a> {
fn from(c: ReleaseInterface) -> Self {
Cmd::ReleaseInterface(c)
}
}
impl<'reply, 'cmd> Message<'reply, 'cmd> for ReleaseInterface {
type Reply = NullReply;
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResetDevice {
pub device: u32,
}
impl<'a> From<ResetDevice> for Cmd<'a> {
fn from(c: ResetDevice) -> Self {
Cmd::ResetDevice(c)
}
}
impl<'reply, 'cmd> Message<'reply, 'cmd> for ResetDevice {
type Reply = NullReply;
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ActiveConfigDescriptor {
pub device: u32,
}
impl<'a> From<ActiveConfigDescriptor> for Cmd<'a> {
fn from(c: ActiveConfigDescriptor) -> Self {
Cmd::ActiveConfigDescriptor(c)
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct USBEndpoint {
pub address: u8,
pub packet_size: u16,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct USBAlternateInterface {
pub alternate_setting: u8,
pub interface_class: u8,
pub interface_subclass: u8,
pub interface_protocol: u8,
pub endpoints: Vec<USBEndpoint>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct USBConfiguration {
pub configuration_value: u8,
pub interfaces: Vec<Vec<USBAlternateInterface>>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ActiveConfigDescriptorReply(pub Result<USBConfiguration, Error>);
impl<'reply, 'cmd> Message<'reply, 'cmd> for ActiveConfigDescriptor {
type Reply = ActiveConfigDescriptorReply;
}
pub trait Message<'reply, 'cmd>: Into<Cmd<'cmd>> + Serialize {
type Reply: Deserialize<'reply> + Debug;
}
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
}
pub fn call<'reply, 'cmd, T: Message<'reply, 'cmd>>(
arr: &Int32Array,
msg: T,
buf: &'reply mut [u8],
) -> Result<T::Reply, rmp_serde::decode::Error> {
let value = serde_wasm_bindgen::to_value(&Into::<Cmd>::into(msg)).unwrap();
let _ = global().post_message(&value);
let _ = Atomics::wait(arr, 0, 0);
let len = arr.get_index(0) as u32;
let _ = Atomics::store(arr, 0, 0);
let js_buf = Uint8Array::new(&arr.buffer()).subarray(4, 4 + len);
let buf = &mut buf[0..(js_buf.length() as usize)];
js_buf.copy_to(buf);
match rmp_serde::from_read_ref(&buf[..]) {
Ok(v) => Ok(v),
Err(e) => Err({
log(&format!("{}", e));
e
}),
}
}

View file

@ -0,0 +1,77 @@
#![allow(non_snake_case)]
use std::os::raw::{c_int, c_uchar};
#[repr(C)]
#[derive(Debug)]
pub struct libusb_config_descriptor {
pub bLength: u8,
pub bDescriptorType: u8,
pub wTotalLength: u16,
pub bNumInterfaces: u8,
pub bConfigurationValue: u8,
pub iConfiguration: u8,
pub bmAttributes: u8,
pub bMaxPower: u8,
pub interface: *const libusb_interface,
pub extra: *const c_uchar,
pub extra_length: c_int,
}
#[repr(C)]
#[derive(Debug)]
pub struct libusb_interface {
pub altsetting: *const libusb_interface_descriptor,
pub num_altsetting: c_int,
}
#[repr(C)]
#[derive(Debug)]
pub struct libusb_interface_descriptor {
pub bLength: u8,
pub bDescriptorType: u8,
pub bInterfaceNumber: u8,
pub bAlternateSetting: u8,
pub bNumEndpoints: u8,
pub bInterfaceClass: u8,
pub bInterfaceSubClass: u8,
pub bInterfaceProtocol: u8,
pub iInterface: u8,
pub endpoint: *const libusb_endpoint_descriptor,
pub extra: *const c_uchar,
pub extra_length: c_int,
}
#[repr(C)]
#[derive(Debug)]
pub struct libusb_endpoint_descriptor {
pub bLength: u8,
pub bDescriptorType: u8,
pub bEndpointAddress: u8,
pub bmAttributes: u8,
pub wMaxPacketSize: u16,
pub bInterval: u8,
pub bRefresh: u8,
pub bSynchAddress: u8,
pub extra: *const c_uchar,
pub extra_length: c_int,
}
#[repr(C)]
#[derive(Default, Debug)]
pub struct libusb_device_descriptor {
pub bLength: u8,
pub bDescriptorType: u8,
pub bcdUSB: u16,
pub bDeviceClass: u8,
pub bDeviceSubClass: u8,
pub bDeviceProtocol: u8,
pub bMaxPacketSize0: u8,
pub idVendor: u16,
pub idProduct: u16,
pub bcdDevice: u16,
pub iManufacturer: u8,
pub iProduct: u8,
pub iSerialNumber: u8,
pub bNumConfigurations: u8,
}