wasm\abi.mbt

0% · 0 / 153 points · 443 lines

Background color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.

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