Compare commits

...
38 Commits
Author SHA1 Message Date
minglipro ed7f034ca0 v5.7.3
Gitea Actions Build / Build (push) Waiting to run
- exception: HttpStatusException、HttpStatusExceptionEnum 及 30 个 httpErrorXXX 快捷函数补齐 KDoc;快捷函数默认 message 改为对应状态短语

- exception: JsonFormatException 从 JsonParserException.kt 拆分为独立文件

- string: 新增 stringBuilder { ... } 工厂函数
2026-11-23 16:55:25 +08:00
minglipro 53e30351a7 v5.7.2
Gitea Actions Build / Build (push) Waiting to run
- spring: 新增 @FastServiceScan 扫描注解与 FastServiceScanRegistrar / FastServiceScannerProcessor,支持扫描 FastBaseIService 和 FastBaseIServiceNew3518 两个基类、value/basePackages 别名、缺失基类跳过

- spring: ApplicationDestroyedRunner / ApplicationReadyEventListener / ApplicationStartedRunner / ContextClosedEventListener 迁移为 Kotlin,弃用注解补全 @Deprecated + ReplaceWith

- build: 新增 VERSIONSTYPE 控制 RELEASES/SNAPSHOT 版本后缀,补充 Spring / MyBatis-Plus 测试依赖

- test: 新增 FastServiceScanRegistrarTest 5 个用例与 FastServiceScannerProcessorTest 2 个用例
2026-11-23 15:23:07 +08:00
minglipro d43f273aa7 v5.7.0
Gitea Actions Build / Build (push) Waiting to run
- lock: 新增 RedisLock 分布式锁工具(Redisson 异步 API、协程挂起等待、看门狗续期、公平锁、tryWithLock)与 RedisLockTimeoutException

- build: 改用 providers.gradleProperty / 显式模板变量,消除 Gradle 9 配置期弃用警告;.gitignore 的 *lock* 改为 *.lock

- test: 新增 RedisLockTest 7 个用例
2026-11-23 10:44:29 +08:00
minglipro 838a03560e docs(changelog): 补充 5.6.0 变更记录
Gitea Actions Build / Build (push) Waiting to run
2026-11-23 09:59:34 +08:00
minglipro c169064637 v5.6.0
Gitea Actions Build / Build (push) Waiting to run
- thread: 重构 GlobalThreadPool(统一池配置、shutdownAll/关闭钩子、Debug 日志、Java 友好 API),调度器改为 kotlinx 共享调度器 + 独立 cpu 池,新增 SuspendUtils

- collection: 新增 ArrayDeque 工厂方法,收紧 toArray 泛型

- stream: toArray 返回类型补 jspecify NonNull;移除 ForEach;更新依赖与版权年份
2026-11-23 09:57:42 +08:00
minglipro ae41240806 v5.5.5
Gitea Actions Build / Build (push) Canceled after 0s
2026-11-18 19:46:57 +08:00
minglipro cb7fdb4f19 添加 import org.springframework.context.event.EventListener 2026-11-18 19:46:10 +08:00
minglipro 3d1896bd64 删除
import com.mingliqiye.utils.springboot.annotation.ContextClosedEventListener
2026-11-18 19:46:00 +08:00
minglipro 0e0d2b03cc 修复
Okhttp3AutoConfiguration->handleContextClosed
不触发
2026-11-18 19:45:21 +08:00
minglipro 2e54e3d651 chore(release): 发布 5.5.4
Gitea Actions Build / Build (push) Canceled after 0s
版本号升级至 5.5.4,CHANGELOG 记录 hash 哈希体系、springboot 注解
迁移、Log4j2 XSD、MediaType 格式化与 signing 笔误修复。
2026-11-18 18:57:59 +08:00
minglipro 528802d881 fix(build): 修正 signing.secretKeyRingFile 属性名笔误 2026-11-18 18:57:59 +08:00
minglipro 487f956f4f style(http): MediaType 枚举项之间补充空行 2026-11-18 18:57:59 +08:00
minglipro 64e3af50ed test(resources): 新增 Log4j2 配置 XSD 并接入 Schema 校验
非官方 Log4j2 配置 Schema,覆盖 21 种 Appender、13 种 Layout、
11 种 Filter、滚动策略与清理条件等;未知插件元素以开放内容模型放行。
2026-11-18 18:57:59 +08:00
minglipro 7760201639 refactor(springboot): 事件监听注解迁移为 Java 实现
新增 ApplicationReadyEventListener、ContextClosedEventListener;
ApplicationStartedRunner、ApplicationDestroyedRunner 标记废弃;
移除 Kotlin 版注解与 ApplicationListener、ApplicationRunnerData;
Okhttp3AutoConfiguration 改用 @ContextClosedEventListener。
2026-11-18 18:57:51 +08:00
minglipro 713342bbc6 feat(hash): 新增 HashCodec 哈希体系与 13 种 JDK 标准算法实现
HashCodec 接口只需重写 hash(InputStream),其余重载、十六进制输出与
常量时间校验均由默认实现提供;MessageDigestCodec 流式基类 8KB 缓冲、
恒定内存、不关闭调用方流;提供 HashUtils 懒加载单例与 HashType 枚举,
TestHash 覆盖已知向量、算法一致性、流生命周期与文件/路径重载。
2026-11-18 18:57:46 +08:00
minglipro 988a0c0dc1 v5.5.3
Gitea Actions Build / Build (push) Canceled after 0s
2026-11-18 00:03:40 +08:00
minglipro 44ea9b114d v5.4.5 修复 java.lang.NoClassDefFoundError: com/google/gson/JsonParseException 2026-11-18 00:03:21 +08:00
minglipro 3bacf90940 v5.4.5 修复 java.lang.NoClassDefFoundError: com/google/gson/JsonParseException
Gitea Actions Build / Build (push) Canceled after 0s
2026-11-18 00:02:34 +08:00
minglipro 28a2987dc3 fix(json): 修正 BaseJsonWriter 中 BaseJsonJudgment 的导入路径
Gitea Actions Build / Build (push) Canceled after 0s
2026-11-17 21:18:25 +08:00
minglipro 8069de37f2 feat(tuple): 实现 Tuple.compareTo 字典序比较并发布 5.5.2
替换原 TODO 占位实现:同类型可比较元素按自然顺序逐位比较,其余按
字符串形式回退,公共前缀相等时短元组在前;新增 TestTuple 6 个用例
全部通过;CHANGELOG 增加 5.5.2 条目,VERSIONS 5.5.1 -> 5.5.2。
2026-11-17 21:17:01 +08:00
minglipro 51eb838a36 docs: 补全 src 全部 Kotlin KDoc 与 Java Javadoc,版本升级至 5.5.1
Gitea Actions Build / Build (push) Canceled after 0s
为所有缺失文档的公开声明补充中文 KDoc/Javadoc(含 exception、json、
springboot、tuple 生成类、MediaType 枚举项及测试),仅插入注释不改代码;
gradle.properties VERSIONS 5.4.4 -> 5.5.1。
2026-11-17 21:07:58 +08:00
minglipro d0887ea1f7 refactor(json): 重构 JSON 转换器体系,新增 reader/writer/judgment 抽象
移除按类型划分的 BaseJson*Converter,统一由 BaseJsonConverter 与
JsonConverterUtils 处理;为 Jackson2/Jackson3 分别实现 JsonReader、
JsonWriter 与 ReaderJudgment,并同步更新 SpringBoot 自动配置与测试。
2026-11-17 20:35:19 +08:00
minglipro 16da482de7 v5.4.4
Gitea Actions Build / Build (push) Canceled after 0s
2026-11-17 10:25:13 +08:00
minglipro aa83f575b1 v5.4.4
Gitea Actions Build / Build (push) Canceled after 0s
2026-11-17 10:16:43 +08:00
minglipro 510ff69e2c v5.4.3
Gitea Actions Build / Build (push) Canceled after 0s
2026-11-10 16:53:35 +08:00
minglipro 184db461d7 修复 JSONA.jsonApi 编译错误
Gitea Actions Build / Build (push) Canceled after 0s
2026-11-07 13:59:42 +08:00
minglipro 535c03d14a feat(mybatisplus): 新增 FastBaseIServiceNew3518 并发布 mingli-utils 5.4.2
Gitea Actions Build / Build (push) Canceled after 0s
2026-11-07 13:55:20 +08:00
minglipro 5714aef444 style: 全项目统一 Tab 缩进并补全尾随逗号 2026-11-07 13:54:46 +08:00
minglipro 7a3bc01b11 a 2026-11-07 13:54:05 +08:00
minglipro 792ddf0255 feat(mybatisplus): 新增 FastBaseIService 并发布 mingli-utils 5.4.0
Gitea Actions Build / Build (push) Canceled after 0s
- 新增 FastBaseIService 服务层便捷基类,与 FastBaseMapper 对齐常用增删改查,移除旧的 BaseMapperQuery
- Jackson 自动配置改用 Jackson2ObjectMapperBuilderCustomizer Bean 注册模块,避免直接依赖 ObjectMapper
- SpringBeanUtils 新增 lazyBean 延迟获取 Bean 便捷函数
- SystemUtil 新增 lineSeparator 相关常量并整理链式调用格式
- FileUtils.writeLines(charset) 修复自递归问题
- build.gradle.kts 增加 mybatis-plus-spring 编译依赖
2026-10-28 23:36:35 +08:00
minglipro f4025cbad9 chore(release): 发布 mingli-utils 5.3.7
Gitea Actions Build / Build (push) Canceled after 0s
配合 FastBaseMapper 便捷函数补全与列条件 bug 修复提升补丁版本号
2026-10-27 10:35:30 +08:00
minglipro eaf7ee7a31 docs(mybatisplus): 为 FastBaseMapper 接口成员补全 KDoc 并修复列条件 bug
Gitea Actions Build / Build (push) Canceled after 0s
- 为 qw/uw/lqw/luw、selectListByColumn(s)、selectOneByColumn、existsByColumn、
  selectMapByColumn、deleteByColumn 及 Tuple 内部类补全文档注释
- 修复 existsByColumn 误用字面量 "existsByColumn" 作为比较值,改为传入的 value
- 修复 deleteByColumn(Collection) 误用 eq 匹配集合,改为 in 条件
2026-10-27 10:33:14 +08:00
minglipro 38ad9884d0 refactor(mybatisplus): 优化 FastBaseMapper 并补充便捷查询函数
- 修复集合查询误用 eq 的问题,改为 in 条件
- 将接口内失效的成员扩展 qw/uw/qcw/ucw 迁移至 companion 并加显式返回类型
- 用显式类型参数消除 ktQueryChain/ktUpdateChain 构造器重载歧义
- 新增 ktQueryChain/ktUpdateChain、update(entity)、selectPage(current,size)、
  selectCount、exists、delete、selectListByColumns、selectOneByColumn、
  existsByColumn、deleteByColumn 等便捷函数,deleteByColumn 对空集合返回 0 以防误删全表
2026-10-26 23:37:32 +08:00
minglipro 0e5ce5597b a 2026-10-26 23:22:29 +08:00
minglipro 85fd391849 a
Gitea Actions Build / Build (push) Canceled after 0s
2026-10-22 22:09:50 +08:00
minglipro 390afa5462 Merge pull request 'feat(thread): 新增线程工具集与线程池构建体系' (#1) from feat/thread-tools into master
Gitea Actions Build / Build (push) Canceled after 0s
Reviewed-on: #1
2026-10-20 20:11:05 +08:00
minglipro 31987b9b14 a 2026-10-20 20:05:40 +08:00
minglipro 474071e43b feat(thread): 新增线程工具集与线程池构建体系
- ThreadPoolBuilder: DSL 风格线程池构建器,含 fixed/single/cached/io/cpu/scheduled 预设
- GlobalThreadPool: 全局 IO/CPU/定时三类共享线程池及便捷提交函数
- ThreadPoolMonitor: 线程池运行快照与周期监控
- ThreadPoolExt: ExecutorService/Future/CompletableFuture 便捷扩展
- AsyncTasks: 并行执行、竞速执行、重试与定时任务编排
- ThreadLocalDelegates: ThreadLocal 属性委托
- ThreadExt: Thread/Runnable 扩展与守护线程便捷创建
- ThreadUtils 增强: 休眠、线程枚举、全线程栈转储
- ThreadEvent 增强: operator invoke、属性委托、isSet 与超时取数
- 移除 pool 包旧 ThreadPool.kt
- 新增 5 个测试类共 83 个单元测试
2026-10-19 21:09:57 +08:00
283 changed files with 66275 additions and 37616 deletions
+1 -1
View File
@@ -43,6 +43,6 @@ bin/
log log
.idea .idea
node_modules node_modules
*lock* *.lock
.kotlin .kotlin
secret.gpg secret.gpg
+206
View File
@@ -0,0 +1,206 @@
# Changelog
![Maven Central](https://img.shields.io/maven-metadata/v.svg?metadataUrl=https://repository.mingliqiye.com/repository/maven-public/com/mingliqiye/utils/mingli-utils/maven-metadata.xml&label=Mingliqiye%20Maven%20Public)
本文件记录 mingli-utils 各版本的主要变更。
## [5.7.3] - 2026-11-23
### 新增
- **string**:新增 `stringBuilder { ... }` 工厂函数,通过 `StringBuilder().apply { ... }`
创建并初始化 `StringBuilder`。
### 变更
- **exception**:`HttpStatusException`、`HttpStatusExceptionEnum` 及 30 个
`httpErrorXXX()` 快捷函数补齐 KDoc(状态码、参数、抛出异常);快捷函数的默认
`message` 从 `null` 改为对应状态短语(如 `"Bad Gateway"`、`"Not Found"`),
未显式传参时异常消息不再为空。
- **exception**:`JsonFormatException` 从 `JsonParserException.kt` 拆分为独立文件,
包名和公开 API 不变;`JsonParserException.kt` 只保留解析异常。
## [5.7.2] - 2026-11-23
### 新增
- **spring**:新增 `@FastServiceScan` 注解及 `FastServiceScanRegistrar`、
`FastServiceScannerProcessor`——扫描继承 `FastBaseIService` 或 `FastBaseIServiceNew3518`
的具体类并注册为 Spring Bean;仅在启动类/配置类标注该注解时生效,扫描时机在所有
`BeanDefinitionRegistryPostProcessor`(包括 `@MapperScan` 的 `MapperScannerConfigurer`)之后。
支持 `value` / `basePackages` / `basePackageClasses`,`value` 与 `basePackages` 通过
`@AliasFor` 互为别名;未指定包时使用标注类所在包;已标注 `@Component` / `@Service`
的类自动跳过,避免重复注册。
- **test**:新增 `FastServiceScanRegistrarTest`(5 个用例)与
`FastServiceScannerProcessorTest`(2 个用例,覆盖两个基类与某个基类缺失时的跳过逻辑)。
### 变更
- **spring**:`ApplicationDestroyedRunner`、`ApplicationReadyEventListener`、
`ApplicationStartedRunner`、`ContextClosedEventListener` 由 Java 迁移为 Kotlin 实现,
包名、属性及 `@AliasFor` 关系保持不变。
- **spring**:`ApplicationDestroyedRunner` / `ApplicationStartedRunner` 补全
`@Deprecated` + `ReplaceWith`,IDE 可一键替换为 `ContextClosedEventListener` /
`ApplicationReadyEventListener`;旧 Java 版本只有 `@Deprecated(since = ...)`。
- **build**:新增 `VERSIONSTYPE`(`r` = RELEASES,`s` = SNAPSHOT)控制版本后缀;
补充 Spring / MyBatis-Plus 测试依赖。
### 修复
- **spring**:`FastServiceScannerProcessor` 改为按类名探测两个服务基类,
仅引入一套 MyBatis-Plus 时只跳过缺失的基类,不再因类字面量加载父类失败抛出
`NoClassDefFoundError`。
### 注意
- 事件监听注解的 `defaultExecution` 属性仅在 Spring Framework 6.2+ 中提供;
在 Spring 5.3 下解析这些组合注解会抛出 `AnnotationConfigurationException`,使用方需按实际
Spring 版本选择。
## [5.7.0] - 2026-11-23
### 新增
- **lock**:新增 `RedisLock` Redis 分布式锁工具——基于 Redisson 异步 API 实现协程挂起式加锁,
等待期间不占用线程;默认启用看门狗自动续期,支持公平锁、自定义 key 前缀与固定租期;
提供 `withLock`(等待获取)与 `tryWithLock`(抢不到立即返回 `null`);
新增 `RedisLockTimeoutException`。Redisson 为可选依赖(`compileOnly`),
使用方需自行引入(建议 Redisson 3.13+ / 4.x)。
### 变更
- **build**:`build.gradle.kts` 与 `settings.gradle.kts` 移除已废弃的 `project.properties`、
`settings.extra` 委托写法,改用 `providers.gradleProperty` 与显式访问器;
`processResources` 的模板展开改为显式变量表,消除 Gradle 9 的配置期弃用警告。
- **build**:`.gitignore` 的 `*lock*` 规则改为 `*.lock`,避免把新增的 `lock` 包整体忽略。
### 测试
- 新增 `RedisLockTest`(7 个用例),通过动态代理模拟 Redisson 客户端,
覆盖正常加锁释放、等待超时、跳过执行、公平锁、业务异常仍释放、wait/lease 透传。
## [5.6.0] - 2026-11-23
### 新增
- **thread**:新增 `SuspendUtils` 协程工具——`CoroutineContext.withContext`、
`CoroutineContext.runBlocking`(按接收者上下文执行)与顶层 `runBlocking`
(使用调用线程的事件循环)、`asCompletableDeferred`。
- **thread**:`GlobalThreadPool` 新增 `mainDispatcher` / `ioDispatcher` / `cpuDispatcher`、
`pools()`、`snapshotAll()`、`isShutdown`,并自动注册 JVM 关闭钩子——
进程正常退出时优雅关闭全部池(最多等待 5 秒,超时强制关闭)。
- **thread**:`runAsync` / `callAsync` / `computeAsync` / `runAsyncAwait` / `callAsyncAwait`
移入 `GlobalThreadPool` 并加 `@JvmStatic`;参数改为 `Runnable` / `Callable`,
Kotlin 与 Java 均可直接使用 lambda。
- **thread**:新增 `namedThreadFactory`;`ioThreadPool` / `cpuThreadPool` /
`scheduledThreadPool` 增加 `daemon` 与 `rejectedHandler` 参数。
- **collection**:新增 `newArrayDeque()` 的三个重载。
### 变更
- **thread**:重构 `GlobalThreadPool`——main / io / cpu / scheduled 统一守护线程与池配置;
`shutdownAll` 覆盖全部池、改用统一截止时间、幂等、超时 `shutdownNow` 并返回是否正常终止;
全局池关闭后提交任务抛出 `RejectedExecutionException`;scheduled 开启 `removeOnCancelPolicy`、
关闭时丢弃未到期延迟任务;补充池与调度器初始化、拒绝策略、关闭流程及关闭钩子的 Debug 日志。
- **thread**:`mainDispatcher` / `ioDispatcher` 复用 kotlinx-coroutines 共享调度器
(命名限流视图),`cpuDispatcher` 绑定独立 cpu 池;`ThreadPoolBuilder` 抽出
`namedThreadFactory` 供各线程池复用。
- **stream**:`SuperStream.toArray` 返回类型补充 jspecify `@NonNull`;
`Collection.toArray` 泛型收紧为 `T : Any`。
- 移除 `ForEach`;更新依赖与版权年份。
### 修复
- **thread**:`CoroutineContext.runBlocking` 未使用接收者上下文,行为与普通 `runBlocking` 相同。
- **thread**:全局池关闭后任务被静默丢弃、`submit` 返回永不完成 `Future` 的问题。
### 测试
- 新增 `SuspendUtilsTest`;补充 `AsyncTasksTest` 中全局池、调度器与关闭钩子相关用例。
## [5.5.4] - 2026-11-18
### 新增
- **hash**:新增 `HashCodec` 哈希编解码器接口——实现类只需重写 `hash(InputStream)` 一个方法,
字节数组/字符串/文件/路径重载、十六进制输出(`hashHex`)与基于 `MessageDigest.isEqual`
的常量时间校验(`verifyHash`)均由默认实现提供;新增 `MessageDigestCodec` 流式基类
(8KB 缓冲、恒定内存、不关闭调用方流)及 13 种 JDK 标准算法实现
(MD2、MD5、SHA-1、SHA-224/256/384/512、SHA-512/224、SHA-512/256、SHA3-224/256/384/512);
提供 `HashUtils` 懒加载单例(`MD2`~`SHA512256`)与 `HashType` 枚举;
新增 `TestHash` 测试覆盖已知向量、全部算法一致性、流生命周期与文件/路径重载。
- **test**:新增非官方 Log4j2 配置 XSD(覆盖 21 种 Appender、13 种 Layout、11 种 Filter、
滚动策略与清理条件等,未知插件元素以开放内容模型放行),`log4j2.xml` 接入 Schema 校验。
### 变更
- **springboot**:事件监听注解迁移为 Java 实现——新增 `ApplicationReadyEventListener`、
`ContextClosedEventListener`;`ApplicationStartedRunner`、`ApplicationDestroyedRunner`
标记为废弃;移除 Kotlin 版注解及 `ApplicationListener`、`ApplicationRunnerData`;
`Okhttp3AutoConfiguration` 改用 `@ContextClosedEventListener`。
- **http**:`MediaType` 枚举项之间补充空行(纯格式化,无内容变更)。
### 修复
- **build**:修正 `signing.secretKeyRingFile` 属性名笔误(误插入空格)。
### 文档
- hash 包全部接口、类、枚举与懒加载单例补全中文 KDoc;
4 个 Spring Boot 事件监听注解补全 Javadoc。
## [5.5.2] - 2026-11-17
### 新增
- **tuple**:实现 `Tuple.compareTo` 字典序比较——同类型可比较元素按自然顺序,
其余按字符串形式比较;公共前缀相等时元素个数较少的元组在前。
新增 `TestTuple` 测试覆盖 6 种比较场景。
## [5.5.1] - 2026-11-17
### 新增
- **json**:新增 `reader` / `witer` / `judgment` 三组抽象,为 Jackson2 与 Jackson3 分别提供
`JsonReader`、`JsonArrayReader`、`JsonObjectReader`、`JsonWriter`、`ArrayWriter`、`ObjectWriter`
与 `ReaderJudgment` 实现(`BaseJsonReader` / `BaseJsonWriter` / `BaseJsonJudgment` 等基类)。
- **exception**:新增 `JsonFormatException`,表示 JSON 格式错误,继承自 `JsonException`。
- **time**:`DateTime.now(zone)` 支持指定时区;新增 `DateTime.atZone(zoneId)` 时区转换方法,
`toString()` 输出包含 `zoneId`。
### 变更
- **json**:重构转换器体系——移除按类型划分的 `BaseJsonIntConverter`、`BaseJsonStringConverter`
等 10 个转换器及 `JsonConverter` 接口,统一由 `BaseJsonConverter` 与 `JsonConverterUtils` 处理;
简化 `DateTimeJsonConverter`、`UUIDJsonConverter`、`NetworkEndpointJsonConverter` 与
Jackson2/Jackson3 序列化/反序列化桥接实现;精简 `JSONA` 与 `JsonApi` 门面。
- **tuple**:`Tuple` 声明实现 `Comparable<Tuple>`;迭代器改为基于 `toMutableList()` 的简化实现。
- **springboot**:`JsonAutoConfiguration` 与 `JacksonJsonBuilder` / `JacksonJsonBuilderImpl`
同步适配新的 JSON 转换器体系。
### 文档
- 补全 src 下全部 Kotlin 文件的中文 KDoc 与 Java 文件的 Javadoc(约 1.3 万处),
覆盖 exception、json、springboot、mybatis/mybatisplus、thread/netty/http、
Tuple1~Tuple100 生成类、MediaType 全部枚举项及测试代码;已有文档保持不变。
## [5.4.4] - 2026-11-17
- 构建脚本调整(build.gradle.kts 发布配置完善)。
- SpringBoot 自动配置重构:新增 `JsonAutoConfiguration` 与 `JacksonBuilder`,
精简 Jackson2/Jackson3 JsonApi 自动配置。
## [5.4.3] - 2026-11-17
- 新增 `JacksonJsonBuilder` / `JacksonJsonBuilderImpl` 构建器。
- `DateTime`、`UUID` 小幅调整;补充 log4j2 测试配置。
## [5.4.2] - 2026-11
- 修复 `JSONA.jsonApi` 编译错误。
- **mybatisplus**:新增 `FastBaseIServiceNew3518`(适配 MyBatis-Plus 3.5.18)。
## [5.4.0] - 2026-11
- **mybatisplus**:新增 `FastBaseIService`。
- 全项目统一 Tab 缩进并补全尾随逗号。
+1 -1
View File
@@ -1,5 +1,5 @@
mingli-utils mingli-utils
Copyright 2025 mingliqiye Copyright 2026 mingliqiye
This product includes software developed by third parties. This product includes software developed by third parties.
The original copyright notices and licenses are reproduced below. The original copyright notices and licenses are reproduced below.
+64 -22
View File
@@ -16,13 +16,37 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils * ModuleName mingli-utils
* CurrentFile build.gradle.kts * CurrentFile build.gradle.kts
* LastUpdate 2026-10-11 16:44:37 * LastUpdate 2026-11-23 15:17:59
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
import java.time.LocalDateTime import java.time.LocalDateTime
import java.time.format.DateTimeFormatter import java.time.format.DateTimeFormatter
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils
* CurrentFile build.gradle.kts
* LastUpdate 2026-11-17 10:18:28
* UpdateUser MingLiPro
*/
plugins { plugins {
idea idea
java java
@@ -35,11 +59,13 @@ plugins {
id("org.jetbrains.dokka-javadoc") version "2.1.0" id("org.jetbrains.dokka-javadoc") version "2.1.0"
kotlin("plugin.spring") version "2.1.0" kotlin("plugin.spring") version "2.1.0"
} }
val GROUPSID = project.properties["GROUPSID"] as String val GROUPSID = providers.gradleProperty("GROUPSID").get()
val VERSIONS = project.properties["VERSIONS"] as String val VERSION = providers.gradleProperty("VERSIONS").get()
val ARTIFACTID = project.properties["ARTIFACTID"] as String val ARTIFACTID = providers.gradleProperty("ARTIFACTID").get()
val JDKVERSIONS = (project.properties["JDKVERSIONS"] as String).toInt() val JDKVERSIONS = providers.gradleProperty("JDKVERSIONS").get().toInt()
val VERSIONSTYPE = providers.gradleProperty("VERSIONSTYPE").get()
val VERSIONS =
VERSION + if (VERSIONSTYPE == "s") "-SNAPSHOT" else if (VERSIONSTYPE == "r") "" else error("VERSIONSTYPE is not supported in gradle.properties $VERSIONSTYPE")
group = GROUPSID group = GROUPSID
version = VERSIONS version = VERSIONS
@@ -61,7 +87,8 @@ kotlin {
repositories { repositories {
mavenLocal() mavenLocal()
maven { maven {
url = uri("https://maven.mingliqiye.com/") name = "mingliqiye-public"
url = uri("https://repository.mingliqiye.com/repository/maven-public/")
} }
mavenCentral() mavenCentral()
} }
@@ -84,8 +111,20 @@ dependencies {
compileOnly("net.java.dev.jna:jna:5.17.0") compileOnly("net.java.dev.jna:jna:5.17.0")
compileOnly("org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.8") compileOnly("org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.8")
compileOnly("com.baomidou:mybatis-plus-extension:3.5.15") compileOnly("com.baomidou:mybatis-plus-extension:3.5.15")
compileOnly("com.baomidou:mybatis-plus-jsqlparser:3.5.15")
compileOnly("com.baomidou:mybatis-plus-spring:3.5.9")
compileOnly("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2")
compileOnly("org.jetbrains.kotlinx:kotlinx-coroutines-reactor:1.10.2")
compileOnly("org.redisson:redisson:4.8.0")
testImplementation("org.junit.jupiter:junit-jupiter:5.7.1") testImplementation("org.junit.jupiter:junit-jupiter:5.7.1")
testRuntimeOnly("org.junit.platform:junit-platform-launcher") testRuntimeOnly("org.junit.platform:junit-platform-launcher")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2")
testImplementation(fileTree("libs"))
testImplementation("com.baomidou:mybatis-plus-core:3.5.15")
testImplementation("com.baomidou:mybatis-plus-extension:3.5.15")
testImplementation("com.baomidou:mybatis-plus-spring:3.5.9")
testImplementation("org.springframework:spring-context:5.3.39")
testImplementation("org.redisson:redisson:4.8.0")
testImplementation("com.mingliqiye.logger:logger-log4j2:1.0.9") testImplementation("com.mingliqiye.logger:logger-log4j2:1.0.9")
testImplementation("com.google.code.gson:gson:2.13.2") testImplementation("com.google.code.gson:gson:2.13.2")
@@ -158,32 +197,31 @@ tasks.withType<org.gradle.jvm.tasks.Jar> {
} }
val isJdk8Build = project.findProperty("buildForJdk8") == "true" val isJdk8Build = project.findProperty("buildForJdk8") == "true"
dokka {
pluginsConfiguration.html {
customAssets.from("logo.png")
}
}
tasks.register<Jar>("javaDocJar") { tasks.register<Jar>("javaDocJar") {
group = "build" group = "build"
archiveClassifier.set("javadoc-dec") archiveClassifier.set("javadoc")
dependsOn("dokkaGeneratePublicationJavadoc") dependsOn("dokkaGenerateJavadoc")
from(buildDir.resolve("dokka/javadoc")) from(buildDir.resolve("dokka/javadoc"))
} }
tasks.register<Jar>("kotlinDocJar") { tasks.register<Jar>("kotlinDocJar") {
group = "build" group = "build"
archiveClassifier.set("javadoc") archiveClassifier.set("kotlindoc")
dependsOn("dokkaGeneratePublicationHtml") dependsOn("dokkaGeneratePublicationHtml")
from(buildDir.resolve("dokka/html")) from(buildDir.resolve("dokka/html"))
} }
publishing { publishing {
repositories {
maven {
name = "mingliqiye"
url = uri("https://repository.mingliqiye.com/repository/maven")
credentials {
username = System.getenv("mingliqiye.username")
password = System.getenv("mingliqiye.password")
}
}
}
publications { publications {
create<MavenPublication>("mavenJava") { create<MavenPublication>("mavenJava") {
from(components["java"]) from(components["java"])
artifact(tasks.named("javaDocJar"))
artifact(tasks.named("kotlinDocJar")) artifact(tasks.named("kotlinDocJar"))
artifactId = ARTIFACTID artifactId = ARTIFACTID
pom { pom {
@@ -226,12 +264,16 @@ tasks.processResources {
outputs.upToDateWhen { false } outputs.upToDateWhen { false }
filesMatching(listOf("META-INF/meta-data", "fabric.mod.json")) { filesMatching(listOf("META-INF/meta-data", "fabric.mod.json")) {
expand( expand(
project.properties + mapOf( mapOf(
"GROUPSID" to GROUPSID,
"ARTIFACTID" to ARTIFACTID,
"VERSIONS" to VERSIONS,
"JDKVERSIONS" to JDKVERSIONS,
"buildTime" to LocalDateTime.now().format( "buildTime" to LocalDateTime.now().format(
DateTimeFormatter.ofPattern( DateTimeFormatter.ofPattern(
"yyyy-MM-dd HH:mm:ss.SSSSSSS" "yyyy-MM-dd HH:mm:ss.SSSSSSS"
) )
) ),
) )
) )
} }
+5 -2
View File
@@ -16,10 +16,13 @@
# ProjectName mingli-utils # ProjectName mingli-utils
# ModuleName mingli-utils # ModuleName mingli-utils
# CurrentFile gradle.properties # CurrentFile gradle.properties
# LastUpdate 2026-10-12 13:57:03 # LastUpdate 2026-11-23 17:04:00
# UpdateUser MingLiPro # UpdateUser MingLiPro
# #
JDKVERSIONS=17 JDKVERSIONS=17
GROUPSID=com.mingliqiye.utils GROUPSID=com.mingliqiye.utils
ARTIFACTID=mingli-utils ARTIFACTID=mingli-utils
VERSIONS=5.3.2 # r = RELEASES
# s = SNAPSHOT
VERSIONSTYPE=r
VERSIONS=5.7.3
Binary file not shown.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

+2 -2
View File
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils * ModuleName mingli-utils
* CurrentFile settings.gradle.kts * CurrentFile settings.gradle.kts
* LastUpdate 2026-02-26 10:52:01 * LastUpdate 2026-11-23 10:23:56
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -24,7 +24,7 @@ plugins {
id("com.gradleup.nmcp.settings").version("1.4.4") id("com.gradleup.nmcp.settings").version("1.4.4")
} }
val ARTIFACTID: String by settings.extra val ARTIFACTID = settings.extra["ARTIFACTID"] as String
rootProject.name = ARTIFACTID rootProject.name = ARTIFACTID
nmcpSettings { nmcpSettings {
@@ -26,7 +26,16 @@ import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.cfg.MapperBuilder; import tools.jackson.databind.cfg.MapperBuilder;
/**
* Jackson 3 API 的 Java 辅助类,用于在 Java 侧调用 Kotlin 内联/受限 API。
*/
public class Jackson3ApiJavaHelper { public class Jackson3ApiJavaHelper {
/**
* 基于现有 ObjectMapper 创建可重新配置的 MapperBuilder。
*
* @param objectMapper 需要重建的 ObjectMapper 实例
* @return 由该 ObjectMapper 派生的 MapperBuilder
*/
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
static MapperBuilder rebuild(ObjectMapper objectMapper) { static MapperBuilder rebuild(ObjectMapper objectMapper) {
return objectMapper.rebuild(); return objectMapper.rebuild();
@@ -29,7 +29,13 @@ import java.net.InetAddress;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
/**
* 工具库入口类,提供启动 Banner 打印以及进程、主机、用户等基础信息的获取方法。
*/
public class Main { public class Main {
/**
* 启动时打印的 ASCII 艺术 Banner 文本
*/
public final static String BANNER = public final static String BANNER =
"| $$\\ $$\\ $$\\ $$\\ $$\\ $$$$$$$$\\ $$$$$$\\ \n" + "| $$\\ $$\\ $$\\ $$\\ $$\\ $$$$$$$$\\ $$$$$$\\ \n" +
"| $$$\\ $$$ |$$ | $$ | $$ |\\__$$ __|$$ __$$\\ \n" + "| $$$\\ $$$ |$$ | $$ | $$ |\\__$$ __|$$ __$$\\ \n" +
@@ -40,6 +46,11 @@ public class Main {
"| $$ | \\_/ $$ |$$$$$$$$\\\\$$$$$$ | $$ | \\$$$$$$ \n" + "| $$ | \\_/ $$ |$$$$$$$$\\\\$$$$$$ | $$ | \\$$$$$$ \n" +
"| \\__| \\__|\\________|\\______/ \\__| \\______/ \n|\n"; "| \\__| \\__|\\________|\\______/ \\__| \\______/ \n|\n";
/**
* 程序入口,打印 Banner 与构建元数据信息,打印失败时静默忽略。
*
* @param args 命令行参数(未使用)
*/
public static void main(String[] args) { public static void main(String[] args) {
try { try {
printb(); printb();
@@ -47,6 +58,11 @@ public class Main {
} }
} }
/**
* 获取当前进程 PID 字符串。
*
* @return 当前进程 PID;获取失败时返回 "-1"
*/
public static String getPid() { public static String getPid() {
try { try {
var name = ManagementFactory.getRuntimeMXBean().getName(); var name = ManagementFactory.getRuntimeMXBean().getName();
@@ -61,6 +77,11 @@ public class Main {
} }
} }
/**
* 获取计算机名,依次尝试环境变量 COMPUTERNAME、HOSTNAME 与本机主机名。
*
* @return 计算机名;获取失败时返回 "unknown"
*/
public static String getComputerName() { public static String getComputerName() {
try { try {
var name = System.getenv("COMPUTERNAME"); var name = System.getenv("COMPUTERNAME");
@@ -76,6 +97,11 @@ public class Main {
} }
} }
/**
* 获取当前用户名,依次尝试环境变量 USERNAME、USER 与 user.name。
*
* @return 当前用户名;获取失败时返回 "unknown"
*/
public static String getUserName() { public static String getUserName() {
try { try {
String user = System.getenv("USERNAME"); String user = System.getenv("USERNAME");
@@ -96,6 +122,12 @@ public class Main {
} }
/**
* 打印 Banner 及构建元数据、JDK 版本、PID、计算机名、用户名与当前时间。
* 若元数据资源不存在则直接返回。
*
* @throws IOException 读取元数据资源失败时抛出
*/
public static void printb() throws IOException { public static void printb() throws IOException {
InputStream inputStream = Main.class.getResourceAsStream("/META-INF/meta-data"); InputStream inputStream = Main.class.getResourceAsStream("/META-INF/meta-data");
if (inputStream == null) return; if (inputStream == null) return;
@@ -0,0 +1,94 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile FastServiceScan.java
* LastUpdate 2026-11-23 14:44:48
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.annotation;
import com.mingliqiye.utils.springboot.autoconfigure.FastServiceScanRegistrar;
import org.springframework.context.annotation.Import;
import org.springframework.core.annotation.AliasFor;
import java.lang.annotation.*;
/**
* 扫描继承自 {@code com.mingliqiye.utils.mybatisplus.FastBaseIService} 或
* {@code com.mingliqiye.utils.mybatisplus.FastBaseIServiceNew3518} 的具体类并注册为 Spring Bean。
* 两个基类分别对应旧版 {@code mybatis-plus-extension} 与新版 {@code mybatis-plus-spring},
* 子类都会被扫描到;行为与 {@code @MapperScan} 类似:只有标注了本注解的启动类/配置类才会触发扫描。
*
* <p>扫描由 {@link FastServiceScanRegistrar} 注册的
* {@code com.mingliqiye.utils.springboot.autoconfigure.FastServiceScannerProcessor} 完成,
* 后者是 {@code BeanFactoryPostProcessor},会在所有 {@code BeanDefinitionRegistryPostProcessor}
* (包括 {@code @MapperScan} 的 {@code MapperScannerConfigurer})之后执行,
* 因此扫描注册时机在 mapper 之后,服务里的 {@code baseMapper} 可以正常注入。</p>
*
* <p>已经标注 {@code @Component} / {@code @Service} 的类会被跳过,交给普通组件扫描处理,避免重复注册。</p>
*
* <p>Java 用法:</p>
* <pre>{@code
* @SpringBootApplication
* @MapperScan(basePackages = "com.example.mapper")
* @FastServiceScan(basePackages = "com.example.service")
* public class ExampleApplication {
* }
* }</pre>
*
* <p>Kotlin 用法:</p>
* <pre>{@code
* @SpringBootApplication
* @MapperScan(basePackages = ["com.example.mapper"])
* @FastServiceScan(basePackages = ["com.example.service"])
* class ExampleApplication
* }</pre>
*
* <p>不指定扫描包时,默认扫描标注类所在包。</p>
* <p>{@code Kotlin} 请指定 {@code Service} 为 {@code open}</p>
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(FastServiceScanRegistrar.class)
public @interface FastServiceScan {
/**
* 要扫描的包,等价于 {@link #basePackages()}。
*
* @return 要扫描的包
*/
@AliasFor("basePackages")
String[] value() default {};
/**
* 要扫描的包。
*
* @return 要扫描的包
*/
@AliasFor("value")
String[] basePackages() default {};
/**
* 以这些类所在包作为扫描包。
*
* @return 用于推导扫描包的类
*/
Class<?>[] basePackageClasses() default {};
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile SuperStream.java * CurrentFile SuperStream.java
* LastUpdate 2026-10-11 17:23:57 * LastUpdate 2026-11-22 10:10:33
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -26,6 +26,7 @@ import com.mingliqiye.utils.collection.Collections;
import com.mingliqiye.utils.functions.P1Function; import com.mingliqiye.utils.functions.P1Function;
import com.mingliqiye.utils.functions.P2Function; import com.mingliqiye.utils.functions.P2Function;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jspecify.annotations.NonNull;
import java.lang.reflect.Array; import java.lang.reflect.Array;
import java.util.*; import java.util.*;
@@ -987,7 +988,7 @@ public class SuperStream<T> implements Stream<T> {
*/ */
@NotNull @NotNull
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public T[] toArray(Class<T> clazz) { public T @NonNull [] toArray(Class<T> clazz) {
return stream.toArray(i -> (T[]) Array.newInstance(clazz, i)); return stream.toArray(i -> (T[]) Array.newInstance(clazz, i));
} }
@@ -997,7 +998,7 @@ public class SuperStream<T> implements Stream<T> {
* @return 转换后的Object数组 * @return 转换后的Object数组
*/ */
@NotNull @NotNull
public Object[] toArray() { public Object @NonNull [] toArray() {
return stream.toArray(); return stream.toArray();
} }
@@ -1,133 +0,0 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile SuprtStreamUtils.kt
* LastUpdate 2026-10-11 17:32:17
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.stream
import java.util.stream.Stream
/**
* [SuperStream] 的工厂工具类,提供把各类常见数据源(Java [Stream]、数组、集合、映射)
* 转换为 [SuperStream] 的扩展函数。
*
* 所有扩展函数均以 `toSuperStream` 命名,遵循 Kotlin 的 `toXxx` 转换命名惯例。
*
* 使用示例:
* ```kotlin
* intArrayOf(1, 2, 3).toSuperStream()
* listOf("a", "b").toSuperStream(parallel = true)
* mapOf(1 to "a").toSuperStream()
* ```
*/
object SuperStreamUtils {
/**
* 将 Java [Stream] 转换为 [SuperStream]。
*
* @param T 流中元素的类型,必须是不可空类型。
* @return 包装当前 [Stream] 的 [SuperStream]。
*/
fun <T : Any> Stream<T>.toSuperStream() = SuperStream.of(this)
/**
* 将 [ByteArray] 转换为 [SuperStream]。
*
* @param parallel 是否创建并行流,默认为 `false`(串行)。
* @return 由当前数组元素构成的 [SuperStream]。
*/
fun ByteArray.toSuperStream(parallel: Boolean = false) = SuperStream.of(this.toList(), parallel)
/**
* 将 [ShortArray] 转换为 [SuperStream]。
*
* @param parallel 是否创建并行流,默认为 `false`(串行)。
* @return 由当前数组元素构成的 [SuperStream]。
*/
fun ShortArray.toSuperStream(parallel: Boolean = false) = SuperStream.of(this.toList(), parallel)
/**
* 将 [IntArray] 转换为 [SuperStream]。
*
* @param parallel 是否创建并行流,默认为 `false`(串行)。
* @return 由当前数组元素构成的 [SuperStream]。
*/
fun IntArray.toSuperStream(parallel: Boolean = false) = SuperStream.of(this.toList(), parallel)
/**
* 将 [LongArray] 转换为 [SuperStream]。
*
* @param parallel 是否创建并行流,默认为 `false`(串行)。
* @return 由当前数组元素构成的 [SuperStream]。
*/
fun LongArray.toSuperStream(parallel: Boolean = false) = SuperStream.of(this.toList(), parallel)
/**
* 将 [FloatArray] 转换为 [SuperStream]。
*
* @param parallel 是否创建并行流,默认为 `false`(串行)。
* @return 由当前数组元素构成的 [SuperStream]。
*/
fun FloatArray.toSuperStream(parallel: Boolean = false) = SuperStream.of(this.toList(), parallel)
/**
* 将 [DoubleArray] 转换为 [SuperStream]。
*
* @param parallel 是否创建并行流,默认为 `false`(串行)。
* @return 由当前数组元素构成的 [SuperStream]。
*/
fun DoubleArray.toSuperStream(parallel: Boolean = false) = SuperStream.of(this.toList(), parallel)
/**
* 将 [BooleanArray] 转换为 [SuperStream]。
*
* @param parallel 是否创建并行流,默认为 `false`(串行)。
* @return 由当前数组元素构成的 [SuperStream]。
*/
fun BooleanArray.toSuperStream(parallel: Boolean = false) = SuperStream.of(this.toList(), parallel)
/**
* 将对象数组 [Array] 转换为 [SuperStream]。
*
* @param T 数组元素类型,必须是不可空类型。
* @param parallel 是否创建并行流,默认为 `false`(串行)。
* @return 由当前数组元素构成的 [SuperStream]。
*/
fun <T : Any> Array<T>.toSuperStream(parallel: Boolean = false) = SuperStream.of(this, parallel)
/**
* 将 [Collection] 转换为 [SuperStream]。
*
* @param T 集合元素类型,必须是不可空类型。
* @param parallel 是否创建并行流,默认为 `false`(串行)。
* @return 由当前集合元素构成的 [SuperStream]。
*/
fun <T : Any> Collection<T>.toSuperStream(parallel: Boolean = false) = SuperStream.of(this, parallel)
/**
* 将 [Map] 转换为 [SuperStream],流中元素为键值对 [Map.Entry]。
*
* @param K 键的类型。
* @param V 值的类型。
* @param parallel 是否创建并行流,默认为 `false`(串行)。
* @return 由当前映射的条目构成的 [SuperStream]。
*/
fun <K, V> Map<K, V>.toSuperStream(parallel: Boolean = false) = SuperStream.of(this, parallel)
}
@@ -34,10 +34,15 @@ import javax.crypto.Cipher
import javax.crypto.spec.GCMParameterSpec import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec import javax.crypto.spec.SecretKeySpec
/** 加密算法名称:AES。 */
const val ALGORITHM = "AES" const val ALGORITHM = "AES"
/** AES 加密变换模式:GCM 模式,无填充。 */
const val TRANSFORMATION = "AES/GCM/NoPadding" const val TRANSFORMATION = "AES/GCM/NoPadding"
/** GCM 模式初始化向量(IV)长度,单位字节。 */
const val GCM_IV_LENGTH = 12 const val GCM_IV_LENGTH = 12
/** GCM 模式认证标签(Tag)长度,单位字节。 */
const val GCM_TAG_LENGTH = 16 const val GCM_TAG_LENGTH = 16
/** 全局安全随机数生成器,用于生成加密安全的随机 IV。 */
val SECURE_RANDOM = SecureRandom() val SECURE_RANDOM = SecureRandom()
@@ -37,5 +37,5 @@ import kotlin.reflect.KClass
@Target(AnnotationTarget.CLASS) @Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.SOURCE) @Retention(AnnotationRetention.SOURCE)
annotation class AutoService( annotation class AutoService(
val value: Array<KClass<*>> = [] val value: Array<KClass<*>> = [],
) )
@@ -34,5 +34,5 @@ import com.mingliqiye.utils.uuid.UUIDFormatType
@Target(AnnotationTarget.FIELD) @Target(AnnotationTarget.FIELD)
annotation class UUIDJsonFormat( annotation class UUIDJsonFormat(
val value: UUIDFormatType = UUIDFormatType.NO_UPPER_SPACE, val value: UUIDFormatType = UUIDFormatType.NO_UPPER_SPACE,
val base: BaseType = BaseType.BASE16 val base: BaseType = BaseType.BASE16,
) )
@@ -33,12 +33,26 @@ import javax.lang.model.type.TypeMirror
import javax.tools.StandardLocation import javax.tools.StandardLocation
/**
* [AutoService] 注解的编译期处理器。
*
* 扫描标注了 [AutoService] 的类,收集服务接口与实现类的映射关系,
* 并在编译输出目录的 META-INF/services 下生成对应的服务注册文件。
*/
@SupportedAnnotationTypes("com.mingliqiye.utils.annotation.AutoService") @SupportedAnnotationTypes("com.mingliqiye.utils.annotation.AutoService")
class AutoServiceProcessor : AbstractProcessor() { class AutoServiceProcessor : AbstractProcessor() {
override fun init(processingEnv: ProcessingEnvironment) { override fun init(processingEnv: ProcessingEnvironment) {
super.init(processingEnv) super.init(processingEnv)
} }
/**
* 处理标注了 [AutoService] 的元素,收集服务接口与实现类的映射并生成服务注册文件。
* 若注解未显式指定服务接口,则默认使用该类直接实现的接口。
*
* @param annotations 本轮处理的注解类型集合
* @param roundEnv 当前轮次的处理环境
* @return 是否已处理该注解,存在标注元素时返回 true,否则返回 false
*/
override fun process( override fun process(
annotations: Set<TypeElement>, annotations: Set<TypeElement>,
roundEnv: RoundEnvironment, roundEnv: RoundEnvironment,
@@ -73,6 +87,12 @@ class AutoServiceProcessor : AbstractProcessor() {
return true return true
} }
/**
* 根据服务接口与实现类的映射,在 META-INF/services 目录下生成服务注册文件。
* 实现列表为空或文件创建失败时打印提示信息并跳过。
*
* @param map 服务接口全限定名到实现类全限定名列表的映射
*/
fun processClassAnnotation(map: Map<String, MutableList<String>>) { fun processClassAnnotation(map: Map<String, MutableList<String>>) {
map.forEach { (interfaceName, implementations) -> map.forEach { (interfaceName, implementations) ->
if (implementations.isEmpty()) { if (implementations.isEmpty()) {
@@ -24,6 +24,11 @@ package com.mingliqiye.utils.base
import java.math.BigInteger import java.math.BigInteger
/**
* Base10 编解码器实现类。
*
* 提供字节数组与十进制字符串之间的相互转换功能,基于 [BigInteger] 实现。
*/
internal class Base10Codec : BaseCodec { internal class Base10Codec : BaseCodec {
/** /**
@@ -32,7 +32,13 @@ package com.mingliqiye.utils.base
*/ */
internal class Base256Codec : BaseCodec { internal class Base256Codec : BaseCodec {
/**
* 伴生对象,持有 Base256 的编码字符集及其反向索引表。
*/
companion object { companion object {
/**
* Base256 编码字符集,共 256 个字符,数组索引即对应的字节值(0~255)。
*/
val code = arrayOf( val code = arrayOf(
'!', '!',
'#', '#',
@@ -291,6 +297,9 @@ internal class Base256Codec : BaseCodec {
'▘', '▘',
'▙' '▙'
) )
/**
* 字符到字节值的反向映射表,用于解码时快速查找字符对应的索引。
*/
val codeMap = code.mapIndexed { index, c -> c to index }.toMap() val codeMap = code.mapIndexed { index, c -> c to index }.toMap()
} }
@@ -303,6 +312,13 @@ internal class Base256Codec : BaseCodec {
return String(result) return String(result)
} }
/**
* 将 Base256 字符串解码为字节数组。
*
* @param string 待解码的字符串,所有字符必须属于编码字符集
* @return 解码后的字节数组
* @throws NullPointerException 如果字符串中包含字符集之外的字符
*/
override fun decode(string: String): ByteArray { override fun decode(string: String): ByteArray {
val result = ByteArray(string.length) val result = ByteArray(string.length)
for (i in string.indices) { for (i in string.indices) {
@@ -22,6 +22,11 @@
package com.mingliqiye.utils.base package com.mingliqiye.utils.base
/**
* Base2 编解码器实现类。
*
* 提供字节数组与二进制字符串(每字节 8 位,高位在前)之间的相互转换功能。
*/
internal class Base2Codec : BaseCodec { internal class Base2Codec : BaseCodec {
override fun encode(bytes: ByteArray): String { override fun encode(bytes: ByteArray): String {
if (bytes.isEmpty()) return "" if (bytes.isEmpty()) return ""
@@ -34,6 +39,13 @@ internal class Base2Codec : BaseCodec {
return result.toString() return result.toString()
} }
/**
* 将二进制字符串解码为字节数组。
*
* @param string 待解码的二进制字符串,长度必须为 8 的倍数且仅包含字符 '0' 和 '1'
* @return 解码后的字节数组
* @throws IllegalArgumentException 如果字符串长度不是 8 的倍数或包含非法字符
*/
override fun decode(string: String): ByteArray { override fun decode(string: String): ByteArray {
if (string.length % 8 != 0) { if (string.length % 8 != 0) {
throw IllegalArgumentException( throw IllegalArgumentException(
@@ -24,25 +24,25 @@ package com.mingliqiye.utils.base
import java.util.* import java.util.*
/* /**
* Base64编解码工具类 * Base64编解码工具类
* 提供Base64编码和解码功能的实现 * 提供Base64编码和解码功能的实现
*/ */
internal class Base64Codec : BaseCodec { internal class Base64Codec : BaseCodec {
/* /**
* Base64编码器实例 * Base64编码器实例
* 用于执行字节数组到Base64字符串的编码操作 * 用于执行字节数组到Base64字符串的编码操作
*/ */
val encoder: Base64.Encoder = Base64.getEncoder() val encoder: Base64.Encoder = Base64.getEncoder()
/* /**
* Base64解码器实例 * Base64解码器实例
* 用于执行Base64字符串到字节数组的解码操作 * 用于执行Base64字符串到字节数组的解码操作
*/ */
val decoder: Base64.Decoder = Base64.getDecoder() val decoder: Base64.Decoder = Base64.getDecoder()
/* /**
* 将字节数组编码为Base64字符串 * 将字节数组编码为Base64字符串
* *
* @param bytes 待编码的字节数组 * @param bytes 待编码的字节数组
@@ -52,7 +52,7 @@ internal class Base64Codec : BaseCodec {
return encoder.encodeToString(bytes) return encoder.encodeToString(bytes)
} }
/* /**
* 将Base64字符串解码为字节数组 * 将Base64字符串解码为字节数组
* *
* @param string 待解码的Base64字符串 * @param string 待解码的Base64字符串
@@ -0,0 +1,65 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Base64NoPaddingCodec.kt
* LastUpdate 2026-11-16 14:24:59
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.base
import java.util.*
/**
* 无填充 Base64 URL 编解码器实现类。
*
* 使用 URL 安全的 Base64 字母表,编码结果不带末尾的 '=' 填充字符。
*/
internal class Base64NoPaddingCodec : BaseCodec {
/**
* Base64编码器实例
* 用于执行字节数组到Base64字符串的编码操作
*/
val encoder: Base64.Encoder = Base64.getUrlEncoder().withoutPadding()
/**
* Base64解码器实例
* 用于执行Base64字符串到字节数组的解码操作
*/
val decoder: Base64.Decoder = Base64.getUrlDecoder()
/**
* 将字节数组编码为Base64字符串
*
* @param bytes 待编码的字节数组
* @return 编码后的Base64字符串
*/
override fun encode(bytes: ByteArray): String {
return encoder.encodeToString(bytes)
}
/**
* 将Base64字符串解码为字节数组
*
* @param string 待解码的Base64字符串
* @return 解码后的字节数组
*/
override fun decode(string: String): ByteArray {
return decoder.decode(string)
}
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile Base64UrlCodec.kt * CurrentFile Base64UrlCodec.kt
* LastUpdate 2026-03-12 10:34:36 * LastUpdate 2026-11-16 14:24:59
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -24,21 +24,26 @@ package com.mingliqiye.utils.base
import java.util.* import java.util.*
/**
* URL 安全 Base64 编解码器实现类。
*
* 使用 '-' 和 '_' 替代标准 Base64 中的 '+' 和 '/',适用于 URL 与文件名场景。
*/
internal class Base64UrlCodec : BaseCodec { internal class Base64UrlCodec : BaseCodec {
/* /**
* Base64编码器实例 * Base64编码器实例
* 用于执行字节数组到Base64字符串的编码操作 * 用于执行字节数组到Base64字符串的编码操作
*/ */
val encoder: Base64.Encoder = Base64.getUrlEncoder() val encoder: Base64.Encoder = Base64.getUrlEncoder()
/* /**
* Base64解码器实例 * Base64解码器实例
* 用于执行Base64字符串到字节数组的解码操作 * 用于执行Base64字符串到字节数组的解码操作
*/ */
val decoder: Base64.Decoder = Base64.getUrlDecoder() val decoder: Base64.Decoder = Base64.getUrlDecoder()
/* /**
* 将字节数组编码为Base64字符串 * 将字节数组编码为Base64字符串
* *
* @param bytes 待编码的字节数组 * @param bytes 待编码的字节数组
@@ -48,7 +53,7 @@ internal class Base64UrlCodec : BaseCodec {
return encoder.encodeToString(bytes) return encoder.encodeToString(bytes)
} }
/* /**
* 将Base64字符串解码为字节数组 * 将Base64字符串解码为字节数组
* *
* @param string 待解码的Base64字符串 * @param string 待解码的Base64字符串
@@ -29,6 +29,9 @@ package com.mingliqiye.utils.base
*/ */
internal class Base91Codec : BaseCodec { internal class Base91Codec : BaseCodec {
/**
* 伴生对象,持有 Base91 的编码表与解码表。
*/
companion object { companion object {
/** /**
* Base91 编码表,共 91 个可打印 ASCII 字符。 * Base91 编码表,共 91 个可打印 ASCII 字符。
@@ -16,23 +16,55 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile BaseType.kt * CurrentFile BaseType.kt
* LastUpdate 2026-03-12 10:08:42 * LastUpdate 2026-11-16 14:21:51
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
package com.mingliqiye.utils.base package com.mingliqiye.utils.base
enum class BaseType(val baseCodec: BaseCodec) : BaseCodec { import com.mingliqiye.utils.base.code.BASE10 as CODE_BASE10
import com.mingliqiye.utils.base.code.BASE16 as CODE_BASE16
import com.mingliqiye.utils.base.code.BASE2 as CODE_BASE2
import com.mingliqiye.utils.base.code.BASE256 as CODE_BASE256
import com.mingliqiye.utils.base.code.BASE64 as CODE_BASE64
import com.mingliqiye.utils.base.code.BASE64_NO_PADDING as CODE_BASE64_NO_PADDING
import com.mingliqiye.utils.base.code.BASE64_URL as CODE_BASE64_URL
import com.mingliqiye.utils.base.code.BASE91 as CODE_BASE91
BASE2(com.mingliqiye.utils.base.code.BASE2), /**
BASE10(com.mingliqiye.utils.base.code.BASE10), * Base 编码类型枚举。
BASE16(com.mingliqiye.utils.base.code.BASE16), *
BASE64(com.mingliqiye.utils.base.code.BASE64), * 每个枚举项持有一个编解码器的工厂函数,枚举本身实现了 [BaseCodec],
BASE64URL(com.mingliqiye.utils.base.code.BASE64URL), * 可直接作为编解码器使用,编码与解码操作委托给对应的编解码器实例。
BASE91(com.mingliqiye.utils.base.code.BASE91), *
BASE256(com.mingliqiye.utils.base.code.BASE256); * @param baseCodec 编解码器的工厂函数,每次访问 [codec] 时调用以创建实例
*/
enum class BaseType(private val baseCodec: () -> BaseCodec) : BaseCodec {
override fun encode(bytes: ByteArray) = baseCodec.encode(bytes) /** 二进制(Base2)编解码。 */
override fun decode(string: String) = baseCodec.decode(string) BASE2(::CODE_BASE2),
/** 十进制(Base10)编解码。 */
BASE10(::CODE_BASE10),
/** 十六进制(Base16)编解码。 */
BASE16(::CODE_BASE16),
/** 标准 Base64 编解码。 */
BASE64(::CODE_BASE64),
/** URL 安全的 Base64 编解码。 */
BASE64_URL(::CODE_BASE64_URL),
/** 无填充(不带末尾 '=')的 URL 安全 Base64 编解码。 */
BASE64_NO_PADDING(::CODE_BASE64_NO_PADDING),
/** Base91 编解码。 */
BASE91(::CODE_BASE91),
/** Base256 编解码。 */
BASE256(::CODE_BASE256);
/**
* 获取当前类型对应的编解码器实例(每次访问都会通过工厂函数新建)。
*/
val codec
get() = baseCodec()
override fun encode(bytes: ByteArray) = codec.encode(bytes)
override fun decode(string: String) = codec.decode(string)
} }
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile BaseCodes.kt * CurrentFile BaseCodes.kt
* LastUpdate 2026-03-12 10:03:32 * LastUpdate 2026-11-16 14:10:57
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -62,11 +62,25 @@ val BASE64: BaseCodec by lazy {
Base64Codec() Base64Codec()
} }
/**
* 提供Base64 URL编码器的懒加载实例。
* 该编码器用于将数据编码为URL安全的Base64格式。
*/
@get:JvmName("base64Url") @get:JvmName("base64Url")
val BASE64URL: BaseCodec by lazy { val BASE64_URL: BaseCodec by lazy {
Base64UrlCodec() Base64UrlCodec()
} }
/**
* 提供无填充Base64 URL编码器的懒加载实例。
* 该编码器用于将数据编码为URL安全的Base64格式,且结果不带末尾的'='填充字符。
*/
@get:JvmName("base64NoPadding")
val BASE64_NO_PADDING: BaseCodec by lazy {
Base64NoPaddingCodec()
}
/** /**
* 提供Base91编码器的懒加载实例。 * 提供Base91编码器的懒加载实例。
* 该编码器用于将数据编码为Base91格式,具有较高的压缩效率。 * 该编码器用于将数据编码为Base91格式,具有较高的压缩效率。
@@ -29,31 +29,69 @@ import java.security.SecureRandom
import org.mindrot.jbcrypt.BCrypt as JBCrypt import org.mindrot.jbcrypt.BCrypt as JBCrypt
/**
* 使用随机生成的盐对字符串进行 BCrypt 哈希。
*
* @param string 需要哈希的明文字符串
* @return BCrypt 哈希字符串
*/
fun hashpw(string: String): String { fun hashpw(string: String): String {
return hashpw(string, gensalt()) return hashpw(string, gensalt())
} }
/**
* 使用指定的盐对字符串进行 BCrypt 哈希。
*
* @param string 需要哈希的明文字符串
* @param salt BCrypt 盐字符串,默认随机生成
* @return BCrypt 哈希字符串
*/
fun hashpw(string: String, salt: String = gensalt()): String { fun hashpw(string: String, salt: String = gensalt()): String {
return JBCrypt.hashpw(string, salt) return JBCrypt.hashpw(string, salt)
} }
/**
* 验证明文字符串与 BCrypt 哈希是否匹配。
*
* @param string 明文字符串
* @param bcrypted 已生成的 BCrypt 哈希字符串
* @return 匹配返回 true,否则返回 false
*/
fun checkpw(string: String, bcrypted: String): Boolean { fun checkpw(string: String, bcrypted: String): Boolean {
return JBCrypt.checkpw(string, bcrypted) return JBCrypt.checkpw(string, bcrypted)
} }
/**
* 生成默认工作因子(10)的 BCrypt 盐。
*
* @return BCrypt 盐字符串
*/
fun gensalt(): String { fun gensalt(): String {
return JBCrypt.gensalt() return JBCrypt.gensalt()
} }
/**
* 生成指定工作因子的 BCrypt 盐。
*
* @param long 工作因子(log2 迭代次数),值越大计算越慢
* @return BCrypt 盐字符串
*/
fun gensalt(long: Int): String { fun gensalt(long: Int): String {
return JBCrypt.gensalt(long) return JBCrypt.gensalt(long)
} }
/**
* 使用指定的安全随机数生成器生成 BCrypt 盐。
*
* @param long 工作因子(log2 迭代次数)
* @param secureRandom 用于生成盐的安全随机数生成器
* @return BCrypt 盐字符串
*/
fun gensalt(long: Int, secureRandom: SecureRandom): String { fun gensalt(long: Int, secureRandom: SecureRandom): String {
return JBCrypt.gensalt(long, secureRandom) return JBCrypt.gensalt(long, secureRandom)
} }
@@ -198,6 +198,9 @@ class ByteBufferWrapper private constructor(private val buffer: ByteBuffer) {
return "ByteBufferWrapper(capacity=$capacity, position=$position, limit=$limit, remaining=$remaining)#${hashCode()}" return "ByteBufferWrapper(capacity=$capacity, position=$position, limit=$limit, remaining=$remaining)#${hashCode()}"
} }
/**
* 伴生对象,提供工厂方法以及类型转换器的注册与查询功能。
*/
companion object { companion object {
/** /**
* 包装现有的 ByteBuffer * 包装现有的 ByteBuffer
@@ -279,6 +282,11 @@ class ByteBufferWrapper private constructor(private val buffer: ByteBuffer) {
byteBufferWrapperConvertor byteBufferWrapperConvertor
} }
/**
* 添加转换器到映射表,通过具体化类型参数自动创建转换器实例
*
* @param T 转换器类型,必须提供无参构造函数
*/
@JvmName("inline_addConvertor") @JvmName("inline_addConvertor")
inline fun <reified T : ByteBufferWrapperConvertor<*>> addConvertor() { inline fun <reified T : ByteBufferWrapperConvertor<*>> addConvertor() {
addConvertor(ByteBufferWrapperConvertor.getInstantiation<T>()) addConvertor(ByteBufferWrapperConvertor.getInstantiation<T>())
@@ -537,24 +545,64 @@ class ByteBufferWrapper private constructor(private val buffer: ByteBuffer) {
return convertor.read(this, parameters) return convertor.read(this, parameters)
} }
/**
* 从缓冲区中读取指定类型的对象(不带额外参数)
*
* @param clazz 要读取的对象类型对应的 Class 对象
* @param T 要读取的对象类型
* @return 读取并转换后的 T 类型对象
* @throws IllegalArgumentException 如果该类型没有注册对应的转换器
*/
fun <T : Any> getObject(clazz: Class<T>): T { fun <T : Any> getObject(clazz: Class<T>): T {
return getObject(clazz, emptyArray()) return getObject(clazz, emptyArray())
} }
/**
* 从缓冲区中读取指定类型的对象,并传入长度参数
*
* @param clazz 要读取的对象类型对应的 Class 对象
* @param size 读取长度(如数组元素个数),作为转换器的第一个参数
* @param T 要读取的对象类型
* @return 读取并转换后的 T 类型对象
* @throws IllegalArgumentException 如果该类型没有注册对应的转换器
*/
fun <T : Any> getObject(clazz: Class<T>, size: Int): T { fun <T : Any> getObject(clazz: Class<T>, size: Int): T {
return getObject(clazz, arrayOf(size)) return getObject(clazz, arrayOf(size))
} }
/**
* 从缓冲区中读取具体化类型 T 的对象,并传入额外参数
*
* @param parameters 传递给转换器的参数数组
* @param T 要读取的对象类型
* @return 读取并转换后的 T 类型对象
* @throws IllegalArgumentException 如果该类型没有注册对应的转换器
*/
@JvmName("inline_getObject") @JvmName("inline_getObject")
inline fun <reified T : Any> getObject(parameters: Array<Any>): T { inline fun <reified T : Any> getObject(parameters: Array<Any>): T {
return getObject(T::class.java, parameters) return getObject(T::class.java, parameters)
} }
/**
* 从缓冲区中读取具体化类型 T 的对象,并传入长度参数
*
* @param size 读取长度(如数组元素个数),作为转换器的第一个参数
* @param T 要读取的对象类型
* @return 读取并转换后的 T 类型对象
* @throws IllegalArgumentException 如果该类型没有注册对应的转换器
*/
@JvmName("inline_getObject") @JvmName("inline_getObject")
inline fun <reified T : Any> getObject(size: Int): T { inline fun <reified T : Any> getObject(size: Int): T {
return getObject(T::class.java, size) return getObject(T::class.java, size)
} }
/**
* 从缓冲区中读取具体化类型 T 的对象(不带额外参数)
*
* @param T 要读取的对象类型
* @return 读取并转换后的 T 类型对象
* @throws IllegalArgumentException 如果该类型没有注册对应的转换器
*/
@JvmName("inline_getObject") @JvmName("inline_getObject")
inline fun <reified T : Any> getObject(): T { inline fun <reified T : Any> getObject(): T {
return getObject(T::class.java) return getObject(T::class.java)
@@ -574,11 +622,24 @@ class ByteBufferWrapper private constructor(private val buffer: ByteBuffer) {
return this return this
} }
/**
* 按初始化函数生成指定长度的字节数组并写入缓冲区
*
* @param size 要生成并写入的字节数
* @param init 初始化函数,根据索引生成每个字节的值
* @return 当前对象(支持链式调用)
*/
fun putByteArray(size: Int, init: (Int) -> Byte): ByteBufferWrapper { fun putByteArray(size: Int, init: (Int) -> Byte): ByteBufferWrapper {
buffer.put(ByteArray(size, init)) buffer.put(ByteArray(size, init))
return this return this
} }
/**
* 将字符数组完整写入缓冲区(每个字符取低 8 位,1字节)
*
* @param charArray 要写入的字符数组
* @return 当前对象(支持链式调用)
*/
fun putCharArray(charArray: CharArray): ByteBufferWrapper { fun putCharArray(charArray: CharArray): ByteBufferWrapper {
putByteArray(charArray.size) { putByteArray(charArray.size) {
charArray[it].code.toByte() charArray[it].code.toByte()
@@ -586,6 +647,12 @@ class ByteBufferWrapper private constructor(private val buffer: ByteBuffer) {
return this return this
} }
/**
* 读取指定长度的字符数组(每个字节转换为一个字符)
*
* @param size 要读取的字符数
* @return 读取的字符数组
*/
fun getCharArray(size: Int): CharArray { fun getCharArray(size: Int): CharArray {
return getByteArray(size).let { return getByteArray(size).let {
CharArray(it.size) { s -> CharArray(it.size) { s ->
@@ -594,52 +661,118 @@ class ByteBufferWrapper private constructor(private val buffer: ByteBuffer) {
} }
} }
/**
* 将整数数组完整写入缓冲区(每个整数4字节)
*
* @param intArray 要写入的整数数组
* @return 当前对象(支持链式调用)
*/
fun putIntArray(intArray: IntArray): ByteBufferWrapper { fun putIntArray(intArray: IntArray): ByteBufferWrapper {
intArray.forEach(::putInt) intArray.forEach(::putInt)
return this return this
} }
/**
* 读取指定长度的整数数组
*
* @param size 要读取的整数个数
* @return 读取的整数数组
*/
fun getIntArray(size: Int): IntArray { fun getIntArray(size: Int): IntArray {
return IntArray(size) { getInt() } return IntArray(size) { getInt() }
} }
/**
* 将短整数数组完整写入缓冲区(每个短整数2字节)
*
* @param shortArray 要写入的短整数数组
* @return 当前对象(支持链式调用)
*/
fun putShortArray(shortArray: ShortArray): ByteBufferWrapper { fun putShortArray(shortArray: ShortArray): ByteBufferWrapper {
shortArray.forEach(::putShort) shortArray.forEach(::putShort)
return this return this
} }
/**
* 读取指定长度的短整数数组
*
* @param size 要读取的短整数个数
* @return 读取的短整数数组
*/
fun getShortArray(size: Int): ShortArray { fun getShortArray(size: Int): ShortArray {
return ShortArray(size) { getShort() } return ShortArray(size) { getShort() }
} }
/**
* 将长整数数组完整写入缓冲区(每个长整数8字节)
*
* @param longArray 要写入的长整数数组
* @return 当前对象(支持链式调用)
*/
fun putLongArray(longArray: LongArray): ByteBufferWrapper { fun putLongArray(longArray: LongArray): ByteBufferWrapper {
longArray.forEach(::putLong) longArray.forEach(::putLong)
return this return this
} }
/**
* 读取指定长度的长整数数组
*
* @param size 要读取的长整数个数
* @return 读取的长整数数组
*/
fun getLongArray(size: Int): LongArray { fun getLongArray(size: Int): LongArray {
return LongArray(size) { getLong() } return LongArray(size) { getLong() }
} }
/**
* 将双精度浮点数数组完整写入缓冲区(每个浮点数8字节)
*
* @param doubleArray 要写入的双精度浮点数数组
* @return 当前对象(支持链式调用)
*/
fun putDoubleArray(doubleArray: DoubleArray): ByteBufferWrapper { fun putDoubleArray(doubleArray: DoubleArray): ByteBufferWrapper {
doubleArray.forEach(::putDouble) doubleArray.forEach(::putDouble)
return this return this
} }
/**
* 读取指定长度的双精度浮点数数组
*
* @param size 要读取的双精度浮点数个数
* @return 读取的双精度浮点数数组
*/
fun getDoubleArray(size: Int): DoubleArray { fun getDoubleArray(size: Int): DoubleArray {
return DoubleArray(size) { getDouble() } return DoubleArray(size) { getDouble() }
} }
/**
* 将单精度浮点数数组完整写入缓冲区(每个浮点数4字节)
*
* @param floatArray 要写入的单精度浮点数数组
* @return 当前对象(支持链式调用)
*/
fun putFloatArray(floatArray: FloatArray): ByteBufferWrapper { fun putFloatArray(floatArray: FloatArray): ByteBufferWrapper {
floatArray.forEach(::putFloat) floatArray.forEach(::putFloat)
return this return this
} }
/**
* 读取指定长度的单精度浮点数数组
*
* @param size 要读取的单精度浮点数个数
* @return 读取的单精度浮点数数组
*/
fun getFloatArray(size: Int): FloatArray { fun getFloatArray(size: Int): FloatArray {
return FloatArray(size) { getFloat() } return FloatArray(size) { getFloat() }
} }
/**
* 将布尔数组完整写入缓冲区(每个布尔值1字节,true = 0x01,false = 0x00)
*
* @param booleanArray 要写入的布尔数组
* @return 当前对象(支持链式调用)
*/
fun putBooleanArray(booleanArray: BooleanArray): ByteBufferWrapper { fun putBooleanArray(booleanArray: BooleanArray): ByteBufferWrapper {
putByteArray(booleanArray.size) { putByteArray(booleanArray.size) {
if (booleanArray[it]) 0x01 else 0x00 if (booleanArray[it]) 0x01 else 0x00
@@ -647,6 +780,13 @@ class ByteBufferWrapper private constructor(private val buffer: ByteBuffer) {
return this return this
} }
/**
* 读取指定长度的布尔数组
*
* @param size 要读取的布尔值个数
* @return 读取的布尔数组
* @throws IllegalArgumentException 如果读取到的字节值不是 0x00 或 0x01
*/
fun getBooleanArray(size: Int): BooleanArray { fun getBooleanArray(size: Int): BooleanArray {
return getByteArray(size).let { return getByteArray(size).let {
BooleanArray(it.size) { index -> BooleanArray(it.size) { index ->
@@ -33,21 +33,67 @@ import java.util.*
import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentHashMap
import java.util.UUID as JUUID import java.util.UUID as JUUID
/**
* ByteBufferWrapper 类型转换器接口。
*
* 定义某种类型与 [ByteBufferWrapper] 之间的读写规则。
*
* @param T 该转换器处理的数据类型
*/
interface ByteBufferWrapperConvertorInterface<T : Any> { interface ByteBufferWrapperConvertorInterface<T : Any> {
/**
* 将对象写入缓冲区。
*
* @param obj 要写入的对象
* @param byteBufferWrapper 目标缓冲区包装器
*/
fun write(obj: T, byteBufferWrapper: ByteBufferWrapper) fun write(obj: T, byteBufferWrapper: ByteBufferWrapper)
/**
* 从缓冲区中读取对象。
*
* @param byteBufferWrapper 源缓冲区包装器
* @param parameters 读取时需要的额外参数(如数组长度)
* @return 读取并转换后的对象
*/
fun read(byteBufferWrapper: ByteBufferWrapper, parameters: Array<Any>): T fun read(byteBufferWrapper: ByteBufferWrapper, parameters: Array<Any>): T
/**
* 获取该转换器处理的数据类型。
*
* @return 类型对应的 Class 对象
*/
fun getType(): Class<T> fun getType(): Class<T>
} }
/**
* ByteBufferWrapper 类型转换器抽象基类。
*
* 提供转换器实例的缓存创建以及默认转换器的注册功能。
*
* @param T 该转换器处理的数据类型
*/
abstract class ByteBufferWrapperConvertor<T : Any> : ByteBufferWrapperConvertorInterface<T> { abstract class ByteBufferWrapperConvertor<T : Any> : ByteBufferWrapperConvertorInterface<T> {
/**
* 返回包含所处理类型信息的字符串表示。
*/
override fun toString(): String { override fun toString(): String {
return "ByteBufferWrapperConvertor(type=${getType()})" return "ByteBufferWrapperConvertor(type=${getType()})"
} }
/**
* 伴生对象,管理转换器实例缓存并提供默认转换器安装方法。
*/
companion object { companion object {
private val _instantiations = private val _instantiations =
ConcurrentHashMap<Class<ByteBufferWrapperConvertor<*>>, ByteBufferWrapperConvertor<*>>() ConcurrentHashMap<Class<ByteBufferWrapperConvertor<*>>, ByteBufferWrapperConvertor<*>>()
/**
* 获取指定转换器类的实例,不存在时通过无参构造函数创建并缓存。
*
* @param clazz 转换器类对应的 Class 对象
* @return 缓存的或新创建的转换器实例
*/
@JvmStatic @JvmStatic
fun getInstantiation(clazz: Class<ByteBufferWrapperConvertor<*>>): ByteBufferWrapperConvertor<*> { fun getInstantiation(clazz: Class<ByteBufferWrapperConvertor<*>>): ByteBufferWrapperConvertor<*> {
return _instantiations.getOrPut(clazz) { return _instantiations.getOrPut(clazz) {
@@ -55,12 +101,23 @@ abstract class ByteBufferWrapperConvertor<T : Any> : ByteBufferWrapperConvertorI
} }
} }
/**
* 获取具体化类型 T 对应的转换器实例,不存在时创建并缓存。
*
* @param T 转换器类型,必须提供无参构造函数
* @return 缓存的或新创建的转换器实例
*/
@JvmStatic @JvmStatic
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
inline fun <reified T : ByteBufferWrapperConvertor<*>> getInstantiation(): ByteBufferWrapperConvertor<*> { inline fun <reified T : ByteBufferWrapperConvertor<*>> getInstantiation(): ByteBufferWrapperConvertor<*> {
return getInstantiation(T::class.java as Class<ByteBufferWrapperConvertor<*>>) return getInstantiation(T::class.java as Class<ByteBufferWrapperConvertor<*>>)
} }
/**
* 安装所有默认转换器。
*
* 将基础类型、大数、字符串、时间、UUID 及各类数组的转换器注册到 [ByteBufferWrapper]。
*/
fun defaultConvertorInstall() { fun defaultConvertorInstall() {
ByteBufferWrapper.addConvertor<BigDecimalBufferWrapperConvertor>() ByteBufferWrapper.addConvertor<BigDecimalBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<BigIntegerBufferWrapperConvertor>() ByteBufferWrapper.addConvertor<BigIntegerBufferWrapperConvertor>()
@@ -91,6 +148,16 @@ abstract class ByteBufferWrapperConvertor<T : Any> : ByteBufferWrapperConvertorI
} }
} }
/**
* 基于读写函数构造的通用对象转换器。
*
* 通过传入的写入函数、读取函数和类型信息实现转换逻辑,读取时忽略额外参数。
*
* @param T 该转换器处理的数据类型
* @param write 写入函数,将对象写入缓冲区
* @param read 读取函数,从缓冲区读取对象
* @param typer 该转换器处理的数据类型对应的 Class 对象
*/
abstract class ObjectBufferWrapperConvertor<T : Any>( abstract class ObjectBufferWrapperConvertor<T : Any>(
val write: ByteBufferWrapper.(obj: T) -> Unit, val write: ByteBufferWrapper.(obj: T) -> Unit,
val read: ByteBufferWrapper.() -> T, val read: ByteBufferWrapper.() -> T,
@@ -104,72 +171,84 @@ abstract class ObjectBufferWrapperConvertor<T : Any>(
} }
/** [Byte] 类型转换器,使用 putByte/getByte 读写。 */
class BytedBufferWrapperConvertor : ObjectBufferWrapperConvertor<Byte>( class BytedBufferWrapperConvertor : ObjectBufferWrapperConvertor<Byte>(
ByteBufferWrapper::putByte, ByteBufferWrapper::putByte,
ByteBufferWrapper::getByte, ByteBufferWrapper::getByte,
Byte::class.java, Byte::class.java,
) )
/** [Char] 类型转换器,使用 putChar/getChar 读写。 */
class CharBufferWrapperConvertor : ObjectBufferWrapperConvertor<Char>( class CharBufferWrapperConvertor : ObjectBufferWrapperConvertor<Char>(
ByteBufferWrapper::putChar, ByteBufferWrapper::putChar,
ByteBufferWrapper::getChar, ByteBufferWrapper::getChar,
Char::class.java, Char::class.java,
) )
/** [Short] 类型转换器,使用 putShort/getShort 读写。 */
class ShortBufferWrapperConvertor : ObjectBufferWrapperConvertor<Short>( class ShortBufferWrapperConvertor : ObjectBufferWrapperConvertor<Short>(
ByteBufferWrapper::putShort, ByteBufferWrapper::putShort,
ByteBufferWrapper::getShort, ByteBufferWrapper::getShort,
Short::class.java, Short::class.java,
) )
/** [Int] 类型转换器,使用 putInt/getInt 读写。 */
class IntBufferWrapperConvertor : ObjectBufferWrapperConvertor<Int>( class IntBufferWrapperConvertor : ObjectBufferWrapperConvertor<Int>(
ByteBufferWrapper::putInt, ByteBufferWrapper::putInt,
ByteBufferWrapper::getInt, ByteBufferWrapper::getInt,
Int::class.java, Int::class.java,
) )
/** [Long] 类型转换器,使用 putLong/getLong 读写。 */
class LongBufferWrapperConvertor : ObjectBufferWrapperConvertor<Long>( class LongBufferWrapperConvertor : ObjectBufferWrapperConvertor<Long>(
ByteBufferWrapper::putLong, ByteBufferWrapper::putLong,
ByteBufferWrapper::getLong, ByteBufferWrapper::getLong,
Long::class.java, Long::class.java,
) )
/** [Double] 类型转换器,使用 putDouble/getDouble 读写。 */
class DoubleBufferWrapperConvertor : ObjectBufferWrapperConvertor<Double>( class DoubleBufferWrapperConvertor : ObjectBufferWrapperConvertor<Double>(
ByteBufferWrapper::putDouble, ByteBufferWrapper::putDouble,
ByteBufferWrapper::getDouble, ByteBufferWrapper::getDouble,
Double::class.java, Double::class.java,
) )
/** [Float] 类型转换器,使用 putFloat/getFloat 读写。 */
class FloatBufferWrapperConvertor : ObjectBufferWrapperConvertor<Float>( class FloatBufferWrapperConvertor : ObjectBufferWrapperConvertor<Float>(
ByteBufferWrapper::putFloat, ByteBufferWrapper::putFloat,
ByteBufferWrapper::getFloat, ByteBufferWrapper::getFloat,
Float::class.java, Float::class.java,
) )
/** [BigInteger] 类型转换器,使用 putBigInteger/getBigInteger 读写。 */
class BigIntegerBufferWrapperConvertor : ObjectBufferWrapperConvertor<BigInteger>( class BigIntegerBufferWrapperConvertor : ObjectBufferWrapperConvertor<BigInteger>(
ByteBufferWrapper::putBigInteger, ByteBufferWrapper::putBigInteger,
ByteBufferWrapper::getBigInteger, ByteBufferWrapper::getBigInteger,
BigInteger::class.java, BigInteger::class.java,
) )
/** [BigDecimal] 类型转换器,使用 putBigDecimal/getBigDecimal 读写。 */
class BigDecimalBufferWrapperConvertor : ObjectBufferWrapperConvertor<BigDecimal>( class BigDecimalBufferWrapperConvertor : ObjectBufferWrapperConvertor<BigDecimal>(
ByteBufferWrapper::putBigDecimal, ByteBufferWrapper::putBigDecimal,
ByteBufferWrapper::getBigDecimal, ByteBufferWrapper::getBigDecimal,
BigDecimal::class.java, BigDecimal::class.java,
) )
/** [Boolean] 类型转换器,使用 putBoolean/getBoolean 读写。 */
class BooleanBufferWrapperConvertor : ObjectBufferWrapperConvertor<Boolean>( class BooleanBufferWrapperConvertor : ObjectBufferWrapperConvertor<Boolean>(
ByteBufferWrapper::putBoolean, ByteBufferWrapper::putBoolean,
ByteBufferWrapper::getBoolean, ByteBufferWrapper::getBoolean,
Boolean::class.java, Boolean::class.java,
) )
/** [String] 类型转换器,使用 putString/getString 读写。 */
class StringBufferWrapperConvertor : ObjectBufferWrapperConvertor<String>( class StringBufferWrapperConvertor : ObjectBufferWrapperConvertor<String>(
ByteBufferWrapper::putString, ByteBufferWrapper::putString,
ByteBufferWrapper::getString, ByteBufferWrapper::getString,
String::class.java, String::class.java,
) )
/** [ByteFlags] 类型转换器,使用 putFlag/getFlag 读写。 */
class ByteFlagsBufferWrapperConvertor : ObjectBufferWrapperConvertor<ByteFlags>( class ByteFlagsBufferWrapperConvertor : ObjectBufferWrapperConvertor<ByteFlags>(
ByteBufferWrapper::putFlag, ByteBufferWrapper::putFlag,
ByteBufferWrapper::getFlag, ByteBufferWrapper::getFlag,
@@ -177,42 +256,62 @@ class ByteFlagsBufferWrapperConvertor : ObjectBufferWrapperConvertor<ByteFlags>(
) )
/** Java [JUUID] 类型转换器,使用 putUUID/getJUUID 读写。 */
class JUUIDBufferWrapperConvertor : ObjectBufferWrapperConvertor<JUUID>( class JUUIDBufferWrapperConvertor : ObjectBufferWrapperConvertor<JUUID>(
ByteBufferWrapper::putUUID, ByteBufferWrapper::putUUID,
ByteBufferWrapper::getJUUID, ByteBufferWrapper::getJUUID,
JUUID::class.java, JUUID::class.java,
) )
/** 自定义 [UUID] 类型转换器,使用 putUUID/getUUID 读写。 */
class UUIDBufferWrapperConvertor : ObjectBufferWrapperConvertor<UUID>( class UUIDBufferWrapperConvertor : ObjectBufferWrapperConvertor<UUID>(
ByteBufferWrapper::putUUID, ByteBufferWrapper::putUUID,
ByteBufferWrapper::getUUID, ByteBufferWrapper::getUUID,
UUID::class.java, UUID::class.java,
) )
/** [DateTime] 类型转换器,使用 putDateTime/getDateTime 读写。 */
class DateTimeFlagsBufferWrapperConvertor : ObjectBufferWrapperConvertor<DateTime>( class DateTimeFlagsBufferWrapperConvertor : ObjectBufferWrapperConvertor<DateTime>(
ByteBufferWrapper::putDateTime, ByteBufferWrapper::putDateTime,
ByteBufferWrapper::getDateTime, ByteBufferWrapper::getDateTime,
DateTime::class.java, DateTime::class.java,
) )
/** [LocalDateTime] 类型转换器,使用 putLocalDateTime/getLocalDateTime 读写。 */
class LocalDateTimeBufferWrapperConvertor : ObjectBufferWrapperConvertor<LocalDateTime>( class LocalDateTimeBufferWrapperConvertor : ObjectBufferWrapperConvertor<LocalDateTime>(
ByteBufferWrapper::putLocalDateTime, ByteBufferWrapper::putLocalDateTime,
ByteBufferWrapper::getLocalDateTime, ByteBufferWrapper::getLocalDateTime,
LocalDateTime::class.java, LocalDateTime::class.java,
) )
/** [Date] 类型转换器,使用 putDate/getDate 读写。 */
class DateBufferWrapperConvertor : ObjectBufferWrapperConvertor<Date>( class DateBufferWrapperConvertor : ObjectBufferWrapperConvertor<Date>(
ByteBufferWrapper::putDate, ByteBufferWrapper::putDate,
ByteBufferWrapper::getDate, ByteBufferWrapper::getDate,
Date::class.java, Date::class.java,
) )
/**
* 基于读写函数构造的通用数组转换器。
*
* 读取时要求额外参数的第一个元素为 Int 类型的数组长度。
*
* @param T 该转换器处理的数组类型
* @param write 写入函数,将数组写入缓冲区
* @param read 读取函数,按指定长度从缓冲区读取数组
* @param typer 该转换器处理的数组类型对应的 Class 对象
*/
abstract class ArrayBufferWrapperConvertor<T : Any>( abstract class ArrayBufferWrapperConvertor<T : Any>(
val write: ByteBufferWrapper.(obj: T) -> Unit, val write: ByteBufferWrapper.(obj: T) -> Unit,
val read: ByteBufferWrapper.(size: Int) -> T, val read: ByteBufferWrapper.(size: Int) -> T,
val typer: Class<T>, val typer: Class<T>,
) : ByteBufferWrapperConvertor<T>() { ) : ByteBufferWrapperConvertor<T>() {
override fun write(obj: T, byteBufferWrapper: ByteBufferWrapper) = write.invoke(byteBufferWrapper, obj) override fun write(obj: T, byteBufferWrapper: ByteBufferWrapper) = write.invoke(byteBufferWrapper, obj)
/**
* 从缓冲区读取数组,要求 parameters[0] 为 Int 类型的长度。
*
* @throws IllegalArgumentException 如果参数为空或第一个参数不是 Int
*/
override fun read(byteBufferWrapper: ByteBufferWrapper, parameters: Array<Any>): T { override fun read(byteBufferWrapper: ByteBufferWrapper, parameters: Array<Any>): T {
if (parameters.isEmpty()) { if (parameters.isEmpty()) {
throw IllegalArgumentException("parameters cannot be empty, must has a Int") throw IllegalArgumentException("parameters cannot be empty, must has a Int")
@@ -226,42 +325,49 @@ abstract class ArrayBufferWrapperConvertor<T : Any>(
override fun getType(): Class<T> = typer override fun getType(): Class<T> = typer
} }
/** [ByteArray] 类型转换器,使用 putByteArray/getByteArray 读写。 */
class ByteArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<ByteArray>( class ByteArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<ByteArray>(
ByteBufferWrapper::putByteArray, ByteBufferWrapper::putByteArray,
ByteBufferWrapper::getByteArray, ByteBufferWrapper::getByteArray,
ByteArray::class.java, ByteArray::class.java,
) )
/** [CharArray] 类型转换器,使用 putCharArray/getCharArray 读写。 */
class CharArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<CharArray>( class CharArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<CharArray>(
ByteBufferWrapper::putCharArray, ByteBufferWrapper::putCharArray,
ByteBufferWrapper::getCharArray, ByteBufferWrapper::getCharArray,
CharArray::class.java, CharArray::class.java,
) )
/** [ShortArray] 类型转换器,使用 putShortArray/getShortArray 读写。 */
class ShortArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<ShortArray>( class ShortArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<ShortArray>(
ByteBufferWrapper::putShortArray, ByteBufferWrapper::putShortArray,
ByteBufferWrapper::getShortArray, ByteBufferWrapper::getShortArray,
ShortArray::class.java, ShortArray::class.java,
) )
/** [IntArray] 类型转换器,使用 putIntArray/getIntArray 读写。 */
class IntArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<IntArray>( class IntArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<IntArray>(
ByteBufferWrapper::putIntArray, ByteBufferWrapper::putIntArray,
ByteBufferWrapper::getIntArray, ByteBufferWrapper::getIntArray,
IntArray::class.java, IntArray::class.java,
) )
/** [LongArray] 类型转换器,使用 putLongArray/getLongArray 读写。 */
class LongArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<LongArray>( class LongArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<LongArray>(
ByteBufferWrapper::putLongArray, ByteBufferWrapper::putLongArray,
ByteBufferWrapper::getLongArray, ByteBufferWrapper::getLongArray,
LongArray::class.java, LongArray::class.java,
) )
/** [FloatArray] 类型转换器,使用 putFloatArray/getFloatArray 读写。 */
class FloatArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<FloatArray>( class FloatArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<FloatArray>(
ByteBufferWrapper::putFloatArray, ByteBufferWrapper::putFloatArray,
ByteBufferWrapper::getFloatArray, ByteBufferWrapper::getFloatArray,
FloatArray::class.java, FloatArray::class.java,
) )
/** [DoubleArray] 类型转换器,使用 putDoubleArray/getDoubleArray 读写。 */
class DoubleArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<DoubleArray>( class DoubleArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<DoubleArray>(
ByteBufferWrapper::putDoubleArray, ByteBufferWrapper::putDoubleArray,
ByteBufferWrapper::getDoubleArray, ByteBufferWrapper::getDoubleArray,
@@ -269,6 +375,7 @@ class DoubleArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<DoubleArra
) )
/** [BooleanArray] 类型转换器,使用 putBooleanArray/getBooleanArray 读写。 */
class BooleanArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<BooleanArray>( class BooleanArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<BooleanArray>(
ByteBufferWrapper::putBooleanArray, ByteBufferWrapper::putBooleanArray,
ByteBufferWrapper::getBooleanArray, ByteBufferWrapper::getBooleanArray,
@@ -295,4 +295,12 @@ fun ByteBuffer.putVarInt(value: Int): ByteBuffer = this.putVarLong(value.toLong(
fun ByteBuffer.putVarShort(value: Short): ByteBuffer = this.putVarLong(value.toLong()) fun ByteBuffer.putVarShort(value: Short): ByteBuffer = this.putVarLong(value.toLong())
/**
* 将 [ByteBuffer] 中剩余的全部字节写入指定的输出流。
*
* 此操作会读取从当前位置到 limit 之间的所有字节,并推进 position。
*
* @param outputStream 目标输出流
* @throws IOException 如果写入过程中发生 I/O 错误
*/
fun ByteBuffer.writeStream(outputStream: OutputStream) = outputStream.write(this.toByteArray()) fun ByteBuffer.writeStream(outputStream: OutputStream) = outputStream.write(this.toByteArray())
@@ -26,23 +26,56 @@ import java.io.OutputStream
import java.io.Serializable import java.io.Serializable
import java.nio.ByteBuffer import java.nio.ByteBuffer
/**
* 可转换为字节数组的对象接口。
*
* 实现该接口的对象可以将自身序列化为字节数组,并支持写入输出流或 [ByteBuffer]。
*/
interface ByteConvertible : Serializable { interface ByteConvertible : Serializable {
/**
* 将当前对象转换为字节数组。
*
* @return 表示当前对象的字节数组
*/
fun toBytes(): ByteArray fun toBytes(): ByteArray
/**
* 将当前对象转换后的字节数组写入指定的输出流。
*
* @param outputStream 目标输出流
*/
fun writeToStream(outputStream: OutputStream) { fun writeToStream(outputStream: OutputStream) {
outputStream.write(toBytes()) outputStream.write(toBytes())
} }
/**
* 将当前对象转换后的字节数组写入指定的 [ByteBuffer]。
*
* @param byteBuffer 目标缓冲区
*/
fun putToByteBuffer(byteBuffer: ByteBuffer) { fun putToByteBuffer(byteBuffer: ByteBuffer) {
byteBuffer.put(toBytes()) byteBuffer.put(toBytes())
} }
/**
* 伴生对象,提供面向输出流和缓冲区的便捷扩展函数。
*/
companion object { companion object {
/**
* 将 [ByteConvertible] 对象写入当前输出流。
*
* @param byteConvertible 要写入的可转换对象
*/
fun OutputStream.write(byteConvertible: ByteConvertible) { fun OutputStream.write(byteConvertible: ByteConvertible) {
byteConvertible.writeToStream(this) byteConvertible.writeToStream(this)
} }
/**
* 将 [ByteConvertible] 对象写入当前 [ByteBuffer]。
*
* @param byteConvertible 要写入的可转换对象
*/
fun ByteBuffer.put(byteConvertible: ByteConvertible) { fun ByteBuffer.put(byteConvertible: ByteConvertible) {
byteConvertible.putToByteBuffer(this) byteConvertible.putToByteBuffer(this)
} }
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile ByteFlags.kt * CurrentFile ByteFlags.kt
* LastUpdate 2026-06-21 10:40:58 * LastUpdate 2026-11-16 21:35:04
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -64,7 +64,7 @@ data class ByteFlags(
* *
* @param byte 要解析的字节 * @param byte 要解析的字节
*/ */
fun fromByte(byte: Byte) { fun fromByte(byte: Byte): ByteFlags {
val value = byte.toInt() and 0xFF val value = byte.toInt() and 0xFF
b0 = (value and 0x01) != 0 b0 = (value and 0x01) != 0
b1 = (value and 0x02) != 0 b1 = (value and 0x02) != 0
@@ -74,6 +74,7 @@ data class ByteFlags(
b5 = (value and 0x20) != 0 b5 = (value and 0x20) != 0
b6 = (value and 0x40) != 0 b6 = (value and 0x40) != 0
b7 = (value and 0x80) != 0 b7 = (value and 0x80) != 0
return this
} }
/** /**
@@ -122,7 +123,7 @@ data class ByteFlags(
* @param value 要设置的布尔值 * @param value 要设置的布尔值
* @throws IndexOutOfBoundsException 如果索引不在 0~7 范围内 * @throws IndexOutOfBoundsException 如果索引不在 0~7 范围内
*/ */
operator fun set(index: Int, value: Boolean) { operator fun set(index: Int, value: Boolean): ByteFlags {
when (index) { when (index) {
0 -> b0 = value 0 -> b0 = value
1 -> b1 = value 1 -> b1 = value
@@ -134,12 +135,13 @@ data class ByteFlags(
7 -> b7 = value 7 -> b7 = value
else -> throw IndexOutOfBoundsException("索引必须在0-7之间") else -> throw IndexOutOfBoundsException("索引必须在0-7之间")
} }
return this
} }
/** /**
* 将所有 8 个位设置为 `true`。 * 将所有 8 个位设置为 `true`。
*/ */
fun setAll() { fun setAll(): ByteFlags {
b0 = true b0 = true
b1 = true b1 = true
b2 = true b2 = true
@@ -148,12 +150,14 @@ data class ByteFlags(
b5 = true b5 = true
b6 = true b6 = true
b7 = true b7 = true
return this
} }
/** /**
* 将所有 8 个位设置为 `false`。 * 将所有 8 个位设置为 `false`。
*/ */
fun clearAll() { fun clearAll(): ByteFlags {
b0 = false b0 = false
b1 = false b1 = false
b2 = false b2 = false
@@ -162,12 +166,14 @@ data class ByteFlags(
b5 = false b5 = false
b6 = false b6 = false
b7 = false b7 = false
return this
} }
/** /**
* 对所有位执行逻辑取反(true ↔ false)。 * 对所有位执行逻辑取反(true ↔ false)。
*/ */
fun toggleAll() { fun toggleAll(): ByteFlags {
b0 = !b0 b0 = !b0
b1 = !b1 b1 = !b1
b2 = !b2 b2 = !b2
@@ -176,6 +182,8 @@ data class ByteFlags(
b5 = !b5 b5 = !b5
b6 = !b6 b6 = !b6
b7 = !b7 b7 = !b7
return this
} }
/** /**
@@ -184,8 +192,9 @@ data class ByteFlags(
* @param index 要切换的位索引(0~7) * @param index 要切换的位索引(0~7)
* @throws IndexOutOfBoundsException 如果索引无效 * @throws IndexOutOfBoundsException 如果索引无效
*/ */
fun toggle(index: Int) { fun toggle(index: Int): ByteFlags {
this[index] = !this[index] this[index] = !this[index]
return this
} }
/** /**
@@ -304,7 +313,7 @@ data class ByteFlags(
* @param array 布尔数组(长度至少为 8) * @param array 布尔数组(长度至少为 8)
* @throws IllegalArgumentException 如果数组长度不足 8 * @throws IllegalArgumentException 如果数组长度不足 8
*/ */
fun fromBooleanArray(array: BooleanArray) { fun fromBooleanArray(array: BooleanArray): ByteFlags {
require(array.size >= 8) { "数组长度至少为8" } require(array.size >= 8) { "数组长度至少为8" }
b0 = array[0] b0 = array[0]
b1 = array[1] b1 = array[1]
@@ -314,6 +323,7 @@ data class ByteFlags(
b5 = array[5] b5 = array[5]
b6 = array[6] b6 = array[6]
b7 = array[7] b7 = array[7]
return this
} }
/** /**
@@ -403,6 +413,9 @@ data class ByteFlags(
return "ByteFlags(${toBinaryString()} = ${toHexString()})" return "ByteFlags(${toBinaryString()} = ${toHexString()})"
} }
/**
* 伴生对象,提供 [ByteFlags] 的多种静态工厂方法。
*/
companion object { companion object {
/** /**
* 创建一个所有位均为 `true` 的 [ByteFlags] 实例。 * 创建一个所有位均为 `true` 的 [ByteFlags] 实例。
@@ -434,7 +447,6 @@ data class ByteFlags(
fun fromBinaryString(binary: String): ByteFlags { fun fromBinaryString(binary: String): ByteFlags {
require(binary.length == 8) { "二进制字符串长度必须为8" } require(binary.length == 8) { "二进制字符串长度必须为8" }
require(binary.all { it == '0' || it == '1' }) { "二进制字符串只能包含0和1" } require(binary.all { it == '0' || it == '1' }) { "二进制字符串只能包含0和1" }
return ByteFlags( return ByteFlags(
binary[7] == '1', // b0 是最低位(对应字符串最后一位) binary[7] == '1', // b0 是最低位(对应字符串最后一位)
binary[6] == '1', binary[6] == '1',
@@ -447,6 +459,19 @@ data class ByteFlags(
) )
} }
/**
* 从布尔数组创建 [ByteFlags] 实例。
*
* 使用数组的前 8 个元素(索引 0~7),分别对应 b0~b7。
*
* @param booleanArray 布尔数组(长度至少为 8)
* @return 对应的 ByteFlags 实例
* @throws IllegalArgumentException 如果数组长度不足 8
*/
fun fromBooleanArray(booleanArray: BooleanArray): ByteFlags {
return ByteFlags().fromBooleanArray(booleanArray)
}
/** /**
* 从整数创建 [ByteFlags] 实例(仅使用低 8 位)。 * 从整数创建 [ByteFlags] 实例(仅使用低 8 位)。
* *
@@ -28,11 +28,24 @@ import com.mingliqiye.utils.json.api.JSONA
import java.io.* import java.io.*
/**
* 通过 Java 序列化机制对当前对象进行深克隆。
*
* @param T 对象类型,必须实现 [Serializable]
* @return 深克隆后的新对象
*/
@JvmName("_inline_deepClone") @JvmName("_inline_deepClone")
inline fun <reified T : Serializable> T.deepClone(): T { inline fun <reified T : Serializable> T.deepClone(): T {
return deepClone(this) return deepClone(this)
} }
/**
* 通过 JSON 序列化与反序列化对当前对象进行深克隆。
*
* @param T 对象类型
* @return 深克隆后的新对象
* @throws JsonException 如果 JSON 转换过程中发生异常
*/
inline fun <reified T> T.deepJsonClone(): T { inline fun <reified T> T.deepJsonClone(): T {
try { try {
return JSONA.convert(this as Any, this!!.javaClass) as T return JSONA.convert(this as Any, this!!.javaClass) as T
@@ -43,6 +56,16 @@ inline fun <reified T> T.deepJsonClone(): T {
} }
} }
/**
* 通过 Java 序列化机制对对象进行深克隆。
*
* 将对象序列化到内存后再反序列化,得到一个全新的对象副本。
*
* @param T 对象类型,必须实现 [Serializable]
* @param obj 要克隆的对象
* @return 深克隆后的新对象
* @throws RuntimeException 如果序列化或反序列化过程中发生 I/O 异常或类找不到
*/
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
fun <T : Serializable?> deepClone(obj: T): T { fun <T : Serializable?> deepClone(obj: T): T {
try { try {
@@ -1,5 +1,5 @@
/* /*
* Copyright 2025 mingliqiye * Copyright 2026 mingliqiye
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile Collection.kt * CurrentFile Collection.kt
* LastUpdate 2025-09-21 14:36:57 * LastUpdate 2026-11-23 07:33:23
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -158,7 +158,7 @@ inline fun <reified T> Array<T>.getLast(): T? {
* @return 指定索引处的元素或默认值 * @return 指定索引处的元素或默认值
*/ */
inline fun <reified T> Collection<T>.getOrDefault( inline fun <reified T> Collection<T>.getOrDefault(
index: Int, defaultValue: T index: Int, defaultValue: T,
): T { ): T {
if (!(!this.isEmpty() && index < this.size)) { if (!(!this.isEmpty() && index < this.size)) {
return defaultValue return defaultValue
@@ -745,6 +745,38 @@ fun <T> newStack(elements: Collection<T>): Stack<T> {
} }
/**
* 创建一个新的 ArrayDeque 实例。
*
* @param T 元素类型
* @return 新创建的 ArrayDeque
*/
fun <T> newArrayDeque(): ArrayDeque<T> {
return ArrayDeque()
}
/**
* 使用可变参数创建一个新的 ArrayDeque 实例。
*
* @param T 元素类型
* @param elements 可变参数列表
* @return 新创建的 ArrayDeque
*/
fun <T> newArrayDeque(vararg elements: T): ArrayDeque<T> {
return newArrayDeque(elements.toList())
}
/**
* 将集合转换为新的 ArrayDeque 实例。
*
* @param T 元素类型
* @param elements 输入集合
* @return 新创建的 ArrayDeque
*/
fun <T> newArrayDeque(elements: Collection<T>): ArrayDeque<T> {
return ArrayDeque(elements)
}
/** /**
* 创建一个新的 TreeSet 实例,并指定比较器。 * 创建一个新的 TreeSet 实例,并指定比较器。
* *
@@ -980,14 +1012,22 @@ fun toArray(list: List<Char>): CharArray {
* @param list 输入的 List * @param list 输入的 List
* @return 转换后的数组 * @return 转换后的数组
*/ */
inline fun <reified T> toArray(list: List<T>): Array<T> { inline fun <reified T : Any> toArray(list: List<T>): Array<T> {
if (list.isEmpty()) if (list.isEmpty())
return arrayOf<T>() return arrayOf()
return SuperStream.of<T>(list) return SuperStream.of<T>(list)
.toArray(T::class.java) .toArray(T::class.java)
} }
fun <T> toArray(list: List<T>, clazz: Class<T>): Array<T> { /**
* 将任意类型的 List 转换为指定类型的数组。
*
* @param T 元素类型
* @param list 输入的 List
* @param clazz 数组元素类型对应的 Class 对象
* @return 转换后的数组
*/
fun <T : Any> toArray(list: List<T>, clazz: Class<T>): Array<T> {
return SuperStream.of<T>(list) return SuperStream.of<T>(list)
.toArray(clazz) .toArray(clazz)
} }
@@ -39,6 +39,9 @@ class IsChanged<T> {
*/ */
private val atomicReferenceData: AtomicReference<T> = AtomicReference() private val atomicReferenceData: AtomicReference<T> = AtomicReference()
/**
* 无参构造函数,初始数据为 null
*/
constructor() constructor()
/** /**
@@ -63,6 +63,9 @@ private fun getGetterName(fieldName: String): String {
*/ */
open class ConfigurationProps { open class ConfigurationProps {
/**
* 伴生对象,提供根据命令行参数初始化配置类实例的静态方法。
*/
companion object { companion object {
/** /**
* 初始化配置类实例,并根据命令行参数填充其字段。 * 初始化配置类实例,并根据命令行参数填充其字段。
@@ -241,6 +244,9 @@ open class ConfigurationProps {
} }
} }
/**
* 打印配置项帮助信息,列出所有标注了 ConfigurationProp 且允许显示帮助的字段名称、类型和描述。
*/
fun printHelp() { fun printHelp() {
val fields = this::class.java.declaredFields val fields = this::class.java.declaredFields
val help = StringBuilder() val help = StringBuilder()
@@ -258,6 +264,9 @@ open class ConfigurationProps {
println(help) println(help)
} }
/**
* 当前配置对象所有声明字段的名称与值的映射。
*/
val fields: Map<String, Any?> val fields: Map<String, Any?>
get() { get() {
val fields = this::class.java.declaredFields val fields = this::class.java.declaredFields
@@ -143,4 +143,3 @@ private fun getAllFields(clazz: Class<*>): List<Field> {
} }
return fields return fields
} }
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile BadGatewayException.kt * CurrentFile BadGatewayException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-11-23 16:14:45
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Bad Gateway" * @param message 异常信息,默认为 "Bad Gateway"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class BadGatewayException( class BadGatewayException @JvmOverloads constructor(
override val message: String? = "Bad Gateway", override val message: String? = "Bad Gateway",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(502, message, cause) ) : HttpStatusException(502, message, cause)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile BadRequestException.kt * CurrentFile BadRequestException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:19
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Bad Request" * @param message 异常信息,默认为 "Bad Request"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class BadRequestException( class BadRequestException @JvmOverloads constructor(
override val message: String? = "Bad Request", override val message: String? = "Bad Request",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(400, message, cause) ) : HttpStatusException(400, message, cause)
@@ -22,6 +22,14 @@
package com.mingliqiye.utils.exception package com.mingliqiye.utils.exception
/**
* 表示编码或解码过程中发生的异常。
*
* @param message 异常信息,默认为 null
* @param throwable 异常原因,默认为 null
* @param enableSuppression 是否启用异常抑制,默认为 false
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
*/
class CodecException @JvmOverloads constructor( class CodecException @JvmOverloads constructor(
message: String? = null, message: String? = null,
throwable: Throwable? = null, throwable: Throwable? = null,
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile ConflictException.kt * CurrentFile ConflictException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:19
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Conflict" * @param message 异常信息,默认为 "Conflict"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class ConflictException( class ConflictException @JvmOverloads constructor(
override val message: String? = "Conflict", override val message: String? = "Conflict",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(409, message, cause) ) : HttpStatusException(409, message, cause)
@@ -22,6 +22,14 @@
package com.mingliqiye.utils.exception package com.mingliqiye.utils.exception
/**
* 表示 JSON 内容为空时抛出的异常。
*
* @param message 异常信息,默认为 null
* @param throwable 异常原因,默认为 null
* @param enableSuppression 是否启用异常抑制,默认为 false
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
*/
class EmptyJsonException @JvmOverloads constructor( class EmptyJsonException @JvmOverloads constructor(
message: String? = null, message: String? = null,
throwable: Throwable? = null, throwable: Throwable? = null,
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile ForbiddenException.kt * CurrentFile ForbiddenException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:19
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Forbidden" * @param message 异常信息,默认为 "Forbidden"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class ForbiddenException( class ForbiddenException @JvmOverloads constructor(
override val message: String? = "Forbidden", override val message: String? = "Forbidden",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(403, message, cause) ) : HttpStatusException(403, message, cause)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile FoundException.kt * CurrentFile FoundException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:19
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Found" * @param message 异常信息,默认为 "Found"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class FoundException( class FoundException @JvmOverloads constructor(
override val message: String? = "Found", override val message: String? = "Found",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(302, message, cause) ) : HttpStatusException(302, message, cause)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile GatewayTimeoutException.kt * CurrentFile GatewayTimeoutException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:48
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Gateway Timeout" * @param message 异常信息,默认为 "Gateway Timeout"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class GatewayTimeoutException( class GatewayTimeoutException @JvmOverloads constructor(
override val message: String? = "Gateway Timeout", override val message: String? = "Gateway Timeout",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(504, message, cause) ) : HttpStatusException(504, message, cause)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile GoneException.kt * CurrentFile GoneException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:48
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Gone" * @param message 异常信息,默认为 "Gone"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class GoneException( class GoneException @JvmOverloads constructor(
override val message: String? = "Gone", override val message: String? = "Gone",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(410, message, cause) ) : HttpStatusException(410, message, cause)
@@ -22,6 +22,14 @@
package com.mingliqiye.utils.exception package com.mingliqiye.utils.exception
/**
* 表示 HTTP 相关异常的基类,继承自 [MingLiUtilsBaseException]。
*
* @param message 异常信息,默认为 null
* @param throwable 异常原因,默认为 null
* @param enableSuppression 是否启用异常抑制,默认为 false
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
*/
open class HttpException @JvmOverloads constructor( open class HttpException @JvmOverloads constructor(
message: String? = null, message: String? = null,
throwable: Throwable? = null, throwable: Throwable? = null,
@@ -16,18 +16,28 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile HttpStatusException.kt * CurrentFile HttpStatusException.kt
* LastUpdate 2026-10-11 17:02:06 * LastUpdate 2026-11-23 17:02:00
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
package com.mingliqiye.utils.exception package com.mingliqiye.utils.exception
import kotlin.reflect.KClass
/** /**
* 表示 HTTP 异常的基类,继承自 [RuntimeException]。 * HTTP 状态异常基类,供所有携带状态码的异常继承。
* *
* @param statusCode HTTP 状态码 * 子类在构造时固定 [statusCode];调用方可以据此统一生成 HTTP 响应,
* @param message 异常信息,默认为 null * 而不必为每一种状态码单独判断异常类型。
* @param cause 异常原因,默认为 null *
* 构造函数标注了 `@JvmOverloads`,Java 侧可以按不同参数个数调用。
*
* @property statusCode HTTP 状态码
* @param message 异常描述;为 `null` 时沿用父类行为
* @param throwable 导致该异常的原始异常
* @param enableSuppression 是否启用异常抑制
* @param writableStackTrace 是否生成堆栈信息
* @see MingLiUtilsBaseException
*/ */
open class HttpStatusException @JvmOverloads constructor( open class HttpStatusException @JvmOverloads constructor(
val statusCode: Int, val statusCode: Int,
@@ -36,3 +46,395 @@ open class HttpStatusException @JvmOverloads constructor(
enableSuppression: Boolean = false, enableSuppression: Boolean = false,
writableStackTrace: Boolean = true, writableStackTrace: Boolean = true,
) : MingLiUtilsBaseException(message, throwable, enableSuppression, writableStackTrace) ) : MingLiUtilsBaseException(message, throwable, enableSuppression, writableStackTrace)
/**
* HTTP 状态异常类型枚举。
*
* 每个枚举项绑定一个 [HttpStatusException] 子类:可以用 [kClazz] / [clazz] 按类型查找,
* 也可以用 [init] 按消息创建对应的异常实例。
*
* @property kClazz 异常类型的 Kotlin 类
* @property init 使用给定消息创建异常的工厂函数
*/
enum class HttpStatusExceptionEnum(
val kClazz: KClass<out HttpStatusException>,
val init: (message: String?) -> HttpStatusException,
) {
/** 502 Bad Gateway,对应 [BadGatewayException]。 */
BAD_GATEWAY_EXCEPTION(BadGatewayException::class, ::BadGatewayException),
/** 400 Bad Request,对应 [BadRequestException]。 */
BAD_REQUEST_EXCEPTION(BadRequestException::class, ::BadRequestException),
/** 409 Conflict,对应 [ConflictException]。 */
CONFLICT_EXCEPTION(ConflictException::class, ::ConflictException),
/** 403 Forbidden,对应 [ForbiddenException]。 */
FORBIDDEN_EXCEPTION(ForbiddenException::class, ::ForbiddenException),
/** 302 Found,对应 [FoundException]。 */
FOUND_EXCEPTION(FoundException::class, ::FoundException),
/** 504 Gateway Timeout,对应 [GatewayTimeoutException]。 */
GATEWAY_TIMEOUT_EXCEPTION(GatewayTimeoutException::class, ::GatewayTimeoutException),
/** 410 Gone,对应 [GoneException]。 */
GONE_EXCEPTION(GoneException::class, ::GoneException),
/** 505 HTTP Version Not Supported,对应 [HttpVersionNotSupportedException]。 */
HTTP_VERSION_NOT_SUPPORTED_EXCEPTION(HttpVersionNotSupportedException::class, ::HttpVersionNotSupportedException),
/** 500 Internal Server Error,对应 [InternalServerErrorException]。 */
INTERNAL_SERVER_ERROR_EXCEPTION(InternalServerErrorException::class, ::InternalServerErrorException),
/** 411 Length Required,对应 [LengthRequiredException]。 */
LENGTH_REQUIRED_EXCEPTION(LengthRequiredException::class, ::LengthRequiredException),
/** 405 Method Not Allowed,对应 [MethodNotAllowedException]。 */
METHOD_NOT_ALLOWED_EXCEPTION(MethodNotAllowedException::class, ::MethodNotAllowedException),
/** 301 Moved Permanently,对应 [MovedPermanentlyException]。 */
MOVED_PERMANENTLY_EXCEPTION(MovedPermanentlyException::class, ::MovedPermanentlyException),
/** 300 Multiple Choices,对应 [MultipleChoicesException]。 */
MULTIPLE_CHOICES_EXCEPTION(MultipleChoicesException::class, ::MultipleChoicesException),
/** 406 Not Acceptable,对应 [NotAcceptableException]。 */
NOT_ACCEPTABLE_EXCEPTION(NotAcceptableException::class, ::NotAcceptableException),
/** 404 Not Found,对应 [NotFoundException]。 */
NOT_FOUND_EXCEPTION(NotFoundException::class, ::NotFoundException),
/** 501 Not Implemented,对应 [NotImplementedException]。 */
NOT_IMPLEMENTED_EXCEPTION(NotImplementedException::class, ::NotImplementedException),
/** 304 Not Modified,对应 [NotModifiedException]。 */
NOT_MODIFIED_EXCEPTION(NotModifiedException::class, ::NotModifiedException),
/** 402 Payment Required,对应 [PaymentRequiredException]。 */
PAYMENT_REQUIRED_EXCEPTION(PaymentRequiredException::class, ::PaymentRequiredException),
/** 412 Precondition Failed,对应 [PreconditionFailedException]。 */
PRECONDITION_FAILED_EXCEPTION(PreconditionFailedException::class, ::PreconditionFailedException),
/** 407 Proxy Authentication Required,对应 [ProxyAuthenticationRequiredException]。 */
PROXY_AUTHENTICATION_REQUIRED_EXCEPTION(
ProxyAuthenticationRequiredException::class,
::ProxyAuthenticationRequiredException
),
/** 416 Requested Range Not Satisfiable,对应 [RequestedRangeNotSatisfiableException]。 */
REQUESTED_RANGE_NOT_SATISFIABLE_EXCEPTION(
RequestedRangeNotSatisfiableException::class,
::RequestedRangeNotSatisfiableException
),
/** 413 Request Entity Too Large,对应 [RequestEntityTooLargeException]。 */
REQUEST_ENTITY_TOO_LARGE_EXCEPTION(RequestEntityTooLargeException::class, ::RequestEntityTooLargeException),
/** 408 Request Timeout,对应 [RequestTimeoutException]。 */
REQUEST_TIMEOUT_EXCEPTION(RequestTimeoutException::class, ::RequestTimeoutException),
/** 414 Request URI Too Large,对应 [RequestUriTooLargeException]。 */
REQUEST_URI_TOO_LARGE_EXCEPTION(RequestUriTooLargeException::class, ::RequestUriTooLargeException),
/** 303 See Other,对应 [SeeOtherException]。 */
SEE_OTHER_EXCEPTION(SeeOtherException::class, ::SeeOtherException),
/** 503 Service Unavailable,对应 [ServiceUnavailableException]。 */
SERVICE_UNAVAILABLE_EXCEPTION(ServiceUnavailableException::class, ::ServiceUnavailableException),
/** 307 Temporary Redirect,对应 [TemporaryRedirectException]。 */
TEMPORARY_REDIRECT_EXCEPTION(TemporaryRedirectException::class, ::TemporaryRedirectException),
/** 401 Unauthorized,对应 [UnauthorizedException]。 */
UNAUTHORIZED_EXCEPTION(UnauthorizedException::class, ::UnauthorizedException),
/** 415 Unsupported Media Type,对应 [UnsupportedMediaTypeException]。 */
UNSUPPORTED_MEDIA_TYPE_EXCEPTION(UnsupportedMediaTypeException::class, ::UnsupportedMediaTypeException),
/** 305 Use Proxy,对应 [UseProxyException]。 */
USE_PROXY_EXCEPTION(UseProxyException::class, ::UseProxyException);
/** [kClazz] 对应的 Java 类,便于反射或按 `Class` 注册。 */
val clazz: Class<out HttpStatusException> = this.kClazz.java
}
/**
* 抛出 HTTP 502 Bad Gateway 异常。
*
* @param message 异常描述,默认为 `"Bad Gateway"`
* @throws BadGatewayException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError502(message: String? = "Bad Gateway"): Nothing = throw BadGatewayException(message)
/**
* 抛出 HTTP 400 Bad Request 异常。
*
* @param message 异常描述,默认为 `"Bad Request"`
* @throws BadRequestException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError400(message: String? = "Bad Request"): Nothing = throw BadRequestException(message)
/**
* 抛出 HTTP 409 Conflict 异常。
*
* @param message 异常描述,默认为 `"Conflict"`
* @throws ConflictException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError409(message: String? = "Conflict"): Nothing = throw ConflictException(message)
/**
* 抛出 HTTP 403 Forbidden 异常。
*
* @param message 异常描述,默认为 `"Forbidden"`
* @throws ForbiddenException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError403(message: String? = "Forbidden"): Nothing = throw ForbiddenException(message)
/**
* 抛出 HTTP 302 Found 异常。
*
* @param message 异常描述,默认为 `"Found"`
* @throws FoundException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError302(message: String? = "Found"): Nothing = throw FoundException(message)
/**
* 抛出 HTTP 504 Gateway Timeout 异常。
*
* @param message 异常描述,默认为 `"Gateway Timeout"`
* @throws GatewayTimeoutException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError504(message: String? = "Gateway Timeout"): Nothing = throw GatewayTimeoutException(message)
/**
* 抛出 HTTP 410 Gone 异常。
*
* @param message 异常描述,默认为 `"Gone"`
* @throws GoneException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError410(message: String? = "Gone"): Nothing = throw GoneException(message)
/**
* 抛出 HTTP 505 HTTP Version Not Supported 异常。
*
* @param message 异常描述,默认为 `"HTTP Version Not Supported"`
* @throws HttpVersionNotSupportedException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError505(message: String? = "HTTP Version Not Supported"): Nothing =
throw HttpVersionNotSupportedException(message)
/**
* 抛出 HTTP 500 Internal Server Error 异常。
*
* @param message 异常描述,默认为 `"Internal Server Error"`
* @throws InternalServerErrorException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError500(message: String? = "Internal Server Error"): Nothing =
throw InternalServerErrorException(message)
/**
* 抛出 HTTP 411 Length Required 异常。
*
* @param message 异常描述,默认为 `"Length Required"`
* @throws LengthRequiredException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError411(message: String? = "Length Required"): Nothing = throw LengthRequiredException(message)
/**
* 抛出 HTTP 405 Method Not Allowed 异常。
*
* @param message 异常描述,默认为 `"Method Not Allowed"`
* @throws MethodNotAllowedException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError405(message: String? = "Method Not Allowed"): Nothing = throw MethodNotAllowedException(message)
/**
* 抛出 HTTP 301 Moved Permanently 异常。
*
* @param message 异常描述,默认为 `"Moved Permanently"`
* @throws MovedPermanentlyException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError301(message: String? = "Moved Permanently"): Nothing = throw MovedPermanentlyException(message)
/**
* 抛出 HTTP 300 Multiple Choices 异常。
*
* @param message 异常描述,默认为 `"Multiple Choices"`
* @throws MultipleChoicesException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError300(message: String? = "Multiple Choices"): Nothing = throw MultipleChoicesException(message)
/**
* 抛出 HTTP 406 Not Acceptable 异常。
*
* @param message 异常描述,默认为 `"Not Acceptable"`
* @throws NotAcceptableException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError406(message: String? = "Not Acceptable"): Nothing = throw NotAcceptableException(message)
/**
* 抛出 HTTP 404 Not Found 异常。
*
* @param message 异常描述,默认为 `"Not Found"`
* @throws NotFoundException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError404(message: String? = "Not Found"): Nothing = throw NotFoundException(message)
/**
* 抛出 HTTP 501 Not Implemented 异常。
*
* @param message 异常描述,默认为 `"Not Implemented"`
* @throws NotImplementedException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError501(message: String? = "Not Implemented"): Nothing = throw NotImplementedException(message)
/**
* 抛出 HTTP 304 Not Modified 异常。
*
* @param message 异常描述,默认为 `"Not Modified"`
* @throws NotModifiedException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError304(message: String? = "Not Modified"): Nothing = throw NotModifiedException(message)
/**
* 抛出 HTTP 402 Payment Required 异常。
*
* @param message 异常描述,默认为 `"Payment Required"`
* @throws PaymentRequiredException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError402(message: String? = "Payment Required"): Nothing = throw PaymentRequiredException(message)
/**
* 抛出 HTTP 412 Precondition Failed 异常。
*
* @param message 异常描述,默认为 `"Precondition Failed"`
* @throws PreconditionFailedException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError412(message: String? = "Precondition Failed"): Nothing = throw PreconditionFailedException(message)
/**
* 抛出 HTTP 407 Proxy Authentication Required 异常。
*
* @param message 异常描述,默认为 `"Proxy Authentication Required"`
* @throws ProxyAuthenticationRequiredException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError407(message: String? = "Proxy Authentication Required"): Nothing =
throw ProxyAuthenticationRequiredException(message)
/**
* 抛出 HTTP 416 Requested Range Not Satisfiable 异常。
*
* @param message 异常描述,默认为 `"Requested Range Not Satisfiable"`
* @throws RequestedRangeNotSatisfiableException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError416(message: String? = "Requested Range Not Satisfiable"): Nothing =
throw RequestedRangeNotSatisfiableException(message)
/**
* 抛出 HTTP 413 Request Entity Too Large 异常。
*
* @param message 异常描述,默认为 `"Request Entity Too Large"`
* @throws RequestEntityTooLargeException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError413(message: String? = "Request Entity Too Large"): Nothing =
throw RequestEntityTooLargeException(message)
/**
* 抛出 HTTP 408 Request Timeout 异常。
*
* @param message 异常描述,默认为 `"Request Timeout"`
* @throws RequestTimeoutException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError408(message: String? = "Request Timeout"): Nothing = throw RequestTimeoutException(message)
/**
* 抛出 HTTP 414 Request URI Too Large 异常。
*
* @param message 异常描述,默认为 `"Request URI Too Large"`
* @throws RequestUriTooLargeException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError414(message: String? = "Request URI Too Large"): Nothing =
throw RequestUriTooLargeException(message)
/**
* 抛出 HTTP 303 See Other 异常。
*
* @param message 异常描述,默认为 `"See Other"`
* @throws SeeOtherException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError303(message: String? = "See Other"): Nothing = throw SeeOtherException(message)
/**
* 抛出 HTTP 503 Service Unavailable 异常。
*
* @param message 异常描述,默认为 `"Service Unavailable"`
* @throws ServiceUnavailableException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError503(message: String? = "Service Unavailable"): Nothing = throw ServiceUnavailableException(message)
/**
* 抛出 HTTP 307 Temporary Redirect 异常。
*
* @param message 异常描述,默认为 `"Temporary Redirect"`
* @throws TemporaryRedirectException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError307(message: String? = "Temporary Redirect"): Nothing = throw TemporaryRedirectException(message)
/**
* 抛出 HTTP 401 Unauthorized 异常。
*
* @param message 异常描述,默认为 `"Unauthorized"`
* @throws UnauthorizedException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError401(message: String? = "Unauthorized"): Nothing = throw UnauthorizedException(message)
/**
* 抛出 HTTP 415 Unsupported Media Type 异常。
*
* @param message 异常描述,默认为 `"Unsupported Media Type"`
* @throws UnsupportedMediaTypeException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError415(message: String? = "Unsupported Media Type"): Nothing =
throw UnsupportedMediaTypeException(message)
/**
* 抛出 HTTP 305 Use Proxy 异常。
*
* @param message 异常描述,默认为 `"Use Proxy"`
* @throws UseProxyException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError305(message: String? = "Use Proxy"): Nothing = throw UseProxyException(message)
@@ -22,6 +22,14 @@
package com.mingliqiye.utils.exception package com.mingliqiye.utils.exception
/**
* 表示 HTTP URL 无效或处理失败时抛出的异常。
*
* @param message 异常信息,默认为 null
* @param throwable 异常原因,默认为 null
* @param enableSuppression 是否启用异常抑制,默认为 false
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
*/
open class HttpUrlException @JvmOverloads constructor( open class HttpUrlException @JvmOverloads constructor(
message: String? = null, message: String? = null,
throwable: Throwable? = null, throwable: Throwable? = null,
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile HttpVersionNotSupportedException.kt * CurrentFile HttpVersionNotSupportedException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:48
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "HTTP Version Not Supported" * @param message 异常信息,默认为 "HTTP Version Not Supported"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class HttpVersionNotSupportedException( class HttpVersionNotSupportedException @JvmOverloads constructor(
override val message: String? = "HTTP Version Not Supported", override val message: String? = "HTTP Version Not Supported",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(505, message, cause) ) : HttpStatusException(505, message, cause)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile InternalServerErrorException.kt * CurrentFile InternalServerErrorException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:19
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Internal Server Error" * @param message 异常信息,默认为 "Internal Server Error"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class InternalServerErrorException( class InternalServerErrorException @JvmOverloads constructor(
override val message: String? = "Internal Server Error", override val message: String? = "Internal Server Error",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(500, message, cause) ) : HttpStatusException(500, message, cause)
@@ -22,6 +22,14 @@
package com.mingliqiye.utils.exception package com.mingliqiye.utils.exception
/**
* 表示 JSON 内容无效或不合法时抛出的异常。
*
* @param message 异常信息,默认为 null
* @param throwable 异常原因,默认为 null
* @param enableSuppression 是否启用异常抑制,默认为 false
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
*/
class InvalidJsonException @JvmOverloads constructor( class InvalidJsonException @JvmOverloads constructor(
message: String? = null, message: String? = null,
throwable: Throwable? = null, throwable: Throwable? = null,
@@ -0,0 +1,38 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JsonFormatException.kt
* LastUpdate 2026-11-23 16:14:00
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.exception
/**
* 表示 JSON 格式不正确时抛出的异常。
*
* @param message 异常信息,默认为 null
* @param throwable 异常原因,默认为 null
* @param enableSuppression 是否启用异常抑制,默认为 false
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
*/
class JsonFormatException @JvmOverloads constructor(
message: String? = null,
throwable: Throwable? = null,
enableSuppression: Boolean = false,
writableStackTrace: Boolean = true,
) : JsonException(message, throwable, enableSuppression, writableStackTrace)
@@ -22,6 +22,14 @@
package com.mingliqiye.utils.exception package com.mingliqiye.utils.exception
/**
* 表示 JSON 对象类型转换失败时抛出的异常。
*
* @param message 异常信息,默认为 null
* @param throwable 异常原因,默认为 null
* @param enableSuppression 是否启用异常抑制,默认为 false
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
*/
class JsonObjectCastException @JvmOverloads constructor( class JsonObjectCastException @JvmOverloads constructor(
message: String? = null, message: String? = null,
throwable: Throwable? = null, throwable: Throwable? = null,
@@ -16,12 +16,21 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile JsonParserException.kt * CurrentFile JsonParserException.kt
* LastUpdate 2026-10-11 16:53:41 * LastUpdate 2026-11-23 16:14:00
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
package com.mingliqiye.utils.exception package com.mingliqiye.utils.exception
/**
* 表示 JSON 解析过程中发生的异常。
*
* @param message 异常信息,默认为 null
* @param throwable 异常原因,默认为 null
* @param enableSuppression 是否启用异常抑制,默认为 false
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
*/
class JsonParserException @JvmOverloads constructor( class JsonParserException @JvmOverloads constructor(
message: String? = null, message: String? = null,
throwable: Throwable? = null, throwable: Throwable? = null,
@@ -22,6 +22,14 @@
package com.mingliqiye.utils.exception package com.mingliqiye.utils.exception
/**
* 表示 JSON 数据类型不匹配时抛出的异常。
*
* @param message 异常信息,默认为 null
* @param throwable 异常原因,默认为 null
* @param enableSuppression 是否启用异常抑制,默认为 false
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
*/
class JsonTypeException @JvmOverloads constructor( class JsonTypeException @JvmOverloads constructor(
message: String? = null, message: String? = null,
throwable: Throwable? = null, throwable: Throwable? = null,
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile LengthRequiredException.kt * CurrentFile LengthRequiredException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:48
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Length Required" * @param message 异常信息,默认为 "Length Required"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class LengthRequiredException( class LengthRequiredException @JvmOverloads constructor(
override val message: String? = "Length Required", override val message: String? = "Length Required",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(411, message, cause) ) : HttpStatusException(411, message, cause)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile MethodNotAllowedException.kt * CurrentFile MethodNotAllowedException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:48
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Method Not Allowed" * @param message 异常信息,默认为 "Method Not Allowed"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class MethodNotAllowedException( class MethodNotAllowedException @JvmOverloads constructor(
override val message: String? = "Method Not Allowed", override val message: String? = "Method Not Allowed",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(405, message, cause) ) : HttpStatusException(405, message, cause)
@@ -22,6 +22,14 @@
package com.mingliqiye.utils.exception package com.mingliqiye.utils.exception
/**
* mingli-utils 工具库所有异常的基类,继承自 [RuntimeException]。
*
* @param message 异常信息,默认为 null
* @param cause 异常原因,默认为 null
* @param enableSuppression 是否启用异常抑制,默认为 false
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
*/
open class MingLiUtilsBaseException @JvmOverloads constructor( open class MingLiUtilsBaseException @JvmOverloads constructor(
message: String? = null, message: String? = null,
cause: Throwable? = null, cause: Throwable? = null,
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile MovedPermanentlyException.kt * CurrentFile MovedPermanentlyException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:48
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Moved Permanently" * @param message 异常信息,默认为 "Moved Permanently"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class MovedPermanentlyException( class MovedPermanentlyException @JvmOverloads constructor(
override val message: String? = "Moved Permanently", override val message: String? = "Moved Permanently",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(301, message, cause) ) : HttpStatusException(301, message, cause)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile MultipleChoicesException.kt * CurrentFile MultipleChoicesException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:48
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Multiple Choices" * @param message 异常信息,默认为 "Multiple Choices"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class MultipleChoicesException( class MultipleChoicesException @JvmOverloads constructor(
override val message: String? = "Multiple Choices", override val message: String? = "Multiple Choices",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(300, message, cause) ) : HttpStatusException(300, message, cause)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile NotAcceptableException.kt * CurrentFile NotAcceptableException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:19
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Not Acceptable" * @param message 异常信息,默认为 "Not Acceptable"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class NotAcceptableException( class NotAcceptableException @JvmOverloads constructor(
override val message: String? = "Not Acceptable", override val message: String? = "Not Acceptable",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(406, message, cause) ) : HttpStatusException(406, message, cause)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile NotFoundException.kt * CurrentFile NotFoundException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:19
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Not Found" * @param message 异常信息,默认为 "Not Found"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class NotFoundException( class NotFoundException @JvmOverloads constructor(
override val message: String? = "Not Found", override val message: String? = "Not Found",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(404, message, cause) ) : HttpStatusException(404, message, cause)
@@ -16,12 +16,20 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile NotFoundResourceException.kt * CurrentFile NotFoundResourceException.kt
* LastUpdate 2026-10-11 16:53:58 * LastUpdate 2026-11-23 16:38:55
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
package com.mingliqiye.utils.exception package com.mingliqiye.utils.exception
/**
* 表示请求的资源未找到时抛出的异常。
*
* @param message 异常信息,默认为 null
* @param throwable 异常原因,默认为 null
* @param enableSuppression 是否启用异常抑制,默认为 false
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
*/
class NotFoundResourceException @JvmOverloads constructor( class NotFoundResourceException @JvmOverloads constructor(
message: String? = null, message: String? = null,
throwable: Throwable? = null, throwable: Throwable? = null,
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile NotImplementedException.kt * CurrentFile NotImplementedException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:19
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Not Implemented" * @param message 异常信息,默认为 "Not Implemented"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class NotImplementedException( class NotImplementedException @JvmOverloads constructor(
override val message: String? = "Not Implemented", override val message: String? = "Not Implemented",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(501, message, cause) ) : HttpStatusException(501, message, cause)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile NotModifiedException.kt * CurrentFile NotModifiedException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:48
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Not Modified" * @param message 异常信息,默认为 "Not Modified"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class NotModifiedException( class NotModifiedException @JvmOverloads constructor(
override val message: String? = "Not Modified", override val message: String? = "Not Modified",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(304, message, cause) ) : HttpStatusException(304, message, cause)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile PaymentRequiredException.kt * CurrentFile PaymentRequiredException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:19
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Payment Required" * @param message 异常信息,默认为 "Payment Required"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class PaymentRequiredException( class PaymentRequiredException @JvmOverloads constructor(
override val message: String? = "Payment Required", override val message: String? = "Payment Required",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(402, message, cause) ) : HttpStatusException(402, message, cause)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile PreconditionFailedException.kt * CurrentFile PreconditionFailedException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:19
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Precondition Failed" * @param message 异常信息,默认为 "Precondition Failed"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class PreconditionFailedException( class PreconditionFailedException @JvmOverloads constructor(
override val message: String? = "Precondition Failed", override val message: String? = "Precondition Failed",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(412, message, cause) ) : HttpStatusException(412, message, cause)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile ProxyAuthenticationRequiredException.kt * CurrentFile ProxyAuthenticationRequiredException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:19
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Proxy Authentication Required" * @param message 异常信息,默认为 "Proxy Authentication Required"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class ProxyAuthenticationRequiredException( class ProxyAuthenticationRequiredException @JvmOverloads constructor(
override val message: String? = "Proxy Authentication Required", override val message: String? = "Proxy Authentication Required",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(407, message, cause) ) : HttpStatusException(407, message, cause)
@@ -0,0 +1,34 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile RedisLockTimeoutException.kt
* LastUpdate 2026-11-23 10:21:41
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.exception
/**
* Redis 分布式锁等待超时异常。
*
* @param lockKey 未获取到的完整锁 key(含前缀)
* @param waitMillis 等待时长(毫秒)
*/
class RedisLockTimeoutException(
val lockKey: String,
val waitMillis: Long,
) : MingLiUtilsBaseException("获取 Redis 分布式锁超时: $lockKey,等待 ${waitMillis}ms")
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile RequestEntityTooLargeException.kt * CurrentFile RequestEntityTooLargeException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:19
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Request Entity Too Large" * @param message 异常信息,默认为 "Request Entity Too Large"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class RequestEntityTooLargeException( class RequestEntityTooLargeException @JvmOverloads constructor(
override val message: String? = "Request Entity Too Large", override val message: String? = "Request Entity Too Large",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(413, message, cause) ) : HttpStatusException(413, message, cause)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile RequestTimeoutException.kt * CurrentFile RequestTimeoutException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:19
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Request Timeout" * @param message 异常信息,默认为 "Request Timeout"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class RequestTimeoutException( class RequestTimeoutException @JvmOverloads constructor(
override val message: String? = "Request Timeout", override val message: String? = "Request Timeout",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(408, message, cause) ) : HttpStatusException(408, message, cause)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile RequestUriTooLargeException.kt * CurrentFile RequestUriTooLargeException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:19
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Request URI Too Large" * @param message 异常信息,默认为 "Request URI Too Large"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class RequestUriTooLargeException( class RequestUriTooLargeException @JvmOverloads constructor(
override val message: String? = "Request URI Too Large", override val message: String? = "Request URI Too Large",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(414, message, cause) ) : HttpStatusException(414, message, cause)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile RequestedRangeNotSatisfiableException.kt * CurrentFile RequestedRangeNotSatisfiableException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:19
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Requested Range Not Satisfiable" * @param message 异常信息,默认为 "Requested Range Not Satisfiable"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class RequestedRangeNotSatisfiableException( class RequestedRangeNotSatisfiableException @JvmOverloads constructor(
override val message: String? = "Requested Range Not Satisfiable", override val message: String? = "Requested Range Not Satisfiable",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(416, message, cause) ) : HttpStatusException(416, message, cause)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile SeeOtherException.kt * CurrentFile SeeOtherException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:19
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "See Other" * @param message 异常信息,默认为 "See Other"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class SeeOtherException( class SeeOtherException @JvmOverloads constructor(
override val message: String? = "See Other", override val message: String? = "See Other",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(303, message, cause) ) : HttpStatusException(303, message, cause)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile ServiceUnavailableException.kt * CurrentFile ServiceUnavailableException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:19
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Service Unavailable" * @param message 异常信息,默认为 "Service Unavailable"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class ServiceUnavailableException( class ServiceUnavailableException @JvmOverloads constructor(
override val message: String? = "Service Unavailable", override val message: String? = "Service Unavailable",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(503, message, cause) ) : HttpStatusException(503, message, cause)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile TemporaryRedirectException.kt * CurrentFile TemporaryRedirectException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:19
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Temporary Redirect" * @param message 异常信息,默认为 "Temporary Redirect"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class TemporaryRedirectException( class TemporaryRedirectException @JvmOverloads constructor(
override val message: String? = "Temporary Redirect", override val message: String? = "Temporary Redirect",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(307, message, cause) ) : HttpStatusException(307, message, cause)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile UnauthorizedException.kt * CurrentFile UnauthorizedException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:19
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Unauthorized" * @param message 异常信息,默认为 "Unauthorized"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class UnauthorizedException( class UnauthorizedException @JvmOverloads constructor(
override val message: String? = "Unauthorized", override val message: String? = "Unauthorized",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(401, message, cause) ) : HttpStatusException(401, message, cause)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile UnsupportedMediaTypeException.kt * CurrentFile UnsupportedMediaTypeException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:19
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Unsupported Media Type" * @param message 异常信息,默认为 "Unsupported Media Type"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class UnsupportedMediaTypeException( class UnsupportedMediaTypeException @JvmOverloads constructor(
override val message: String? = "Unsupported Media Type", override val message: String? = "Unsupported Media Type",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(415, message, cause) ) : HttpStatusException(415, message, cause)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile UseProxyException.kt * CurrentFile UseProxyException.kt
* LastUpdate 2026-02-05 14:55:04 * LastUpdate 2026-10-22 22:09:48
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -28,7 +28,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 "Use Proxy" * @param message 异常信息,默认为 "Use Proxy"
* @param cause 异常原因,默认为 null * @param cause 异常原因,默认为 null
*/ */
class UseProxyException( class UseProxyException @JvmOverloads constructor(
override val message: String? = "Use Proxy", override val message: String? = "Use Proxy",
override val cause: Throwable? = null, override val cause: Throwable? = null,
) : HttpStatusException(305, message, cause) ) : HttpStatusException(305, message, cause)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile FileUtils.kt * CurrentFile FileUtils.kt
* LastUpdate 2026-01-28 10:49:14 * LastUpdate 2026-10-28 22:40:34
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@file:JvmName("FileUtils") @file:JvmName("FileUtils")
@@ -627,7 +627,9 @@ fun File.writeLines(lines: List<String>) {
*/ */
fun File.writeLines(lines: List<String>, charset: Charset) { fun File.writeLines(lines: List<String>, charset: Charset) {
this.parentFile?.mkdirs() this.parentFile?.mkdirs()
this.writeLines(lines, charset) for (line in lines) {
this.writeText(line + System.lineSeparator(), charset)
}
} }
// 复制文件 // 复制文件
@@ -1,707 +0,0 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ForEach.kt
* LastUpdate 2026-02-27 12:45:39
* UpdateUser MingLiPro
*/
@file:JvmName("ForEach")
package com.mingliqiye.utils.foreach
import com.mingliqiye.utils.functions.*
/**
* 对给定的可迭代对象执行指定的操作,同时处理元素值和索引。
* 根据可迭代对象是否实现 RandomAccess 接口选择最优的遍历方式。
*
* @param iterable 要遍历的可迭代对象
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
* @param <T> 可迭代对象中元素的类型
*/
fun <T> forEach(
iterable: Iterable<T>, action: P2Function<in T, in Int>
) {
when (iterable) {
is RandomAccess if iterable is MutableList<*> -> {
// 如果是支持随机访问的可变列表,则使用索引遍历以提高性能
val list = iterable as MutableList<T>
for (i in list.indices) {
action.call(list[i], i)
}
}
is MutableList<*> -> {
// 对于普通可变列表,使用迭代器进行遍历,并手动维护索引
var index = 0
val it = iterable.iterator()
while (it.hasNext()) {
action.call(it.next(), index)
index++
}
}
else -> {
// 对于其他类型的可迭代对象,使用增强 for 循环并手动维护索引
for ((index, element) in iterable.withIndex()) {
action.call(element, index)
}
}
}
}
/**
* 对给定的可迭代对象执行指定的操作,仅处理元素值。
* 根据可迭代对象是否实现 RandomAccess 接口选择最优的遍历方式。
*
* @param iterable 要遍历的可迭代对象
* @param action 要对每个元素执行的操作,只接收元素值作为参数
* @param <T> 可迭代对象中元素的类型
*/
fun <T> forEach(
iterable: Iterable<T>, action: P1Function<in T>
) {
if (iterable is RandomAccess) {
// 如果是支持随机访问的列表,则使用索引遍历以提高性能
val list = iterable as MutableList<T>
for (i in list.indices) {
action.call(list[i])
}
} else {
// 否则使用增强 for 循环进行遍历
for (element in iterable) {
action.call(element)
}
}
}
/**
* 对给定的可迭代对象执行指定的操作,同时处理元素值和索引。
* 如果操作返回 true,则提前终止遍历。
* 根据可迭代对象是否实现 RandomAccess 接口选择最优的遍历方式。
*
* @param iterable 要遍历的可迭代对象
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
* @param <T> 可迭代对象中元素的类型
*/
fun <T> forEachB(
iterable: Iterable<T>, action: P2RFunction<in T, in Int, out Boolean>
) {
when (iterable) {
is RandomAccess if iterable is MutableList<*> -> {
// 如果是支持随机访问的可变列表,则使用索引遍历以提高性能
val list = iterable as MutableList<T>
for (i in list.indices) {
if (action.call(list[i], i)) return
}
}
is MutableList<*> -> {
// 对于普通可变列表,使用迭代器进行遍历,并手动维护索引
var index = 0
val it = iterable.iterator()
while (it.hasNext()) {
if (action.call(it.next(), index)) return
index++
}
}
else -> {
// 对于其他类型的可迭代对象,使用增强 for 循环并手动维护索引
var index = 0
for (element in iterable) {
if (action.call(element, index)) return
index++
}
}
}
}
/**
* 对给定的可迭代对象执行指定的操作,仅处理元素值。
* 如果操作返回 true,则提前终止遍历。
* 根据可迭代对象是否实现 RandomAccess 接口选择最优的遍历方式。
*
* @param iterable 要遍历的可迭代对象
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
* @param <T> 可迭代对象中元素的类型
*/
fun <T> forEachB(
iterable: Iterable<T>, action: P1RFunction<in T, out Boolean>
) {
if (iterable is RandomAccess) {
// 如果是支持随机访问的列表,则使用索引遍历以提高性能
val list = iterable as MutableList<T>
for (i in list.indices) {
if (action.call(list[i])) return
}
} else {
// 否则使用增强 for 循环进行遍历
for (element in iterable) {
if (action.call(element)) return
}
}
}
/**
* 对给定的数组执行指定的操作,同时处理元素值和索引。
*
* @param array 要遍历的数组
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
* @param <T> 数组中元素的类型
*/
fun <T> forEach(
array: Array<T>, action: P2Function<in T, in Int>
) {
forEach(array.toList(), action)
}
/**
* 对给定的数组执行指定的操作,仅处理元素值。
*
* @param array 要遍历的数组
* @param action 要对每个元素执行的操作,只接收元素值作为参数
* @param <T> 数组中元素的类型
*/
fun <T> forEach(
array: Array<T>, action: P1Function<in T>
) {
forEach(array.toList(), action)
}
/**
* 对给定的数组执行指定的操作,同时处理元素值和索引。
* 如果操作返回 true,则提前终止遍历。
*
* @param array 要遍历的数组
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
* @param <T> 数组中元素的类型
*/
fun <T> forEachB(
array: Array<T>, action: P2RFunction<in T, in Int, out Boolean>
) {
forEachB(array.toList(), action)
}
/**
* 对给定的数组执行指定的操作,仅处理元素值。
* 如果操作返回 true,则提前终止遍历。
*
* @param array 要遍历的数组
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
* @param <T> 数组中元素的类型
*/
fun <T> forEachB(
array: Array<T>, action: P1RFunction<in T, out Boolean>
) {
forEachB(array.toList(), action)
}
/**
* 对给定的字节数组执行指定的操作,同时处理元素值和索引。
*
* @param array 要遍历的字节数组
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
*/
fun forEach(
array: ByteArray, action: P2Function<in Byte, in Int>
) {
forEach(array.toList(), action)
}
/**
* 对给定的字节数组执行指定的操作,仅处理元素值。
*
* @param array 要遍历的字节数组
* @param action 要对每个元素执行的操作,只接收元素值作为参数
*/
fun forEach(
array: ByteArray, action: P1Function<in Byte>
) {
forEach(array.toList(), action)
}
/**
* 对给定的字节数组执行指定的操作,同时处理元素值和索引。
* 如果操作返回 true,则提前终止遍历。
*
* @param array 要遍历的字节数组
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
*/
fun forEachB(
array: ByteArray, action: P2RFunction<in Byte, in Int, out Boolean>
) {
forEachB(array.toList(), action)
}
/**
* 对给定的字节数组执行指定的操作,仅处理元素值。
* 如果操作返回 true,则提前终止遍历。
*
* @param array 要遍历的字节数组
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
*/
fun forEachB(
array: ByteArray, action: P1RFunction<in Byte, out Boolean>
) {
forEachB(array.toList(), action)
}
/**
* 对给定的字符数组执行指定的操作,同时处理元素值和索引。
*
* @param array 要遍历的字符数组
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
*/
fun forEach(
array: CharArray, action: P2Function<in Char, in Int>
) {
forEach(array.toList(), action)
}
/**
* 对给定的字符数组执行指定的操作,仅处理元素值。
*
* @param array 要遍历的字符数组
* @param action 要对每个元素执行的操作,只接收元素值作为参数
*/
fun forEach(
array: CharArray, action: P1Function<in Char>
) {
forEach(array.toList(), action)
}
/**
* 对给定的字符数组执行指定的操作,同时处理元素值和索引。
* 如果操作返回 true,则提前终止遍历。
*
* @param array 要遍历的字符数组
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
*/
fun forEachB(
array: CharArray, action: P2RFunction<in Char, in Int, out Boolean>
) {
forEachB(array.toList(), action)
}
/**
* 对给定的字符数组执行指定的操作,仅处理元素值。
* 如果操作返回 true,则提前终止遍历。
*
* @param array 要遍历的字符数组
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
*/
fun forEachB(
array: CharArray, action: P1RFunction<in Char, out Boolean>
) {
forEachB(array.toList(), action)
}
/**
* 对给定的整型数组执行指定的操作,同时处理元素值和索引。
*
* @param array 要遍历的整型数组
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
*/
fun forEach(
array: IntArray, action: P2Function<in Int, in Int>
) {
forEach(array.toList(), action)
}
/**
* 对给定的整型数组执行指定的操作,仅处理元素值。
*
* @param array 要遍历的整型数组
* @param action 要对每个元素执行的操作,只接收元素值作为参数
*/
fun forEach(
array: IntArray, action: P1Function<in Int>
) {
forEach(array.toList(), action)
}
/**
* 对给定的整型数组执行指定的操作,同时处理元素值和索引。
* 如果操作返回 true,则提前终止遍历。
*
* @param array 要遍历的整型数组
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
*/
fun forEachB(
array: IntArray, action: P2RFunction<in Int, in Int, out Boolean>
) {
forEachB(array.toList(), action)
}
/**
* 对给定的整型数组执行指定的操作,仅处理元素值。
* 如果操作返回 true,则提前终止遍历。
*
* @param array 要遍历的整型数组
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
*/
fun forEachB(
array: IntArray, action: P1RFunction<in Int, out Boolean>
) {
forEachB(array.toList(), action)
}
/**
* 对给定的长整型数组执行指定的操作,同时处理元素值和索引。
*
* @param array 要遍历的长整型数组
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
*/
fun forEach(
array: LongArray, action: P2Function<in Long, in Int>
) {
forEach(array.toList(), action)
}
/**
* 对给定的长整型数组执行指定的操作,仅处理元素值。
*
* @param array 要遍历的长整型数组
* @param action 要对每个元素执行的操作,只接收元素值作为参数
*/
fun forEach(
array: LongArray, action: P1Function<in Long>
) {
forEach(array.toList(), action)
}
/**
* 对给定的长整型数组执行指定的操作,同时处理元素值和索引。
* 如果操作返回 true,则提前终止遍历。
*
* @param array 要遍历的长整型数组
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
*/
fun forEachB(
array: LongArray, action: P2RFunction<in Long, in Int, out Boolean>
) {
forEachB(array.toList(), action)
}
/**
* 对给定的长整型数组执行指定的操作,仅处理元素值。
* 如果操作返回 true,则提前终止遍历。
*
* @param array 要遍历的长整型数组
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
*/
fun forEachB(
array: LongArray, action: P1RFunction<in Long, out Boolean>
) {
forEachB(array.toList(), action)
}
/**
* 对给定的短整型数组执行指定的操作,同时处理元素值和索引。
*
* @param array 要遍历的短整型数组
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
*/
fun forEach(
array: ShortArray, action: P2Function<in Short, in Int>
) {
forEach(array.toList(), action)
}
/**
* 对给定的短整型数组执行指定的操作,仅处理元素值。
*
* @param array 要遍历的短整型数组
* @param action 要对每个元素执行的操作,只接收元素值作为参数
*/
fun forEach(
array: ShortArray, action: P1Function<in Short>
) {
forEach(array.toList(), action)
}
/**
* 对给定的短整型数组执行指定的操作,同时处理元素值和索引。
* 如果操作返回 true,则提前终止遍历。
*
* @param array 要遍历的短整型数组
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
*/
fun forEachB(
array: ShortArray, action: P2RFunction<in Short, in Int, out Boolean>
) {
forEachB(array.toList(), action)
}
/**
* 对给定的短整型数组执行指定的操作,仅处理元素值。
* 如果操作返回 true,则提前终止遍历。
*
* @param array 要遍历的短整型数组
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
*/
fun forEachB(
array: ShortArray, action: P1RFunction<in Short, out Boolean>
) {
forEachB(array.toList(), action)
}
/**
* 对给定的浮点数组执行指定的操作,同时处理元素值和索引。
*
* @param array 要遍历的浮点数组
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
*/
fun forEach(
array: FloatArray, action: P2Function<in Float, in Int>
) {
forEach(array.toList(), action)
}
/**
* 对给定的浮点数组执行指定的操作,仅处理元素值。
*
* @param array 要遍历的浮点数组
* @param action 要对每个元素执行的操作,只接收元素值作为参数
*/
fun forEach(
array: FloatArray, action: P1Function<in Float>
) {
forEach(array.toList(), action)
}
/**
* 对给定的浮点数组执行指定的操作,同时处理元素值和索引。
* 如果操作返回 true,则提前终止遍历。
*
* @param array 要遍历的浮点数组
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
*/
fun forEachB(
array: FloatArray, action: P2RFunction<in Float, in Int, out Boolean>
) {
forEachB(array.toList(), action)
}
/**
* 对给定的浮点数组执行指定的操作,仅处理元素值。
* 如果操作返回 true,则提前终止遍历。
*
* @param array 要遍历的浮点数组
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
*/
fun forEachB(
array: FloatArray, action: P1RFunction<in Float, out Boolean>
) {
forEachB(array.toList(), action)
}
/**
* 对给定的双精度浮点数组执行指定的操作,同时处理元素值和索引。
*
* @param array 要遍历的双精度浮点数组
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
*/
fun forEach(
array: DoubleArray, action: P2Function<in Double, in Int>
) {
forEach(array.toList(), action)
}
/**
* 对给定的双精度浮点数组执行指定的操作,仅处理元素值。
*
* @param array 要遍历的双精度浮点数组
* @param action 要对每个元素执行的操作,只接收元素值作为参数
*/
fun forEach(
array: DoubleArray, action: P1Function<in Double>
) {
forEach(array.toList(), action)
}
/**
* 对给定的双精度浮点数组执行指定的操作,同时处理元素值和索引。
* 如果操作返回 true,则提前终止遍历。
*
* @param array 要遍历的双精度浮点数组
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
*/
fun forEachB(
array: DoubleArray, action: P2RFunction<in Double, in Int, out Boolean>
) {
forEachB(array.toList(), action)
}
/**
* 对给定的双精度浮点数组执行指定的操作,仅处理元素值。
* 如果操作返回 true,则提前终止遍历。
*
* @param array 要遍历的双精度浮点数组
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
*/
fun forEachB(
array: DoubleArray, action: P1RFunction<in Double, out Boolean>
) {
forEachB(array.toList(), action)
}
/**
* 对给定的布尔数组执行指定的操作,同时处理元素值和索引。
*
* @param array 要遍历的布尔数组
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
*/
fun forEach(
array: BooleanArray, action: P2Function<in Boolean, in Int>
) {
forEach(array.toList(), action)
}
/**
* 对给定的布尔数组执行指定的操作,仅处理元素值。
*
* @param array 要遍历的布尔数组
* @param action 要对每个元素执行的操作,只接收元素值作为参数
*/
fun forEach(
array: BooleanArray, action: P1Function<in Boolean>
) {
forEach(array.toList(), action)
}
/**
* 对给定的布尔数组执行指定的操作,同时处理元素值和索引。
* 如果操作返回 true,则提前终止遍历。
*
* @param array 要遍历的布尔数组
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
*/
fun forEachB(
array: BooleanArray, action: P2RFunction<in Boolean, in Int, out Boolean>
) {
forEachB(array.toList(), action)
}
/**
* 对给定的布尔数组执行指定的操作,仅处理元素值。
* 如果操作返回 true,则提前终止遍历。
*
* @param array 要遍历的布尔数组
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
*/
fun forEachB(
array: BooleanArray, action: P1RFunction<in Boolean, out Boolean>
) {
forEachB(array.toList(), action)
}
/**
* 对给定的键值对集合执行指定的操作,同时处理键、值和索引。
* 如果操作返回 true,则提前终止遍历。
*
* @param array 要遍历的键值对集合
* @param action 要对每个键值对执行的操作,接收键、值和索引作为参数,返回 Boolean 表示是否提前终止
* @param <K> 键的类型
* @param <V> 值的类型
* @param <A> 集合的具体类型
*/
fun <K, V, A : Collection<Map.Entry<K, V>>> forEachB(
array: A, action: P3RFunction<in K, in V, in Int, out Boolean>
) {
forEachB(array, P2RFunction<Map.Entry<K, V>, Int, Boolean> { p1, p2 -> action.call(p1.key, p1.value, p2) })
}
/**
* 对给定的映射执行指定的操作,同时处理键、值和索引。
* 如果操作返回 true,则提前终止遍历。
*
* @param map 要遍历的映射
* @param action 要对每个键值对执行的操作,接收键、值和索引作为参数,返回 Boolean 表示是否提前终止
* @param <K> 键的类型
* @param <V> 值的类型
* @param <A> 映射的具体类型
*/
fun <K, V, A : Map<K, V>> forEachB(
map: A, action: P3RFunction<in K, in V, in Int, out Boolean>
) {
forEachB(map.entries, P2RFunction<Map.Entry<K, V>, Int, Boolean> { p1, p2 -> action.call(p1.key, p1.value, p2) })
}
/**
* 对给定的键值对集合执行指定的操作,仅处理键和值。
*
* @param array 要遍历的键值对集合
* @param action 要对每个键值对执行的操作,接收键和值作为参数
* @param <K> 键的类型
* @param <V> 值的类型
* @param <A> 集合的具体类型
*/
fun <K, V, A : Collection<Map.Entry<K, V>>> forEachMap(
array: A, action: P2Function<in K, in V>
) {
forEach(array, P1Function<Map.Entry<K, V>> { p1 -> action.call(p1.key, p1.value) })
}
/**
* 对给定的映射执行指定的操作,仅处理键和值。
*
* @param map 要遍历的映射
* @param action 要对每个键值对执行的操作,接收键和值作为参数
* @param <K> 键的类型
* @param <V> 值的类型
* @param <A> 映射的具体类型
*/
fun <K, V, A : Map<K, V>> forEachMap(
map: A, action: P2Function<in K, in V>
) {
forEach(map.entries, P1Function<Map.Entry<K, V>> { p1 -> action.call(p1.key, p1.value) })
}
/**
* 对给定的键值对集合执行指定的操作,仅处理键和值。
* 如果操作返回 true,则提前终止遍历。
*
* @param array 要遍历的键值对集合
* @param action 要对每个键值对执行的操作,接收键和值作为参数,返回 Boolean 表示是否提前终止
* @param <K> 键的类型
* @param <V> 值的类型
* @param <A> 集合的具体类型
*/
fun <K, V, A : Collection<Map.Entry<K, V>>> forEachMapB(
array: A, action: P2RFunction<in K, in V, out Boolean>
) {
forEachB(array, P1RFunction<Map.Entry<K, V>, Boolean> { p1 -> action.call(p1.key, p1.value) })
}
/**
* 对给定的映射执行指定的操作,仅处理键和值。
* 如果操作返回 true,则提前终止遍历。
*
* @param map 要遍历的映射
* @param action 要对每个键值对执行的操作,接收键和值作为参数,返回 Boolean 表示是否提前终止
* @param <K> 键的类型
* @param <V> 值的类型
* @param <A> 映射的具体类型
*/
fun <K, V, A : Map<K, V>> forEachMapB(
map: A, action: P2RFunction<in K, in V, out Boolean>
) {
forEachB(map.entries, P1RFunction<Map.Entry<K, V>, Boolean> { p1 -> action.call(p1.key, p1.value) })
}
@@ -24,151 +24,381 @@
package com.mingliqiye.utils.functions package com.mingliqiye.utils.functions
/**
* 对任意对象执行无参函数调用,执行完成后返回接收者自身。
*
* @param function 要执行的无参函数
* @return 接收者自身
*/
fun <T> T.with(function: Function): T = function.call().let { fun <T> T.with(function: Function): T = function.call().let {
this this
} }
/**
* 以接收者自身作为参数执行函数调用,执行完成后返回接收者自身。
*
* @param function 接收一个参数的函数,调用时传入接收者自身
* @return 接收者自身
*/
fun <T> T.with(function: P1Function<T>): T = function.call(this).let { fun <T> T.with(function: P1Function<T>): T = function.call(this).let {
this this
} }
/**
* 无参数且无返回值的函数式接口。
*/
@FunctionalInterface @FunctionalInterface
fun interface Function { fun interface Function {
/**
* 执行函数调用。
*/
fun call() fun call()
} }
/**
* 接收 1 个参数且无返回值的函数式接口。
*
* @param P 参数类型
*/
@FunctionalInterface @FunctionalInterface
fun interface P1Function<P> { fun interface P1Function<P> {
/**
* 执行函数调用。
*
* @param p 参数
*/
fun call(p: P) fun call(p: P)
} }
/**
* 无参数且带返回值的函数式接口。
*
* @param R 返回值类型
*/
@FunctionalInterface @FunctionalInterface
fun interface RFunction<R> { fun interface RFunction<R> {
/**
* 执行函数调用。
*
* @return 函数执行结果
*/
fun call(): R fun call(): R
} }
/**
* 接收 1 个参数且带返回值的函数式接口。
*
* @param P 参数类型
* @param R 返回值类型
*/
@FunctionalInterface @FunctionalInterface
fun interface P1RFunction<P, R> { fun interface P1RFunction<P, R> {
/**
* 执行函数调用。
*
* @param p 参数
* @return 函数执行结果
*/
fun call(p: P): R fun call(p: P): R
} }
/**
* 接收 2 个参数且无返回值的函数式接口。
*
* @param P 第 1 个参数类型
* @param P1 第 2 个参数类型
*/
@FunctionalInterface @FunctionalInterface
fun interface P2Function<P, P1> { fun interface P2Function<P, P1> {
/**
* 执行函数调用。
*
* @param p 第 1 个参数
* @param p1 第 2 个参数
*/
fun call(p: P, p1: P1) fun call(p: P, p1: P1)
} }
/**
* 接收 2 个参数且带返回值的函数式接口。
*
* @param P 第 1 个参数类型
* @param P1 第 2 个参数类型
* @param R 返回值类型
*/
@FunctionalInterface @FunctionalInterface
fun interface P2RFunction<P, P1, R> { fun interface P2RFunction<P, P1, R> {
/**
* 执行函数调用。
*
* @param p 第 1 个参数
* @param p1 第 2 个参数
* @return 函数执行结果
*/
fun call(p: P, p1: P1): R fun call(p: P, p1: P1): R
} }
/**
* 接收 3 个参数且无返回值的函数式接口,参数类型依次为 P、P1、P2。
*/
@FunctionalInterface @FunctionalInterface
fun interface P3Function<P, P1, P2> { fun interface P3Function<P, P1, P2> {
/**
* 执行函数调用,参数依次为 p、p1、p2。
*/
fun call(p: P, p1: P1, p2: P2) fun call(p: P, p1: P1, p2: P2)
} }
/**
* 接收 3 个参数且带返回值的函数式接口,参数类型依次为 P、P1、P2,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P3RFunction<P, P1, P2, R> { fun interface P3RFunction<P, P1, P2, R> {
/**
* 执行函数调用,参数依次为 p、p1、p2。
*
* @return 函数执行结果
*/
fun call(p: P, p1: P1, p2: P2): R fun call(p: P, p1: P1, p2: P2): R
} }
/**
* 接收 4 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P3。
*/
@FunctionalInterface @FunctionalInterface
fun interface P4Function<P, P1, P2, P3> { fun interface P4Function<P, P1, P2, P3> {
/**
* 执行函数调用,参数依次为 p、p1 至 p3。
*/
fun call(p: P, p1: P1, p2: P2, p3: P3) fun call(p: P, p1: P1, p2: P2, p3: P3)
} }
/**
* 接收 4 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P3,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P4RFunction<P, P1, P2, P3, R> { fun interface P4RFunction<P, P1, P2, P3, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p3。
*
* @return 函数执行结果
*/
fun call(p: P, p1: P1, p2: P2, p3: P3): R fun call(p: P, p1: P1, p2: P2, p3: P3): R
} }
/**
* 接收 5 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P4。
*/
@FunctionalInterface @FunctionalInterface
fun interface P5Function<P, P1, P2, P3, P4> { fun interface P5Function<P, P1, P2, P3, P4> {
/**
* 执行函数调用,参数依次为 p、p1 至 p4。
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4) fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4)
} }
/**
* 接收 5 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P4,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P5RFunction<P, P1, P2, P3, P4, R> { fun interface P5RFunction<P, P1, P2, P3, P4, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p4。
*
* @return 函数执行结果
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4): R fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4): R
} }
/**
* 接收 6 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P5。
*/
@FunctionalInterface @FunctionalInterface
fun interface P6Function<P, P1, P2, P3, P4, P5> { fun interface P6Function<P, P1, P2, P3, P4, P5> {
/**
* 执行函数调用,参数依次为 p、p1 至 p5。
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5) fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5)
} }
/**
* 接收 6 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P5,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P6RFunction<P, P1, P2, P3, P4, P5, R> { fun interface P6RFunction<P, P1, P2, P3, P4, P5, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p5。
*
* @return 函数执行结果
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5): R fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5): R
} }
/**
* 接收 7 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P6。
*/
@FunctionalInterface @FunctionalInterface
fun interface P7Function<P, P1, P2, P3, P4, P5, P6> { fun interface P7Function<P, P1, P2, P3, P4, P5, P6> {
/**
* 执行函数调用,参数依次为 p、p1 至 p6。
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6) fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6)
} }
/**
* 接收 7 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P6,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P7RFunction<P, P1, P2, P3, P4, P5, P6, R> { fun interface P7RFunction<P, P1, P2, P3, P4, P5, P6, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p6。
*
* @return 函数执行结果
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6): R fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6): R
} }
/**
* 接收 8 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P7。
*/
@FunctionalInterface @FunctionalInterface
fun interface P8Function<P, P1, P2, P3, P4, P5, P6, P7> { fun interface P8Function<P, P1, P2, P3, P4, P5, P6, P7> {
/**
* 执行函数调用,参数依次为 p、p1 至 p7。
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7) fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7)
} }
/**
* 接收 8 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P7,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P8RFunction<P, P1, P2, P3, P4, P5, P6, P7, R> { fun interface P8RFunction<P, P1, P2, P3, P4, P5, P6, P7, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p7。
*
* @return 函数执行结果
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7): R fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7): R
} }
/**
* 接收 9 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P8。
*/
@FunctionalInterface @FunctionalInterface
fun interface P9Function<P, P1, P2, P3, P4, P5, P6, P7, P8> { fun interface P9Function<P, P1, P2, P3, P4, P5, P6, P7, P8> {
/**
* 执行函数调用,参数依次为 p、p1 至 p8。
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8) fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8)
} }
/**
* 接收 9 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P8,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P9RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, R> { fun interface P9RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p8。
*
* @return 函数执行结果
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8): R fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8): R
} }
/**
* 接收 10 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P9。
*/
@FunctionalInterface @FunctionalInterface
fun interface P10Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9> { fun interface P10Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9> {
/**
* 执行函数调用,参数依次为 p、p1 至 p9。
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9) fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9)
} }
/**
* 接收 10 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P9,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P10RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, R> { fun interface P10RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p9。
*
* @return 函数执行结果
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9): R fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9): R
} }
/**
* 接收 11 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P10。
*/
@FunctionalInterface @FunctionalInterface
fun interface P11Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10> { fun interface P11Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10> {
/**
* 执行函数调用,参数依次为 p、p1 至 p10。
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10) fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10)
} }
/**
* 接收 11 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P10,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P11RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, R> { fun interface P11RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p10。
*
* @return 函数执行结果
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10): R fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10): R
} }
/**
* 接收 12 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P11。
*/
@FunctionalInterface @FunctionalInterface
fun interface P12Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11> { fun interface P12Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11> {
/**
* 执行函数调用,参数依次为 p、p1 至 p11。
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11) fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11)
} }
/**
* 接收 12 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P11,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P12RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, R> { fun interface P12RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p11。
*
* @return 函数执行结果
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11): R fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11): R
} }
/**
* 接收 13 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P12。
*/
@FunctionalInterface @FunctionalInterface
fun interface P13Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12> { fun interface P13Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12> {
/**
* 执行函数调用,参数依次为 p、p1 至 p12。
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11, p12: P12) fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11, p12: P12)
} }
/**
* 接收 13 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P12,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P13RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, R> { fun interface P13RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p12。
*
* @return 函数执行结果
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -182,12 +412,18 @@ fun interface P13RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
p9: P9, p9: P9,
p10: P10, p10: P10,
p11: P11, p11: P11,
p12: P12 p12: P12,
): R ): R
} }
/**
* 接收 14 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P13。
*/
@FunctionalInterface @FunctionalInterface
fun interface P14Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13> { fun interface P14Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13> {
/**
* 执行函数调用,参数依次为 p、p1 至 p13。
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -202,12 +438,20 @@ fun interface P14Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
p10: P10, p10: P10,
p11: P11, p11: P11,
p12: P12, p12: P12,
p13: P13 p13: P13,
) )
} }
/**
* 接收 14 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P13,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P14RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, R> { fun interface P14RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p13。
*
* @return 函数执行结果
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -222,12 +466,18 @@ fun interface P14RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
p10: P10, p10: P10,
p11: P11, p11: P11,
p12: P12, p12: P12,
p13: P13 p13: P13,
): R ): R
} }
/**
* 接收 15 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P14。
*/
@FunctionalInterface @FunctionalInterface
fun interface P15Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14> { fun interface P15Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14> {
/**
* 执行函数调用,参数依次为 p、p1 至 p14。
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -243,12 +493,20 @@ fun interface P15Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
p11: P11, p11: P11,
p12: P12, p12: P12,
p13: P13, p13: P13,
p14: P14 p14: P14,
) )
} }
/**
* 接收 15 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P14,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P15RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, R> { fun interface P15RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p14。
*
* @return 函数执行结果
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -264,12 +522,18 @@ fun interface P15RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
p11: P11, p11: P11,
p12: P12, p12: P12,
p13: P13, p13: P13,
p14: P14 p14: P14,
): R ): R
} }
/**
* 接收 16 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P15。
*/
@FunctionalInterface @FunctionalInterface
fun interface P16Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15> { fun interface P16Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15> {
/**
* 执行函数调用,参数依次为 p、p1 至 p15。
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -286,12 +550,20 @@ fun interface P16Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
p12: P12, p12: P12,
p13: P13, p13: P13,
p14: P14, p14: P14,
p15: P15 p15: P15,
) )
} }
/**
* 接收 16 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P15,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P16RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, R> { fun interface P16RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p15。
*
* @return 函数执行结果
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -308,12 +580,18 @@ fun interface P16RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
p12: P12, p12: P12,
p13: P13, p13: P13,
p14: P14, p14: P14,
p15: P15 p15: P15,
): R ): R
} }
/**
* 接收 17 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P16。
*/
@FunctionalInterface @FunctionalInterface
fun interface P17Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16> { fun interface P17Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16> {
/**
* 执行函数调用,参数依次为 p、p1 至 p16。
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -331,12 +609,20 @@ fun interface P17Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
p13: P13, p13: P13,
p14: P14, p14: P14,
p15: P15, p15: P15,
p16: P16 p16: P16,
) )
} }
/**
* 接收 17 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P16,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P17RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, R> { fun interface P17RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p16。
*
* @return 函数执行结果
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -354,12 +640,18 @@ fun interface P17RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
p13: P13, p13: P13,
p14: P14, p14: P14,
p15: P15, p15: P15,
p16: P16 p16: P16,
): R ): R
} }
/**
* 接收 18 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P17。
*/
@FunctionalInterface @FunctionalInterface
fun interface P18Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17> { fun interface P18Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17> {
/**
* 执行函数调用,参数依次为 p、p1 至 p17。
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -378,12 +670,20 @@ fun interface P18Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
p14: P14, p14: P14,
p15: P15, p15: P15,
p16: P16, p16: P16,
p17: P17 p17: P17,
) )
} }
/**
* 接收 18 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P17,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P18RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, R> { fun interface P18RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p17。
*
* @return 函数执行结果
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -402,12 +702,18 @@ fun interface P18RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
p14: P14, p14: P14,
p15: P15, p15: P15,
p16: P16, p16: P16,
p17: P17 p17: P17,
): R ): R
} }
/**
* 接收 19 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P18。
*/
@FunctionalInterface @FunctionalInterface
fun interface P19Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18> { fun interface P19Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18> {
/**
* 执行函数调用,参数依次为 p、p1 至 p18。
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -427,12 +733,20 @@ fun interface P19Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
p15: P15, p15: P15,
p16: P16, p16: P16,
p17: P17, p17: P17,
p18: P18 p18: P18,
) )
} }
/**
* 接收 19 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P18,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P19RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, R> { fun interface P19RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p18。
*
* @return 函数执行结果
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -452,12 +766,18 @@ fun interface P19RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
p15: P15, p15: P15,
p16: P16, p16: P16,
p17: P17, p17: P17,
p18: P18 p18: P18,
): R ): R
} }
/**
* 接收 20 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P19。
*/
@FunctionalInterface @FunctionalInterface
fun interface P20Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19> { fun interface P20Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19> {
/**
* 执行函数调用,参数依次为 p、p1 至 p19。
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -478,12 +798,20 @@ fun interface P20Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
p16: P16, p16: P16,
p17: P17, p17: P17,
p18: P18, p18: P18,
p19: P19 p19: P19,
) )
} }
/**
* 接收 20 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P19,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P20RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, R> { fun interface P20RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p19。
*
* @return 函数执行结果
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -504,12 +832,18 @@ fun interface P20RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
p16: P16, p16: P16,
p17: P17, p17: P17,
p18: P18, p18: P18,
p19: P19 p19: P19,
): R ): R
} }
/**
* 接收 21 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P20。
*/
@FunctionalInterface @FunctionalInterface
fun interface P21Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20> { fun interface P21Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20> {
/**
* 执行函数调用,参数依次为 p、p1 至 p20。
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -531,12 +865,20 @@ fun interface P21Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
p17: P17, p17: P17,
p18: P18, p18: P18,
p19: P19, p19: P19,
p20: P20 p20: P20,
) )
} }
/**
* 接收 21 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P20,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P21RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, R> { fun interface P21RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p20。
*
* @return 函数执行结果
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -558,12 +900,18 @@ fun interface P21RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
p17: P17, p17: P17,
p18: P18, p18: P18,
p19: P19, p19: P19,
p20: P20 p20: P20,
): R ): R
} }
/**
* 接收 22 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P21。
*/
@FunctionalInterface @FunctionalInterface
fun interface P22Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21> { fun interface P22Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21> {
/**
* 执行函数调用,参数依次为 p、p1 至 p21。
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -586,12 +934,20 @@ fun interface P22Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
p18: P18, p18: P18,
p19: P19, p19: P19,
p20: P20, p20: P20,
p21: P21 p21: P21,
) )
} }
/**
* 接收 22 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P21,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P22RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, R> { fun interface P22RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p21。
*
* @return 函数执行结果
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -614,12 +970,18 @@ fun interface P22RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
p18: P18, p18: P18,
p19: P19, p19: P19,
p20: P20, p20: P20,
p21: P21 p21: P21,
): R ): R
} }
/**
* 接收 23 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P22。
*/
@FunctionalInterface @FunctionalInterface
fun interface P23Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22> { fun interface P23Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22> {
/**
* 执行函数调用,参数依次为 p、p1 至 p22。
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -643,41 +1005,20 @@ fun interface P23Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
p19: P19, p19: P19,
p20: P20, p20: P20,
p21: P21, p21: P21,
p22: P22 p22: P22,
) )
} }
/**
* 接收 23 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P22,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P23RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, R> { fun interface P23RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, R> {
fun call( /**
p: P, * 执行函数调用,参数依次为 p、p1 至 p22。
p1: P1, *
p2: P2, * @return 函数执行结果
p3: P3, */
p4: P4,
p5: P5,
p6: P6,
p7: P7,
p8: P8,
p9: P9,
p10: P10,
p11: P11,
p12: P12,
p13: P13,
p14: P14,
p15: P15,
p16: P16,
p17: P17,
p18: P18,
p19: P19,
p20: P20,
p21: P21,
p22: P22
): R
}
@FunctionalInterface
fun interface P24Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, P23> {
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -702,12 +1043,55 @@ fun interface P24Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
p20: P20, p20: P20,
p21: P21, p21: P21,
p22: P22, p22: P22,
p23: P23 ): R
}
/**
* 接收 24 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P23。
*/
@FunctionalInterface
fun interface P24Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, P23> {
/**
* 执行函数调用,参数依次为 p、p1 至 p23。
*/
fun call(
p: P,
p1: P1,
p2: P2,
p3: P3,
p4: P4,
p5: P5,
p6: P6,
p7: P7,
p8: P8,
p9: P9,
p10: P10,
p11: P11,
p12: P12,
p13: P13,
p14: P14,
p15: P15,
p16: P16,
p17: P17,
p18: P18,
p19: P19,
p20: P20,
p21: P21,
p22: P22,
p23: P23,
) )
} }
/**
* 接收 24 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P23,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P24RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, P23, R> { fun interface P24RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, P23, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p23。
*
* @return 函数执行结果
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -732,6 +1116,6 @@ fun interface P24RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
p20: P20, p20: P20,
p21: P21, p21: P21,
p22: P22, p22: P22,
p23: P23 p23: P23,
): R ): R
} }
@@ -16,13 +16,13 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile Pipeline.kt * CurrentFile Pipeline.kt
* LastUpdate 2026-02-24 09:10:26 * LastUpdate 2026-10-20 20:59:13
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
package com.mingliqiye.utils.functions package com.mingliqiye.utils.functions
import com.mingliqiye.utils.require.Require import com.mingliqiye.utils.require.requireTrue
import kotlin.reflect.KClass import kotlin.reflect.KClass
/** /**
@@ -159,9 +159,9 @@ class Pipeline<T>(private val value: T) {
* @return 当前Pipeline实例 * @return 当前Pipeline实例
*/ */
fun require( fun require(
any: Any, message: String, exception: Class<out Exception> = IllegalArgumentException::class.java any: Any, message: String, exception: Class<out Exception> = IllegalArgumentException::class.java,
): Pipeline<T> { ): Pipeline<T> {
Require.require(any == value, message, exception) requireTrue(any == value, exception, message)
return this return this
} }
@@ -173,9 +173,9 @@ class Pipeline<T>(private val value: T) {
* @return 当前Pipeline实例 * @return 当前Pipeline实例
*/ */
fun require( fun require(
any: Any, message: String any: Any, message: String,
): Pipeline<T> { ): Pipeline<T> {
Require.require(any == value, message) requireTrue(any == value, message)
return this return this
} }
@@ -189,9 +189,9 @@ class Pipeline<T>(private val value: T) {
fun require( fun require(
must: P1RFunction<T, Boolean>, must: P1RFunction<T, Boolean>,
message: String, message: String,
exception: Class<out Throwable> = IllegalArgumentException::class.java exception: Class<out Throwable> = IllegalArgumentException::class.java,
): Pipeline<T> { ): Pipeline<T> {
Require.require(must.call(value), message, exception) requireTrue(must.call(value), exception, message)
return this return this
} }
@@ -205,9 +205,9 @@ class Pipeline<T>(private val value: T) {
fun require( fun require(
any: Any, any: Any,
message: String, message: String,
exception: KClass<out Throwable> = IllegalArgumentException::class exception: KClass<out Throwable> = IllegalArgumentException::class,
): Pipeline<T> { ): Pipeline<T> {
Require.require(any == value, message, exception) requireTrue(any == value, exception.java, message)
return this return this
} }
@@ -219,11 +219,11 @@ class Pipeline<T>(private val value: T) {
* @return 当前Pipeline实例 * @return 当前Pipeline实例
*/ */
fun require( fun require(
must: P1RFunction<T, Boolean>, must: (T) -> Boolean,
message: String, message: String,
exception: KClass<out Throwable> = IllegalArgumentException::class exception: KClass<out Throwable> = IllegalArgumentException::class,
): Pipeline<T> { ): Pipeline<T> {
Require.require(must.call(value), message, exception) requireTrue(must(value), exception.java, message)
return this return this
} }
@@ -234,9 +234,9 @@ class Pipeline<T>(private val value: T) {
* @return 当前Pipeline实例 * @return 当前Pipeline实例
*/ */
fun require( fun require(
must: P1RFunction<T, Boolean>, message: String must: P1RFunction<T, Boolean>, message: String,
): Pipeline<T> { ): Pipeline<T> {
Require.require(must.call(value), message, IllegalArgumentException::class.java) requireTrue(must.call(value), message)
return this return this
} }
@@ -259,7 +259,7 @@ class Pipeline<T>(private val value: T) {
*/ */
fun require( fun require(
predicate: P1RFunction<T, Boolean>, predicate: P1RFunction<T, Boolean>,
lazyMessage: P1RFunction<T, Any> = P1RFunction { "Requirement failed" } lazyMessage: P1RFunction<T, Any> = P1RFunction { "Requirement failed" },
): Pipeline<T> { ): Pipeline<T> {
if (!predicate.call(value)) { if (!predicate.call(value)) {
throw IllegalArgumentException(lazyMessage.call(value).toString()) throw IllegalArgumentException(lazyMessage.call(value).toString())
@@ -0,0 +1,81 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile HashType.kt
* LastUpdate 2026-11-18 18:48:01
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash
import com.mingliqiye.utils.hash.code.HashCodec
import java.io.InputStream
/**
* 哈希算法类型枚举。
*
* 每个枚举项持有一个哈希编解码器的工厂函数,枚举本身实现了 [HashCodec],
* 可直接作为编解码器使用,哈希操作委托给对应的编解码器实例。
*
* @param codec 哈希编解码器的工厂函数,每次访问 [code] 时调用以创建实例
*/
enum class HashType(private val codec: () -> HashCodec) : HashCodec {
/** MD2 哈希(输出 128 位,已过时,仅用于兼容遗留系统)。 */
MD2(::MD2),
/** MD5 哈希(输出 128 位,存在碰撞漏洞,不得用于安全场景)。 */
MD5(::MD5),
/** SHA-1 哈希(输出 160 位,存在碰撞攻击,不得用于安全场景)。 */
SHA1(::SHA1),
/** SHA-224 哈希(SHA-2 家族,输出 224 位)。 */
SHA224(::SHA224),
/** SHA-256 哈希(SHA-2 家族,输出 256 位)。 */
SHA256(::SHA256),
/** SHA-384 哈希(SHA-2 家族,输出 384 位)。 */
SHA384(::SHA384),
/** SHA-512 哈希(SHA-2 家族,输出 512 位)。 */
SHA512(::SHA512),
/** SHA3-224 哈希(SHA-3 家族,输出 224 位)。 */
SHA3224(::SHA3224),
/** SHA3-256 哈希(SHA-3 家族,输出 256 位)。 */
SHA3256(::SHA3256),
/** SHA3-384 哈希(SHA-3 家族,输出 384 位)。 */
SHA3384(::SHA3384),
/** SHA3-512 哈希(SHA-3 家族,输出 512 位)。 */
SHA3512(::SHA3512),
/** SHA-512/224 哈希(SHA-2 家族,输出 224 位)。 */
SHA512224(::SHA512224),
/** SHA-512/256 哈希(SHA-2 家族,输出 256 位)。 */
SHA512256(::SHA512256);
/**
* 获取当前类型对应的哈希编解码器实例(每次访问都会通过工厂函数新建)。
*/
val code get() = codec()
/**
* 计算输入流内容的哈希值,委托给 [code] 对应的编解码器。
*
* @param input 待计算哈希的输入流
* @return 哈希结果字节数组
*/
override fun hash(input: InputStream): ByteArray {
return code.hash(input)
}
}
@@ -16,71 +16,103 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile HashUtils.kt * CurrentFile HashUtils.kt
* LastUpdate 2026-01-11 09:09:52 * LastUpdate 2026-11-18 18:53:11
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@file:JvmName("HashUtils") @file:JvmName("HashUtils")
package com.mingliqiye.utils.hash package com.mingliqiye.utils.hash
import com.mingliqiye.utils.hash.code.*
import com.mingliqiye.utils.bcrypt.checkpw
import com.mingliqiye.utils.bcrypt.hashpw
import com.mingliqiye.utils.bytes.bytesToHex
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
/** /**
* 计算指定文件的哈希值。 * 提供 MD2 哈希器的懒加载实例。
* * 该哈希器输出 128 位摘要,算法已过时,仅用于兼容遗留系统。
* @param file 要计算哈希值的文件对象
* @param algorithm 使用的哈希算法名称(如 SHA-256、MD5 等)
* @return 文件的十六进制格式哈希值字符串
* @throws IOException 当文件不存在或读取过程中发生 I/O 错误时抛出
* @throws NoSuchAlgorithmException 当指定的哈希算法不可用时抛出
*/ */
@Throws(IOException::class, NoSuchAlgorithmException::class) @get:JvmName("getMd2Codec")
fun calculateFileHash(file: File, algorithm: String): String { val MD2 by lazy(::Md2Codec)
// 检查文件是否存在
if (!file.exists()) {
throw IOException("File not found: " + file.absolutePath)
}
val digest = MessageDigest.getInstance(algorithm)
FileInputStream(file).use { fis ->
val buffer = ByteArray(8192)
var bytesRead: Int
// 分块读取文件内容并更新摘要
while (fis.read(buffer).also { bytesRead = it } != -1) {
digest.update(buffer, 0, bytesRead)
}
}
return bytesToHex(digest.digest())
}
/** /**
* 使用 BCrypt 算法对字符串进行加密。 * 提供 MD5 哈希器的懒加载实例。
* * 该哈希器输出 128 位摘要,存在碰撞漏洞,不得用于安全场景,仅建议非安全性校验。
* @param string 需要加密的明文字符串
* @return 加密后的 BCrypt 哈希字符串
*/ */
fun bcrypt(string: String): String { @get:JvmName("getMd5Codec")
return hashpw(string) val MD5 by lazy(::Md5Codec)
}
/** /**
* 验证给定字符串与 BCrypt 哈希是否匹配。 * 提供 SHA-1 哈希器的懒加载实例。
* * 该哈希器输出 160 位摘要,存在碰撞攻击,不得用于安全场景,仅建议非安全性校验。
* @param string 明文字符串
* @param bcrypted 已经使用 BCrypt 加密的哈希字符串
* @return 如果匹配返回 true,否则返回 false
*/ */
fun checkBcrypt(string: String, bcrypted: String): Boolean { @get:JvmName("getSha1Codec")
return checkpw(string, bcrypted) val SHA1 by lazy(::Sha1Codec)
}
/**
* 提供 SHA-224 哈希器的懒加载实例。
* 该哈希器属于 SHA-2 家族,输出 224 位摘要。
*/
@get:JvmName("getSha224Codec")
val SHA224 by lazy(::Sha224Codec)
/**
* 提供 SHA-256 哈希器的懒加载实例。
* 该哈希器属于 SHA-2 家族,输出 256 位摘要,适用于文件校验、数字签名等场景。
*/
@get:JvmName("getSha256Codec")
val SHA256 by lazy(::Sha256Codec)
/**
* 提供 SHA-384 哈希器的懒加载实例。
* 该哈希器属于 SHA-2 家族,输出 384 位摘要。
*/
@get:JvmName("getSha384Codec")
val SHA384 by lazy(::Sha384Codec)
/**
* 提供 SHA-512 哈希器的懒加载实例。
* 该哈希器属于 SHA-2 家族,输出 512 位摘要,在 64 位平台上通常比 SHA-256 更快。
*/
@get:JvmName("getSha512Codec")
val SHA512 by lazy(::Sha512Codec)
/**
* 提供 SHA3-224 哈希器的懒加载实例。
* 该哈希器属于 SHA-3 家族(Keccak 结构),输出 224 位摘要。
*/
@get:JvmName("getSha3224Codec")
val SHA3224 by lazy(::Sha3224Codec)
/**
* 提供 SHA3-256 哈希器的懒加载实例。
* 该哈希器属于 SHA-3 家族(Keccak 结构),输出 256 位摘要。
*/
@get:JvmName("getSha3256Codec")
val SHA3256 by lazy(::Sha3256Codec)
/**
* 提供 SHA3-384 哈希器的懒加载实例。
* 该哈希器属于 SHA-3 家族(Keccak 结构),输出 384 位摘要。
*/
@get:JvmName("getSha3384Codec")
val SHA3384 by lazy(::Sha3384Codec)
/**
* 提供 SHA3-512 哈希器的懒加载实例。
* 该哈希器属于 SHA-3 家族(Keccak 结构),输出 512 位摘要。
*/
@get:JvmName("getSha3512Codec")
val SHA3512 by lazy(::Sha3512Codec)
/**
* 提供 SHA-512/224 哈希器的懒加载实例。
* 该哈希器以 SHA-512 的运算结构截断输出至 224 位,在 64 位平台上性能优于 SHA-224。
*/
@get:JvmName("getSha512224Codec")
val SHA512224 by lazy(::Sha512224Codec)
/**
* 提供 SHA-512/256 哈希器的懒加载实例。
* 该哈希器以 SHA-512 的运算结构截断输出至 256 位,在 64 位平台上性能优于 SHA-256。
*/
@get:JvmName("getSha512256Codec")
val SHA512256 by lazy(::Sha512256Codec)
@@ -0,0 +1,176 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile HashCodec.kt
* LastUpdate 2026-11-18 18:36:00
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
import com.mingliqiye.utils.base.BaseType
import java.io.File
import java.io.InputStream
import java.nio.charset.Charset
import java.nio.file.Files
import java.nio.file.Path
import java.security.MessageDigest
/**
* 哈希编解码器接口。
*
* 实现类只需重写 [hash](InputStream 版本)一个方法,
* 其余字节数组、字符串、文件、路径的重载以及十六进制输出、
* 哈希校验均由接口提供默认实现。
*
* 使用示例(以 SHA-256 为例):
* ```
* val sha256 = Sha256Codec()
* val hex = sha256.hashHex("hello")
* val ok = sha256.verifyHash("hello", hex)
* ```
*/
interface HashCodec {
/**
* 计算输入流内容的哈希值(唯一需要实现的方法)。
*
* 实现不需要关闭输入流,由调用方负责流的生命周期。
*
* @param input 待计算哈希的输入流
* @return 哈希结果字节数组
*/
fun hash(input: InputStream): ByteArray
/**
* 计算字节数组的哈希值。
*
* @param bytes 待计算哈希的字节数组
* @return 哈希结果字节数组
*/
fun hash(bytes: ByteArray): ByteArray = hash(bytes.inputStream())
/**
* 计算字符串的哈希值。
*
* @param string 待计算哈希的字符串
* @param charset 字符串编码字符集,默认 UTF-8
* @return 哈希结果字节数组
*/
fun hash(string: String, charset: Charset = Charsets.UTF_8): ByteArray = hash(string.toByteArray(charset))
/**
* 计算文件内容的哈希值。
*
* @param file 待计算哈希的文件
* @return 哈希结果字节数组
*/
fun hash(file: File): ByteArray = file.inputStream().use { hash(it) }
/**
* 计算路径指向文件内容的哈希值。
*
* @param path 待计算哈希的文件路径
* @return 哈希结果字节数组
*/
fun hash(path: Path): ByteArray = Files.newInputStream(path).use { hash(it) }
/**
* 计算输入流内容的哈希值并以小写十六进制字符串返回。
*
* @param input 待计算哈希的输入流
* @return 十六进制格式的哈希字符串
*/
fun hashHex(input: InputStream): String = BaseType.BASE16.encode(hash(input))
/**
* 计算字节数组的哈希值并以小写十六进制字符串返回。
*
* @param bytes 待计算哈希的字节数组
* @return 十六进制格式的哈希字符串
*/
fun hashHex(bytes: ByteArray): String = BaseType.BASE16.encode(hash(bytes))
/**
* 计算字符串的哈希值并以小写十六进制字符串返回。
*
* @param string 待计算哈希的字符串
* @param charset 字符串编码字符集,默认 UTF-8
* @return 十六进制格式的哈希字符串
*/
fun hashHex(string: String, charset: Charset = Charsets.UTF_8): String =
BaseType.BASE16.encode(hash(string, charset))
/**
* 计算文件内容的哈希值并以小写十六进制字符串返回。
*
* @param file 待计算哈希的文件
* @return 十六进制格式的哈希字符串
*/
fun hashHex(file: File): String = BaseType.BASE16.encode(hash(file))
/**
* 计算路径指向文件内容的哈希值并以小写十六进制字符串返回。
*
* @param path 待计算哈希的文件路径
* @return 十六进制格式的哈希字符串
*/
fun hashHex(path: Path): String = BaseType.BASE16.encode(hash(path))
/**
* 校验输入流内容的哈希值是否与期望值一致。
*
* 使用 [java.security.MessageDigest.isEqual] 进行常量时间比较,避免时序攻击。
*
* @param input 待校验的输入流
* @param hashed 期望的哈希值字节数组
* @return 一致返回 true,否则返回 false
*/
fun verifyHash(input: InputStream, hashed: ByteArray): Boolean = MessageDigest.isEqual(hash(input), hashed)
/**
* 校验字节数组的哈希值是否与期望值一致。
*
* @param bytes 待校验的字节数组
* @param hashed 期望的哈希值字节数组
* @return 一致返回 true,否则返回 false
*/
fun verifyHash(bytes: ByteArray, hashed: ByteArray): Boolean = MessageDigest.isEqual(hash(bytes), hashed)
/**
* 校验字符串的哈希值是否与期望值一致。
*
* @param string 待校验的字符串
* @param hashed 期望的哈希值字节数组
* @param charset 字符串编码字符集,默认 UTF-8
* @return 一致返回 true,否则返回 false
*/
fun verifyHash(string: String, hashed: ByteArray, charset: Charset = Charsets.UTF_8): Boolean =
MessageDigest.isEqual(hash(string, charset), hashed)
/**
* 校验字符串的哈希值是否与期望的十六进制字符串一致(忽略大小写)。
*
* @param string 待校验的字符串
* @param hashedHex 期望的十六进制哈希字符串
* @param charset 字符串编码字符集,默认 UTF-8
* @return 一致返回 true,否则返回 false
*/
fun verifyHash(string: String, hashedHex: String, charset: Charset = Charsets.UTF_8): Boolean =
MessageDigest.isEqual(hash(string, charset), BaseType.BASE16.decode(hashedHex.lowercase()))
}
@@ -15,19 +15,16 @@
* *
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile ApplicationRunnerData.kt * CurrentFile Md2Codec.kt
* LastUpdate 2026-03-10 09:10:50 * LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
package com.mingliqiye.utils.springboot.listener package com.mingliqiye.utils.hash.code
import java.lang.reflect.Method /**
* MD2 哈希编解码器(输出 128 位 / 16 字节)。
data class ApplicationRunnerData( *
val beanName: String, val order: Int, val bean: Any, val method: Method * MD2 已过时且存在安全缺陷,仅用于兼容遗留系统,不建议在任何新场景使用。
) { */
fun run() { class Md2Codec : MessageDigestCodec("MD2")
method.invoke(bean)
}
}
@@ -0,0 +1,31 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Md5Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* MD5 哈希编解码器(输出 128 位 / 16 字节)。
*
* MD5 已被证实存在碰撞漏洞,不得用于数字签名、密码存储等安全场景,
* 仅建议用于兼容遗留系统或非安全性校验(如文件完整性粗检)。
*/
class Md5Codec : MessageDigestCodec("MD5")
@@ -0,0 +1,63 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile MessageDigestCodec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
import java.io.InputStream
import java.security.MessageDigest
/**
* 基于 JDK [MessageDigest] 的哈希编解码器抽象基类。
*
* 以固定 8KB 缓冲区流式读取输入,内存占用恒定,适用于任意大小的文件与数据流。
* 每次调用 [hash] 都会新建 [MessageDigest] 实例(其本身非线程安全),
* 因此本类实例无状态、可安全地在多线程间共享。
*
* 遵循 [HashCodec] 契约:不关闭输入流,由调用方负责流的生命周期。
*
* 子类只需指定算法名称,也可借此扩展 JDK 默认提供者之外的算法
* (如 BouncyCastle 提供的 SM3),前提是相应 [java.security.Provider] 已注册。
*
* @param algorithm [MessageDigest.getInstance] 所用的算法名称
*/
abstract class MessageDigestCodec(private val algorithm: String) : HashCodec {
/**
* 以 8KB 缓冲区流式计算输入流内容的哈希值。
*
* 不关闭输入流;每次调用新建 [MessageDigest] 实例,线程安全。
*
* @param input 待计算哈希的输入流
* @return 哈希结果字节数组
* @throws java.security.NoSuchAlgorithmException 当前环境无指定算法的提供者时抛出
*/
override fun hash(input: InputStream): ByteArray {
val digest = MessageDigest.getInstance(algorithm)
val buffer = ByteArray(8192)
while (true) {
val n = input.read(buffer)
if (n == -1) break
digest.update(buffer, 0, n)
}
return digest.digest()
}
}
@@ -0,0 +1,31 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha1Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA-1 哈希编解码器(输出 160 位 / 20 字节)。
*
* SHA-1 已被证实存在碰撞攻击(SHAttered),不得用于安全场景,
* 仅建议用于兼容遗留系统或非安全性校验。
*/
class Sha1Codec : MessageDigestCodec("SHA-1")
@@ -15,18 +15,14 @@
* *
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile Listener.kt * CurrentFile Sha224Codec.kt
* LastUpdate 2026-03-10 09:04:02 * LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
package com.mingliqiye.utils.springboot.annotation package com.mingliqiye.utils.hash.code
import org.springframework.core.annotation.AliasFor /**
import org.springframework.stereotype.Component * SHA-224 哈希编解码器(SHA-2 家族,输出 224 位 / 28 字节)。
*/
@Component class Sha224Codec : MessageDigestCodec("SHA-224")
annotation class Listener(
@get:AliasFor(annotation = Component::class)
val value: String = ""
)
@@ -0,0 +1,37 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha256Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA-256 哈希编解码器(SHA-2 家族,输出 256 位 / 32 字节)。
*
* 目前广泛使用的安全哈希算法,适用于文件校验、数字签名、消息摘要等场景。
*
* 使用示例:
* ```
* val sha256 = Sha256Codec()
* val hex = sha256.hashHex("hello")
* val ok = sha256.verifyHash("hello", hex)
* ```
*/
class Sha256Codec : MessageDigestCodec("SHA-256")
@@ -0,0 +1,28 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha3224Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA3-224 哈希编解码器(SHA-3 家族,Keccak 结构,输出 224 位 / 28 字节)。
*/
class Sha3224Codec : MessageDigestCodec("SHA3-224")
@@ -0,0 +1,28 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha3256Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA3-256 哈希编解码器(SHA-3 家族,Keccak 结构,输出 256 位 / 32 字节)。
*/
class Sha3256Codec : MessageDigestCodec("SHA3-256")
@@ -0,0 +1,28 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha3384Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA3-384 哈希编解码器(SHA-3 家族,Keccak 结构,输出 384 位 / 48 字节)。
*/
class Sha3384Codec : MessageDigestCodec("SHA3-384")
@@ -0,0 +1,28 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha3512Codec.kt
* LastUpdate 2026-11-18 11:18:52
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA3-512 哈希编解码器(SHA-3 家族,Keccak 结构,输出 512 位 / 64 字节)。
*/
class Sha3512Codec : MessageDigestCodec("SHA3-512")
@@ -0,0 +1,28 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha384Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA-384 哈希编解码器(SHA-2 家族,输出 384 位 / 48 字节)。
*/
class Sha384Codec : MessageDigestCodec("SHA-384")
@@ -0,0 +1,30 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha512224Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA-512/224 哈希编解码器(SHA-2 家族,输出 224 位 / 28 字节)。
*
* 以 SHA-512 的运算结构截断输出至 224 位,在 64 位平台上性能优于 SHA-224。
*/
class Sha512224Codec : MessageDigestCodec("SHA-512/224")
@@ -0,0 +1,30 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha512256Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA-512/256 哈希编解码器(SHA-2 家族,输出 256 位 / 32 字节)。
*
* 以 SHA-512 的运算结构截断输出至 256 位,在 64 位平台上性能优于 SHA-256。
*/
class Sha512256Codec : MessageDigestCodec("SHA-512/256")

Some files were not shown because too many files have changed in this diff Show More