break_array/
lib.rs

1//! Want indexing arrays to not work anymore?
2//! 
3//! Simply create a crate that depends on `break_array`:
4//! 
5//! ```compile_fail
6//! use break_array as _;
7//! fn main(){
8//!     let array=[0,1,2,3];
9//!     assert_eq!( array[0], 0 );
10//! }
11//! ```
12//! and marvel at the compiler error:
13//! ```text
14//!   |
15//! 6 |     assert_eq!( array[0], 0 );
16//!   |                       ^ expected struct `break_array::MyType`, found integer
17//! 
18//! error: aborting due to previous error
19//! 
20//! For more information about this error, try `rustc --explain E0308`.
21//! ```
22//! 
23
24#![no_std]
25
26use core::ops::{Index,IndexMut};
27
28struct MyType;
29
30macro_rules! array_impls {
31    ( $($size:expr),* ) => (
32        $(
33            impl<T> Index<MyType> for [T;$size]{
34                type Output=T;
35                fn index(&self,_:MyType)->&T{
36                    &coerce_slice(self)[0]
37                }
38            }
39
40            impl<T> IndexMut<MyType> for [T;$size]{
41                fn index_mut(&mut self,_:MyType)->&mut T{
42                    &mut coerce_slice_mut(self)[0]
43                }
44            }
45        )*
46    )
47}
48
49
50array_impls!{
51    0,1,2,3,4,5,6,7,8,9,
52    10,11,12,13,14,15,16,17,18,19,
53    20,21,22,23,24,25,26,27,28,29,
54    30,31,32
55}
56
57
58/// Used to coerce `&[T;N]` to `&[T]`.
59#[inline(always)]
60const fn coerce_slice<'a, T>(slic: &'a [T]) -> &'a [T] {
61    slic
62}
63
64/// Used to coerce `&mut [T;N]` to `&mut [T]`.
65#[inline(always)]
66fn coerce_slice_mut<'a, T>(slic: &'a mut [T]) -> &'a mut [T] {
67    slic
68}
69
70
71#[cfg(test)]
72mod tests{
73    use crate::MyType;
74
75    #[test]
76    fn can_index_my_type(){
77        assert_eq!(&[3,4,5][MyType], &3);
78        assert_eq!(&mut [6,7,8][MyType], &mut 6);
79    }
80}
81