Unverified Commit c82d85e6 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

[Turbopack] add active_counter to keep tasks active (#74772)

Rename AggregateRoot to Activeness and split into both sources

improve readablility

add active_counter as source of activeness

add Debug for DequeSet

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the PR.
- Read the Docs Contribution Guide to ensure your contribution follows the docs guidelines: https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See: https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. (A discussion must be opened, see https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added (https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to understand the PR)
- When linking to a Slack thread, you might want to share details of the conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->
parent 3256ff86
...@@ -44,13 +44,13 @@ use crate::{ ...@@ -44,13 +44,13 @@ use crate::{
ExecuteContext, ExecuteContextImpl, Operation, OutdatedEdge, TaskDirtyCause, TaskGuard, ExecuteContext, ExecuteContextImpl, Operation, OutdatedEdge, TaskDirtyCause, TaskGuard,
}, },
persisted_storage_log::PersistedStorageLog, persisted_storage_log::PersistedStorageLog,
storage::{get, get_many, get_mut, iter_many, remove, Storage}, storage::{get, get_many, get_mut, get_mut_or_insert_with, iter_many, remove, Storage},
}, },
backing_storage::BackingStorage, backing_storage::BackingStorage,
data::{ data::{
ActiveType, AggregationNumber, CachedDataItem, CachedDataItemKey, CachedDataItemType, ActivenessState, AggregationNumber, CachedDataItem, CachedDataItemKey, CachedDataItemType,
CachedDataItemValue, CachedDataItemValueRef, CachedDataUpdate, CellRef, CollectibleRef, CachedDataItemValue, CachedDataItemValueRef, CachedDataUpdate, CellRef, CollectibleRef,
CollectiblesRef, DirtyState, InProgressCellState, InProgressState, OutputValue, RootState, CollectiblesRef, DirtyState, InProgressCellState, InProgressState, OutputValue, RootType,
}, },
utils::{bi_map::BiMap, chunked_vec::ChunkedVec, ptr_eq_arc::PtrEqArc, sharded::Sharded}, utils::{bi_map::BiMap, chunked_vec::ChunkedVec, ptr_eq_arc::PtrEqArc, sharded::Sharded},
}; };
...@@ -447,7 +447,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> { ...@@ -447,7 +447,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
.unwrap_or_default() .unwrap_or_default()
.get(self.session_id); .get(self.session_id);
if dirty_tasks > 0 || is_dirty { if dirty_tasks > 0 || is_dirty {
let root = get!(task, AggregateRoot); let root = get!(task, Activeness);
let mut task_ids_to_schedule: Vec<_> = Vec::new(); let mut task_ids_to_schedule: Vec<_> = Vec::new();
// When there are dirty task, subscribe to the all_clean_event // When there are dirty task, subscribe to the all_clean_event
let root = if let Some(root) = root { let root = if let Some(root) = root {
...@@ -456,10 +456,9 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> { ...@@ -456,10 +456,9 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
// If we don't have a root state, add one. This also makes sure all tasks stay // If we don't have a root state, add one. This also makes sure all tasks stay
// active and this task won't stale. CachedActiveUntilClean // active and this task won't stale. CachedActiveUntilClean
// is automatically removed when this task is clean. // is automatically removed when this task is clean.
task.add_new(CachedDataItem::AggregateRoot { get_mut_or_insert_with!(task, Activeness, || ActivenessState::new(task_id))
value: RootState::new(ActiveType::CachedActiveUntilClean, task_id), .set_active_until_clean();
}); // A newly added Activeness need to make sure to schedule the tasks
// A newly added AggregateRoot need to make sure to schedule the tasks
task_ids_to_schedule = get_many!( task_ids_to_schedule = get_many!(
task, task,
AggregatedDirtyContainer { AggregatedDirtyContainer {
...@@ -471,7 +470,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> { ...@@ -471,7 +470,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
if is_dirty { if is_dirty {
task_ids_to_schedule.push(task_id); task_ids_to_schedule.push(task_id);
} }
get!(task, AggregateRoot).unwrap() get!(task, Activeness).unwrap()
}; };
let listener = root.all_clean_event.listen_with_note(move || { let listener = root.all_clean_event.listen_with_note(move || {
format!( format!(
...@@ -1373,10 +1372,11 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> { ...@@ -1373,10 +1372,11 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
}; };
if !aggregated_update.is_zero() { if !aggregated_update.is_zero() {
if aggregated_update.get(self.session_id) < 0 { if aggregated_update.get(self.session_id) < 0 {
if let Some(root_state) = get!(task, AggregateRoot) { if let Some(root_state) = get_mut!(task, Activeness) {
root_state.all_clean_event.notify(usize::MAX); root_state.all_clean_event.notify(usize::MAX);
if matches!(root_state.ty, ActiveType::CachedActiveUntilClean) { root_state.unset_active_until_clean();
task.remove(&CachedDataItemKey::AggregateRoot {}); if root_state.is_empty() {
task.remove(&CachedDataItemKey::Activeness {});
} }
} }
} }
...@@ -1700,8 +1700,8 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> { ...@@ -1700,8 +1700,8 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
fn create_transient_task(&self, task_type: TransientTaskType) -> TaskId { fn create_transient_task(&self, task_type: TransientTaskType) -> TaskId {
let task_id = self.transient_task_id_factory.get(); let task_id = self.transient_task_id_factory.get();
let root_type = match task_type { let root_type = match task_type {
TransientTaskType::Root(_) => ActiveType::RootTask, TransientTaskType::Root(_) => RootType::RootTask,
TransientTaskType::Once(_) => ActiveType::OnceTask, TransientTaskType::Once(_) => RootType::OnceTask,
}; };
self.transient_tasks.insert( self.transient_tasks.insert(
task_id, task_id,
...@@ -1719,13 +1719,12 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> { ...@@ -1719,13 +1719,12 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
effective: u32::MAX, effective: u32::MAX,
}, },
}); });
task.add(CachedDataItem::AggregateRoot { task.add(CachedDataItem::Activeness {
value: RootState::new(root_type, task_id), value: ActivenessState::new_root(root_type, task_id),
}); });
task.add(CachedDataItem::new_scheduled(move || match root_type { task.add(CachedDataItem::new_scheduled(move || match root_type {
ActiveType::RootTask => "Root Task".to_string(), RootType::RootTask => "Root Task".to_string(),
ActiveType::OnceTask => "Once Task".to_string(), RootType::OnceTask => "Once Task".to_string(),
_ => unreachable!(),
})); }));
} }
task_id task_id
...@@ -1744,11 +1743,12 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> { ...@@ -1744,11 +1743,12 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
dirty_containers.get(self.session_id) > 0 dirty_containers.get(self.session_id) > 0
}); });
if is_dirty || has_dirty_containers { if is_dirty || has_dirty_containers {
if let Some(root_state) = get_mut!(task, AggregateRoot) { if let Some(root_state) = get_mut!(task, Activeness) {
// We will finish the task, but it would be removed after the task is done // We will finish the task, but it would be removed after the task is done
root_state.ty = ActiveType::CachedActiveUntilClean; root_state.unset_root_type();
root_state.set_active_until_clean();
}; };
} else if let Some(root_state) = remove!(task, AggregateRoot) { } else if let Some(root_state) = remove!(task, Activeness) {
// Technically nobody should be listening to this event, but just in case // Technically nobody should be listening to this event, but just in case
// we notify it anyway // we notify it anyway
root_state.all_clean_event.notify(usize::MAX); root_state.all_clean_event.notify(usize::MAX);
......
...@@ -5,6 +5,7 @@ use turbo_tasks::{TaskId, ValueTypeId}; ...@@ -5,6 +5,7 @@ use turbo_tasks::{TaskId, ValueTypeId};
use crate::{ use crate::{
backend::{ backend::{
get,
operation::{ operation::{
aggregation_update::{ aggregation_update::{
get_aggregation_number, get_uppers, is_aggregating_node, AggregationUpdateJob, get_aggregation_number, get_uppers, is_aggregating_node, AggregationUpdateJob,
...@@ -89,6 +90,13 @@ impl Operation for CleanupOldEdgesOperation { ...@@ -89,6 +90,13 @@ impl Operation for CleanupOldEdgesOperation {
}); });
} else { } else {
let upper_ids = get_uppers(&task); let upper_ids = get_uppers(&task);
if get!(task, Activeness).is_some_and(|a| a.active_counter > 0)
{
// TODO combine both operations to avoid the clone
queue.push(AggregationUpdateJob::DecreaseActiveCounts {
task_ids: children.clone(),
});
}
queue.push(AggregationUpdateJob::InnerOfUppersLostFollowers { queue.push(AggregationUpdateJob::InnerOfUppersLostFollowers {
upper_ids, upper_ids,
lost_follower_ids: children, lost_follower_ids: children,
......
...@@ -60,6 +60,12 @@ impl ConnectChildOperation { ...@@ -60,6 +60,12 @@ impl ConnectChildOperation {
}) { }) {
let mut queue = AggregationUpdateQueue::new(); let mut queue = AggregationUpdateQueue::new();
if get!(parent_task, Activeness).is_some_and(|a| a.active_counter > 0) {
queue.push(AggregationUpdateJob::IncreaseActiveCount {
task: child_task_id,
})
}
// Get the children count // Get the children count
let children_count = count!(parent_task, Child); let children_count = count!(parent_task, Child);
......
...@@ -232,7 +232,7 @@ pub fn make_task_dirty_internal( ...@@ -232,7 +232,7 @@ pub fn make_task_dirty_internal(
AggregatedDataUpdate::new().dirty_container_update(task_id, aggregated_update), AggregatedDataUpdate::new().dirty_container_update(task_id, aggregated_update),
)); ));
} }
task.has_key(&CachedDataItemKey::AggregateRoot {}) task.has_key(&CachedDataItemKey::Activeness {})
} else { } else {
true true
}; };
......
...@@ -370,6 +370,11 @@ pub trait TaskGuard: Debug { ...@@ -370,6 +370,11 @@ pub trait TaskGuard: Debug {
fn remove(&mut self, key: &CachedDataItemKey) -> Option<CachedDataItemValue>; fn remove(&mut self, key: &CachedDataItemKey) -> Option<CachedDataItemValue>;
fn get(&self, key: &CachedDataItemKey) -> Option<CachedDataItemValueRef<'_>>; fn get(&self, key: &CachedDataItemKey) -> Option<CachedDataItemValueRef<'_>>;
fn get_mut(&mut self, key: &CachedDataItemKey) -> Option<CachedDataItemValueRefMut<'_>>; fn get_mut(&mut self, key: &CachedDataItemKey) -> Option<CachedDataItemValueRefMut<'_>>;
fn get_mut_or_insert_with(
&mut self,
key: &CachedDataItemKey,
insert: impl FnOnce() -> CachedDataItemValue,
) -> CachedDataItemValueRefMut<'_>;
fn has_key(&self, key: &CachedDataItemKey) -> bool; fn has_key(&self, key: &CachedDataItemKey) -> bool;
fn count(&self, ty: CachedDataItemType) -> usize; fn count(&self, ty: CachedDataItemType) -> usize;
fn iter( fn iter(
...@@ -596,6 +601,15 @@ impl<B: BackingStorage> TaskGuard for TaskGuardImpl<'_, B> { ...@@ -596,6 +601,15 @@ impl<B: BackingStorage> TaskGuard for TaskGuardImpl<'_, B> {
self.task.get_mut(key) self.task.get_mut(key)
} }
fn get_mut_or_insert_with(
&mut self,
key: &CachedDataItemKey,
insert: impl FnOnce() -> CachedDataItemValue,
) -> CachedDataItemValueRefMut<'_> {
self.check_access(key.category());
self.task.get_mut_or_insert_with(key, insert)
}
fn has_key(&self, key: &CachedDataItemKey) -> bool { fn has_key(&self, key: &CachedDataItemKey) -> bool {
self.check_access(key.category()); self.check_access(key.category());
self.task.has_key(key) self.task.has_key(key)
......
...@@ -193,6 +193,15 @@ impl InnerStorage { ...@@ -193,6 +193,15 @@ impl InnerStorage {
self.get_map_mut(key.ty()).and_then(|m| m.get_mut(key)) self.get_map_mut(key.ty()).and_then(|m| m.get_mut(key))
} }
pub fn get_mut_or_insert_with(
&mut self,
key: &CachedDataItemKey,
f: impl FnOnce() -> CachedDataItemValue,
) -> CachedDataItemValueRefMut<'_> {
self.get_or_create_map_mut(key.ty())
.get_mut_or_insert_with(key, f)
}
pub fn has_key(&self, key: &CachedDataItemKey) -> bool { pub fn has_key(&self, key: &CachedDataItemKey) -> bool {
self.get_map(key.ty()) self.get_map(key.ty())
.map(|m| m.contains_key(key)) .map(|m| m.contains_key(key))
...@@ -366,6 +375,24 @@ macro_rules! get_mut { ...@@ -366,6 +375,24 @@ macro_rules! get_mut {
}; };
} }
macro_rules! get_mut_or_insert_with {
($task:ident, $key:ident $input:tt, $f:expr) => {{
#[allow(unused_imports)]
use $crate::backend::operation::TaskGuard;
let () = $crate::data::allow_mut_access::$key;
let functor = $f;
let $crate::data::CachedDataItemValueRefMut::$key {
value,
} = $task.get_mut_or_insert_with(&$crate::data::CachedDataItemKey::$key $input, move || $crate::data::CachedDataItemValue::$key { value: functor() }) else {
unreachable!()
};
value
}};
($task:ident, $key:ident, $f:expr) => {
$crate::backend::storage::get_mut_or_insert_with!($task, $key {}, $f)
};
}
/// Creates an iterator over all [`CachedDataItemKey::$key`][crate::data::CachedDataItemKey]s in /// Creates an iterator over all [`CachedDataItemKey::$key`][crate::data::CachedDataItemKey]s in
/// `$task` matching the given `$key_pattern`, optional `$value_pattern`, and optional `if $cond`. /// `$task` matching the given `$key_pattern`, optional `$value_pattern`, and optional `if $cond`.
/// ///
...@@ -530,6 +557,7 @@ pub(crate) use count; ...@@ -530,6 +557,7 @@ pub(crate) use count;
pub(crate) use get; pub(crate) use get;
pub(crate) use get_many; pub(crate) use get_many;
pub(crate) use get_mut; pub(crate) use get_mut;
pub(crate) use get_mut_or_insert_with;
pub(crate) use iter_many; pub(crate) use iter_many;
pub(crate) use remove; pub(crate) use remove;
pub(crate) use update; pub(crate) use update;
......
...@@ -67,23 +67,78 @@ impl OutputValue { ...@@ -67,23 +67,78 @@ impl OutputValue {
} }
#[derive(Debug)] #[derive(Debug)]
pub struct RootState { pub struct ActivenessState {
pub ty: ActiveType, /// When this counter is > 0, the task is active.
pub active_counter: i32,
/// The task is a root or once task and is active due to that.
pub root_ty: Option<RootType>,
/// The subgraph is active as long it's dirty. Once it become clean, it will unset this flag.
///
/// This happens primarily when a dirty subgraph wants to be scheduled. It will set this flag
/// to "cache" the activeness.
///
/// It also happens when a task is strongly consistently read. We need the `all_clean_event` in
/// that case and want to keep the task active to not stale the task.
pub active_until_clean: bool,
/// An event which is notifies when the subgraph is no longer dirty. It must be combined with
/// `active_until_clean` to avoid staling the task.
pub all_clean_event: Event, pub all_clean_event: Event,
} }
impl RootState { impl ActivenessState {
pub fn new(ty: ActiveType, id: TaskId) -> Self { pub fn new(id: TaskId) -> Self {
Self { Self {
ty, active_counter: 0,
all_clean_event: Event::new(move || format!("RootState::all_clean_event {:?}", id)), root_ty: None,
active_until_clean: false,
all_clean_event: Event::new(move || {
format!("ActivenessState::all_clean_event {:?}", id)
}),
} }
} }
pub fn new_root(root_ty: RootType, id: TaskId) -> Self {
let mut this = Self::new(id);
this.set_root(root_ty);
this
}
pub fn set_root(&mut self, root_ty: RootType) {
self.root_ty = Some(root_ty);
}
pub fn set_active_until_clean(&mut self) {
self.active_until_clean = true;
}
/// Increment the active counter and return true if the counter was 0 before.
pub fn increment_active_counter(&mut self) -> bool {
self.active_counter += 1;
self.active_counter == 1
}
/// Decrement the active counter and return true if the counter is 0 after.
pub fn decrement_active_counter(&mut self) -> bool {
self.active_counter -= 1;
self.active_counter == 0
}
pub fn unset_root_type(&mut self) {
self.root_ty = None;
}
pub fn unset_active_until_clean(&mut self) {
self.active_until_clean = false;
}
pub fn is_empty(&self) -> bool {
self.root_ty.is_none() && !self.active_until_clean && self.active_counter == 0
}
} }
transient_traits!(RootState); transient_traits!(ActivenessState);
impl Eq for RootState {} impl Eq for ActivenessState {}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub struct DirtyState { pub struct DirtyState {
...@@ -239,13 +294,9 @@ impl DirtyContainerCount { ...@@ -239,13 +294,9 @@ impl DirtyContainerCount {
} }
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub enum ActiveType { pub enum RootType {
RootTask, RootTask,
OnceTask, OnceTask,
/// The aggregated task graph was scheduled because it has reached an AggregatedRoot while
/// propagating the dirty container or is read strongly consistent. This state is reset when
/// all this sub graph becomes clean again.
CachedActiveUntilClean,
} }
#[derive(Debug)] #[derive(Debug)]
...@@ -390,8 +441,8 @@ pub enum CachedDataItem { ...@@ -390,8 +441,8 @@ pub enum CachedDataItem {
// Transient Root Type // Transient Root Type
#[serde(skip)] #[serde(skip)]
AggregateRoot { Activeness {
value: RootState, value: ActivenessState,
}, },
// Transient In Progress state // Transient In Progress state
...@@ -464,7 +515,7 @@ impl CachedDataItem { ...@@ -464,7 +515,7 @@ impl CachedDataItem {
!collectible.cell.task.is_transient() !collectible.cell.task.is_transient()
} }
CachedDataItem::AggregatedDirtyContainerCount { .. } => true, CachedDataItem::AggregatedDirtyContainerCount { .. } => true,
CachedDataItem::AggregateRoot { .. } => false, CachedDataItem::Activeness { .. } => false,
CachedDataItem::InProgress { .. } => false, CachedDataItem::InProgress { .. } => false,
CachedDataItem::InProgressCell { .. } => false, CachedDataItem::InProgressCell { .. } => false,
CachedDataItem::OutdatedCollectible { .. } => false, CachedDataItem::OutdatedCollectible { .. } => false,
...@@ -530,7 +581,7 @@ impl CachedDataItem { ...@@ -530,7 +581,7 @@ impl CachedDataItem {
| Self::InProgressCell { .. } | Self::InProgressCell { .. }
| Self::InProgress { .. } | Self::InProgress { .. }
| Self::Error { .. } | Self::Error { .. }
| Self::AggregateRoot { .. } => TaskDataCategory::All, | Self::Activeness { .. } => TaskDataCategory::All,
} }
} }
} }
...@@ -562,7 +613,7 @@ impl CachedDataItemKey { ...@@ -562,7 +613,7 @@ impl CachedDataItemKey {
!collectible.cell.task.is_transient() !collectible.cell.task.is_transient()
} }
CachedDataItemKey::AggregatedDirtyContainerCount { .. } => true, CachedDataItemKey::AggregatedDirtyContainerCount { .. } => true,
CachedDataItemKey::AggregateRoot { .. } => false, CachedDataItemKey::Activeness { .. } => false,
CachedDataItemKey::InProgress { .. } => false, CachedDataItemKey::InProgress { .. } => false,
CachedDataItemKey::InProgressCell { .. } => false, CachedDataItemKey::InProgressCell { .. } => false,
CachedDataItemKey::OutdatedCollectible { .. } => false, CachedDataItemKey::OutdatedCollectible { .. } => false,
...@@ -616,7 +667,7 @@ impl CachedDataItemType { ...@@ -616,7 +667,7 @@ impl CachedDataItemType {
| Self::InProgressCell { .. } | Self::InProgressCell { .. }
| Self::InProgress { .. } | Self::InProgress { .. }
| Self::Error { .. } | Self::Error { .. }
| Self::AggregateRoot { .. } => TaskDataCategory::All, | Self::Activeness { .. } => TaskDataCategory::All,
} }
} }
} }
...@@ -627,7 +678,7 @@ impl CachedDataItemType { ...@@ -627,7 +678,7 @@ impl CachedDataItemType {
#[allow(non_upper_case_globals, dead_code)] #[allow(non_upper_case_globals, dead_code)]
pub mod allow_mut_access { pub mod allow_mut_access {
pub const InProgress: () = (); pub const InProgress: () = ();
pub const AggregateRoot: () = (); pub const Activeness: () = ();
} }
impl CachedDataItemValue { impl CachedDataItemValue {
......
use std::{ use std::{
collections::{HashSet, VecDeque}, collections::{HashSet, VecDeque},
fmt::Debug,
hash::{BuildHasher, BuildHasherDefault, Hash}, hash::{BuildHasher, BuildHasherDefault, Hash},
}; };
...@@ -20,6 +21,12 @@ pub struct DequeSet<T, B: BuildHasher = BuildHasherDefault<FxHasher>> { ...@@ -20,6 +21,12 @@ pub struct DequeSet<T, B: BuildHasher = BuildHasherDefault<FxHasher>> {
queue: VecDeque<T>, queue: VecDeque<T>,
} }
impl<T: Debug, B: BuildHasher> Debug for DequeSet<T, B> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.queue.fmt(f)
}
}
impl<T, B: BuildHasher + Default> Default for DequeSet<T, B> { impl<T, B: BuildHasher + Default> Default for DequeSet<T, B> {
fn default() -> Self { fn default() -> Self {
Self { Self {
......
...@@ -152,6 +152,19 @@ pub fn derive_key_value_pair(input: TokenStream) -> TokenStream { ...@@ -152,6 +152,19 @@ pub fn derive_key_value_pair(input: TokenStream) -> TokenStream {
.map(|#(#value_fields)*| #value_ref_mut_name::#variant_name { #(#value_fields)* }) .map(|#(#value_fields)*| #value_ref_mut_name::#variant_name { #(#value_fields)* })
} }
}, },
get_mut_or_insert_with: quote! {
(#storage_name::#variant_name { storage }, #key_name::#variant_name {}) => {
#value_ref_mut_name::#variant_name {
#(#value_fields)*: storage
.get_or_insert_with(|| {
let #value_name::#variant_name { #(#value_fields)* } = insert_with() else {
unreachable!();
};
#(#value_fields)*
})
}
}
},
shrink_to_fit: quote! { shrink_to_fit: quote! {
#storage_name::#variant_name { .. } => { #storage_name::#variant_name { .. } => {
// nothing to do // nothing to do
...@@ -229,6 +242,20 @@ pub fn derive_key_value_pair(input: TokenStream) -> TokenStream { ...@@ -229,6 +242,20 @@ pub fn derive_key_value_pair(input: TokenStream) -> TokenStream {
.map(|#(#value_fields)*| #value_ref_mut_name::#variant_name { #(#value_fields)* }) .map(|#(#value_fields)*| #value_ref_mut_name::#variant_name { #(#value_fields)* })
} }
}, },
get_mut_or_insert_with: quote! {
(#storage_name::#variant_name { storage }, #key_name::#variant_name { #(#key_fields)* }) => {
#value_ref_mut_name::#variant_name {
#(#value_fields)*: storage
.entry(*#(#key_fields)*)
.or_insert_with(|| {
let #value_name::#variant_name { #(#value_fields)* } = insert_with() else {
unreachable!();
};
#(#value_fields)*
})
}
}
},
shrink_to_fit: quote! { shrink_to_fit: quote! {
#storage_name::#variant_name { storage } => { #storage_name::#variant_name { storage } => {
storage.shrink_to_fit() storage.shrink_to_fit()
...@@ -307,6 +334,20 @@ pub fn derive_key_value_pair(input: TokenStream) -> TokenStream { ...@@ -307,6 +334,20 @@ pub fn derive_key_value_pair(input: TokenStream) -> TokenStream {
.map(|#(#value_fields)*| #value_ref_mut_name::#variant_name { #(#value_fields)* }) .map(|#(#value_fields)*| #value_ref_mut_name::#variant_name { #(#value_fields)* })
} }
}, },
get_mut_or_insert_with: quote! {
(#storage_name::#variant_name { storage }, #key_name::#variant_name { #(#key_fields),* }) => {
#value_ref_mut_name::#variant_name {
#(#value_fields)*: storage
.entry((#(*#key_fields),*))
.or_insert_with(|| {
let #value_name::#variant_name { #(#value_fields)* } = insert_with() else {
unreachable!();
};
#(#value_fields)*
})
}
}
},
shrink_to_fit: quote! { shrink_to_fit: quote! {
#storage_name::#variant_name { storage } => { #storage_name::#variant_name { storage } => {
storage.shrink_to_fit() storage.shrink_to_fit()
...@@ -351,6 +392,10 @@ pub fn derive_key_value_pair(input: TokenStream) -> TokenStream { ...@@ -351,6 +392,10 @@ pub fn derive_key_value_pair(input: TokenStream) -> TokenStream {
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let storage_get = storage.iter().map(|decl| &decl.get).collect::<Vec<_>>(); let storage_get = storage.iter().map(|decl| &decl.get).collect::<Vec<_>>();
let storage_get_mut = storage.iter().map(|decl| &decl.get_mut).collect::<Vec<_>>(); let storage_get_mut = storage.iter().map(|decl| &decl.get_mut).collect::<Vec<_>>();
let storage_get_mut_or_insert_with = storage
.iter()
.map(|decl| &decl.get_mut_or_insert_with)
.collect::<Vec<_>>();
let storage_shrink_to_fit = storage let storage_shrink_to_fit = storage
.iter() .iter()
.map(|decl| &decl.shrink_to_fit) .map(|decl| &decl.shrink_to_fit)
...@@ -590,6 +635,15 @@ pub fn derive_key_value_pair(input: TokenStream) -> TokenStream { ...@@ -590,6 +635,15 @@ pub fn derive_key_value_pair(input: TokenStream) -> TokenStream {
} }
} }
pub fn get_mut_or_insert_with(&mut self, key: &#key_name, insert_with: impl FnOnce() -> #value_name) -> #value_ref_mut_name {
match (self, key) {
#(
#storage_get_mut_or_insert_with
)*
_ => unreachable!(),
}
}
pub fn shrink_to_fit(&mut self) { pub fn shrink_to_fit(&mut self) {
match self { match self {
#( #(
...@@ -786,6 +840,7 @@ struct StorageDecl { ...@@ -786,6 +840,7 @@ struct StorageDecl {
contains_key: proc_macro2::TokenStream, contains_key: proc_macro2::TokenStream,
get: proc_macro2::TokenStream, get: proc_macro2::TokenStream,
get_mut: proc_macro2::TokenStream, get_mut: proc_macro2::TokenStream,
get_mut_or_insert_with: proc_macro2::TokenStream,
shrink_to_fit: proc_macro2::TokenStream, shrink_to_fit: proc_macro2::TokenStream,
is_empty: proc_macro2::TokenStream, is_empty: proc_macro2::TokenStream,
len: proc_macro2::TokenStream, len: proc_macro2::TokenStream,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment