rust_rsm/common/
tsidallocator.rs1#![allow(non_camel_case_types)]
2#![allow(non_snake_case)]
3#![allow(non_upper_case_globals)]
4
5use crate::common::errcode;
6use std::collections::{VecDeque};
7use crate::common::{spin_lock::spin_lock_t,bitmap::bitmap_t};
8
9pub struct TsIdAllocator {
10 start: i32,
11 cap: i32,
12 allocator: VecDeque<i32>,
13 used: bitmap_t,
14 lock: spin_lock_t,
15}
16
17impl TsIdAllocator {
18 pub const INVALID_ID: i32 = -1;
19
20 pub fn new(start: i32, capacity: i32) -> Self {
21 let mut allocator = TsIdAllocator {
22 start: start,
23 cap: capacity,
24 allocator: VecDeque::with_capacity(capacity as usize),
25 used: bitmap_t::new(capacity),
26 lock: spin_lock_t::new(),
27 };
28 allocator.init();
29 allocator
30 }
31 fn init(&mut self) {
33 for i in self.start..self.start + self.cap {
34 self.allocator.push_back(i);
35 }
36 }
37 pub fn allocate_id(&mut self) -> i32 {
38 self.lock.lock();
39 let id = match self.allocator.pop_front() {
40 None => Self::INVALID_ID,
41 Some(i) => {
42 let idx = i - self.start;
43 self.used.set_bitmap(idx);
44 i
45 },
46 };
47 self.lock.unlock();
48 return id
49 }
50 pub fn release_id(&mut self, id: i32) -> errcode::RESULT {
52 if id>=self.cap {
53 return errcode::ERROR_OUTOF_SCOPE
54 }
55 self.lock.lock();
56 let idx = id - self.start;
57 let res = match self.used.is_bit_set(idx) {
58 false => errcode::ERROR_NOT_FOUND,
59 true => {
60 self.allocator.push_front(id);
61 self.used.unset_bitmap(idx);
62 errcode::RESULT_SUCCESS
63 },
64 };
65
66 self.lock.unlock();
67 return res
68
69 }
70
71 pub fn reserve_id(&mut self,id:i32)->errcode::RESULT {
72 if id>=self.cap {
73 return errcode::ERROR_OUTOF_SCOPE
74 }
75 let idx = id - self.start;
76 self.lock.lock();
77
78 let res = match self.used.is_bit_set(idx) {
79 true => errcode::ERROR_ALREADY_EXIST,
80 false => {
81 let mut v=usize::MAX;
82 for r in 0..self.allocator.len() {
83 if self.allocator[r]==id {
84 v=r;
85 }
86 }
87
88 if v!=usize::MAX {
89 self.allocator.remove(v);
90 }
91 self.used.set_bitmap(idx);
92 errcode::RESULT_SUCCESS
93 },
94 };
95
96 self.lock.unlock();
97 return res
98 }
99
100 pub fn capacity(&self) -> i32 {
101 self.cap
102 }
103
104 pub fn used_count(&self) -> i32 {
105 self.lock.lock();
106 let len = self.used.get_used_count() as i32;
107 self.lock.unlock();
108 return len;
109 }
110}