image.core\safe_math\safe_math.mbt

100% · 61 / 61 points · 733 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/// # 安全算术与核心证明模块 Safe Arithmetic & Core Proof Module
  3. 3///
  4. 4/// 提供溢出安全的整数运算、钳制函数、索引检查、编解码核心算法。 Provides overflow-safe integer arithmetic, clamp functions, index checks, and codec core algorithms.
  5. 5/// 带 `proof_ensure` 的函数附带形式化验证契约(moon prove), Functions with `proof_ensure` carry formal verification contracts (moon prove),
  6. 6/// 确保 SMT 可机检的数学正确性。 ensuring SMT-machine-checkable mathematical correctness.
  7. 7///
  8. 8/// 证明谓词定义在 `safe_math.mbtp` 中。 Proof predicates are defined in `safe_math.mbtp`.
  9. 9///
  10. 10/// 核心函数 Core functions:
  11. 11/// - `safe_mul` / `safe_mul3` - 溢出安全乘法 Overflow-safe multiplication
  12. 12/// - `dims_valid_check` - 维度合法性检查 Dimension validity check
  13. 13/// - `clamp_int` / `clamp_pixel_value` / `clamp_byte` / `clamp_coord` - 整数钳制 Integer clamp
  14. 14/// - `clamp_float` / `clamp_double` - 浮点钳制 Float clamp
  15. 15/// - `int_max` / `int_min` - 整数极值 Integer extrema
  16. 16/// - `is_valid_index` / `is_valid_2d_index` - 索引合法性 Index validity
  17. 17/// - `rotate90_power_is_identity` - 旋转恒等性 Rotation identity
  18. 18/// - `paeth_predict` / `qoi_hash` / `quantize_332` / `hamming_distance` - 编解码核心 Codec core
  19. 19///
  20. 20/// MoonBit 证明系统限制(实验性): MoonBit proof system limitations (experimental):
  21. 21/// - 契约函数体中不支持:raise、return、let mut、while、.abs()、>>、& Contract function bodies do not support: raise, return, let mut, while, .abs(), >>, &
  22. 22/// - 谓词中不支持:>>、&、=>(用 !P || Q 替代)、match Bool Predicates do not support: >>, &, => (use !P || Q instead), match Bool
  23. 23/// - 含复杂类型(Bytes/Array)的包导致 Why3 翻译失败 Packages with complex types (Bytes/Array) cause Why3 translation failure
  24. 24
  25. 25///|
  26. 26/// 图像维度上限(单边最大像素数)。 Maximum image dimension limit (max pixels per side).
  27. 27///
  28. 28/// 65535 覆盖常见图像格式最大尺寸(PNG/TIFF 32-bit、JPEG 65500、BMP 32-bit)。 65535 covers max sizes of common formats (PNG/TIFF 32-bit, JPEG 65500, BMP 32-bit).
  29. 29pub const MAX_IMAGE_DIMENSION : Int32 = 65535
  30. 30
  31. 31// ============================================================================
  32. 32// Section: 溢出安全乘法 Overflow-safe multiplication
  33. 33// ============================================================================
  34. 34
  35. 35///|
  36. 36/// 安全乘法:返回 a * b,溢出时返回 None。
  37. 37/// 安全乘法:返回 a * b,溢出时返回 None。 Safe multiplication: returns a * b, or None on overflow.
  38. 38///
  39. 39/// 用于在分配大数组前检查是否会溢出。
  40. 40/// 用于在分配大数组前检查是否会溢出。 Used to check for overflow before allocating large arrays.
  41. 41///
  42. 42/// ✅ 形式化验证:证明后置条件 safe_mul_ok 成立。 ✅ Formal verification: proves postcondition safe_mul_ok holds.
  43. 43///
  44. 44/// 参数 Parameters:
  45. 45/// - `a` - 乘数 Multiplicand
  46. 46/// - `b` - 乘数 Multiplier
  47. 47///
  48. 48/// 返回 Return:
  49. 49/// - `Some(result)` - 乘积 The product
  50. 50/// - `None` - 溢出 Overflow occurred
  51. 51///
  52. 52/// 示例 Example:
  53. 53/// ```mbt check
  54. 54/// test "doc_safe_mul_normal" {
  55. 55/// assert_eq(@safe_math.safe_mul(3, 4), Some(12))
  56. 56/// }
  57. 57/// ```
  58. 58///
  59. 59/// ```mbt check
  60. 60/// test "doc_safe_mul_overflow" {
  61. 61/// assert_eq(@safe_math.safe_mul(1073741824, 2), None)
  62. 62/// }
  63. 63/// ```
  64. 64///
  65. 65/// ```mbt check
  66. 66/// test "doc_safe_mul_zero" {
  67. 67/// assert_eq(@safe_math.safe_mul(0, 100), Some(0))
  68. 68/// }
  69. 69/// ```
  70. 70pub fn safe_mul(
  71. 71 a : Int32,
  72. 72 b : Int32,
  73. 73) -> Int32? where {
  74. 74 proof_ensure: result => safe_mul_ok(a, b, result),
  75. 75} {
  76. 76● if a <= 0 || b <= 0 {
  77. 77● Some(0)
  78. 78 } else {
  79. 79● let max_int = 2147483647
  80. 80 if a > max_int / b {
  81. 81● None
  82. 82 } else {
  83. 83● Some(a * b)
  84. 84 }
  85. 85 }
  86. 86}
  87. 87
  88. 88///|
  89. 89/// 安全三参数乘法:返回 a * b * c,溢出时返回 None。 Safe three-argument multiplication: returns a * b * c, or None on overflow.
  90. 90///
  91. 91/// 常用于计算 w * h * channels 的数组大小。 Commonly used to compute array size as w * h * channels.
  92. 92///
  93. 93/// 参数 Parameters:
  94. 94/// - `a` - 第一乘数 First multiplicand
  95. 95/// - `b` - 第二乘数 Second multiplicand
  96. 96/// - `c` - 第三乘数 Third multiplicand
  97. 97///
  98. 98/// 返回 Return:
  99. 99/// - `Some(result)` - 乘积 The product
  100. 100/// - `None` - 溢出 Overflow occurred
  101. 101///
  102. 102/// 示例 Example:
  103. 103/// ```mbt check
  104. 104/// test "doc_safe_mul3_normal" {
  105. 105/// assert_eq(@safe_math.safe_mul3(2, 3, 4), Some(24))
  106. 106/// }
  107. 107/// ```
  108. 108///
  109. 109/// ```mbt check
  110. 110/// test "doc_safe_mul3_overflow" {
  111. 111/// assert_eq(@safe_math.safe_mul3(1073741824, 2, 1), None)
  112. 112/// }
  113. 113/// ```
  114. 114pub fn safe_mul3(a : Int32, b : Int32, c : Int32) -> Int32? {
  115. 115● match safe_mul(a, b) {
  116. 116 Some(ab) =>
  117. 117● match safe_mul(ab, c) {
  118. 118● Some(abc) => Some(abc)
  119. 119● None => None
  120. 120 }
  121. 121● None => None
  122. 122 }
  123. 123}
  124. 124
  125. 125///|
  126. 126/// 判断维度是否在安全范围内(纯函数)。 Check if dimensions are within safe bounds (pure function).
  127. 127///
  128. 128/// 返回 true 当且仅当 width/height/channels 均为正、不超过 MAX_IMAGE_DIMENSION、且乘积不溢出 Int32。 Returns true iff width/height/channels are all positive, do not exceed MAX_IMAGE_DIMENSION, and product does not overflow Int32.
  129. 129
  130. 130///|
  131. 131/// ✅ 形式化验证:证明结果等价于维度合法性谓词。 ✅ Formal verification: proves result is equivalent to dimension validity predicate.
  132. 132///
  133. 133/// 参数 Parameters:
  134. 134/// - `w` - 宽度 Width
  135. 135/// - `h` - 高度 Height
  136. 136/// - `c` - 通道数 Channels
  137. 137///
  138. 138/// 返回 Return:
  139. 139/// - 维度是否合法 Whether dimensions are valid
  140. 140///
  141. 141/// 示例 Example:
  142. 142/// ```mbt check
  143. 143/// test "doc_dims_valid_check_valid" {
  144. 144/// assert_true(@safe_math.dims_valid_check(100, 200, 3))
  145. 145/// }
  146. 146/// ```
  147. 147///
  148. 148/// ```mbt check
  149. 149/// test "doc_dims_valid_check_invalid" {
  150. 150/// assert_true(!@safe_math.dims_valid_check(0, 100, 3))
  151. 151/// }
  152. 152/// ```
  153. 153#inline
  154. 154pub fn dims_valid_check(
  155. 155 w : Int32,
  156. 156 h : Int32,
  157. 157 c : Int32,
  158. 158) -> Bool where {
  159. 159 proof_ensure: result => dims_valid_pred(w, h, c, result),
  160. 160} {
  161. 161● 1 <= w &&
  162. 162 w <= 65535 &&
  163. 163 1 <= h &&
  164. 164 h <= 65535 &&
  165. 165 1 <= c &&
  166. 166 w <= 2147483647 / h &&
  167. 167 w * h <= 500000000 &&
  168. 168 w * h <= 2147483647 / c
  169. 169}
  170. 170
  171. 171// ============================================================================
  172. 172// Section: 钳制函数(Clamp)
  173. 173// ============================================================================
  174. 174
  175. 175///|
  176. 176/// 通用整数钳制:将 v 限制在 [lo, hi] 范围内。 General integer clamp: constrains v to [lo, hi] range.
  177. 177///
  178. 178/// 谓词 clamp_int_ok 保证结果在 [lo, hi] 范围内。 Predicate clamp_int_ok guarantees the result is in [lo, hi] range.
  179. 179/// 注意:当前 moon prove 对此函数后置条件求解超时,待优化。 Note: current moon prove solver times out on this postcondition, pending optimization.
  180. 180///
  181. 181/// 参数 Parameters:
  182. 182/// - `v` - 输入值 Input value
  183. 183/// - `lo` - 下界 Lower bound
  184. 184/// - `hi` - 上界 Upper bound
  185. 185///
  186. 186/// 返回 Return:
  187. 187/// - 钳制后的值 Clamped value
  188. 188///
  189. 189/// 示例 Example:
  190. 190/// ```mbt check
  191. 191/// test "doc_clamp_int_within" {
  192. 192/// assert_eq(@safe_math.clamp_int(5, 0, 10), 5)
  193. 193/// }
  194. 194/// ```
  195. 195///
  196. 196/// ```mbt check
  197. 197/// test "doc_clamp_int_below" {
  198. 198/// assert_eq(@safe_math.clamp_int(-3, 0, 10), 0)
  199. 199/// }
  200. 200/// ```
  201. 201///
  202. 202/// ```mbt check
  203. 203/// test "doc_clamp_int_above" {
  204. 204/// assert_eq(@safe_math.clamp_int(15, 0, 10), 10)
  205. 205/// }
  206. 206/// ```
  207. 207#inline
  208. 208pub fn clamp_int(v : Int32, lo : Int32, hi : Int32) -> Int32 {
  209. 209● if v < lo {
  210. 210● lo
  211. 211● } else if v > hi {
  212. 212● hi
  213. 213 } else {
  214. 214● v
  215. 215 }
  216. 216}
  217. 217
  218. 218///|
  219. 219/// 像素值钳制:将 value 限制在 [0, 255] 范围内。 Pixel value clamp: constrains value to [0, 255] range.
  220. 220///
  221. 221/// ✅ 形式化验证:证明结果在 [0, 255] 范围内。 ✅ Formal verification: proves result is in [0, 255] range.
  222. 222///
  223. 223/// 参数 Parameters:
  224. 224/// - `value` - 输入像素值 Input pixel value
  225. 225///
  226. 226/// 返回 Return:
  227. 227/// - 钳制后的像素值(0-255)Clamped pixel value (0-255)
  228. 228///
  229. 229/// 示例 Example:
  230. 230/// ```mbt check
  231. 231/// test "doc_clamp_pixel_value_normal" {
  232. 232/// assert_eq(@safe_math.clamp_pixel_value(128), 128)
  233. 233/// }
  234. 234/// ```
  235. 235///
  236. 236/// ```mbt check
  237. 237/// test "doc_clamp_pixel_value_negative" {
  238. 238/// assert_eq(@safe_math.clamp_pixel_value(-10), 0)
  239. 239/// }
  240. 240/// ```
  241. 241///
  242. 242/// ```mbt check
  243. 243/// test "doc_clamp_pixel_value_overflow" {
  244. 244/// assert_eq(@safe_math.clamp_pixel_value(300), 255)
  245. 245/// }
  246. 246/// ```
  247. 247pub fn clamp_pixel_value(
  248. 248 value : Int32,
  249. 249) -> Int32 where {
  250. 250 proof_ensure: result => clamp_pixel_ok(value, result),
  251. 251} {
  252. 252● if value < 0 {
  253. 253● 0
  254. 254● } else if value > 255 {
  255. 255● 255
  256. 256 } else {
  257. 257● value
  258. 258 }
  259. 259}
  260. 260
  261. 261///|
  262. 262/// 坐标钳制:将坐标 v 限制在 [0, max_val-1] 范围内。 Coordinate clamp: constrains coordinate v to [0, max_val-1] range.
  263. 263///
  264. 264/// 用于图像像素坐标的边界检查。 Used for boundary checking of image pixel coordinates.
  265. 265/// 谓词 clamp_coord_ok 保证结果在 [0, max_val-1] 范围内(当 max > 0)。 Predicate clamp_coord_ok guarantees result is in [0, max_val-1] range (when max > 0).
  266. 266/// 注意:当前 moon prove 对此函数后置条件求解超时,待优化。 Note: current moon prove solver times out on this postcondition, pending optimization.
  267. 267///
  268. 268/// 参数 Parameters:
  269. 269/// - `v` - 坐标值 Coordinate value
  270. 270/// - `max_val` - 最大值(上限为 max_val-1)Maximum value (upper bound is max_val-1)
  271. 271///
  272. 272/// 返回 Return:
  273. 273/// - 钳制后的坐标 Clamped coordinate
  274. 274///
  275. 275/// 示例 Example:
  276. 276/// ```mbt check
  277. 277/// test "doc_clamp_coord_within" {
  278. 278/// assert_eq(@safe_math.clamp_coord(5, 10), 5)
  279. 279/// }
  280. 280/// ```
  281. 281///
  282. 282/// ```mbt check
  283. 283/// test "doc_clamp_coord_negative" {
  284. 284/// assert_eq(@safe_math.clamp_coord(-1, 10), 0)
  285. 285/// }
  286. 286/// ```
  287. 287///
  288. 288/// ```mbt check
  289. 289/// test "doc_clamp_coord_exceeds" {
  290. 290/// assert_eq(@safe_math.clamp_coord(15, 10), 9)
  291. 291/// }
  292. 292/// ```
  293. 293#inline
  294. 294pub fn clamp_coord(v : Int32, max_val : Int32) -> Int32 {
  295. 295● if v < 0 {
  296. 296● 0
  297. 297● } else if v >= max_val {
  298. 298● max_val - 1
  299. 299 } else {
  300. 300● v
  301. 301 }
  302. 302}
  303. 303
  304. 304///|
  305. 305/// 字节钳制:将 Int32 值限制在 [0, 255] 并转为 Byte。 Byte clamp: constrains Int32 value to [0, 255] and converts to Byte.
  306. 306///
  307. 307/// 等价于 clamp_pixel_value(v).to_byte(),用于像素赋值。 Equivalent to clamp_pixel_value(v).to_byte(), used for pixel assignment.
  308. 308///
  309. 309/// 参数 Parameters:
  310. 310/// - `v` - 输入值 Input value
  311. 311///
  312. 312/// 返回 Return:
  313. 313/// - 钳制后的字节 Clamped byte
  314. 314///
  315. 315/// 示例 Example:
  316. 316/// ```mbt check
  317. 317/// test "doc_clamp_byte_normal" {
  318. 318/// assert_eq(@safe_math.clamp_byte(100), b'\x64')
  319. 319/// }
  320. 320/// ```
  321. 321///
  322. 322/// ```mbt check
  323. 323/// test "doc_clamp_byte_overflow" {
  324. 324/// assert_eq(@safe_math.clamp_byte(500), b'\xff')
  325. 325/// }
  326. 326/// ```
  327. 327#inline
  328. 328pub fn clamp_byte(v : Int32) -> Byte {
  329. 329● clamp_pixel_value(v).to_byte()
  330. 330}
  331. 331
  332. 332///|
  333. 333/// 浮点钳制:将 Float 值 v 限制在 [lo, hi] 范围内。 Float clamp: constrains Float value v to [lo, hi] range.
  334. 334///
  335. 335/// 用于 16-bit/float 图像处理的范围约束。 Used for range constraints in 16-bit/float image processing.
  336. 336///
  337. 337/// 参数 Parameters:
  338. 338/// - `v` - 输入值 Input value
  339. 339/// - `lo` - 下界 Lower bound
  340. 340/// - `hi` - 上界 Upper bound
  341. 341///
  342. 342/// 返回 Return:
  343. 343/// - 钳制后的值 Clamped value
  344. 344///
  345. 345/// 示例 Example:
  346. 346/// ```mbt check
  347. 347/// test "doc_clamp_float_within" {
  348. 348/// assert_eq(@safe_math.clamp_float(0.5F, 0.0F, 1.0F), 0.5F)
  349. 349/// }
  350. 350/// ```
  351. 351///
  352. 352/// ```mbt check
  353. 353/// test "doc_clamp_float_below" {
  354. 354/// assert_eq(@safe_math.clamp_float(-0.5F, 0.0F, 1.0F), 0.0F)
  355. 355/// }
  356. 356/// ```
  357. 357#inline
  358. 358pub fn clamp_float(v : Float, lo : Float, hi : Float) -> Float {
  359. 359● if v < lo {
  360. 360● lo
  361. 361● } else if v > hi {
  362. 362● hi
  363. 363 } else {
  364. 364● v
  365. 365 }
  366. 366}
  367. 367
  368. 368///|
  369. 369/// 双精度浮点钳制:将 Double 值 v 限制在 [lo, hi] 范围内。 Double clamp: constrains Double value v to [lo, hi] range.
  370. 370///
  371. 371/// 用于高精度图像处理(HDR/频域)的范围约束。 Used for range constraints in high-precision image processing (HDR/frequency domain).
  372. 372///
  373. 373/// 参数 Parameters:
  374. 374/// - `v` - 输入值 Input value
  375. 375/// - `lo` - 下界 Lower bound
  376. 376/// - `hi` - 上界 Upper bound
  377. 377///
  378. 378/// 返回 Return:
  379. 379/// - 钳制后的值 Clamped value
  380. 380///
  381. 381/// 示例 Example:
  382. 382/// ```mbt check
  383. 383/// test "doc_clamp_double_within" {
  384. 384/// assert_eq(@safe_math.clamp_double(0.5, 0.0, 1.0), 0.5)
  385. 385/// }
  386. 386/// ```
  387. 387///
  388. 388/// ```mbt check
  389. 389/// test "doc_clamp_double_above" {
  390. 390/// assert_eq(@safe_math.clamp_double(1.5, 0.0, 1.0), 1.0)
  391. 391/// }
  392. 392/// ```
  393. 393#inline
  394. 394pub fn clamp_double(v : Double, lo : Double, hi : Double) -> Double {
  395. 395● if v < lo {
  396. 396● lo
  397. 397● } else if v > hi {
  398. 398● hi
  399. 399 } else {
  400. 400● v
  401. 401 }
  402. 402}
  403. 403
  404. 404// ============================================================================
  405. 405// Section: 整数 min/max(替代散布全项目的私有 min_/max_ 函数)
  406. 406// Integer min/max (replaces scattered private min_/max_ functions across the project)
  407. 407// ============================================================================
  408. 408
  409. 409///|
  410. 410/// 整数最大值:返回 a 和 b 中较大的那个。 Integer maximum: returns the larger of a and b.
  411. 411///
  412. 412/// ✅ 形式化验证:证明结果确实是 a 和 b 中的较大者。 ✅ Formal verification: proves the result is indeed the larger of a and b.
  413. 413///
  414. 414/// 参数 Parameters:
  415. 415/// - `a` - 第一个值 First value
  416. 416/// - `b` - 第二个值 Second value
  417. 417///
  418. 418/// 返回 Return:
  419. 419/// - 较大值 The larger value
  420. 420///
  421. 421/// 示例 Example:
  422. 422/// ```mbt check
  423. 423/// test "doc_int_max_a_larger" {
  424. 424/// assert_eq(@safe_math.int_max(10, 5), 10)
  425. 425/// }
  426. 426/// ```
  427. 427///
  428. 428/// ```mbt check
  429. 429/// test "doc_int_max_b_larger" {
  430. 430/// assert_eq(@safe_math.int_max(3, 7), 7)
  431. 431/// }
  432. 432/// ```
  433. 433#inline
  434. 434pub fn int_max(
  435. 435 a : Int32,
  436. 436 b : Int32,
  437. 437) -> Int32 where {
  438. 438 proof_ensure: result => int_max_ok(a, b, result),
  439. 439} {
  440. 440● if a > b {
  441. 441● a
  442. 442 } else {
  443. 443● b
  444. 444 }
  445. 445}
  446. 446
  447. 447///|
  448. 448/// 整数最小值:返回 a 和 b 中较小的那个。 Integer minimum: returns the smaller of a and b.
  449. 449///
  450. 450/// ✅ 形式化验证:证明结果确实是 a 和 b 中的较小者。 ✅ Formal verification: proves the result is indeed the smaller of a and b.
  451. 451///
  452. 452/// 参数 Parameters:
  453. 453/// - `a` - 第一个值 First value
  454. 454/// - `b` - 第二个值 Second value
  455. 455///
  456. 456/// 返回 Return:
  457. 457/// - 较小值 The smaller value
  458. 458///
  459. 459/// 示例 Example:
  460. 460/// ```mbt check
  461. 461/// test "doc_int_min_a_smaller" {
  462. 462/// assert_eq(@safe_math.int_min(3, 7), 3)
  463. 463/// }
  464. 464/// ```
  465. 465///
  466. 466/// ```mbt check
  467. 467/// test "doc_int_min_equal" {
  468. 468/// assert_eq(@safe_math.int_min(5, 5), 5)
  469. 469/// }
  470. 470/// ```
  471. 471#inline
  472. 472pub fn int_min(
  473. 473 a : Int32,
  474. 474 b : Int32,
  475. 475) -> Int32 where {
  476. 476 proof_ensure: result => int_min_ok(a, b, result),
  477. 477} {
  478. 478● if a < b {
  479. 479● a
  480. 480 } else {
  481. 481● b
  482. 482 }
  483. 483}
  484. 484
  485. 485// ============================================================================
  486. 486// Section: 索引合法性检查 Index validity checks
  487. 487// ============================================================================
  488. 488
  489. 489///|
  490. 490/// 安全的一维索引检查:0 <= index < length。 Safe 1D index check: 0 <= index < length.
  491. 491///
  492. 492/// ✅ 形式化验证:证明结果正确判定索引合法性。 ✅ Formal verification: proves result correctly determines index validity.
  493. 493///
  494. 494/// 参数 Parameters:
  495. 495/// - `index` - 索引值 Index value
  496. 496/// - `length` - 数组长度 Array length
  497. 497///
  498. 498/// 返回 Return:
  499. 499/// - 索引是否合法 Whether the index is valid
  500. 500///
  501. 501/// 示例 Example:
  502. 502/// ```mbt check
  503. 503/// test "doc_is_valid_index_valid" {
  504. 504/// assert_true(@safe_math.is_valid_index(2, 5))
  505. 505/// }
  506. 506/// ```
  507. 507///
  508. 508/// ```mbt check
  509. 509/// test "doc_is_valid_index_out_of_bounds" {
  510. 510/// assert_true(!@safe_math.is_valid_index(5, 5))
  511. 511/// }
  512. 512/// ```
  513. 513#inline
  514. 514pub fn is_valid_index(
  515. 515 index : Int32,
  516. 516 length : Int32,
  517. 517) -> Bool where {
  518. 518 proof_ensure: result => valid_index(index, length, result),
  519. 519} {
  520. 520● index >= 0 && index < length
  521. 521}
  522. 522
  523. 523///|
  524. 524/// 安全的二维索引检查:0 <= x < width && 0 <= y < height。 Safe 2D index check: 0 <= x < width && 0 <= y < height.
  525. 525///
  526. 526/// ✅ 形式化验证:证明结果正确判定 2D 索引合法性。 ✅ Formal verification: proves result correctly determines 2D index validity.
  527. 527///
  528. 528/// 参数 Parameters:
  529. 529/// - `x` - x 坐标 x coordinate
  530. 530/// - `y` - y 坐标 y coordinate
  531. 531/// - `width` - 图像宽度 Image width
  532. 532/// - `height` - 图像高度 Image height
  533. 533///
  534. 534/// 返回 Return:
  535. 535/// - 索引是否合法 Whether the index is valid
  536. 536///
  537. 537/// 示例 Example:
  538. 538/// ```mbt check
  539. 539/// test "doc_is_valid_2d_index_valid" {
  540. 540/// assert_true(@safe_math.is_valid_2d_index(1, 2, 10, 20))
  541. 541/// }
  542. 542/// ```
  543. 543///
  544. 544/// ```mbt check
  545. 545/// test "doc_is_valid_2d_index_invalid" {
  546. 546/// assert_true(!@safe_math.is_valid_2d_index(-1, 5, 10, 20))
  547. 547/// }
  548. 548/// ```
  549. 549#inline
  550. 550pub fn is_valid_2d_index(
  551. 551 x : Int32,
  552. 552 y : Int32,
  553. 553 width : Int32,
  554. 554 height : Int32,
  555. 555) -> Bool where {
  556. 556 proof_ensure: result => valid_2d_index(x, y, width, height, result),
  557. 557} {
  558. 558● x >= 0 && x < width && y >= 0 && y < height
  559. 559}
  560. 560
  561. 561// ============================================================================
  562. 562// Section: 几何/旋转恒等性 Geometry/rotation identity
  563. 563// ============================================================================
  564. 564
  565. 565///|
  566. 566/// 判断 Rotate90 的连续次数是否为恒等变换。 Determine whether n consecutive Rotate90 operations result in identity.
  567. 567///
  568. 568/// 当 n 是 4 的倍数时,连续旋转 n 次 90° 回到原始状态。 When n is a multiple of 4, rotating 90° n times returns to the original state.
  569. 569///
  570. 570/// ✅ 形式化验证:证明结果等价于 n % 4 == 0。 ✅ Formal verification: proves result is equivalent to n % 4 == 0.
  571. 571///
  572. 572/// 参数 Parameters:
  573. 573/// - `n` - 旋转次数 Number of rotations
  574. 574///
  575. 575/// 返回 Return:
  576. 576/// - 是否为恒等变换 Whether it is an identity transformation
  577. 577///
  578. 578/// 示例 Example:
  579. 579/// ```mbt check
  580. 580/// test "doc_rotate90_identity" {
  581. 581/// assert_true(@safe_math.rotate90_power_is_identity(4))
  582. 582/// assert_true(@safe_math.rotate90_power_is_identity(8))
  583. 583/// assert_true(!@safe_math.rotate90_power_is_identity(3))
  584. 584/// }
  585. 585/// ```
  586. 586#inline
  587. 587pub fn rotate90_power_is_identity(
  588. 588 n : Int32,
  589. 589) -> Bool where {
  590. 590 proof_ensure: result => rotate90_identity(n, result),
  591. 591} {
  592. 592● n % 4 == 0
  593. 593}
  594. 594
  595. 595// ============================================================================
  596. 596// Section: 编解码核心算法 Codec core algorithms
  597. 597// 注意:以下函数使用位运算/方法调用,当前 moon prove 不支持在
  598. 598// 契约函数体中使用,因此不带 proof_ensure 契约。
  599. 599// 仍提供安全范围谓词供未来证明系统扩展时使用。
  600. 600//
  601. 601// Note: The following functions use bitwise operations/method calls,
  602. 602// which the current moon prove does not support in contract bodies,
  603. 603// so they do not carry proof_ensure contracts.
  604. 604// Safety range predicates are still provided for future proof system extensions.
  605. 605// ============================================================================
  606. 606
  607. 607///|
  608. 608/// PNG Paeth 预测函数。PNG Paeth predictor function.
  609. 609///
  610. 610/// 选择 a、b、c 中最接近预测值 p = a + b - c 的那个。 Selects the one among a, b, c closest to the predicted value p = a + b - c.
  611. 611/// 结果必为 {a, b, c} 之一(PNG 规范保证)。 The result is guaranteed to be one of {a, b, c} (PNG spec guarantee).
  612. 612///
  613. 613/// 参数 Parameters:
  614. 614/// - `a` - 左方像素 Left pixel
  615. 615/// - `b` - 上方像素 Above pixel
  616. 616/// - `c` - 左上方像素 Upper-left pixel
  617. 617///
  618. 618/// 返回 Return:
  619. 619/// - 预测值 Predicted value
  620. 620///
  621. 621/// 示例 Example:
  622. 622/// ```mbt check
  623. 623/// test "doc_paeth_predict_equal" {
  624. 624/// // 当 pa == pb == pc 时选 a assert_eq(@safe_math.paeth_predict(0, 0, 0), 0)
  625. 625
  626. 626///|
  627. 627/// }
  628. 628/// ```
  629. 629#inline
  630. 630pub fn paeth_predict(a : Int32, b : Int32, c : Int32) -> Int32 {
  631. 631● let p = a + b - c
  632. 632● let pa = (p - a).abs()
  633. 633● let pb = (p - b).abs()
  634. 634● let pc = (p - c).abs()
  635. 635 if pa <= pb && pa <= pc {
  636. 636● a
  637. 637● } else if pb <= pc {
  638. 638● b
  639. 639 } else {
  640. 640● c
  641. 641 }
  642. 642}
  643. 643
  644. 644///|
  645. 645/// QOI 哈希函数:将 RGBA 像素映射到 [0, 63] 的索引。 QOI hash function: maps RGBA pixel to an index in [0, 63].
  646. 646///
  647. 647/// 结果在 [0, 63] 范围内(QOI 规范保证)。 Result is guaranteed in [0, 63] range (QOI spec guarantee).
  648. 648///
  649. 649/// 参数 Parameters:
  650. 650/// - `r` - 红色通道 Red channel
  651. 651/// - `g` - 绿色通道 Green channel
  652. 652/// - `b` - 蓝色通道 Blue channel
  653. 653/// - `a` - 透明通道 Alpha channel
  654. 654///
  655. 655/// 返回 Return:
  656. 656/// - 哈希索引(0-63)Hash index (0-63)
  657. 657///
  658. 658/// 示例 Example:
  659. 659/// ```mbt check
  660. 660/// test "doc_qoi_hash" {
  661. 661/// let h = @safe_math.qoi_hash(255, 0, 0, 255)
  662. 662/// assert_true(h >= 0 && h < 64)
  663. 663/// }
  664. 664/// ```
  665. 665#inline
  666. 666pub fn qoi_hash(r : Int32, g : Int32, b : Int32, a : Int32) -> Int32 {
  667. 667● (r * 3 + g * 5 + b * 7 + a * 11) % 64
  668. 668}
  669. 669
  670. 670///|
  671. 671/// GIF 3-3-2 量化:将 RGB 像素映射到 256 色调色板索引。 GIF 3-3-2 quantization: maps RGB pixel to 256-color palette index.
  672. 672///
  673. 673/// 结果在 [0, 255] 范围内。 Result is guaranteed in [0, 255] range.
  674. 674///
  675. 675/// 参数 Parameters:
  676. 676/// - `r` - 红色通道(0-255)Red channel (0-255)
  677. 677/// - `g` - 绿色通道(0-255)Green channel (0-255)
  678. 678/// - `b` - 蓝色通道(0-255)Blue channel (0-255)
  679. 679///
  680. 680/// 返回 Return:
  681. 681/// - 调色板索引(0-255)Palette index (0-255)
  682. 682///
  683. 683/// 示例 Example:
  684. 684/// ```mbt check
  685. 685/// test "doc_quantize_332" {
  686. 686/// let idx = @safe_math.quantize_332(255, 128, 0)
  687. 687/// assert_true(idx >= 0 && idx <= 255)
  688. 688/// }
  689. 689/// ```
  690. 690#inline
  691. 691pub fn quantize_332(r : Int32, g : Int32, b : Int32) -> Int32 {
  692. 692● let r_level = (r >> 5) & 0x07
  693. 693 let g_level = (g >> 5) & 0x07
  694. 694 let b_level = (b >> 6) & 0x03
  695. 695 r_level * 32 + g_level * 4 + b_level
  696. 696}
  697. 697
  698. 698///|
  699. 699/// 汉明距离:计算两个整数在二进制表示下不同位的数量。 Hamming distance: counts the number of differing bits between two integers.
  700. 700///
  701. 701/// 结果 >= 0。 Result >= 0.
  702. 702///
  703. 703/// 参数 Parameters:
  704. 704/// - `a` - 第一个整数 First integer
  705. 705/// - `b` - 第二个整数 Second integer
  706. 706///
  707. 707/// 返回 Return:
  708. 708/// - 不同位的数量 Number of differing bits
  709. 709///
  710. 710/// 示例 Example:
  711. 711/// ```mbt check
  712. 712/// test "doc_hamming_distance" {
  713. 713/// // 0b1010 (10) vs 0b1100 (12): 2 bits differ
  714. 714/// assert_eq(@safe_math.hamming_distance(10, 12), 2)
  715. 715/// }
  716. 716/// ```
  717. 717///
  718. 718/// ```mbt check
  719. 719/// test "doc_hamming_distance_same" {
  720. 720/// assert_eq(@safe_math.hamming_distance(42, 42), 0)
  721. 721/// }
  722. 722/// ```
  723. 723#inline
  724. 724pub fn hamming_distance(a : Int32, b : Int32) -> Int32 {
  725. 725● let xor_val = a ^ b
  726. 726 let mut count = 0
  727. 727 let mut x = xor_val
  728. 728 while x > 0 {
  729. 729● count += x & 1
  730. 730 x = x >> 1
  731. 731 }
  732. 732 count
  733. 733}