image.domain\production_utils\production_utils.mbt

76.7% · 69 / 90 points · 441 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/// # 生产工具 production_utils/production_utils
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// production_utils.mbt:生产级工具函数
  7. 7// 提供统一的输入验证、错误处理、性能监控、内存安全等功能
  8. 8
  9. 9///|
  10. 10/// 图像验证结果
  11. 11#derive(Eq, Default, @debug.Debug)
  12. 12pub(all) struct ImageValidationResult {
  13. 13 is_valid : Bool
  14. 14 errors : Array[String]
  15. 15 warnings : Array[String]
  16. 16 width : Int32
  17. 17 height : Int32
  18. 18 channels : Int32
  19. 19 data_size : Int32
  20. 20 expected_data_size : Int32
  21. 21}
  22. 22
  23. 23///|
  24. 24pub extend ImageValidationResult with @debug.Debug::{to_repr}
  25. 25
  26. 26///|
  27. 27pub extend ImageValidationResult with Eq::{not_equal, equal}
  28. 28
  29. 29///|
  30. 30pub extend ImageValidationResult with Default::{default}
  31. 31
  32. 32///|
  33. 33/// 验证图像有效性
  34. 34pub fn validate_image(img : @types.Image) -> ImageValidationResult {
  35. 35● let errors : Array[String] = []
  36. 36 let warnings : Array[String] = []
  37. 37
  38. 38 // 验证尺寸
  39. 39 if img.width <= 0 {
  40. 40● errors.push("宽度必须大于0")
  41. 41 }
  42. 42 if img.height <= 0 {
  43. 43○ errors.push("高度必须大于0")
  44. 44 }
  45. 45 if img.width > 65535 {
  46. 46○ warnings.push("宽度超过65535,可能导致内存问题")
  47. 47 }
  48. 48 if img.height > 65535 {
  49. 49○ warnings.push("高度超过65535,可能导致内存问题")
  50. 50 }
  51. 51
  52. 52 // 验证通道数
  53. 53 if img.channels < 1 || img.channels > 4 {
  54. 54● errors.push("通道数必须在1-4之间")
  55. 55 }
  56. 56
  57. 57 // 验证数据大小
  58. 58 let expected_size = img.width * img.height * img.channels
  59. 59● let actual_size = img.data.length()
  60. 60 if actual_size != expected_size {
  61. 61● errors.push(
  62. 62 "数据大小不匹配:期望 " +
  63. 63● expected_size.to_string() +
  64. 64 ",实际 " +
  65. 65● actual_size.to_string(),
  66. 66 )
  67. 67 }
  68. 68
  69. 69 // 检查潜在的整数溢出
  70. 70 if img.width > 0 && img.height > 0 {
  71. 71● let pixel_count = img.width * img.height
  72. 72 if pixel_count / img.width != img.height {
  73. 73○ errors.push("像素计数溢出")
  74. 74 }
  75. 75 }
  76. 76
  77. 77 ImageValidationResult::{
  78. 78● is_valid: errors.length() == 0,
  79. 79 errors,
  80. 80 warnings,
  81. 81 width: img.width,
  82. 82 height: img.height,
  83. 83 channels: img.channels,
  84. 84 data_size: actual_size,
  85. 85 expected_data_size: expected_size,
  86. 86 }
  87. 87}
  88. 88
  89. 89///|
  90. 90/// 验证图像并在无效时抛出错误
  91. 91pub fn validate_image_or_raise(
  92. 92 img : @types.Image,
  93. 93) -> Unit raise @types.LoadError {
  94. 94● let result = validate_image(img)
  95. 95 if !result.is_valid {
  96. 96● let mut error_msg = "图像验证失败:"
  97. 97 for err in result.errors {
  98. 98● error_msg = error_msg + err + "; "
  99. 99 }
  100. 100 raise @types.LoadError::DecodeFailed(error_msg)
  101. 101 }
  102. 102}
  103. 103
  104. 104///|
  105. 105/// 验证图像通道数
  106. 106pub fn validate_channels(
  107. 107 img : @types.Image,
  108. 108 expected_channels : Array[Int32],
  109. 109) -> Bool {
  110. 110● for ch in expected_channels {
  111. 111● if img.channels == ch {
  112. 112● return true
  113. 113 }
  114. 114 }
  115. 115 false
  116. 116}
  117. 117
  118. 118///|
  119. 119/// 验证图像通道数并在无效时抛出错误
  120. 120pub fn validate_channels_or_raise(
  121. 121 img : @types.Image,
  122. 122 expected_channels : Array[Int32],
  123. 123 function_name : String,
  124. 124) -> Unit raise @types.LoadError {
  125. 125● if !validate_channels(img, expected_channels) {
  126. 126● let mut expected_str = ""
  127. 127● for i in 0..<expected_channels.length() {
  128. 128● if i > 0 {
  129. 129● expected_str = expected_str + ", "
  130. 130 }
  131. 131● expected_str = expected_str + expected_channels[i].to_string()
  132. 132 }
  133. 133 raise @types.LoadError::DecodeFailed(
  134. 134 function_name +
  135. 135 " 需要通道数为 [" +
  136. 136 expected_str +
  137. 137 "],实际为 " +
  138. 138● img.channels.to_string(),
  139. 139 )
  140. 140 }
  141. 141}
  142. 142
  143. 143///|
  144. 144/// 验证参数范围
  145. 145pub fn validate_range(
  146. 146 value : Double,
  147. 147 min : Double,
  148. 148 max : Double,
  149. 149 param_name : String,
  150. 150) -> Result[Unit, String] {
  151. 151● if value < min || value > max {
  152. 152● Result::Err(
  153. 153 param_name +
  154. 154 " 必须在 [" +
  155. 155● min.to_string() +
  156. 156 ", " +
  157. 157● max.to_string() +
  158. 158 "] 范围内,实际为 " +
  159. 159● value.to_string(),
  160. 160 )
  161. 161 } else {
  162. 162● Result::Ok(())
  163. 163 }
  164. 164}
  165. 165
  166. 166///|
  167. 167/// 验证参数范围并在无效时抛出错误
  168. 168pub fn validate_range_or_raise(
  169. 169 value : Double,
  170. 170 min : Double,
  171. 171 max : Double,
  172. 172 param_name : String,
  173. 173) -> Unit raise @types.LoadError {
  174. 174● let result = validate_range(value, min, max, param_name)
  175. 175● match result {
  176. 176● Result::Err(msg) => raise @types.LoadError::DecodeFailed(msg)
  177. 177● Result::Ok(_) => ()
  178. 178 }
  179. 179}
  180. 180
  181. 181///|
  182. 182/// 验证整数参数范围
  183. 183pub fn validate_int_range(
  184. 184 value : Int32,
  185. 185 min : Int32,
  186. 186 max : Int32,
  187. 187 param_name : String,
  188. 188) -> Result[Unit, String] {
  189. 189● if value < min || value > max {
  190. 190● Result::Err(
  191. 191 param_name +
  192. 192 " 必须在 [" +
  193. 193● min.to_string() +
  194. 194 ", " +
  195. 195● max.to_string() +
  196. 196 "] 范围内,实际为 " +
  197. 197● value.to_string(),
  198. 198 )
  199. 199 } else {
  200. 200● Result::Ok(())
  201. 201 }
  202. 202}
  203. 203
  204. 204///|
  205. 205/// 验证整数参数范围并在无效时抛出错误
  206. 206pub fn validate_int_range_or_raise(
  207. 207 value : Int32,
  208. 208 min : Int32,
  209. 209 max : Int32,
  210. 210 param_name : String,
  211. 211) -> Unit raise @types.LoadError {
  212. 212● let result = validate_int_range(value, min, max, param_name)
  213. 213● match result {
  214. 214● Result::Err(msg) => raise @types.LoadError::DecodeFailed(msg)
  215. 215● Result::Ok(_) => ()
  216. 216 }
  217. 217}
  218. 218
  219. 219///|
  220. 220pub let clamp_pixel_value : (Int32) -> Int32 = @safe_math.clamp_pixel_value
  221. 221
  222. 222///|
  223. 223pub fn clamp_pixel_value_double(value : Double) -> Double {
  224. 224● @safe_math.clamp_double(value, 0.0, 255.0)
  225. 225}
  226. 226
  227. 227///|
  228. 228pub let is_valid_index : (Int32, Int32) -> Bool = @safe_math.is_valid_index
  229. 229
  230. 230///|
  231. 231pub let is_valid_2d_index : (Int32, Int32, Int32, Int32) -> Bool = @safe_math.is_valid_2d_index
  232. 232
  233. 233///|
  234. 234/// 性能计时器
  235. 235#derive(Eq, Default, @debug.Debug)
  236. 236pub(all) struct PerformanceTimer {
  237. 237 start_time_ms : Double
  238. 238 end_time_ms : Double
  239. 239 elapsed_ms : Double
  240. 240 operation_name : String
  241. 241}
  242. 242
  243. 243///|
  244. 244pub extend PerformanceTimer with @debug.Debug::{to_repr}
  245. 245
  246. 246///|
  247. 247pub extend PerformanceTimer with Eq::{not_equal, equal}
  248. 248
  249. 249///|
  250. 250pub extend PerformanceTimer with Default::{default}
  251. 251
  252. 252///|
  253. 253/// 创建性能计时器
  254. 254pub fn create_performance_timer(operation_name : String) -> PerformanceTimer {
  255. 255● PerformanceTimer::{
  256. 256 start_time_ms: 0.0,
  257. 257 end_time_ms: 0.0,
  258. 258 elapsed_ms: 0.0,
  259. 259 operation_name,
  260. 260 }
  261. 261}
  262. 262
  263. 263///|
  264. 264/// 内存使用统计
  265. 265#derive(Eq, Default, @debug.Debug)
  266. 266pub(all) struct MemoryUsageStats {
  267. 267 allocated_bytes : Int32
  268. 268 freed_bytes : Int32
  269. 269 current_usage_bytes : Int32
  270. 270 peak_usage_bytes : Int32
  271. 271 allocation_count : Int32
  272. 272 free_count : Int32
  273. 273}
  274. 274
  275. 275///|
  276. 276pub extend MemoryUsageStats with @debug.Debug::{to_repr}
  277. 277
  278. 278///|
  279. 279pub extend MemoryUsageStats with Eq::{not_equal, equal}
  280. 280
  281. 281///|
  282. 282pub extend MemoryUsageStats with Default::{default}
  283. 283
  284. 284///|
  285. 285/// 创建内存使用统计
  286. 286pub fn create_memory_stats() -> MemoryUsageStats {
  287. 287● MemoryUsageStats::{
  288. 288 allocated_bytes: 0,
  289. 289 freed_bytes: 0,
  290. 290 current_usage_bytes: 0,
  291. 291 peak_usage_bytes: 0,
  292. 292 allocation_count: 0,
  293. 293 free_count: 0,
  294. 294 }
  295. 295}
  296. 296
  297. 297///|
  298. 298/// 错误码枚举
  299. 299/// `#non_exhaustive` 表示未来可能添加新构造器
  300. 300#derive(Eq)
  301. 301#non_exhaustive
  302. 302pub(all) enum ProductionErrorCode {
  303. 303 InvalidInput
  304. 304 OutOfMemory
  305. 305 IndexOutOfBounds
  306. 306 UnsupportedFormat
  307. 307 OperationFailed
  308. 308 Timeout
  309. 309 InternalError
  310. 310 Unknown
  311. 311}
  312. 312
  313. 313///|
  314. 314pub extend ProductionErrorCode with Eq::{not_equal, equal}
  315. 315
  316. 316///|
  317. 317/// 生产级错误
  318. 318pub(all) struct ProductionError {
  319. 319 code : ProductionErrorCode
  320. 320 message : String
  321. 321 function_name : String
  322. 322 timestamp_ms : Double
  323. 323 recoverable : Bool
  324. 324}
  325. 325
  326. 326///|
  327. 327/// 创建生产级错误
  328. 328pub fn create_production_error(
  329. 329 code : ProductionErrorCode,
  330. 330 message : String,
  331. 331 function_name : String,
  332. 332) -> ProductionError {
  333. 333● ProductionError::{
  334. 334 code,
  335. 335 message,
  336. 336 function_name,
  337. 337 timestamp_ms: 0.0,
  338. 338 recoverable: code != ProductionErrorCode::InternalError,
  339. 339 }
  340. 340}
  341. 341
  342. 342///|
  343. 343/// 重试配置
  344. 344#derive(Eq, Default, @debug.Debug)
  345. 345pub(all) struct RetryConfig {
  346. 346 max_retries : Int32
  347. 347 initial_delay_ms : Double
  348. 348 max_delay_ms : Double
  349. 349 backoff_factor : Double
  350. 350 retry_on_timeout : Bool
  351. 351 retry_on_internal_error : Bool
  352. 352}
  353. 353
  354. 354///|
  355. 355pub extend RetryConfig with @debug.Debug::{to_repr}
  356. 356
  357. 357///|
  358. 358pub extend RetryConfig with Eq::{not_equal, equal}
  359. 359
  360. 360///|
  361. 361pub extend RetryConfig with Default::{default}
  362. 362
  363. 363///|
  364. 364/// 创建默认重试配置
  365. 365pub fn create_default_retry_config() -> RetryConfig {
  366. 366● RetryConfig::{
  367. 367 max_retries: 3,
  368. 368 initial_delay_ms: 100.0,
  369. 369 max_delay_ms: 5000.0,
  370. 370 backoff_factor: 2.0,
  371. 371 retry_on_timeout: true,
  372. 372 retry_on_internal_error: false,
  373. 373 }
  374. 374}
  375. 375
  376. 376///|
  377. 377/// 计算重试延迟
  378. 378pub fn calculate_retry_delay(config : RetryConfig, attempt : Int32) -> Double {
  379. 379● let mut factor = 1.0
  380. 380 for _ in 0..<attempt {
  381. 381● factor = factor * config.backoff_factor
  382. 382 }
  383. 383 let base_delay = config.initial_delay_ms * factor
  384. 384 if base_delay > config.max_delay_ms {
  385. 385○ config.max_delay_ms
  386. 386 } else {
  387. 387● base_delay
  388. 388 }
  389. 389}
  390. 390
  391. 391///|
  392. 392/// 验证结果转字符串
  393. 393pub fn validation_result_to_string(result : ImageValidationResult) -> String {
  394. 394● let mut report = "## 图像验证报告\n\n"
  395. 395 report = report + "| 指标 | 值 |\n|------|------|\n"
  396. 396 report = report +
  397. 397 "| 验证结果 | " +
  398. 398◐ (if result.is_valid { "通过" } else { "失败" }) +
  399. 399 " |\n"
  400. 400● report = report + "| 宽度 | " + result.width.to_string() + " |\n"
  401. 401● report = report + "| 高度 | " + result.height.to_string() + " |\n"
  402. 402● report = report + "| 通道数 | " + result.channels.to_string() + " |\n"
  403. 403● report = report + "| 数据大小 | " + result.data_size.to_string() + " |\n"
  404. 404 report = report +
  405. 405 "| 期望数据大小 | " +
  406. 406● result.expected_data_size.to_string() +
  407. 407 " |\n"
  408. 408
  409. 409● if result.errors.length() > 0 {
  410. 410○ report = report + "\n### 错误\n\n"
  411. 411 for err in result.errors {
  412. 412○ report = report + "- " + err + "\n"
  413. 413 }
  414. 414 }
  415. 415
  416. 416● if result.warnings.length() > 0 {
  417. 417○ report = report + "\n### 警告\n\n"
  418. 418 for warn in result.warnings {
  419. 419○ report = report + "- " + warn + "\n"
  420. 420 }
  421. 421 }
  422. 422
  423. 423 report
  424. 424}
  425. 425
  426. 426///|
  427. 427/// 生产级错误转字符串
  428. 428pub fn production_error_to_string(err : ProductionError) -> String {
  429. 429● let code_str = match err.code {
  430. 430● ProductionErrorCode::InvalidInput => "无效输入"
  431. 431○ ProductionErrorCode::OutOfMemory => "内存不足"
  432. 432○ ProductionErrorCode::IndexOutOfBounds => "索引越界"
  433. 433○ ProductionErrorCode::UnsupportedFormat => "不支持的格式"
  434. 434○ ProductionErrorCode::OperationFailed => "操作失败"
  435. 435○ ProductionErrorCode::Timeout => "超时"
  436. 436○ ProductionErrorCode::InternalError => "内部错误"
  437. 437○ _ => "未知错误"
  438. 438 }
  439. 439
  440. 440 "[" + code_str + "] " + err.function_name + ": " + err.message
  441. 441}