use std::{
ops::Deref,
sync::{atomic::AtomicUsize, Arc, Weak},
};
use parking_lot::Mutex;
use crate::{
messages::{Message, MessageCopyState, MessageRingBuffer},
progress::{Id, Key, Task},
tree::{Item, Root},
};
impl Root {
pub fn new() -> Arc<Root> {
Options::default().into()
}
pub fn messages_capacity(&self) -> usize {
self.inner.lock().messages.lock().buf.capacity()
}
pub fn num_tasks(&self) -> usize {
#[cfg(feature = "progress-tree-hp-hashmap")]
{
self.inner.lock().tree.len()
}
#[cfg(not(feature = "progress-tree-hp-hashmap"))]
{
self.inner.lock().tree.len()
}
}
pub fn add_child(&self, name: impl Into<String>) -> Item {
self.inner.lock().add_child(name)
}
pub fn add_child_with_id(&self, name: impl Into<String>, id: Id) -> Item {
self.inner.lock().add_child_with_id(name, id)
}
pub fn sorted_snapshot(&self, out: &mut Vec<(Key, Task)>) {
out.clear();
#[cfg(feature = "progress-tree-hp-hashmap")]
out.extend(self.inner.lock().tree.iter().map(|r| (*r.key(), r.value().clone())));
#[cfg(not(feature = "progress-tree-hp-hashmap"))]
self.inner.lock().tree.extend_to(out);
out.sort_by_key(|t| t.0);
}
pub fn copy_messages(&self, out: &mut Vec<Message>) {
self.inner.lock().messages.lock().copy_all(out);
}
pub fn copy_new_messages(&self, out: &mut Vec<Message>, prev: Option<MessageCopyState>) -> MessageCopyState {
self.inner.lock().messages.lock().copy_new(out, prev)
}
pub fn deep_clone(&self) -> Arc<Root> {
Arc::new(Root {
inner: Mutex::new(self.inner.lock().deep_clone()),
})
}
}
#[derive(Clone, Debug)]
pub struct Options {
pub initial_capacity: usize,
pub message_buffer_capacity: usize,
}
impl Options {
pub fn create(self) -> Root {
self.into()
}
}
impl Default for Options {
fn default() -> Self {
Options {
initial_capacity: 100,
message_buffer_capacity: 20,
}
}
}
impl From<Options> for Arc<Root> {
fn from(opts: Options) -> Self {
Arc::new(opts.into())
}
}
impl From<Options> for Root {
fn from(
Options {
initial_capacity,
message_buffer_capacity,
}: Options,
) -> Self {
Root {
inner: Mutex::new(Item {
highest_child_id: 0,
value: Arc::new(AtomicUsize::default()),
key: Key::default(),
tree: Arc::new(crate::tree::HashMap::with_capacity(initial_capacity)),
messages: Arc::new(Mutex::new(MessageRingBuffer::with_capacity(message_buffer_capacity))),
}),
}
}
}
impl crate::WeakRoot for Weak<Root> {
type Root = Arc<Root>;
fn upgrade(&self) -> Option<Self::Root> {
Weak::upgrade(self)
}
}
impl crate::Root for Arc<Root> {
type WeakRoot = Weak<Root>;
fn messages_capacity(&self) -> usize {
self.deref().messages_capacity()
}
fn num_tasks(&self) -> usize {
self.deref().num_tasks()
}
fn sorted_snapshot(&self, out: &mut Vec<(Key, Task)>) {
self.deref().sorted_snapshot(out)
}
fn copy_messages(&self, out: &mut Vec<Message>) {
self.deref().copy_messages(out)
}
fn copy_new_messages(&self, out: &mut Vec<Message>, prev: Option<MessageCopyState>) -> MessageCopyState {
self.deref().copy_new_messages(out, prev)
}
fn downgrade(&self) -> Self::WeakRoot {
Arc::downgrade(self)
}
}