增强 BitSetBloomFilter 构造器的参数有效性校验逻辑

This commit is contained in:
yanzhongxin
2025-12-25 15:41:47 +08:00
parent de93fa7670
commit cdd0bd1699
2 changed files with 40 additions and 1 deletions

View File

@@ -2,6 +2,7 @@ package cn.hutool.bloomfilter;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.HashUtil;
@@ -32,7 +33,9 @@ public class BitSetBloomFilter implements BloomFilter {
* @param k 哈希函数的个数等同每条记录要占用的bit数此处值取值为1~8
*/
public BitSetBloomFilter(int c, int n, int k) {
this.hashFunctionNumber = k;
Assert.isTrue(c > 0, "Parameter c must be positive");
Assert.isTrue(n > 0, "Parameter n must be positive");
this.hashFunctionNumber = Assert.checkBetween(k, 1, 8,"hashFunctionNumber must be between 1 and 8");
this.bitSetSize = (int) Math.ceil(c * k);
this.addedElements = n;
this.bitSet = new BitSet(this.bitSetSize);

View File

@@ -0,0 +1,36 @@
package cn.hutool.bloomfilter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class BitSetBloomFilterTest {
@Test
public void testConstructorWithInvalidParameters() {
// 测试参数 c 的无效情况c <= 0
assertThrows(IllegalArgumentException.class, () -> {
new BitSetBloomFilter(0, 100, 3);
});
assertThrows(IllegalArgumentException.class, () -> {
new BitSetBloomFilter(-5, 100, 3);
});
// 测试参数 n 的无效情况 (n <= 0)
assertThrows(IllegalArgumentException.class, () -> {
new BitSetBloomFilter(200, 0, 3);
});
assertThrows(IllegalArgumentException.class, () -> {
new BitSetBloomFilter(200, -10, 3);
});
// 测试参数 k 的无效情况k < 1 或 k > 8
assertThrows(IllegalArgumentException.class, () -> {
new BitSetBloomFilter(200, 100, 0);
});
assertThrows(IllegalArgumentException.class, () -> {
new BitSetBloomFilter(200, 100, 9);
});
assertThrows(IllegalArgumentException.class, () -> {
new BitSetBloomFilter(200, 100, -2);
});
}
}