]>
Commit | Line | Data |
---|---|---|
9cc50fc6 SL |
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. | |
4 | // | |
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. | |
10 | ||
11 | use std::slice; | |
12 | ||
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]; | |
17 | } | |
18 | ||
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] { | |
23 | unsafe { | |
24 | let ptr = &self.0 as *const T; | |
25 | slice::from_raw_parts(ptr, $size) | |
26 | } | |
27 | } | |
28 | ||
29 | fn as_mut_slice(&mut self) -> &mut [T] { | |
30 | unsafe { | |
31 | let ptr = &mut self.0 as *mut T; | |
32 | slice::from_raw_parts_mut(ptr, $size) | |
33 | } | |
34 | } | |
35 | } | |
36 | } | |
37 | } | |
38 | ||
54a0048b SL |
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); | |
9cc50fc6 SL |
46 | |
47 | #[test] | |
48 | fn test_sliced_tuples() { | |
49 | let t2 = (100i32, 101i32); | |
50 | assert_eq!(t2.as_slice(), &[100i32, 101i32]); | |
51 | ||
52 | let t3 = (102i32, 103i32, 104i32); | |
53 | assert_eq!(t3.as_slice(), &[102i32, 103i32, 104i32]); | |
54 | ||
55 | let t4 = (105i32, 106i32, 107i32, 108i32); | |
56 | assert_eq!(t4.as_slice(), &[105i32, 106i32, 107i32, 108i32]); | |
57 | ||
58 | let t5 = (109i32, 110i32, 111i32, 112i32, 113i32); | |
59 | assert_eq!(t5.as_slice(), &[109i32, 110i32, 111i32, 112i32, 113i32]); | |
60 | } |