1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
|
use std::{
cell::RefCell,
ffi::c_int,
marker::PhantomData,
ptr::NonNull,
rc::Rc,
time::{Duration, Instant},
};
use libc::{c_void, free};
use crate::timeout_bind::*;
/// timeout flag: relative time or absolute time, default relative time
/// it could use as i32
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TimeoutType {
INT = TIMEOUT_INT as isize, // relative time
ABS = TIMEOUT_ABS as isize, // absolute time
Default = TIMEOUT_DEFAULT as isize, // relative time
}
// as i32
impl From<TimeoutType> for i32 {
fn from(timeout_type: TimeoutType) -> Self {
timeout_type as i32
}
}
impl TimeoutType {
// i32 -> TimeoutType
fn new(flag: i32) -> Self {
match flag {
TIMEOUT_INT => TimeoutType::INT,
TIMEOUT_ABS => TimeoutType::ABS,
_ => TimeoutType::Default,
}
}
}
type TimeoutCallBack = timeout_cb;
impl TimeoutCallBack {
pub fn new<T>(callback: extern "C" fn(arg: *mut c_void), arg: *mut T) -> Self {
let fn_ptr = Some(callback);
TimeoutCallBack {
fn_ptr,
arg: arg as *mut c_void,
}
}
pub fn call(&self) -> bool {
if let Some(callback) = self.fn_ptr {
callback(self.arg);
return true;
}
return false;
}
}
type Timeout = timeout;
// pub struct Timeout {
// // raw: Box<timeout>, // raw pointer
// raw: NonNull<timeout>,
// registered: Rc<RefCell<bool>>,
// }
impl Timeout {
pub fn new(flags: TimeoutType) -> Result<Timeout, &'static str> {
// timeout instantiated in rust rather than C side
let raw = Box::into_raw(Box::new(timeout::default()));
// Box::into_raw let instance ownership transfer to C
let raw = unsafe { timeout_init(raw, flags as i32) };
if raw.is_null() {
return Err("Failed to create Timeout");
}
// Box::from_raw: instance ownership from C side to rust.
Ok(*unsafe { Box::from_raw(raw) })
}
/// transfer *timeout to Timeout
/// instance ownership form C side to rust
pub fn transfer(to: *mut timeout) -> Timeout {
*unsafe { Box::from_raw(to) }
}
pub fn set_cb(&mut self, cb: TimeoutCallBack) {
self.callback = cb;
}
/// return true if timeout is registered and on timing wheel
pub fn is_pending(&self) -> bool {
//C code: return to->pending && to->pending != &to->timeouts->expired;
if !self.pending.is_null() // pending not null
&& !self.timeouts.is_null() // timeouts not null
&& self.pending != (unsafe { &mut (*self.timeouts).expired // pending not expired
})
{
return true;
}
false
}
/// return true if timeout is registered and on expired queue
pub fn is_expired(&self) -> bool {
//return to->pending && to->pending == &to->timeouts->expired;
if !self.pending.is_null() // pending not null
&& !self.timeouts.is_null() // timeouts not null
&& self.pending == (unsafe { &mut (*self.timeouts).expired // pending is expired
}) {
return true;
}
false
}
/// remove timeout from any timing wheel or expired queue (okay if on neither)
pub fn delete(&mut self) {
unsafe { timeout_del(self) };
}
pub fn run_cb(&self) -> bool {
let cb = self.callback;
return cb.call();
}
}
impl Drop for Timeout {
fn drop(&mut self) {
self.delete(); // delete
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TimeoutSItFlag {
PENDING = TIMEOUTS_PENDING as isize,
EXPIRED = TIMEOUTS_EXPIRED as isize,
ALL = TIMEOUTS_ALL as isize,
// CLEAR = TIMEOUTS_CLEAR as isize,
}
// as i32
impl From<TimeoutSItFlag> for i32 {
fn from(flag: TimeoutSItFlag) -> Self {
flag as i32
}
}
impl TimeoutSItFlag {
pub fn new(flag: i32) -> Self {
match flag {
TIMEOUTS_PENDING => TimeoutSItFlag::PENDING,
TIMEOUTS_EXPIRED => TimeoutSItFlag::EXPIRED,
TIMEOUTS_ALL => TimeoutSItFlag::ALL,
// TIMEOUTS_CLEAR => TimeoutSItFlag::CLEAR, // CLEAR means clear all expired timeout on expire queue.
// this creates complications in ownership
_ => TimeoutSItFlag::ALL,
}
}
}
pub struct TimeoutSIt {
raw: NonNull<timeouts_it>,
}
impl TimeoutSIt {
/// flag has 4 value: PENDING, EXPIRED, ALL, CLEAR
fn new(flags: TimeoutSItFlag) -> Result<TimeoutSIt, &'static str> {
let instance = Box::into_raw(Box::new(timeouts_it::default()));
TIMEOUTS_IT_INIT(instance, flags as i32);
let raw = NonNull::new(instance).ok_or("Failed to create TimeoutSIt")?;
Ok(TimeoutSIt { raw })
}
}
impl Drop for TimeoutSIt {
fn drop(&mut self) {
unsafe {
let raw_ptr = self.raw.as_ptr() as *mut c_void;
free(raw_ptr);
}
}
}
// TimeoutManager
pub struct TimeoutManager {
tos: NonNull<timeouts>,
}
impl TimeoutManager {
/// if hz_set = 0, default hz_set = TIMEOUT_mHZ
pub fn new(hz_set: timeout_t) -> Result<TimeoutManager, &'static str> {
let mut err = 0 as usize;
// if hz_set = 0, default set to TIMEOUT_mHZ (timeouts_open)
let tos = unsafe { timeouts_open(hz_set, &mut err) };
if err != 0 {
return Err("Failed to create timeout manager, null");
}
let tos = NonNull::new(tos).ok_or("Failed to create timeout manager, null")?;
Ok(TimeoutManager { tos })
}
// get raw pointer
fn get_raw(&self) -> *mut timeouts {
self.tos.as_ptr()
}
// close
pub fn close(&mut self) {
unsafe {
timeouts_close(self.get_raw());
}
}
fn update_time(&mut self, time: timeout_t, timeout_type: TimeoutType) {
match timeout_type {
TimeoutType::INT => unsafe { timeouts_step(self.get_raw(), time) },
TimeoutType::ABS => unsafe { timeouts_update(self.get_raw(), time) },
TimeoutType::Default => unsafe { timeouts_step(self.get_raw(), time) },
}
}
/// update time: relative time
pub fn update_time_int(&mut self, time: timeout_t) {
self.update_time(time, TimeoutType::INT);
}
/// update time: absolute time
pub fn update_time_abs(&mut self, current_time: timeout_t) {
self.update_time(current_time, TimeoutType::ABS);
}
/// get tos hz
pub fn get_hz(&self) -> timeout_t {
unsafe { timeouts_hz(self.get_raw()) }
}
/// return interval to next required update
/// careful for two case:
/// - return value could be u64::MAX, it means no timeout
/// - return value will always be less than next timeout
pub fn get_next_wait_time(&mut self) -> timeout_t {
unsafe { timeouts_timeout(self.get_raw()) }
}
/// return true if any timeouts pending on timing wheel
pub fn any_pending(&mut self) -> bool {
unsafe { timeouts_pending(self.get_raw()) }
}
/// return true if any timeouts on expired queue
pub fn any_expired(&mut self) -> bool {
unsafe { timeouts_expired(self.get_raw()) }
}
// return true if TimeoutManager is effective
pub fn check(&mut self) -> bool {
unsafe { timeouts_check(self.get_raw(), stderr) }
}
}
impl TimeoutManager {
/// add Timeout to timing wheel
/// Pass in ownership of the Timeout object
pub fn add(&mut self, to: Timeout, time: timeout_t) {
let to_ptr = Box::into_raw(Box::new(to));
unsafe { timeouts_add(self.get_raw(), to_ptr, time) };
}
/// remove Timeout from any timing wheel or expired queue (okay if on neither)
/// No ownership of the Timeout object is passed in
pub fn delete(&mut self, to: &mut Timeout) {
unsafe { timeouts_del(self.get_raw(), to) };
}
/// return next expired timeout, or NULL if none
/// Ownership of timeout objects moved from C to rust
pub fn expired_timeout(&mut self) -> Option<Timeout> {
let to_ptr: *mut timeout = unsafe { timeouts_get(self.get_raw()) };
if to_ptr.is_null() {
return None;
}
return Some(Timeout::transfer(to_ptr));
}
/// return next quote of timeout as timeout_sit requested, or NULL if none
/// No ownership of the Timeout object is passed in from C to rust
//
pub fn next_timeout<'a, 'b>(&'a mut self, timeout_sit: &'b TimeoutSIt) -> Option<&'b Timeout> {
let to_ptr: *mut timeout =
unsafe { timeouts_next(self.get_raw(), timeout_sit.raw.as_ptr()) };
if to_ptr.is_null() {
return None;
}
return Some(unsafe { &*to_ptr });
}
}
impl Drop for TimeoutManager {
fn drop(&mut self) {
self.close();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_timeout_type() {
let int_type = TimeoutType::INT;
let abs_type = TimeoutType::ABS;
let default_type = TimeoutType::Default;
assert_eq!(i32::from(int_type), TIMEOUT_INT);
assert_eq!(i32::from(abs_type), TIMEOUT_ABS);
assert_eq!(i32::from(default_type), TIMEOUT_DEFAULT);
assert_eq!(TimeoutType::new(TIMEOUT_INT), int_type);
assert_eq!(TimeoutType::new(TIMEOUT_ABS), abs_type);
assert_eq!(TimeoutType::new(123), default_type);
}
#[test]
fn test_timeout() {
let mut timeout = Timeout::new(TimeoutType::Default).unwrap(); // relative timeout
assert!(!timeout.is_pending());
assert!(!timeout.is_expired());
// callback
extern "C" fn rust_callback(arg: *mut c_void) {
let value = unsafe { *(arg as *mut i32) };
println!("Callback executed with arg: {}", value);
}
let arg: i32 = 42;
let callback = TimeoutCallBack::new(rust_callback, &arg as *const _ as *mut c_void);
timeout.set_cb(callback);
let mut tos = TimeoutManager::new(TIMEOUT_mHZ).unwrap();
tos.update_time_int(0); // tos.now = 0
tos.add(timeout, 100); // expired time = tos.now + 100
let tos_it = TimeoutSIt::new(TimeoutSItFlag::PENDING).unwrap();
let to = tos.next_timeout(&tos_it);
let to = to.unwrap();
tos.update_time_int(1); // tos.now = 1
assert!(to.is_pending());
assert!(!to.is_expired());
tos.update_time_int(98); // tos.now = 99
assert!(to.is_pending());
assert!(!to.is_expired());
tos.update_time_int(10); // tos.now = 109
assert!(!to.is_pending());
assert!(to.is_expired());
assert!(to.run_cb());
}
#[test]
fn test_timeout_sit_flag_into_i32() {
let pending = TimeoutSItFlag::PENDING;
let expired = TimeoutSItFlag::EXPIRED;
let all = TimeoutSItFlag::ALL;
assert_eq!(i32::from(pending), TIMEOUTS_PENDING);
assert_eq!(i32::from(expired), TIMEOUTS_EXPIRED);
assert_eq!(i32::from(all), TIMEOUTS_ALL);
assert_eq!(TimeoutSItFlag::new(TIMEOUTS_PENDING), pending);
assert_eq!(TimeoutSItFlag::new(TIMEOUTS_EXPIRED), expired);
assert_eq!(TimeoutSItFlag::new(TIMEOUTS_ALL), all);
assert_eq!(TimeoutSItFlag::new(123), all);
}
#[test]
fn test_timeout_sit_new() {
let sit = TimeoutSIt::new(TimeoutSItFlag::PENDING);
assert!(sit.is_ok());
}
#[test]
fn test_timeout_manger() {
let mut tos = TimeoutManager::new(TIMEOUT_mHZ).unwrap();
assert_eq!(tos.get_hz(), TIMEOUT_mHZ);
assert!(tos.check());
tos.update_time_abs(0);
assert_eq!(tos.get_next_wait_time(), u64::MAX); // no timeout wait, so wait time is u64::MAX
let timeout = Timeout::new(TimeoutType::Default).unwrap(); // relative timeout
tos.add(timeout, 100); // expired time = tos.now + 100
let tos_it = TimeoutSIt::new(TimeoutSItFlag::PENDING).unwrap();
let to = tos.next_timeout(&tos_it);
let to = to.unwrap();
tos.update_time_abs(30);
assert!(tos.any_pending());
assert!(!tos.any_expired());
assert!(tos.get_next_wait_time() < 70);
assert!(to.is_pending());
assert!(!to.is_expired());
tos.update_time_abs(100);
assert!(!tos.any_pending());
assert!(tos.any_expired());
assert_eq!(tos.get_next_wait_time(), 0);
tos.update_time_abs(150);
assert!(!to.is_pending());
assert!(to.is_expired());
let timeout2 = tos.expired_timeout();
assert!(timeout2.is_some());
}
#[test]
#[allow(unused_variables)]
fn test_callback() {
let mut timeout = Timeout::new(TimeoutType::Default).unwrap(); // relative timeout
// callback
extern "C" fn rust_callback(arg: *mut c_void) {
let value = unsafe { *(arg as *mut &str) };
println!("Callback executed with arg: {}", value);
}
let mut arg = "hello world";
let callback = TimeoutCallBack::new(rust_callback, &arg as *const _ as *mut c_void);
timeout.set_cb(callback);
timeout.run_cb();
arg = "hello rust";
timeout.run_cb();
}
}
|