tuplities_remove/lib.rs
1//! A trait for removing elements at specific indices from tuples.
2//!
3//! This crate provides the `TupleRemove<Idx>` trait, which allows removing an element
4//! at a compile-time known index from a tuple, returning the element and the
5//! remaining tuple.
6
7#![no_std]
8
9/// A trait for removing an element at a specific index from a tuple.
10///
11/// This trait allows removing an element at compile-time known index `Idx`
12/// from a tuple, returning the element and the remaining tuple.
13///
14/// # Examples
15///
16/// ```
17/// use tuplities_remove::TupleRemove;
18/// use typenum::U1;
19///
20/// let tuple = (1, "hello", 3.14);
21/// let (removed, remainder) = TupleRemove::<U1>::remove(tuple);
22/// assert_eq!(removed, "hello");
23/// assert_eq!(remainder, (1, 3.14));
24/// ```
25///
26/// Part of the [`tuplities`](https://docs.rs/tuplities/latest/tuplities/) crate.
27#[tuplities_derive::impl_remove]
28pub trait TupleRemove<Idx> {
29 /// The type of the element being removed.
30 type Type;
31
32 /// The type of the remaining tuple after removing.
33 type Remainder;
34
35 /// Removes the element at index `Idx` from the tuple.
36 ///
37 /// Returns a tuple containing the removed element and the remaining tuple.
38 fn remove(self) -> (Self::Type, Self::Remainder);
39}
40
41#[cfg(test)]
42mod tests {
43 use super::TupleRemove;
44 use typenum::{U0, U1};
45
46 #[test]
47 fn test_remove_single_element_tuple() {
48 let tuple = (42,);
49 let (removed, _remainder): (i32, ()) = TupleRemove::<U0>::remove(tuple);
50 // Check types: (i32,) remove U0 -> Type = i32, Remainder = ()
51 let expected_removed: i32 = 42;
52 assert_eq!(removed, expected_removed);
53 }
54
55 #[test]
56 fn test_remove_two_element_tuple() {
57 // Remove at U0
58 let tuple = (1, 2);
59 let (removed0, remainder0) = TupleRemove::<U0>::remove(tuple);
60 let expected_removed0: i32 = 1;
61 let expected_remainder0: (i32,) = (2,);
62 assert_eq!(removed0, expected_removed0);
63 assert_eq!(remainder0, expected_remainder0);
64
65 // Remove at U1
66 let tuple = (1, 2);
67 let (removed1, remainder1) = TupleRemove::<U1>::remove(tuple);
68 let expected_removed1: i32 = 2;
69 let expected_remainder1: (i32,) = (1,);
70 assert_eq!(removed1, expected_removed1);
71 assert_eq!(remainder1, expected_remainder1);
72 }
73}