tuplities_insert/lib.rs
1//! A trait for inserting elements at specific indices into tuples.
2//!
3//! This crate provides the `TupleInsert<Idx, T>` trait, which allows inserting an element
4//! at a compile-time known index into a tuple, returning the tuple with the element inserted.
5
6#![no_std]
7
8/// A trait for inserting an element at a specific index into a tuple.
9///
10/// This trait allows inserting an element at compile-time known index `Idx`
11/// into a tuple, returning the tuple with the element inserted.
12///
13/// # Examples
14///
15/// ```
16/// use tuplities_insert::TupleInsert;
17/// use typenum::U1;
18///
19/// let tuple = (1, 3.14);
20/// let inserted = TupleInsert::<U1, _>::insert(tuple, "hello");
21/// assert_eq!(inserted, (1, "hello", 3.14));
22/// ```
23#[tuplities_derive::impl_insert]
24pub trait TupleInsert<Idx: typenum::Unsigned, T> {
25 /// The type of the tuple after inserting the element.
26 type Output;
27
28 /// Inserts the element at index `Idx` into the tuple.
29 ///
30 /// Returns the tuple with the element inserted at the specified index.
31 fn insert(self, value: T) -> Self::Output;
32}
33
34#[cfg(test)]
35mod tests {
36 use super::TupleInsert;
37 use typenum::{U0, U1, U2};
38
39 #[test]
40 fn test_insert_zero_elements() {
41 let tuple = ();
42 let result = TupleInsert::<U0, _>::insert(tuple, 42);
43 // () insert at U0 -> (i32,)
44 let expected: (i32,) = (42,);
45 assert_eq!(result, expected);
46 }
47
48 #[test]
49 fn test_insert_single_element() {
50 let tuple = (1,);
51 // Insert at U0
52 let result0 = TupleInsert::<U0, _>::insert(tuple, 42);
53 let expected0: (i32, i32) = (42, 1);
54 assert_eq!(result0, expected0);
55
56 // Insert at U1
57 let tuple = (1,);
58 let result1 = TupleInsert::<U1, _>::insert(tuple, 42);
59 let expected1: (i32, i32) = (1, 42);
60 assert_eq!(result1, expected1);
61 }
62
63 #[test]
64 fn test_insert_two_elements() {
65 let tuple = (1, 2);
66 // Insert at U0
67 let result0 = TupleInsert::<U0, _>::insert(tuple, 42);
68 let expected0: (i32, i32, i32) = (42, 1, 2);
69 assert_eq!(result0, expected0);
70
71 // Insert at U1
72 let tuple = (1, 2);
73 let result1 = TupleInsert::<U1, _>::insert(tuple, 42);
74 let expected1: (i32, i32, i32) = (1, 42, 2);
75 assert_eq!(result1, expected1);
76
77 // Insert at U2
78 let tuple = (1, 2);
79 let result2 = TupleInsert::<U2, _>::insert(tuple, 42);
80 let expected2: (i32, i32, i32) = (1, 2, 42);
81 assert_eq!(result2, expected2);
82 }
83}