1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
#![allow(unused_parens)]
#![cfg_attr(feature="impl_simd", feature(portable_simd))]
/*!
# Feature flags
- `impl_num` add support for traits from the num crate. (default on)
- `impl_simd` add support for simd types. (default off)
- `impl_serde` impl Serialize and Deserialize from serde
# Examples
```
extern crate tuple;
use tuple::*;
# fn main() {}
```
All following operations are defined on the `T1` .. `Tn` type of this crate,
as well for the normal tuple types.
## Element-wise operations
```
# extern crate tuple;
# use tuple::*;
# fn main() {
let a = T2(3, 4) + T2(5, 4);
assert_eq!(a, T2(8, 8));
let b = T2(3u32, 4.0f32) * T2(7, 3.0);
assert_eq!(b, T2(21, 12.));
assert_eq!(T3(1, 2, 3).map(|x| x * 2), T3(2, 4, 6));
# }
```
## Indexing
This is implemented in the [`TupleElements`](trait.TupleElements.html) trait.
Indexing works as expected and panics when out of bounds.
There are also `get` and `get_mut` functions that return `Option<&T>` and `Option<&mut T>`.
```
# extern crate tuple;
# use tuple::*;
# fn main() {
assert_eq!(T3(1, 2, 3)[2], 3);
assert_eq!(T2(7, 8).get(1), Some(&8));
assert_eq!(T2(7, 8).get(2), None);
# }
```
## Iterate over the elements of a tuple
```
# extern crate tuple;
# use tuple::*;
# fn main() {
for i in T2(1, 2).elements() {
println!("{}", i);
}
let mut b = T3(3, 4, 5);
for i in b.elements_mut() {
*i += 1;
}
assert_eq!(b.elements().sum::<u32>(), 15);
# }
```
### Consume a tuple and iterate over the elements
```
# extern crate tuple;
# use tuple::*;
# fn main() {
for i in T2(String::from("hello"), String::from("world")).into_elements() {
let s: String = i; // it's really a String
println!("{}", s);
}
# }
```
## Conversions
```
# extern crate tuple;
# use tuple::*;
# fn main() {
// slice to tuple
assert_eq!(T3::from_slice(&[1u8, 2, 3, 4, 5][..]), Some(T3(1, 2, 3)));
// tuple to and from array
let t = T3(1, 2, 3);
let a: [u8; 3] = t.into();
let t: T3<_, _, _> = a.into();
assert_eq!(T2(Some(1), Some(2)).collect(), Some(T2(1, 2)));
# }
```
## Joining two tuples
```
# extern crate tuple;
# use tuple::*;
# fn main() {
let a = T2(1, 2);
let b = T3(3, 4, 5);
assert_eq!(a.join(b), T5(1, 2, 3, 4, 5));
# }
```
## Splitting a tuple in two parts
```
# extern crate tuple;
# use tuple::*;
# fn main() {
let a = T4(1, 2, 3, 4);
let (b, c): (T1<_>, _) = a.split(); // split needs a type hint for the left side
assert_eq!(b, T1(1));
assert_eq!(c, T3(2, 3, 4));
# }
```
## Rotate and Reverse
```
# extern crate tuple;
# use tuple::*;
# fn main() {
let a = T4((), 2, 3, true);
assert_eq!(a.rot_l(), T4(2, 3, true, ())); // rotate left
assert_eq!(a.rot_r(), T4(true, (), 2, 3)); // rotate right
assert_eq!(a.reverse(), T4(true, 3, 2, ())); // reverse
# }
```
## Adding a Trait
```
#[macro_use]
extern crate tuple;
extern crate num_traits;
use tuple::*;
use num_traits::Zero;
use std::ops::{Add, Sub, Mul};
use std::fmt::Debug;
trait Ring: Add + Sub + Mul + Zero + Debug + Sized {}
// The name is up to you
macro_rules! impl_ring {
// This line is defined by this crate and can't be changed
($($Tuple:ident $Arr:ident { $($T:ident . $t:ident . $idx:tt),* } )*) => ($(
// This is expanded for every Tuple type
impl<$($T),*> Ring for $Tuple<$($T),*> where Self: Zero, $( $T: Ring ),* {}
// this has to match again
)*)
}
// actually implement it!
impl_tuple!(impl_ring);
# fn main() {}
```
**/
#![cfg_attr(not(feature="std"), no_std)]
#![allow(non_camel_case_types, non_snake_case)]
#[cfg(feature="impl_num")]
extern crate num_traits;
#[cfg(feature="impl_num")]
use num_traits as num;
#[cfg(feature="std")]
extern crate core;
#[cfg(feature="impl_serde")]
extern crate serde;
use core::{ptr, mem};
pub struct Elements<T> {
tuple: T,
index: usize
}
impl<T> Elements<T> {
#[inline(always)]
fn new(t: T) -> Elements<T> {
Elements { tuple: t, index: 0 }
}
}
pub struct IntoElements<T: TupleElements> {
tuple: Option<T>,
index: usize
}
impl<T: TupleElements> IntoElements<T> {
#[inline(always)]
fn new(t: T) -> IntoElements<T> {
IntoElements { tuple: Some(t), index: 0 }
}
}
/// This trait is marked as unsafe, due to the requirement of the get_mut method,
/// which is required work as an injective map of `index -> element`
///
/// A tuple must not have a `Drop` implementation.
pub unsafe trait TupleElements: Sized {
type Element;
const N: usize;
/// returns an Iterator over references to the elements of the tuple
#[inline(always)]
fn elements(&self) -> Elements<&Self> { Elements::new(self) }
/// returns an Iterator over mutable references to elements of the tuple
#[inline(always)]
fn elements_mut(&mut self) -> Elements<&mut Self> { Elements::new(self) }
// return an Iterator over the elements of the tuple
#[inline(always)]
fn into_elements(self) -> IntoElements<Self> { IntoElements::new(self) }
/// attempt to access the n-th element
fn get(&self, n: usize) -> Option<&Self::Element>;
/// attempt to access the n-th element mutablbly.
/// This function shall not return the same data for two different indices.
fn get_mut(&mut self, n: usize) -> Option<&mut Self::Element>;
fn from_iter<I>(iter: I) -> Option<Self> where I: Iterator<Item=Self::Element>;
}
pub trait Map<T>: TupleElements {
type Output: TupleElements<Element=T>;
/// apply a function to each element and return the result
fn map<F>(self, f: F) -> Self::Output where F: Fn(Self::Element) -> T;
/// same as `map`, but accepts a FnMut
fn map_mut<F>(self, f: F) -> Self::Output where F: FnMut(Self::Element) -> T;
}
/**
splat: copy the argument into all elements
```
# use tuple::*;
# fn main() {
let a = T4::splat(42);
assert_eq!(a, T4(42, 42, 42, 42));
# }
```
*/
pub trait Splat<T> {
fn splat(t: T) -> Self;
}
/// Call a `Fn` and unpack the arguments.
/**
```
# use tuple::*;
# fn main() {
fn foo(a: u32, b: &str) { }
foo.call((1, "hi"));
foo.call(T2(1, "hi"));
# }
```
**/
pub trait Call<T> {
type Output;
fn call(&self, args: T) -> Self::Output;
}
/// Call a `FnOnce` and unpack the arguments.
pub trait CallOnce<T> {
type Output;
fn call_once(self, args: T) -> Self::Output;
}
/// Call a `FnMut` and unpack the arguments.
pub trait CallMut<T> {
type Output;
fn call_mut(&mut self, args: T) -> Self::Output;
}
#[derive(Debug, Eq, PartialEq)]
pub enum ConvertError {
OutOfBounds
}
impl<'a, T> Iterator for Elements<&'a T> where T: TupleElements {
type Item = &'a T::Element;
#[inline(always)]
fn next(&mut self) -> Option<Self::Item> {
let t = self.tuple.get(self.index);
if let Some(_) = t {
self.index += 1;
}
t
}
}
impl<'a, T> Iterator for Elements<&'a mut T> where T: TupleElements {
type Item = &'a mut T::Element;
#[inline(always)]
fn next(&mut self) -> Option<Self::Item> {
if let Some(t) = self.tuple.get_mut(self.index) {
self.index += 1;
// we only hand out one reference to each item
// and that lifetime is limited to the Elements struct
Some(unsafe { &mut *(t as *mut T::Element) })
} else {
None
}
}
}
impl<T> Iterator for IntoElements<T> where T: TupleElements {
type Item = T::Element;
#[inline(always)]
fn next(&mut self) -> Option<Self::Item> {
match self.tuple.as_mut().unwrap().get(self.index) {
Some(p) => {
self.index += 1; // mark as taken
let v = unsafe { ptr::read(p) }; // read it
Some(v)
},
None => None
}
}
}
impl<T> Drop for IntoElements<T> where T: TupleElements {
#[inline(always)]
fn drop(&mut self) {
let mut tuple = self.tuple.take().unwrap();
// only drop remaining elements
for i in self.index .. T::N {
unsafe {
ptr::drop_in_place(tuple.get_mut(i).unwrap());
}
}
mem::forget(tuple);
}
}
/// Allows to join/concatenate two tuples
pub trait OpJoin<RHS> {
type Output;
fn join(self, rhs: RHS) -> Self::Output;
}
pub trait OpSplit<L> {
type R;
fn split(self) -> (L, Self::R);
}
pub trait OpRotateLeft {
type Output;
/// rotate left. The previously first element is now the first.
fn rot_l(self) -> Self::Output;
}
pub trait OpRotateRight {
type Output;
/// rotate right. The previously last element is now the last.
fn rot_r(self) -> Self::Output;
}
pub trait OpReverse {
type Output;
/// reverse the elements.
fn reverse(self) -> Self::Output;
}
#[macro_use]
mod utils;
/* python3:
import string
for i in range(1, 17):
print("T{i} A{i} {{ {inner} }}".format(i=i, inner=", ".join("{a}.{b}.{n}".format(a=string.ascii_uppercase[j],b=string.ascii_lowercase[j],n=j) for j in range(i))))
*/
#[macro_export]
macro_rules! impl_tuple {
($def:ident) => ($def!(
T1 A1 { A.a.0 }
T2 A2 { A.a.0, B.b.1 }
T3 A3 { A.a.0, B.b.1, C.c.2 }
T4 A4 { A.a.0, B.b.1, C.c.2, D.d.3 }
T5 A5 { A.a.0, B.b.1, C.c.2, D.d.3, E.e.4 }
T6 A6 { A.a.0, B.b.1, C.c.2, D.d.3, E.e.4, F.f.5 }
T7 A7 { A.a.0, B.b.1, C.c.2, D.d.3, E.e.4, F.f.5, G.g.6 }
T8 A8 { A.a.0, B.b.1, C.c.2, D.d.3, E.e.4, F.f.5, G.g.6, H.h.7 }
T9 A9 { A.a.0, B.b.1, C.c.2, D.d.3, E.e.4, F.f.5, G.g.6, H.h.7, I.i.8 }
T10 A10 { A.a.0, B.b.1, C.c.2, D.d.3, E.e.4, F.f.5, G.g.6, H.h.7, I.i.8, J.j.9 }
T11 A11 { A.a.0, B.b.1, C.c.2, D.d.3, E.e.4, F.f.5, G.g.6, H.h.7, I.i.8, J.j.9, K.k.10 }
T12 A12 { A.a.0, B.b.1, C.c.2, D.d.3, E.e.4, F.f.5, G.g.6, H.h.7, I.i.8, J.j.9, K.k.10, L.l.11 }
T13 A13 { A.a.0, B.b.1, C.c.2, D.d.3, E.e.4, F.f.5, G.g.6, H.h.7, I.i.8, J.j.9, K.k.10, L.l.11, M.m.12 }
T14 A14 { A.a.0, B.b.1, C.c.2, D.d.3, E.e.4, F.f.5, G.g.6, H.h.7, I.i.8, J.j.9, K.k.10, L.l.11, M.m.12, N.n.13 }
T15 A15 { A.a.0, B.b.1, C.c.2, D.d.3, E.e.4, F.f.5, G.g.6, H.h.7, I.i.8, J.j.9, K.k.10, L.l.11, M.m.12, N.n.13, O.o.14 }
T16 A16 { A.a.0, B.b.1, C.c.2, D.d.3, E.e.4, F.f.5, G.g.6, H.h.7, I.i.8, J.j.9, K.k.10, L.l.11, M.m.12, N.n.13, O.o.14, P.p.15 }
);)
}
macro_rules! init {
($($Tuple:ident $Arr:ident { $($T:ident . $t:ident . $idx:tt),* } )*) => ($(
pub struct $Tuple<$($T),*>($(pub $T),*);
pub type $Arr<T> = $Tuple<$(A!(T, $T)),*>;
)*)
}
impl_tuple!(init);
mod m_init;
mod m_ops;
mod m_convert;
mod m_array;
#[cfg(feature="impl_num")]
mod m_num;
mod m_tuple;
mod m_iter;
mod m_call;
#[cfg(all(feature="impl_simd", any(target_arch="x86", target_arch="x86_64")))]
#[macro_use]
mod m_simd;
#[cfg(feature="std")]
mod m_std;
//#[cfg(feature="impl_simd")]
//impl_tuple!(m_simd);
#[cfg(feature="impl_serde")]
mod m_serde;
/*
use itertools::tuple_impl::TupleCollect;
#[macro_use]
mod impl_itertools;
trace_macros!(true);
impl_tuple!(impl_itertools);
*/
/**
```
# extern crate tuple;
# use tuple::*;
# fn main() {
assert_eq!(tuple("hello world".split(' ')), Some(("hello", "world")));
# }
```
**/
pub fn tuple<T, I>(iter: I) -> Option<T> where
T: TupleElements, I: Iterator<Item=T::Element>
{
T::from_iter(iter)
}