pub const DEFAULT_BASE_TIME: i64 = 1582136402000;
#[derive(Debug, Clone)]
pub struct IGOptions {
pub method: u16, pub base_time: i64, pub worker_id: u16, pub worker_id_bit_length: u8, pub seq_bit_length: u8, pub max_seq_number: u32, pub min_seq_number: u32, pub top_over_cost_count: u32, }
impl IGOptions {
pub fn new(worker_id: u16) -> Self {
IGOptions {
method: 1,
base_time: DEFAULT_BASE_TIME,
worker_id,
worker_id_bit_length: 6,
seq_bit_length: 6,
max_seq_number: 0,
min_seq_number: 5,
top_over_cost_count: 2000,
}
}
pub fn builder(worker_id: u16) -> IGOptionsBuilder {
IGOptionsBuilder::new(worker_id)
}
pub fn quick_init(worker_id: u16) -> Self {
Self::new(worker_id)
}
pub fn with_capacity(worker_id: u16, max_nodes: u32, max_qps: u32) -> Self {
let worker_id_bit_length = if max_nodes <= 1 {
1
} else {
(32 - max_nodes.leading_zeros()) as u8
};
let ids_per_ms = ((max_qps as f64 / 1000.0).ceil() as u32).max(1);
let seq_bits_raw = (32 - (ids_per_ms + ids_per_ms / 5).leading_zeros()) as u8;
let total = worker_id_bit_length + seq_bits_raw;
let seq_bit_length = if total > 22 {
(22 - worker_id_bit_length).max(3)
} else {
seq_bits_raw.max(3)
};
Self {
method: 1,
base_time: DEFAULT_BASE_TIME,
worker_id,
worker_id_bit_length,
seq_bit_length,
max_seq_number: 0,
min_seq_number: 5,
top_over_cost_count: 2000,
}
}
}
#[derive(Debug, Clone)]
pub struct IGOptionsBuilder {
inner: IGOptions,
}
impl IGOptionsBuilder {
pub fn new(worker_id: u16) -> Self {
Self {
inner: IGOptions::new(worker_id),
}
}
pub fn method(mut self, method: u16) -> Self {
self.inner.method = method;
self
}
pub fn base_time_ms(mut self, base_time: i64) -> Self {
self.inner.base_time = base_time;
self
}
pub fn base_time(mut self, base_time: chrono::DateTime<chrono::Utc>) -> Self {
self.inner.base_time = base_time.timestamp_millis();
self
}
pub fn worker_id_bit_length(mut self, length: u8) -> Self {
self.inner.worker_id_bit_length = length;
self
}
pub fn seq_bit_length(mut self, length: u8) -> Self {
self.inner.seq_bit_length = length;
self
}
pub fn max_seq_number(mut self, max: u32) -> Self {
self.inner.max_seq_number = max;
self
}
pub fn min_seq_number(mut self, min: u32) -> Self {
self.inner.min_seq_number = min;
self
}
pub fn top_over_cost_count(mut self, count: u32) -> Self {
self.inner.top_over_cost_count = count;
self
}
pub fn build(self) -> IGOptions {
self.inner
}
}