imgcli\serve_run.mbt

79.6% · 227 / 285 points · 621 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/// # `imgtool serve` 的监听实现(serve@1,native only)
  3. 3///
  4. 4/// 契约在 [serve_contract.mbt] 与 `docs/serve_contract.md`;这里只负责把它跑起来:
  5. 5/// `async/http` 的 `Server::run_forever(handler, max_connections=max_conn)`,
  6. 6/// 每个连接一个任务,单线程并发,峰值内存 ≈ max_conn × 单请求预算。
  7. 7///
  8. 8/// 不做的事(与契约 §9 一致):不落盘、不做 TLS、不做鉴权、不自己造请求队列。
  9. 9/// 满载时 `run_forever` 停止 accept,新连接停在内核 listen backlog —— 这正是契约里
  10. 10/// 「满载不排队、延迟不失控」的实现形态,另造一个队列只会让它反悔。
  11. 11
  12. 12///|
  13. 13#cfg(target="native")
  14. 14priv struct ServeCtx {
  15. 15 max_conn : Int32
  16. 16 mem_budget : Int32
  17. 17 max_ms : Int32
  18. 18 quiet : Bool
  19. 19 started : Int64
  20. 20}
  21. 21
  22. 22///|
  23. 23/// 绑定结果。把「解析地址失败」和「端口占用」分开,是为了让调用方看到可区分的码,
  24. 24/// 也让这两条错误路径能被白盒测试直接喂进坏地址 / 已占端口。
  25. 25#cfg(target="native")
  26. 26priv enum BindOut {
  27. 27 Bound(@http.Server)
  28. 28 BadAddr
  29. 29 BindFailed
  30. 30}
  31. 31
  32. 32///|
  33. 33#cfg(target="native")
  34. 34fn bad_addr_json(addr : String, port : Int32) -> String {
  35. 35● "{\"ok\":false,\"code\":\"serve/bad_addr\",\"message\":\"地址无法解析:\{addr}:\{port}\",\"hint\":\"用 --addr 127.0.0.1 --port 8730 这种形式\"}"
  36. 36}
  37. 37
  38. 38///|
  39. 39#cfg(target="native")
  40. 40fn bind_failed_json(addr : String, port : Int32) -> String {
  41. 41● "{\"ok\":false,\"code\":\"serve/bind_failed\",\"message\":\"绑定失败:\{addr}:\{port}\",\"hint\":\"端口被占用就换一个;对外暴露才需要 --addr 0.0.0.0\"}"
  42. 42}
  43. 43
  44. 44///|
  45. 45#cfg(target="native")
  46. 46fn listen_json(addr : String, max_conn : Int32) -> String {
  47. 47● "{\"ok\":true,\"event\":\"listen\",\"addr\":\"\{addr}\",\"schema\":\"\{SERVE_SCHEMA}\",\"max_conn\":\{max_conn}}"
  48. 48}
  49. 49
  50. 50///|
  51. 51#cfg(target="native")
  52. 52async fn serve_bind(addr : String, port : Int32) -> BindOut {
  53. 53● let a = @socket.Addr::parse("\{addr}:\{port}") catch { _ => return BadAddr }
  54. 54○ let s = @http.Server::Server(a) catch { _ => return BindFailed }
  55. 55 Bound(s)
  56. 56}
  57. 57
  58. 58///|
  59. 59/// 事件循环本体:只剩 `run_forever` 这一层不可测的尾巴,所以刻意做薄。
  60. 60#cfg(target="native")
  61. 61async fn serve_loop(server : @http.Server, ctx : ServeCtx) -> Unit {
  62. 62○ server.run_forever(
  63. 63○ async fn(req, conn) { serve_handle(req, conn, ctx) },
  64. 64 max_connections=ctx.max_conn,
  65. 65 )
  66. 66}
  67. 67
  68. 68///|
  69. 69/// 同步入口:`fn main` 里直接调用;内部 `run_async_main` 驱动事件循环。
  70. 70/// 因此 `imgtool` 的普通子命令仍是纯同步路径,不多背一次运行时启动。
  71. 71#cfg(target="native")
  72. 72pub fn serve_run(
  73. 73 addr : String,
  74. 74 port : Int32,
  75. 75 max_conn : Int32,
  76. 76 mem_budget : Int32,
  77. 77 max_ms : Int32,
  78. 78 quiet : Bool,
  79. 79) -> Unit {
  80. 80○ @async.run_async_main(async fn() {
  81. 81○ match serve_bind(addr, port) {
  82. 82○ Bound(server) => {
  83. 83 let ctx : ServeCtx = {
  84. 84 max_conn,
  85. 85 mem_budget,
  86. 86 max_ms,
  87. 87 quiet,
  88. 88○ started: @async.now(),
  89. 89 }
  90. 90 if !quiet {
  91. 91○ println(listen_json(server.local_addr().to_string(), max_conn))
  92. 92 }
  93. 93○ serve_loop(server, ctx)
  94. 94 }
  95. 95○ BadAddr => {
  96. 96○ eprintln(bad_addr_json(addr, port))
  97. 97○ @env.exit(1)
  98. 98 }
  99. 99○ BindFailed => {
  100. 100○ eprintln(bind_failed_json(addr, port))
  101. 101○ @env.exit(1)
  102. 102 }
  103. 103 }
  104. 104 })
  105. 105}
  106. 106
  107. 107///|
  108. 108/// max_ms 的**事后**判定:Recipe 链路还没有 Deadline 参数,只能在结果出来时判
  109. 109/// 「超了没有」,超了把这次成功降级成 422,让调用方拿到确定信号而不是一条慢成功。
  110. 110#cfg(target="native")
  111. 111fn build_reply(
  112. 112 code0 : Int32,
  113. 113 ctype0 : String,
  114. 114 body0 : Bytes,
  115. 115 elapsed : Int64,
  116. 116 max_ms : Int32,
  117. 117) -> (Int32, String, Bytes) {
  118. 118● if code0 == 200 && max_ms > 0 && elapsed > max_ms.to_int64() * 1000 {
  119. 119● (
  120. 120 422,
  121. 121 "application/json",
  122. 122● err_body(
  123. 123 "budget/limit_time",
  124. 124 "本次处理 \{ms_text(elapsed)}ms 超过 --max-ms \{max_ms}",
  125. 125 "调高 --max-ms,或缩小请求(图太大就先缩再发);Recipe 链路的真中断还没接线",
  126. 126 ),
  127. 127 )
  128. 128 } else {
  129. 129● (code0, ctype0, body0)
  130. 130 }
  131. 131}
  132. 132
  133. 133///|
  134. 134/// 一个请求的全过程:解析 path/query → 决策 → 回字节或 JSON。
  135. 135#cfg(target="native")
  136. 136async fn serve_handle(
  137. 137 req : @http.RequestHeader,
  138. 138 conn : @http.ServerConnection,
  139. 139 ctx : ServeCtx,
  140. 140) -> Unit {
  141. 141○ let t0 = @async.now()
  142. 142 let raw = req.path
  143. 143○ let (path, query) = split_path_query(raw)
  144. 144○ let verb = verb_of(req.meth)
  145. 145 let (code0, ctype0, body0) = match
  146. 146○ route_plan(
  147. 147 verb,
  148. 148 path,
  149. 149 query,
  150. 150○ declared_length(req.headers),
  151. 151○ @async.now(),
  152. 152 ctx,
  153. 153 ) {
  154. 154○ Reply(c, t, b) => (c, t, b)
  155. 155 NeedBody(name, q) =>
  156. 156○ match read_body(conn) {
  157. 157 None =>
  158. 158○ (
  159. 159 400,
  160. 160 "application/json",
  161. 161○ err_body(
  162. 162 "decode/body_read", "请求体读取失败", "重发一次;确认没有用 chunked",
  163. 163 ),
  164. 164 )
  165. 165○ Some(b) => recipe_reply(name, b, q, req.headers, ctx)
  166. 166 }
  167. 167 }
  168. 168○ let (code, ctype, body) = build_reply(
  169. 169 code0,
  170. 170 ctype0,
  171. 171 body0,
  172. 172○ @async.now() - t0,
  173. 173 ctx.max_ms,
  174. 174 )
  175. 175 let hdrs : Map[@http.CaseInsensitiveString, String] = Map([])
  176. 176 hdrs["Content-Type"] = ctype
  177. 177○ hdrs["Content-Length"] = body.length().to_string()
  178. 178○ hdrs["X-Img-Ms"] = ms_text(@async.now() - t0)
  179. 179○ conn.send_response(code, reason_of(code), extra_headers=hdrs)
  180. 180○ conn.write(body)
  181. 181○ conn.end_response()
  182. 182 if !ctx.quiet {
  183. 183○ println(
  184. 184 "{\"event\":\"req\",\"method\":\"\{verb}\",\"path\":\"\{path}\",\"status\":\{code},\"out\":\{body.length()},\"ms\":\"\{ms_text(@async.now() - t0)}}",
  185. 185 )
  186. 186 }
  187. 187}
  188. 188
  189. 189///|
  190. 190/// 路由决策的两种结果:要么直接回,要么还需要请求体才能算。
  191. 191#cfg(target="native")
  192. 192priv enum RoutePlan {
  193. 193 Reply(Int32, String, Bytes)
  194. 194 NeedBody(String, Map[String, String])
  195. 195}
  196. 196
  197. 197///|
  198. 198/// 路由决策(纯函数,不碰连接):查表 + 参数校验,**副作用为零**,所以能直接单测。
  199. 199/// `now` 显式传入而不是在函数里取时间,一是可测,二是让 uptime 只有一个来源。
  200. 200#cfg(target="native")
  201. 201fn route_plan(
  202. 202 verb : String,
  203. 203 path : String,
  204. 204 query : Map[String, String],
  205. 205 declared : Int32,
  206. 206 now : Int64,
  207. 207 ctx : ServeCtx,
  208. 208) -> RoutePlan {
  209. 209● if path == "/healthz" {
  210. 210● if verb != "GET" {
  211. 211● return Reply(
  212. 212 405,
  213. 213 "application/json",
  214. 214● err_body(
  215. 215 "method_not_allowed", "healthz 只接受 GET", "换 GET 再来",
  216. 216 ),
  217. 217 )
  218. 218 }
  219. 219 return Reply(
  220. 220 200,
  221. 221 "application/json",
  222. 222● json_bytes({
  223. 223● "ok": jbool(true),
  224. 224● "version": jstr(version),
  225. 225● "uptime_s": jnum(((now - ctx.started) / 1000).to_int()),
  226. 226● "max_conn": jnum(ctx.max_conn),
  227. 227 }),
  228. 228 )
  229. 229 }
  230. 230 if path == "/version" {
  231. 231● if verb != "GET" {
  232. 232● return Reply(
  233. 233 405,
  234. 234 "application/json",
  235. 235● err_body(
  236. 236 "method_not_allowed", "version 只接受 GET", "换 GET 再来",
  237. 237 ),
  238. 238 )
  239. 239 }
  240. 240 return Reply(
  241. 241 200,
  242. 242 "application/json",
  243. 243○ json_bytes({
  244. 244○ "ok": jbool(true),
  245. 245○ "version": jstr(version),
  246. 246○ "target": jstr("native"),
  247. 247○ "schema": jstr(SERVE_SCHEMA),
  248. 248 }),
  249. 249 )
  250. 250 }
  251. 251 if path == "/recipes" {
  252. 252● if verb != "GET" {
  253. 253● return Reply(
  254. 254 405,
  255. 255 "application/json",
  256. 256● err_body(
  257. 257 "method_not_allowed", "recipes 只接受 GET", "换 GET 再来",
  258. 258 ),
  259. 259 )
  260. 260 }
  261. 261 let items : Array[@json.Json] = []
  262. 262● for n in @recipe.recipe_names() {
  263. 263● items.push(
  264. 264● @json.Json::object({
  265. 265● "id": jstr(n),
  266. 266● "about": jstr(@recipe.recipe_about(n)),
  267. 267 }),
  268. 268 )
  269. 269 }
  270. 270 return Reply(
  271. 271 200,
  272. 272 "application/json",
  273. 273● json_bytes({ "ok": jbool(true), "recipes": @json.Json::array(items) }),
  274. 274 )
  275. 275 }
  276. 276● if path.has_prefix("/recipe/") {
  277. 277● let name = path[8:].to_owned()
  278. 278 if verb != "POST" {
  279. 279● return Reply(
  280. 280 405,
  281. 281 "application/json",
  282. 282● err_body(
  283. 283 "method_not_allowed", "recipe 只接受 POST", "把图片字节放进请求体",
  284. 284 ),
  285. 285 )
  286. 286 }
  287. 287● if !is_known_recipe(name) {
  288. 288● return Reply(
  289. 289 404,
  290. 290 "application/json",
  291. 291● err_body(
  292. 292 "unknown_recipe",
  293. 293 "未注册的 Recipe:\{name}",
  294. 294 "GET /recipes 看全部 8 条",
  295. 295 ),
  296. 296 )
  297. 297 }
  298. 298 // 预算先于读取:Content-Length 超了就直接 413,一个字节都不读进内存。
  299. 299 if declared > ctx.mem_budget {
  300. 300● return Reply(
  301. 301 413,
  302. 302 "application/json",
  303. 303● err_body(
  304. 304 "budget/limit_bytes",
  305. 305 "请求体 \{declared} 字节超过 --mem-budget \{ctx.mem_budget}",
  306. 306 "调高 --mem-budget 或先缩图再发",
  307. 307 ),
  308. 308 )
  309. 309 }
  310. 310 return NeedBody(name, query)
  311. 311 }
  312. 312 Reply(
  313. 313 404,
  314. 314 "application/json",
  315. 315● err_body(
  316. 316 "unknown_path",
  317. 317 "没有这条路由:\{path}",
  318. 318 "GET /healthz · GET /version · GET /recipes · POST /recipe/<name>",
  319. 319 ),
  320. 320 )
  321. 321}
  322. 322
  323. 323///|
  324. 324/// 读请求体:失败给 `None`,由调用方决定回什么(读失败不是「空体」)。
  325. 325#cfg(target="native")
  326. 326async fn read_body(conn : @http.ServerConnection) -> Bytes? {
  327. 327○ let b = conn.read_all() catch { _ => return None }
  328. 328 Some(b)
  329. 329}
  330. 330
  331. 331///|
  332. 332/// 请求体到手之后的全部工作:空体 / 超预算 / 跑 Recipe / 决定回图还是回 JSON。
  333. 333/// 纯同步(`run_recipe` 本身是同步的),因此也能单测。
  334. 334#cfg(target="native")
  335. 335fn recipe_reply(
  336. 336 name : String,
  337. 337 in_bytes : Bytes,
  338. 338 query : Map[String, String],
  339. 339 headers : @http.Headers,
  340. 340 ctx : ServeCtx,
  341. 341) -> (Int32, String, Bytes) {
  342. 342● if in_bytes.length() == 0 {
  343. 343● return (
  344. 344 400,
  345. 345 "application/json",
  346. 346● err_body(
  347. 347 "decode/empty", "请求体为空", "POST /recipe/<name> 时把图片字节放进 body",
  348. 348 ),
  349. 349 )
  350. 350 }
  351. 351● if in_bytes.length() > ctx.mem_budget {
  352. 352● return (
  353. 353 413,
  354. 354 "application/json",
  355. 355● err_body(
  356. 356 "budget/limit_bytes",
  357. 357 "请求体 \{in_bytes.length()} 字节超过 --mem-budget \{ctx.mem_budget}",
  358. 358 "调高 --mem-budget 或先缩图再发",
  359. 359 ),
  360. 360 )
  361. 361 }
  362. 362● let opts = opts_of(query)
  363. 363● let r = @recipe.run_recipe(name, in_bytes, opts) catch {
  364. 364 e =>
  365. 365● return (
  366. 366● status_of_image_error(e),
  367. 367 "application/json",
  368. 368● json_bytes(error_json(e)),
  369. 369 )
  370. 370 }
  371. 371● if query.get("dry-run") == Some("1") || wants_json(headers, query) {
  372. 372● let steps : Array[@json.Json] = []
  373. 373 for s in r.steps {
  374. 374● steps.push(
  375. 375● @json.Json::object({
  376. 376● "name": jstr(s.name),
  377. 377● "width": jnum(s.width),
  378. 378● "height": jnum(s.height),
  379. 379● "bytes": jnum(s.bytes),
  380. 380● "ms": jnum(s.ms.to_int()),
  381. 381 }),
  382. 382 )
  383. 383 }
  384. 384 return (
  385. 385 200,
  386. 386 "application/json",
  387. 387● json_bytes({
  388. 388● "ok": jbool(true),
  389. 389● "recipe": jstr(r.recipe),
  390. 390● "width": jnum(r.image.width()),
  391. 391● "height": jnum(r.image.height()),
  392. 392● "channels": jnum(r.image.channels()),
  393. 393● "bytes": jnum(r.bytes.length().to_int()),
  394. 394● "format": jstr(format_name(r.format)),
  395. 395● "quality": jnum(r.quality),
  396. 396● "steps": @json.Json::array(steps),
  397. 397 }),
  398. 398 )
  399. 399 }
  400. 400● (200, mime_of(r.format), r.bytes)
  401. 401}
  402. 402
  403. 403// ---------------------------------------------------------------------------
  404. 404// 小工具
  405. 405// ---------------------------------------------------------------------------
  406. 406
  407. 407///|
  408. 408#cfg(target="native")
  409. 409fn split_path_query(raw : String) -> (String, Map[String, String]) {
  410. 410● match raw.find("?") {
  411. 411● Some(i) => (raw[0:i].to_owned(), parse_query(raw[i + 1:].to_owned()))
  412. 412● None => (raw, Map([]))
  413. 413 }
  414. 414}
  415. 415
  416. 416///|
  417. 417#cfg(target="native")
  418. 418fn parse_query(s : String) -> Map[String, String] {
  419. 419● let out : Map[String, String] = Map([])
  420. 420● for pair_v in s.split("&") {
  421. 421● let pair = pair_v.to_owned()
  422. 422● if pair.length() == 0 {
  423. 423● continue
  424. 424 }
  425. 425● match pair.find("=") {
  426. 426● Some(i) => out[pair[0:i].to_owned()] = pair[i + 1:].to_owned()
  427. 427● None => out[pair] = "1"
  428. 428 }
  429. 429 }
  430. 430 out
  431. 431}
  432. 432
  433. 433///|
  434. 434#cfg(target="native")
  435. 435fn verb_of(m : @http.RequestMethod) -> String {
  436. 436● match m {
  437. 437● @http.RequestMethod::Get => "GET"
  438. 438● @http.RequestMethod::Post => "POST"
  439. 439● @http.RequestMethod::Head => "HEAD"
  440. 440○ _ => "OTHER"
  441. 441 }
  442. 442}
  443. 443
  444. 444///|
  445. 445#cfg(target="native")
  446. 446fn declared_length(headers : @http.Headers) -> Int32 {
  447. 447● match headers.get(@http.CaseInsensitiveString("content-length")) {
  448. 448 Some(s) =>
  449. 449● match parse_int(s.trim().to_owned()) {
  450. 450● Some(n) => n
  451. 451● None => -1
  452. 452 }
  453. 453● None => -1
  454. 454 }
  455. 455}
  456. 456
  457. 457///|
  458. 458#cfg(target="native")
  459. 459fn warns_json(headers : @http.Headers) -> Bool {
  460. 460● match headers.get(@http.CaseInsensitiveString("accept")) {
  461. 461● Some(a) => a.contains("application/json")
  462. 462● None => false
  463. 463 }
  464. 464}
  465. 465
  466. 466///|
  467. 467#cfg(target="native")
  468. 468fn wants_json(headers : @http.Headers, query : Map[String, String]) -> Bool {
  469. 469● match query.get("format") {
  470. 470● Some(f) => f == "json"
  471. 471● None => warns_json(headers)
  472. 472 }
  473. 473}
  474. 474
  475. 475///|
  476. 476#cfg(target="native")
  477. 477fn is_known_recipe(name : String) -> Bool {
  478. 478● for n in @recipe.recipe_names() {
  479. 479● if n == name {
  480. 480● return true
  481. 481 }
  482. 482 }
  483. 483 false
  484. 484}
  485. 485
  486. 486///|
  487. 487#cfg(target="native")
  488. 488fn opts_of(query : Map[String, String]) -> @recipe.RecipeOpts {
  489. 489● let mut opts = @recipe.RecipeOpts::new()
  490. 490● match query.get("format") {
  491. 491 Some(f) =>
  492. 492● match format_of(f) {
  493. 493● Some(fmt) => opts = { ..opts, format: fmt, }
  494. 494● None => ()
  495. 495 }
  496. 496● None => ()
  497. 497 }
  498. 498● match query.get("quality") {
  499. 499 Some(q) =>
  500. 500● match parse_int(q) {
  501. 501● Some(n) => opts = { ..opts, quality: n, }
  502. 502● None => ()
  503. 503 }
  504. 504● None => ()
  505. 505 }
  506. 506● match query.get("max-bytes") {
  507. 507 Some(b) =>
  508. 508● match parse_int(b) {
  509. 509● Some(n) => opts = { ..opts, max_bytes: n, }
  510. 510○ None => ()
  511. 511 }
  512. 512● None => ()
  513. 513 }
  514. 514● match query.get("longest") {
  515. 515 Some(l) =>
  516. 516● match parse_int(l) {
  517. 517● Some(n) => opts = { ..opts, longest: n, }
  518. 518● None => ()
  519. 519 }
  520. 520● None => ()
  521. 521 }
  522. 522 opts
  523. 523}
  524. 524
  525. 525///|
  526. 526#cfg(target="native")
  527. 527fn format_of(s : String) -> @types.ImageFormat? {
  528. 528● match s {
  529. 529● "png" => Some(@types.ImageFormat::Png)
  530. 530● "jpeg" | "jpg" => Some(@types.ImageFormat::Jpeg)
  531. 531● "webp" => Some(@types.ImageFormat::Webp)
  532. 532● "pnm" | "pgm" | "ppm" => Some(@types.ImageFormat::Pnm)
  533. 533● "bmp" => Some(@types.ImageFormat::Bmp)
  534. 534● "qoi" => Some(@types.ImageFormat::Qoi)
  535. 535● _ => None
  536. 536 }
  537. 537}
  538. 538
  539. 539///|
  540. 540#cfg(target="native")
  541. 541fn mime_of(f : @types.ImageFormat) -> String {
  542. 542● match f {
  543. 543● @types.ImageFormat::Png => "image/png"
  544. 544● @types.ImageFormat::Jpeg => "image/jpeg"
  545. 545● @types.ImageFormat::Webp => "image/webp"
  546. 546● @types.ImageFormat::Pnm => "image/x-portable-anymap"
  547. 547● @types.ImageFormat::Bmp => "image/bmp"
  548. 548● @types.ImageFormat::Qoi => "image/qoi"
  549. 549● _ => "application/octet-stream"
  550. 550 }
  551. 551}
  552. 552
  553. 553///|
  554. 554#cfg(target="native")
  555. 555fn reason_of(code : Int32) -> String {
  556. 556● match code {
  557. 557● 200 => "OK"
  558. 558● 400 => "Bad Request"
  559. 559● 404 => "Not Found"
  560. 560● 405 => "Method Not Allowed"
  561. 561● 413 => "Payload Too Large"
  562. 562● 422 => "Unprocessable Entity"
  563. 563○ 503 => "Service Unavailable"
  564. 564● _ => "Internal Server Error"
  565. 565 }
  566. 566}
  567. 567
  568. 568///|
  569. 569#cfg(target="native")
  570. 570fn status_of_image_error(e : @types.ImageError) -> Int32 {
  571. 571● let code = e.code()
  572. 572● if code.has_prefix("decode/") {
  573. 573● 400
  574. 574● } else if code == "budget/limit_bytes" {
  575. 575● 413
  576. 576● } else if code.has_prefix("budget/") || code.has_prefix("process/") {
  577. 577● 422
  578. 578 } else {
  579. 579○ 500
  580. 580 }
  581. 581}
  582. 582
  583. 583///|
  584. 584#cfg(target="native")
  585. 585fn json_bytes(out : Out) -> Bytes {
  586. 586● @utf8.encode(@json.Json::object(out).stringify())
  587. 587}
  588. 588
  589. 589///|
  590. 590#cfg(target="native")
  591. 591fn err_body(code : String, message : String, hint : String) -> Bytes {
  592. 592● json_bytes({
  593. 593● "ok": jbool(false),
  594. 594● "code": jstr(code),
  595. 595● "message": jstr(message),
  596. 596● "hint": jstr(hint),
  597. 597 })
  598. 598}
  599. 599
  600. 600///|
  601. 601/// 十进制解析:复用 core 的 `parse_int`,失败给 `None`(query 参数是用户输入,不能 abort)。
  602. 602#cfg(target="native")
  603. 603fn parse_int(s : String) -> Int32? {
  604. 604● let v = @string.parse_int(s) catch { _ => return None }
  605. 605 Some(v)
  606. 606}
  607. 607
  608. 608///|
  609. 609#cfg(target="native")
  610. 610fn ms_text(us : Int64) -> String {
  611. 611● let ms = us / 1000
  612. 612● let frac = (us % 1000).to_int()
  613. 613 let f = if frac < 10 {
  614. 614● "00" + frac.to_string()
  615. 615● } else if frac < 100 {
  616. 616● "0" + frac.to_string()
  617. 617 } else {
  618. 618● frac.to_string()
  619. 619 }
  620. 620● ms.to_string() + "." + f
  621. 621}