refactor(ids): IdGen 降为 pub(crate),收回公开面
- ids: IdGen 及其 new/next_at/next 降为 pub(crate),只留 next_id() 为公开面 (next_at 可注入任意墙钟,不应成为公开后门) - ids: 顺手清掉测试里的 3 处 clippy warning(同类型 cast / 无效 | 0) Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
1 parent
b477865d8c
commit
4c2bdcda52
1 file changed
+10
-7
+10
-7
@@ -62,13 +62,16 @@ fn advance(last: u64, wall_ms: u64) -> u64 {
|
||||
///
|
||||
/// 抽成类型是为了**测试不碰全局状态**:测试可自建实例、用可控的墙钟驱动,
|
||||
/// 不会与其它测试或进程级 `next_id()` 相互干扰。
|
||||
pub struct IdGen {
|
||||
///
|
||||
/// 🔴 仅 crate 内可见 —— 计划要求的公开面只有 `ids::next_id() -> String`;
|
||||
/// `next_at` 能注入任意墙钟,不应成为公开后门。
|
||||
pub(crate) struct IdGen {
|
||||
/// 最近一次发出的 id:高 52 位是毫秒时间戳,低 12 位是序列。
|
||||
last: AtomicU64,
|
||||
}
|
||||
|
||||
impl IdGen {
|
||||
pub const fn new() -> Self {
|
||||
pub(crate) const fn new() -> Self {
|
||||
Self {
|
||||
last: AtomicU64::new(0),
|
||||
}
|
||||
@@ -77,7 +80,7 @@ impl IdGen {
|
||||
/// 用给定的墙钟毫秒(纪元偏移后)生成下一个 id。
|
||||
///
|
||||
/// CAS 循环:并发下别的线程可能抢先,此时重读重算。
|
||||
pub fn next_at(&self, wall_ms: u64) -> String {
|
||||
pub(crate) fn next_at(&self, wall_ms: u64) -> String {
|
||||
loop {
|
||||
let last = self.last.load(Ordering::Relaxed);
|
||||
let candidate = advance(last, wall_ms);
|
||||
@@ -93,7 +96,7 @@ impl IdGen {
|
||||
}
|
||||
|
||||
/// 用当前墙钟生成下一个 id。
|
||||
pub fn next(&self) -> String {
|
||||
pub(crate) fn next(&self) -> String {
|
||||
self.next_at(now_ms())
|
||||
}
|
||||
}
|
||||
@@ -185,7 +188,7 @@ mod tests {
|
||||
|
||||
// 本毫秒共 4096 个 id(seq 0..=4095)。
|
||||
let mut last = first;
|
||||
for i in 1..=(SEQ_MASK as u64) {
|
||||
for i in 1..=SEQ_MASK {
|
||||
let id: u64 = gen.next_at(MS).parse().unwrap();
|
||||
assert_eq!(id & SEQ_MASK, i, "序列应递增到 {}", i);
|
||||
assert_eq!(id >> TS_SHIFT, MS, "毫秒部分应不变");
|
||||
@@ -208,7 +211,7 @@ mod tests {
|
||||
);
|
||||
|
||||
// 且回绕值(若真回绕)**恰好等于**本毫秒首个 id —— 这就是旧实现会产出重复 id 的实证。
|
||||
let wrapped = (MS << TS_SHIFT) | 0;
|
||||
let wrapped = MS << TS_SHIFT;
|
||||
assert_eq!(
|
||||
wrapped, first,
|
||||
"回绕值与首个 id 相同 ⇒ 旧实现会产出重复 id(本次改动已阻止该路径)"
|
||||
@@ -242,7 +245,7 @@ mod tests {
|
||||
const MS: u64 = 1000;
|
||||
let gen = IdGen::new();
|
||||
// 先在同一毫秒内耗尽序列。
|
||||
for _ in 0..=(SEQ_MASK as u64) {
|
||||
for _ in 0..=SEQ_MASK {
|
||||
gen.next_at(MS);
|
||||
}
|
||||
// 墙钟回拨到 500(远低于已记录的高水位 1000)⇒ 此时再取 id。
|
||||
|
||||
Reference in new issue
Block a user