Skip to content

Commit d62de4c

Browse files
Add TupleSlice trait to rustc_data_structures.
1 parent ae1cf98 commit d62de4c

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

src/librustc_data_structures/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ pub mod snapshot_vec;
4242
pub mod transitive_relation;
4343
pub mod unify;
4444
pub mod fnv;
45+
pub mod tuple_slice;
4546

4647
// See comments in src/librustc/lib.rs
4748
#[doc(hidden)]
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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 = (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+
}

0 commit comments

Comments
 (0)