JairusSW / as-json

The only JSON library you'll need for AssemblyScript. SIMD enabled
MIT License
80 stars 16 forks source link

Support for default values #51

Closed casimiro closed 1 year ago

casimiro commented 1 year ago

Hello,

I noticed as-json doesn't support attributes with default values. Consider the following example:

import { Console } from "as-wasi/assembly";
import { JSON } from "json-as/assembly";

@json
class Config {
  c1: String = "d1";
  c2: String = "d2";
}

let s = '{"c1": "n1"}';
let p = JSON.parse<Config>(s);

Console.log(p.c1);  // prints `n1`  to standard output.
Console.log(p.c2);  // causes memory fault

Trying to access p.c2 will cause the following error:

Error: failed to run main module `build/debug.wasm`

Caused by:
    0: failed to instantiate "build/debug.wasm"
    1: error while executing at wasm backtrace:
           0:  0x20c - <unknown>!~lib/rt/common/OBJECT#get:rtSize
           1: 0x1269 - <unknown>!~lib/string/String.UTF8.byteLength
           2: 0x2317 - <unknown>!~lib/string/String.UTF8.encode
           3: 0x2390 - <unknown>!~lib/string/String.UTF8.encode@varargs
           4: 0x23ca - <unknown>!~lib/as-wasi/assembly/as-wasi/Descriptor#writeStringLn
           5: 0x245f - <unknown>!~lib/as-wasi/assembly/as-wasi/Descriptor#writeString
           6: 0x24fb - <unknown>!~lib/as-wasi/assembly/as-wasi/Console.write
           7: 0x2528 - <unknown>!~lib/as-wasi/assembly/as-wasi/Console.log
           8: 0x2b86 - <unknown>!start:assembly/index
           9: 0x169a - <unknown>!~start
    2: memory fault at wasm address 0xfffffffc in linear memory of size 0x10000
    3: wasm trap: out of bounds memory access

This error can only be observed when trying to access a default-valued attribute that hasn't been overwritten by JSON.parse; in the example above, p.c1 is successfully accessed and its value is printed to the standard output.

Being able to define default values is especially useful when dealing with user configuration as it allows merging default values with user provided ones quite seamlessly.

Finally, thank you for developing this library!

JairusSW commented 1 year ago

I'm working on pushing out a fix to this now

JairusSW commented 1 year ago

Implemented in the latest commit (https://github.com/JairusSW/as-json/commit/eb62149198c4b013d9ee1b7b17b5db19d8ff2b0f) Use JSON.parse<Vec3>("{}", true)

JairusSW commented 1 year ago

Let me know if this works fine for you Perhaps I can have it pass an actual config object through for more options in the future.