Skip to main content

moirai_core/pool/
wrapper.rs

1use crate::platform::*;
2use crate::{Priority, TaskId};
3
4/// Task wrapper for object pooling.
5///
6/// This wrapper allows tasks to be reset and reused, reducing allocation overhead.
7pub struct TaskWrapper<T> {
8    inner: Option<T>,
9    task_id: Option<TaskId>,
10    priority: Priority,
11    /// Creation timestamp for age tracking
12    creation_time: Instant,
13    /// Number of times this wrapper has been reset
14    reset_count: usize,
15}
16
17impl<T> Default for TaskWrapper<T> {
18    fn default() -> Self {
19        Self {
20            inner: None,
21            task_id: None,
22            priority: Priority::Normal,
23            creation_time: Instant::now(),
24            reset_count: 0,
25        }
26    }
27}
28
29impl<T> TaskWrapper<T> {
30    /// Create a new task wrapper.
31    #[must_use]
32    pub fn new() -> Self {
33        Self {
34            inner: None,
35            task_id: None,
36            priority: Priority::Normal,
37            creation_time: Instant::now(),
38            reset_count: 0,
39        }
40    }
41
42    /// Initialize the wrapper with a task.
43    pub fn init(&mut self, task: T, task_id: TaskId, priority: Priority) {
44        self.inner = Some(task);
45        self.task_id = Some(task_id);
46        self.priority = priority;
47        self.creation_time = Instant::now();
48    }
49
50    /// Reset the wrapper for reuse.
51    pub fn reset(&mut self) {
52        self.inner = None;
53        self.task_id = None;
54        self.priority = Priority::Normal;
55        self.creation_time = Instant::now();
56        self.reset_count += 1;
57    }
58
59    /// Take the inner task.
60    pub fn take(&mut self) -> Option<T> {
61        self.inner.take()
62    }
63
64    /// Get the task ID.
65    pub fn task_id(&self) -> Option<TaskId> {
66        self.task_id
67    }
68
69    /// Get the priority.
70    pub fn priority(&self) -> Priority {
71        self.priority
72    }
73
74    /// Get the age of this wrapper.
75    pub fn age(&self) -> Duration {
76        self.creation_time.elapsed()
77    }
78
79    /// Get the number of times this wrapper has been reset.
80    pub fn reset_count(&self) -> usize {
81        self.reset_count
82    }
83}