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///
24/// Part of the [`tuplities`](https://docs.rs/tuplities/latest/tuplities/) crate.
25#[tuplities_derive::impl_insert]
26pub trait TupleInsert<Idx, T> {
27    /// The type of the tuple after inserting the element.
28    type Output;
29
30    /// Inserts the element at index `Idx` into the tuple.
31    ///
32    /// Returns the tuple with the element inserted at the specified index.
33    fn insert(self, value: T) -> Self::Output;
34}
35
36#[cfg(test)]
37mod tests {
38    use super::TupleInsert;
39    use typenum::{U0, U1, U2};
40
41    #[test]
42    fn test_insert_zero_elements() {
43        let tuple = ();
44        let result = TupleInsert::<U0, _>::insert(tuple, 42);
45        // () insert at U0 -> (i32,)
46        let expected: (i32,) = (42,);
47        assert_eq!(result, expected);
48    }
49
50    #[test]
51    fn test_insert_single_element() {
52        let tuple = (1,);
53        // Insert at U0
54        let result0 = TupleInsert::<U0, _>::insert(tuple, 42);
55        let expected0: (i32, i32) = (42, 1);
56        assert_eq!(result0, expected0);
57
58        // Insert at U1
59        let tuple = (1,);
60        let result1 = TupleInsert::<U1, _>::insert(tuple, 42);
61        let expected1: (i32, i32) = (1, 42);
62        assert_eq!(result1, expected1);
63    }
64
65    #[test]
66    fn test_insert_two_elements() {
67        let tuple = (1, 2);
68        // Insert at U0
69        let result0 = TupleInsert::<U0, _>::insert(tuple, 42);
70        let expected0: (i32, i32, i32) = (42, 1, 2);
71        assert_eq!(result0, expected0);
72
73        // Insert at U1
74        let tuple = (1, 2);
75        let result1 = TupleInsert::<U1, _>::insert(tuple, 42);
76        let expected1: (i32, i32, i32) = (1, 42, 2);
77        assert_eq!(result1, expected1);
78
79        // Insert at U2
80        let tuple = (1, 2);
81        let result2 = TupleInsert::<U2, _>::insert(tuple, 42);
82        let expected2: (i32, i32, i32) = (1, 2, 42);
83        assert_eq!(result2, expected2);
84    }
85}