Skip to content

Commit 68ac534

Browse files
committed
add IdAllocator
Signed-off-by: Richard Chien <[email protected]>
1 parent 07782ab commit 68ac534

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

src/common/src/util/id_alloc.rs

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// Copyright 2024 RisingWave Labs
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
use std::ops::Add;
16+
17+
use num_traits::{CheckedAdd, One};
18+
19+
#[derive(Debug, Clone, Copy)]
20+
pub struct IdAllocator<T> {
21+
next: T,
22+
}
23+
24+
impl<T> IdAllocator<T>
25+
where
26+
T: One,
27+
{
28+
pub fn new() -> Self {
29+
Self { next: T::one() }
30+
}
31+
}
32+
33+
impl<T> Default for IdAllocator<T>
34+
where
35+
T: One,
36+
{
37+
fn default() -> Self {
38+
Self::new()
39+
}
40+
}
41+
42+
impl<T> IdAllocator<T>
43+
where
44+
T: Copy + Add<Output = T> + One,
45+
{
46+
pub fn next(&mut self) -> T {
47+
let next_next = self.next + T::one();
48+
std::mem::replace(&mut self.next, next_next)
49+
}
50+
}
51+
52+
impl<T> IdAllocator<T>
53+
where
54+
T: CheckedAdd + One,
55+
{
56+
pub fn checked_next(&mut self) -> Option<T> {
57+
let next_next = self.next.checked_add(&T::one())?;
58+
Some(std::mem::replace(&mut self.next, next_next))
59+
}
60+
}

src/common/src/util/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,4 @@ pub mod value_encoding;
4343
pub mod worker_util;
4444
pub use tokio_util;
4545
pub mod cluster_limit;
46+
pub mod id_alloc;

0 commit comments

Comments
 (0)