Skip to content

feat: Add TraversableFold and Folder#22

Draft
tisonkun wants to merge 4 commits into
mainfrom
codex/traversable-fold
Draft

feat: Add TraversableFold and Folder#22
tisonkun wants to merge 4 commits into
mainfrom
codex/traversable-fold

Conversation

@tisonkun

@tisonkun tisonkun commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

Summary

  • add TraversableFold and Folder for owned bottom-up traversal and transformation
  • add derive support for #[derive(TraversableFold)] with existing traverse attributes
  • add folder helper closures and fold impls for core/std container types

Verification

  • cargo test --workspace
  • cargo test --workspace --all-features
  • cargo clippy --workspace --all-features --all-targets

Refs #19

tisonkun added 2 commits June 3, 2026 21:29
Signed-off-by: tison <wander4096@gmail.com>
Comment thread traversable/src/function.rs Outdated
Comment on lines +107 to +139
fn fold_if_type<T, U, B, F>(this: U, fold: &mut F) -> ControlFlow<B, U>
where
T: Any,
U: Any,
F: FnMut(T) -> ControlFlow<B, T>,
{
if TypeId::of::<T>() != TypeId::of::<U>() {
return ControlFlow::Continue(this);
}

let this = cast_between_equal_any_types::<U, T>(this);
match fold(this) {
ControlFlow::Continue(this) => {
ControlFlow::Continue(cast_between_equal_any_types::<T, U>(this))
}
ControlFlow::Break(break_value) => ControlFlow::Break(break_value),
}
}

fn cast_between_equal_any_types<From, To>(from: From) -> To
where
From: Any,
To: Any,
{
debug_assert_eq!(TypeId::of::<From>(), TypeId::of::<To>());

let from = ManuallyDrop::new(from);
// SAFETY: `fold_if_type` only calls this function after verifying that `From` and `To` have
// the same `TypeId`. `Any` is implemented only for `'static` concrete types, so equal TypeIds
// identify the same type. `ManuallyDrop` prevents dropping the source after ownership has been
// transferred through `ptr::read`.
unsafe { ptr::read((&*from as *const From).cast::<To>()) }
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use case for rust-lang/libs-team's issue.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tisonkun tisonkun marked this pull request as draft June 3, 2026 14:33
@tisonkun tisonkun changed the title Add TraversableFold and Folder feat: Add TraversableFold and Folder Jun 3, 2026
tisonkun added 2 commits June 4, 2026 09:36
Signed-off-by: tison <wander4096@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant