Skip to content

Commit 35165ec

Browse files
bushrat011899teor2345
authored andcommitted
Add type_info-based example
Demonstrates getting information about the splatted tuple through `type_info` (compile-time reflection), which allows working with arbitrarily large tuples under certain circumstances.
1 parent f768ea7 commit 35165ec

5 files changed

Lines changed: 175 additions & 0 deletions

File tree

‎Cargo.lock‎

Lines changed: 4 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@
22
resolver = "3"
33
members = [
44
"cpp-hypot-overload",
5+
"tuple-reflection",
56
]
67
default-members = [
78
"cpp-hypot-overload",
9+
"tuple-reflection",
810
]
911

1012
[workspace.package]

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,5 @@ cd overloading-examples
1313
rustup override set nightly
1414
cargo run
1515
cargo run --bin rust-hypot-overload
16+
cargo run --bin tuple-reflection
1617
```

‎tuple-reflection/Cargo.toml‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
[package]
2+
name = "tuple-reflection"
3+
version.workspace = true
4+
authors = [
5+
"bushrat011899 <zac@harrold.com.au>",
6+
]
7+
edition.workspace = true
8+
homepage.workspace = true
9+
keywords.workspace = true
10+
license.workspace = true
11+
readme.workspace = true
12+
repository.workspace = true
13+
rust-version.workspace = true
14+
15+
[dependencies]

‎tuple-reflection/src/main.rs‎

Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
//! Demonstrates combining the type_info and splat features for creating functions that can accept
2+
//! arbitrarily large numbers of arguments.
3+
//! We also use various const features to move runtime checks into compiletime.
4+
//!
5+
//! In this example, we're recreating [`min`](core::cmp::min) but able to accept
6+
//! unlimited arguments. A natural instinct would be to reach for `From<(T, ..)> for [T; _]`,
7+
//! however this is only implemented for up to twelve elements, and not at all
8+
//! in const yet.
9+
10+
#![allow(incomplete_features)]
11+
#![feature(const_cmp)]
12+
#![feature(const_convert)]
13+
#![feature(const_destruct)]
14+
#![feature(const_iter)]
15+
#![feature(const_trait_impl)]
16+
#![feature(splat)]
17+
#![feature(tuple_trait)]
18+
#![feature(type_info)]
19+
20+
use core::marker::{Destruct, PhantomData, Tuple};
21+
use core::mem::MaybeUninit;
22+
use core::mem::type_info::{Type, TypeKind};
23+
24+
/// This is a simple version of what we're trying to create, but it has several issues:
25+
///
26+
/// 1. Not const, because `From<(T, ..)> for [T; N]` is not const.
27+
/// 2. Requires a redundant `N` parameter since we cannot use the tuple arity to infer
28+
/// the array's length.
29+
/// 3. `From<(T, ..)> for [T; N]` is only implemented up to 12 elements
30+
pub fn min_simple<const N: usize, T: Ord>(
31+
x: T,
32+
#[rustc_splat] args: impl Tuple + Into<[T; N]>,
33+
) -> T {
34+
args.into().into_iter().fold(x, Ord::min)
35+
}
36+
37+
/// This is what we'll make instead.
38+
pub const fn min<T: [const] Destruct + [const] Ord>(x: T, #[rustc_splat] args: impl Tuple) -> T {
39+
TupleArray::from(args).fold(x, Ord::min)
40+
}
41+
42+
/// This type is a bridge between homogeneous tuples and arrays.
43+
/// While the `A` parameter implies it can accept any [`Tuple`],
44+
/// the only way to construct this type is through [`new`](TupleArray::new),
45+
/// which const-asserts the tuple is homogeneous and only includes the type `T`.
46+
pub struct TupleArray<T, A: Tuple> {
47+
/// Because we're moving one item at a time out of the tuple, it will spend
48+
/// most of its life in an invalid state, so we must wrap it in [`MaybeUninit`].
49+
tuple: MaybeUninit<A>,
50+
index: usize,
51+
_phantom: PhantomData<T>,
52+
}
53+
54+
/// We may drop [`TupleArray`] before moving all items out of it.
55+
/// During drop, we'll remove the rest, if any.
56+
const impl<T: [const] Destruct, A: Tuple> Drop for TupleArray<T, A> {
57+
fn drop(&mut self) {
58+
while self.next().is_some() {}
59+
}
60+
}
61+
62+
const impl<T, A: Tuple> Iterator for TupleArray<T, A> {
63+
type Item = T;
64+
65+
fn next(&mut self) -> Option<T> {
66+
// While a homogeneous tuple looks like an array, we aren't guaranteed they
67+
// have the same layout, so we use type_info to retrieve the offsets of
68+
// each item within the tuple.
69+
let info = const {
70+
let TypeKind::Tuple(info) = Type::of::<A>().kind else {
71+
unreachable!()
72+
};
73+
info
74+
};
75+
76+
if self.index >= info.fields.len() {
77+
return None;
78+
}
79+
80+
// SAFETY:
81+
// * A is a tuple of the form (T, ... T), where each field is aligned
82+
// * info provides accurate offsets for each field
83+
// * self.index points to a field we have yet to read from
84+
let x = unsafe {
85+
self.tuple
86+
.as_ptr()
87+
.byte_add(info.fields[self.index].offset)
88+
.cast::<T>()
89+
.read()
90+
};
91+
self.index += 1;
92+
93+
Some(x)
94+
}
95+
}
96+
97+
/// While it looks like we can turn any tuple into a [`TupleArray`], this trait
98+
/// can only be successfully implemented for tuples where all fields are equivalent
99+
/// and of the type `T`. Since we can't (yet) express this in the type system,
100+
/// we use panic within a const to fail at compiletime if attempting to call this
101+
/// on an invalid tuple.
102+
const impl<T, A: Tuple> From<A> for TupleArray<T, A> {
103+
fn from(tuple: A) -> Self {
104+
// We use a runtime assert over a const value to ensure the constant is evaluated.
105+
// This wont ever panic at runtime, only compiletime.
106+
assert!(
107+
const {
108+
let TypeKind::Tuple(a_info) = Type::of::<A>().kind else {
109+
unreachable!()
110+
};
111+
let TypeKind::Tuple(t_info) = Type::of::<(T,)>().kind else {
112+
unreachable!()
113+
};
114+
let mut i = 1;
115+
while i < a_info.fields.len() {
116+
if a_info.fields[i].ty != a_info.fields[i - 1].ty {
117+
panic!("Not a homogeneous tuple");
118+
}
119+
i += 1;
120+
}
121+
if !a_info.fields.is_empty() && t_info.fields[0].ty != a_info.fields[0].ty {
122+
panic!("Not a homogeneous tuple of the required type");
123+
}
124+
true
125+
}
126+
);
127+
Self {
128+
tuple: MaybeUninit::new(tuple),
129+
index: 0,
130+
_phantom: PhantomData,
131+
}
132+
}
133+
}
134+
135+
fn main() {
136+
dbg!(min_simple(1, 2, 3, 4));
137+
// the 14th item will cause this to fail
138+
dbg!(min_simple(
139+
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, /* 14 */
140+
));
141+
142+
dbg!(min(1, 2, 3, 4));
143+
// our type_info based alternative is able to accept an arbitrary number of
144+
// arguments, but practically compilation times will become prohibitively long
145+
// around 15,000 arguments.
146+
dbg!(min(
147+
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
148+
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
149+
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
150+
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
151+
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
152+
));
153+
}

0 commit comments

Comments
 (0)