]> git.lizzy.rs Git - rust.git/blob - src/librustc_data_structures/tuple_slice.rs
Auto merge of #38907 - alexcrichton:curl-retry, r=japaric
[rust.git] / src / librustc_data_structures / tuple_slice.rs
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
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);
46
47 #[test]
48 fn test_sliced_tuples() {
49     let t2 = (100, 101);
50     assert_eq!(t2.as_slice(), &[100, 101]);
51
52     let t3 = (102, 103, 104);
53     assert_eq!(t3.as_slice(), &[102, 103, 104]);
54
55     let t4 = (105, 106, 107, 108);
56     assert_eq!(t4.as_slice(), &[105, 106, 107, 108]);
57
58     let t5 = (109, 110, 111, 112, 113);
59     assert_eq!(t5.as_slice(), &[109, 110, 111, 112, 113]);
60
61     let t6 = (114, 115, 116, 117, 118, 119);
62     assert_eq!(t6.as_slice(), &[114, 115, 116, 117, 118, 119]);
63
64     let t7 = (120, 121, 122, 123, 124, 125, 126);
65     assert_eq!(t7.as_slice(), &[120, 121, 122, 123, 124, 125, 126]);
66
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]);
69
70 }