wasm\abi.mbt
0% · 0 / 153 points · 443 linesBackground color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.
- 1
///| - 2
/// # wasm(MVP)字节 ABI 导出层(S12) - 3
/// - 4
/// 为什么单独一层:wasm-gc 的字符串常量是 `(ref extern)` 全局导入,Node 侧无法提供 - 5
/// 非空 externref 全局,只能在 MoonBit 自己的 host 里实例化。wasm(MVP)没有这个问题: - 6
/// 线性内存可导出,`Bytes` 参数/返回值就是内存里的 i32 指针,JS 直接读写。 - 7
/// - 8
/// 约定: - 9
/// - 输入:先调 `abi_alloc(n)` 拿到指针,把原始字节写进导出内存的同地址; - 10
/// - 输出:函数返回 `Bytes`(= 指针),长度用 `abi_last_len()` 取,数据从同一地址读; - 11
/// - 元信息:`abi_last_ok/format/width/height/channels`; - 12
/// - 错误:`abi_last_ok()==0`,`abi_last_error()` 返回 UTF-8 的 `code\nmessage\nhint`。 - 13
/// - 14
/// 本文件只在 `--target wasm` 下编译,不影响其它目标。 - 15
#cfg(target="wasm") - 16
priv struct AbiState { - 17
mut ok : Int32 - 18
mut format : Int32 - 19
mut width : Int32 - 20
mut height : Int32 - 21
mut channels : Int32 - 22
mut len : Int32 - 23
mut error : String - 24
} - 25
- 26
///| - 27
#cfg(target="wasm") - 28
let state : AbiState = { - 29
ok: 0, - 30
format: 0, - 31
width: 0, - 32
height: 0, - 33
channels: 0, - 34
len: 0, - 35
error: "", - 36
} - 37
- 38
///| - 39
#cfg(target="wasm") - 40
fn empty_bytes() -> Bytes { - 41○
Bytes::make(0, b'\x00') - 42
} - 43
- 44
///| - 45
/// 指针保活表的容量。8 足够覆盖「一条链上最多同时存在几块缓冲」: - 46
/// 输入 1 块 + 若干中间输出(错误体、元信息体),再留几块给调用方自己 staging。 - 47
#cfg(target="wasm") - 48
const ABI_PIN_CAP : Int32 = 8 - 49
- 50
///| - 51
/// 指针保活表(F-07)。 - 52
/// - 53
/// 为什么需要:wasm(MVP)导出的 `Bytes` 只给 JS 一个线性内存地址,MoonBit 侧一旦 - 54
/// 没有活引用,GC 可以在任意点回收这块内存,地址随即悬垂。同步调用里踩不到这个坑 - 55
/// (`abi_alloc` 与 `abi_convert` 在同一个 tick 内),但两段式调用 - 56
/// (alloc → 写入 → 等一轮事件循环 → convert)必然踩到,S36 就是为这条路径补的。 - 57
/// - 58
/// 策略是环形保留最近 `ABI_PIN_CAP` 块:满了覆盖最老的一块,因此 - 59
/// 「能保证有效的窗口」= 最近 8 次分配,可用 `abi_pin_count()` 观测,不会无限涨。 - 60
#cfg(target="wasm") - 61
priv struct PinTable { - 62
items : Array[Bytes] - 63
mut next : Int32 - 64
} - 65
- 66
///| - 67
#cfg(target="wasm") - 68
let pin_table : PinTable = { items: [], next: 0, } - 69
- 70
///| - 71
#cfg(target="wasm") - 72
fn pin_keep(b : Bytes) -> Unit { - 73○
if pin_table.items.length() < ABI_PIN_CAP.to_int() { - 74○
pin_table.items.push(b) - 75
} else { - 76○
pin_table.items[pin_table.next.to_int()] = b - 77
pin_table.next = (pin_table.next + 1) % ABI_PIN_CAP - 78
} - 79
} - 80
- 81
///| - 82
/// 保活表当前持有几块(上限 `abi_pin_cap`)。给调用方/门禁一个可观测信号, - 83
/// 免得「有没有保活」只能靠读源码。 - 84
#cfg(target="wasm") - 85
#export_name("abi_pin_count") - 86
pub fn abi_pin_count() -> Int32 { - 87○
pin_table.items.length().to_int() - 88
} - 89
- 90
///| - 91
#cfg(target="wasm") - 92
#export_name("abi_pin_cap") - 93
pub fn abi_pin_cap() -> Int32 { - 94○
ABI_PIN_CAP - 95
} - 96
- 97
///| - 98
/// 显式清空保活表。清空后**先前拿到的地址立即失效**——只在调用方确认 - 99
/// 手上一块都不再用时调用(例如一次批处理收尾)。 - 100
#cfg(target="wasm") - 101
#export_name("abi_pin_clear") - 102
pub fn abi_pin_clear() -> Unit { - 103○
pin_table.items.clear() - 104
pin_table.next = 0 - 105
} - 106
- 107
///| - 108
/// 两段式调用的显式句柄表 —— F-07 的正解。 - 109
/// - 110
/// `abi_alloc` 的保活窗口只有最近 8 块(环形覆盖),够覆盖一条同步链, - 111
/// 但挡不住「拿缓冲 → 去渲染/发网络 → 回来再写」这类跨业务的等待: - 112
/// 中间插进来的分配会把这个窗口里的旧块挤出去。 - 113
/// - 114
/// 句柄表换一种交换方式:`abi_stage(n)` 返回**句柄**(不是地址), - 115
/// `abi_stage_ptr(h)` 把句柄换成当前地址,`abi_stage_release(h)` 显式释放。 - 116
/// 表不设上限、也不自动淘汰,代价写在契约里:**不 release 就一直占着内存**, - 117
/// 与 malloc/free 同责,但不会悄悄失效。 - 118
#cfg(target="wasm") - 119
priv struct StageTable { - 120
items : Array[Bytes?] - 121
} - 122
- 123
///| - 124
#cfg(target="wasm") - 125
let stage_table : StageTable = { items: [], } - 126
- 127
///| - 128
/// 单块上限 512 MiB:超过直接回 -1,避免一个手误的句柄把线性内存撑爆。 - 129
#cfg(target="wasm") - 130
const ABI_STAGE_MAX : Int32 = 536870912 - 131
- 132
///| - 133
#cfg(target="wasm") - 134
#export_name("abi_stage") - 135
pub fn abi_stage(n : Int32) -> Int32 { - 136○
if n <= 0 || n > ABI_STAGE_MAX { - 137○
return -1 - 138
} - 139○
let b = Bytes::make(n, b'\x00') - 140○
stage_table.items.push(Some(b)) - 141○
stage_table.items.length().to_int() - 1 - 142
} - 143
- 144
///| - 145
#cfg(target="wasm") - 146
#export_name("abi_stage_ptr") - 147
pub fn abi_stage_ptr(h : Int32) -> Bytes { - 148○
let idx = h.to_int() - 149○
if idx < 0 || idx >= stage_table.items.length() { - 150○
return empty_bytes() - 151
} - 152○
match stage_table.items[idx] { - 153○
Some(b) => b - 154○
None => empty_bytes() - 155
} - 156
} - 157
- 158
///| - 159
#cfg(target="wasm") - 160
#export_name("abi_stage_release") - 161
pub fn abi_stage_release(h : Int32) -> Unit { - 162○
let idx = h.to_int() - 163○
if idx >= 0 && idx < stage_table.items.length() { - 164○
stage_table.items[idx] = None - 165
} - 166
} - 167
- 168
///| - 169
/// 当前仍未释放的句柄数。给调用方/门禁一个可观测信号: - 170
/// 「我是不是忘了 release」这件事不该只能靠猜。 - 171
#cfg(target="wasm") - 172
#export_name("abi_stage_live") - 173
pub fn abi_stage_live() -> Int32 { - 174○
let mut n = 0 - 175
for it in stage_table.items { - 176○
if it is Some(_) { - 177○
n = n + 1 - 178
} - 179
} - 180
(n : Int32) - 181
} - 182
- 183
///| - 184
#cfg(target="wasm") - 185
fn format_code(f : @types.ImageFormat) -> Int32 { - 186○
match f { - 187○
@types.ImageFormat::Png => 1 - 188○
@types.ImageFormat::Jpeg => 2 - 189○
@types.ImageFormat::Webp => 3 - 190○
@types.ImageFormat::Gif => 4 - 191○
@types.ImageFormat::Bmp => 5 - 192○
@types.ImageFormat::Qoi => 6 - 193○
@types.ImageFormat::Pnm => 7 - 194○
@types.ImageFormat::Tga => 8 - 195○
_ => 0 - 196
} - 197
} - 198
- 199
///| - 200
#cfg(target="wasm") - 201
fn format_of_code(code : Int32) -> @types.ImageFormat raise @types.ImageError { - 202○
match code { - 203○
1 => @types.ImageFormat::Png - 204○
2 => @types.ImageFormat::Jpeg - 205○
3 => @types.ImageFormat::Webp - 206○
4 => @types.ImageFormat::Gif - 207○
5 => @types.ImageFormat::Bmp - 208○
6 => @types.ImageFormat::Qoi - 209○
7 => @types.ImageFormat::Pnm - 210○
8 => @types.ImageFormat::Tga - 211○
9 => @types.ImageFormat::Unknown // 占位,best 走单独分支 - 212
_ => - 213○
raise @types.ImageError::Process( - 214
@types.ErrorCode::InvalidArgument, - 215
"未知格式码: \{code}(可用 1=png 2=jpeg 3=webp 4=gif 5=bmp 6=qoi 7=pnm 8=tga 9=best)", - 216
) - 217
} - 218
} - 219
- 220
///| - 221
#cfg(target="wasm") - 222
fn set_ok(img : @types.Image, fmt : @types.ImageFormat, size : Int32) -> Unit { - 223○
state.ok = 1 - 224○
state.format = format_code(fmt) - 225○
state.width = img.width.to_int() - 226○
state.height = img.height.to_int() - 227○
state.channels = img.channels.to_int() - 228
state.len = size - 229
state.error = "" - 230
} - 231
- 232
///| - 233
#cfg(target="wasm") - 234
fn set_err(e : @types.ImageError) -> Bytes { - 235○
state.ok = 0 - 236
state.format = 0 - 237
state.width = 0 - 238
state.height = 0 - 239
state.channels = 0 - 240
state.len = 0 - 241○
let code = e.code() - 242
state.error = "\{code}\n\{e.message()}\n\{@types.image_error_hint(code)}" - 243○
empty_bytes() - 244
} - 245
- 246
///| - 247
#cfg(target="wasm") - 248
fn encode_payload( - 249
img : @types.Image, - 250
code : Int32, - 251
quality : Int32, - 252
) -> @lib.EncodedImage raise @types.ImageError { - 253○
if code == 9 { - 254○
@lib.encode_best(img, quality) - 255
} else { - 256○
let fmt = format_of_code(code) - 257○
let data = @lib.save_image_with_quality(img, fmt, quality) catch { - 258○
e => raise @types.image_error_from_load(e) - 259
} - 260
{ format: fmt, bytes: data, } - 261
} - 262
} - 263
- 264
///| - 265
/// 分配 `n` 字节的输入缓冲,返回其指针(JS 直接往导出内存写)。 - 266
#cfg(target="wasm") - 267
#export_name("abi_alloc") - 268
pub fn abi_alloc(n : Int32) -> Bytes { - 269○
if n <= 0 { - 270○
return empty_bytes() - 271
} - 272○
let b = Bytes::make(n, b'\x00') - 273
// 关键:这块内存必须由 MoonBit 侧持有,否则两段式调用里 JS 写的是野地址。 - 274○
pin_keep(b) - 275
b - 276
} - 277
- 278
///| - 279
#cfg(target="wasm") - 280
#export_name("abi_last_len") - 281
pub fn abi_last_len() -> Int32 { - 282○
state.len - 283
} - 284
- 285
///| - 286
#cfg(target="wasm") - 287
#export_name("abi_last_ok") - 288
pub fn abi_last_ok() -> Int32 { - 289○
state.ok - 290
} - 291
- 292
///| - 293
#cfg(target="wasm") - 294
#export_name("abi_last_format") - 295
pub fn abi_last_format() -> Int32 { - 296○
state.format - 297
} - 298
- 299
///| - 300
#cfg(target="wasm") - 301
#export_name("abi_last_width") - 302
pub fn abi_last_width() -> Int32 { - 303○
state.width - 304
} - 305
- 306
///| - 307
#cfg(target="wasm") - 308
#export_name("abi_last_height") - 309
pub fn abi_last_height() -> Int32 { - 310○
state.height - 311
} - 312
- 313
///| - 314
#cfg(target="wasm") - 315
#export_name("abi_last_channels") - 316
pub fn abi_last_channels() -> Int32 { - 317○
state.channels - 318
} - 319
- 320
///| - 321
#cfg(target="wasm") - 322
fn utf8_bytes(s : String) -> Bytes { - 323○
let out : Array[Byte] = [] - 324
for c in s { - 325○
let cp = c.to_int() - 326
if cp < 0x80 { - 327○
out.push(cp.to_byte()) - 328○
} else if cp < 0x800 { - 329○
out.push((0xC0 | (cp >> 6)).to_byte()) - 330○
out.push((0x80 | (cp & 0x3F)).to_byte()) - 331○
} else if cp < 0x10000 { - 332○
out.push((0xE0 | (cp >> 12)).to_byte()) - 333○
out.push((0x80 | ((cp >> 6) & 0x3F)).to_byte()) - 334○
out.push((0x80 | (cp & 0x3F)).to_byte()) - 335
} else { - 336○
out.push((0xF0 | (cp >> 18)).to_byte()) - 337○
out.push((0x80 | ((cp >> 12) & 0x3F)).to_byte()) - 338○
out.push((0x80 | ((cp >> 6) & 0x3F)).to_byte()) - 339○
out.push((0x80 | (cp & 0x3F)).to_byte()) - 340
} - 341
} - 342○
Bytes::from_array(out) - 343
} - 344
- 345
///| - 346
#cfg(target="wasm") - 347
#export_name("abi_last_error") - 348
pub fn abi_last_error() -> Bytes { - 349○
let b = utf8_bytes(state.error) - 350○
state.len = b.length() - 351○
pin_keep(b) - 352
b - 353
} - 354
- 355
///| - 356
/// 格式/尺寸/体积探测。输入为 `abi_alloc` 分配并写入的原始字节。 - 357
#cfg(target="wasm") - 358
#export_name("abi_info") - 359
pub fn abi_info(input : Bytes) -> Bytes { - 360○
try { - 361○
let (w, h) = @lib.check_decode_budget( - 362
input, - 363○
@types.DecodeLimits::default_limits(), - 364
) - 365○
let fmt = @lib.detect_format(input) - 366
state.ok = 1 - 367○
state.format = format_code(fmt) - 368○
state.width = w.to_int() - 369○
state.height = h.to_int() - 370
state.channels = 0 - 371○
state.len = input.length() - 372
state.error = "" - 373○
empty_bytes() - 374
} catch { - 375○
e => set_err(e) - 376
} - 377
} - 378
- 379
///| - 380
/// 解码 + 重新编码,`code` 见 `format_of_code`(9 = best)。 - 381
#cfg(target="wasm") - 382
#export_name("abi_convert") - 383
pub fn abi_convert(input : Bytes, code : Int32, quality : Int32) -> Bytes { - 384○
try { - 385○
let img = @lib.decode_with_limits( - 386
input, - 387○
@types.DecodeLimits::default_limits(), - 388
) - 389○
let enc = encode_payload(img, code, quality) - 390○
set_ok(img, enc.format, enc.bytes.length()) - 391○
pin_keep(enc.bytes) - 392
enc.bytes - 393
} catch { - 394○
e => set_err(e) - 395
} - 396
} - 397
- 398
///| - 399
/// 缩放 + 编码。`mode` 0=cover,1=contain(白底填充)。 - 400
#cfg(target="wasm") - 401
#export_name("abi_resize") - 402
pub fn abi_resize( - 403
input : Bytes, - 404
w : Int32, - 405
h : Int32, - 406
mode : Int32, - 407
code : Int32, - 408
quality : Int32, - 409
) -> Bytes { - 410○
if w <= 0 || h <= 0 { - 411○
return set_err( - 412
@types.ImageError::Process( - 413
@types.ErrorCode::InvalidArgument, - 414
"resize 需要正整数宽高(收到 \{w}x\{h})", - 415
), - 416
) - 417
} - 418
try { - 419○
let img = @lib.decode_with_limits( - 420
input, - 421○
@types.DecodeLimits::default_limits(), - 422
) - 423
let resized = try { - 424
if mode == 1 { - 425○
let fill : Array[Byte] = [] - 426
for _ in 0..<img.channels { - 427○
fill.push(b'\xff') - 428
} - 429○
@transform.resize_to_contain(img, w, h, fill) - 430
} else { - 431○
@transform.resize_to_cover(img, w, h) - 432
} - 433
} catch { - 434○
e => raise @types.image_error_from_load(e) - 435
} - 436○
let enc = encode_payload(resized, code, quality) - 437○
set_ok(resized, enc.format, enc.bytes.length()) - 438○
pin_keep(enc.bytes) - 439
enc.bytes - 440
} catch { - 441○
e => set_err(e) - 442
} - 443
}