]> git.proxmox.com Git - rustc.git/blame - src/librustc_data_structures/tuple_slice.rs
Imported Upstream version 1.9.0+dfsg1
[rustc.git] / src / librustc_data_structures / tuple_slice.rs
CommitLineData
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
11use std::slice;
12
13/// Allows to view uniform tuples as slices
14pub trait TupleSlice<T> {
15 fn as_slice(&self) -> &[T];
16 fn as_mut_slice(&mut self) -> &mut [T];
17}
18
19macro_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
39impl_tuple_slice!((T, T), 2);
40impl_tuple_slice!((T, T, T), 3);
41impl_tuple_slice!((T, T, T, T), 4);
42impl_tuple_slice!((T, T, T, T, T), 5);
43impl_tuple_slice!((T, T, T, T, T, T), 6);
44impl_tuple_slice!((T, T, T, T, T, T, T), 7);
45impl_tuple_slice!((T, T, T, T, T, T, T, T), 8);
9cc50fc6
SL
46
47#[test]
48fn 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}