1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 /// Allows to view uniform tuples as slices
14 pub trait TupleSlice<T> {
15 fn as_slice(&self) -> &[T];
16 fn as_mut_slice(&mut self) -> &mut [T];
19 macro_rules! impl_tuple_slice {
20 ($tuple_type:ty, $size:expr) => {
21 impl<T> TupleSlice<T> for $tuple_type {
22 fn as_slice(&self) -> &[T] {
24 let ptr = &self.0 as *const T;
25 slice::from_raw_parts(ptr, $size)
29 fn as_mut_slice(&mut self) -> &mut [T] {
31 let ptr = &mut self.0 as *mut T;
32 slice::from_raw_parts_mut(ptr, $size)
39 impl_tuple_slice!((T, T), 2);
40 impl_tuple_slice!((T, T, T), 3);
41 impl_tuple_slice!((T, T, T, T), 4);
42 impl_tuple_slice!((T, T, T, T, T), 5);
43 impl_tuple_slice!((T, T, T, T, T, T), 6);
44 impl_tuple_slice!((T, T, T, T, T, T, T), 7);
45 impl_tuple_slice!((T, T, T, T, T, T, T, T), 8);
48 fn test_sliced_tuples() {
50 assert_eq!(t2.as_slice(), &[100, 101]);
52 let t3 = (102, 103, 104);
53 assert_eq!(t3.as_slice(), &[102, 103, 104]);
55 let t4 = (105, 106, 107, 108);
56 assert_eq!(t4.as_slice(), &[105, 106, 107, 108]);
58 let t5 = (109, 110, 111, 112, 113);
59 assert_eq!(t5.as_slice(), &[109, 110, 111, 112, 113]);
61 let t6 = (114, 115, 116, 117, 118, 119);
62 assert_eq!(t6.as_slice(), &[114, 115, 116, 117, 118, 119]);
64 let t7 = (120, 121, 122, 123, 124, 125, 126);
65 assert_eq!(t7.as_slice(), &[120, 121, 122, 123, 124, 125, 126]);
67 let t8 = (127, 128, 129, 130, 131, 132, 133, 134);
68 assert_eq!(t8.as_slice(), &[127, 128, 129, 130, 131, 132, 133, 134]);