]> git.proxmox.com Git - rustc.git/blob - vendor/generic-array/src/lib.rs
New upstream version 1.44.1+dfsg1
[rustc.git] / vendor / generic-array / src / lib.rs
1 //! This crate implements a structure that can be used as a generic array type.use
2 //! Core Rust array types `[T; N]` can't be used generically with
3 //! respect to `N`, so for example this:
4 //!
5 //! ```{should_fail}
6 //! struct Foo<T, N> {
7 //! data: [T; N]
8 //! }
9 //! ```
10 //!
11 //! won't work.
12 //!
13 //! **generic-array** exports a `GenericArray<T,N>` type, which lets
14 //! the above be implemented as:
15 //!
16 //! ```
17 //! # use generic_array::{ArrayLength, GenericArray};
18 //! struct Foo<T, N: ArrayLength<T>> {
19 //! data: GenericArray<T,N>
20 //! }
21 //! ```
22 //!
23 //! The `ArrayLength<T>` trait is implemented by default for
24 //! [unsigned integer types](../typenum/uint/index.html) from
25 //! [typenum](../typenum/index.html).
26 //!
27 //! For ease of use, an `arr!` macro is provided - example below:
28 //!
29 //! ```
30 //! # #[macro_use]
31 //! # extern crate generic_array;
32 //! # extern crate typenum;
33 //! # fn main() {
34 //! let array = arr![u32; 1, 2, 3];
35 //! assert_eq!(array[2], 3);
36 //! # }
37 //! ```
38
39 #![deny(missing_docs)]
40 #![no_std]
41
42 #[cfg(feature = "serde")]
43 extern crate serde;
44
45 #[cfg(test)]
46 extern crate bincode;
47
48 pub extern crate typenum;
49
50 mod hex;
51 mod impls;
52
53 #[cfg(feature = "serde")]
54 pub mod impl_serde;
55
56 use core::iter::FromIterator;
57 use core::marker::PhantomData;
58 use core::mem::ManuallyDrop;
59 use core::ops::{Deref, DerefMut};
60 use core::{mem, ptr, slice};
61 use typenum::bit::{B0, B1};
62 use typenum::uint::{UInt, UTerm, Unsigned};
63
64 #[cfg_attr(test, macro_use)]
65 pub mod arr;
66 pub mod functional;
67 pub mod iter;
68 pub mod sequence;
69
70 use functional::*;
71 pub use iter::GenericArrayIter;
72 use sequence::*;
73
74 /// Trait making `GenericArray` work, marking types to be used as length of an array
75 pub unsafe trait ArrayLength<T>: Unsigned {
76 /// Associated type representing the array type for the number
77 type ArrayType;
78 }
79
80 unsafe impl<T> ArrayLength<T> for UTerm {
81 #[doc(hidden)]
82 type ArrayType = ();
83 }
84
85 /// Internal type used to generate a struct of appropriate size
86 #[allow(dead_code)]
87 #[repr(C)]
88 #[doc(hidden)]
89 pub struct GenericArrayImplEven<T, U> {
90 parent1: U,
91 parent2: U,
92 _marker: PhantomData<T>,
93 }
94
95 impl<T: Clone, U: Clone> Clone for GenericArrayImplEven<T, U> {
96 fn clone(&self) -> GenericArrayImplEven<T, U> {
97 GenericArrayImplEven {
98 parent1: self.parent1.clone(),
99 parent2: self.parent2.clone(),
100 _marker: PhantomData,
101 }
102 }
103 }
104
105 impl<T: Copy, U: Copy> Copy for GenericArrayImplEven<T, U> {}
106
107 /// Internal type used to generate a struct of appropriate size
108 #[allow(dead_code)]
109 #[repr(C)]
110 #[doc(hidden)]
111 pub struct GenericArrayImplOdd<T, U> {
112 parent1: U,
113 parent2: U,
114 data: T,
115 }
116
117 impl<T: Clone, U: Clone> Clone for GenericArrayImplOdd<T, U> {
118 fn clone(&self) -> GenericArrayImplOdd<T, U> {
119 GenericArrayImplOdd {
120 parent1: self.parent1.clone(),
121 parent2: self.parent2.clone(),
122 data: self.data.clone(),
123 }
124 }
125 }
126
127 impl<T: Copy, U: Copy> Copy for GenericArrayImplOdd<T, U> {}
128
129 unsafe impl<T, N: ArrayLength<T>> ArrayLength<T> for UInt<N, B0> {
130 #[doc(hidden)]
131 type ArrayType = GenericArrayImplEven<T, N::ArrayType>;
132 }
133
134 unsafe impl<T, N: ArrayLength<T>> ArrayLength<T> for UInt<N, B1> {
135 #[doc(hidden)]
136 type ArrayType = GenericArrayImplOdd<T, N::ArrayType>;
137 }
138
139 /// Struct representing a generic array - `GenericArray<T, N>` works like [T; N]
140 #[allow(dead_code)]
141 pub struct GenericArray<T, U: ArrayLength<T>> {
142 data: U::ArrayType,
143 }
144
145 unsafe impl<T: Send, N: ArrayLength<T>> Send for GenericArray<T, N> {}
146 unsafe impl<T: Sync, N: ArrayLength<T>> Sync for GenericArray<T, N> {}
147
148 impl<T, N> Deref for GenericArray<T, N>
149 where
150 N: ArrayLength<T>,
151 {
152 type Target = [T];
153
154 #[inline(always)]
155 fn deref(&self) -> &[T] {
156 unsafe { slice::from_raw_parts(self as *const Self as *const T, N::to_usize()) }
157 }
158 }
159
160 impl<T, N> DerefMut for GenericArray<T, N>
161 where
162 N: ArrayLength<T>,
163 {
164 #[inline(always)]
165 fn deref_mut(&mut self) -> &mut [T] {
166 unsafe { slice::from_raw_parts_mut(self as *mut Self as *mut T, N::to_usize()) }
167 }
168 }
169
170 /// Creates an array one element at a time using a mutable iterator
171 /// you can write to with `ptr::write`.
172 ///
173 /// Incremenent the position while iterating to mark off created elements,
174 /// which will be dropped if `into_inner` is not called.
175 #[doc(hidden)]
176 pub struct ArrayBuilder<T, N: ArrayLength<T>> {
177 array: ManuallyDrop<GenericArray<T, N>>,
178 position: usize,
179 }
180
181 impl<T, N: ArrayLength<T>> ArrayBuilder<T, N> {
182 #[doc(hidden)]
183 #[inline]
184 pub unsafe fn new() -> ArrayBuilder<T, N> {
185 ArrayBuilder {
186 array: ManuallyDrop::new(mem::uninitialized()),
187 position: 0,
188 }
189 }
190
191 /// Creates a mutable iterator for writing to the array using `ptr::write`.
192 ///
193 /// Increment the position value given as a mutable reference as you iterate
194 /// to mark how many elements have been created.
195 #[doc(hidden)]
196 #[inline]
197 pub unsafe fn iter_position(&mut self) -> (slice::IterMut<T>, &mut usize) {
198 (self.array.iter_mut(), &mut self.position)
199 }
200
201 /// When done writing (assuming all elements have been written to),
202 /// get the inner array.
203 #[doc(hidden)]
204 #[inline]
205 pub unsafe fn into_inner(self) -> GenericArray<T, N> {
206 let array = ptr::read(&self.array);
207
208 mem::forget(self);
209
210 ManuallyDrop::into_inner(array)
211 }
212 }
213
214 impl<T, N: ArrayLength<T>> Drop for ArrayBuilder<T, N> {
215 fn drop(&mut self) {
216 for value in &mut self.array[..self.position] {
217 unsafe {
218 ptr::drop_in_place(value);
219 }
220 }
221 }
222 }
223
224 /// Consumes an array.
225 ///
226 /// Increment the position while iterating and any leftover elements
227 /// will be dropped if position does not go to N
228 #[doc(hidden)]
229 pub struct ArrayConsumer<T, N: ArrayLength<T>> {
230 array: ManuallyDrop<GenericArray<T, N>>,
231 position: usize,
232 }
233
234 impl<T, N: ArrayLength<T>> ArrayConsumer<T, N> {
235 #[doc(hidden)]
236 #[inline]
237 pub unsafe fn new(array: GenericArray<T, N>) -> ArrayConsumer<T, N> {
238 ArrayConsumer {
239 array: ManuallyDrop::new(array),
240 position: 0,
241 }
242 }
243
244 /// Creates an iterator and mutable reference to the internal position
245 /// to keep track of consumed elements.
246 ///
247 /// Increment the position as you iterate to mark off consumed elements
248 #[doc(hidden)]
249 #[inline]
250 pub unsafe fn iter_position(&mut self) -> (slice::Iter<T>, &mut usize) {
251 (self.array.iter(), &mut self.position)
252 }
253 }
254
255 impl<T, N: ArrayLength<T>> Drop for ArrayConsumer<T, N> {
256 fn drop(&mut self) {
257 for value in &mut self.array[self.position..N::to_usize()] {
258 unsafe {
259 ptr::drop_in_place(value);
260 }
261 }
262 }
263 }
264
265 impl<'a, T: 'a, N> IntoIterator for &'a GenericArray<T, N>
266 where
267 N: ArrayLength<T>,
268 {
269 type IntoIter = slice::Iter<'a, T>;
270 type Item = &'a T;
271
272 fn into_iter(self: &'a GenericArray<T, N>) -> Self::IntoIter {
273 self.as_slice().iter()
274 }
275 }
276
277 impl<'a, T: 'a, N> IntoIterator for &'a mut GenericArray<T, N>
278 where
279 N: ArrayLength<T>,
280 {
281 type IntoIter = slice::IterMut<'a, T>;
282 type Item = &'a mut T;
283
284 fn into_iter(self: &'a mut GenericArray<T, N>) -> Self::IntoIter {
285 self.as_mut_slice().iter_mut()
286 }
287 }
288
289 impl<T, N> FromIterator<T> for GenericArray<T, N>
290 where
291 N: ArrayLength<T>,
292 {
293 fn from_iter<I>(iter: I) -> GenericArray<T, N>
294 where
295 I: IntoIterator<Item = T>,
296 {
297 unsafe {
298 let mut destination = ArrayBuilder::new();
299
300 {
301 let (destination_iter, position) = destination.iter_position();
302
303 for (src, dst) in iter.into_iter().zip(destination_iter) {
304 ptr::write(dst, src);
305
306 *position += 1;
307 }
308 }
309
310 if destination.position < N::to_usize() {
311 from_iter_length_fail(destination.position, N::to_usize());
312 }
313
314 destination.into_inner()
315 }
316 }
317 }
318
319 #[inline(never)]
320 #[cold]
321 fn from_iter_length_fail(length: usize, expected: usize) -> ! {
322 panic!(
323 "GenericArray::from_iter received {} elements but expected {}",
324 length, expected
325 );
326 }
327
328 unsafe impl<T, N> GenericSequence<T> for GenericArray<T, N>
329 where
330 N: ArrayLength<T>,
331 Self: IntoIterator<Item = T>,
332 {
333 type Length = N;
334 type Sequence = Self;
335
336 fn generate<F>(mut f: F) -> GenericArray<T, N>
337 where
338 F: FnMut(usize) -> T,
339 {
340 unsafe {
341 let mut destination = ArrayBuilder::new();
342
343 {
344 let (destination_iter, position) = destination.iter_position();
345
346 for (i, dst) in destination_iter.enumerate() {
347 ptr::write(dst, f(i));
348
349 *position += 1;
350 }
351 }
352
353 destination.into_inner()
354 }
355 }
356
357 #[doc(hidden)]
358 fn inverted_zip<B, U, F>(
359 self,
360 lhs: GenericArray<B, Self::Length>,
361 mut f: F,
362 ) -> MappedSequence<GenericArray<B, Self::Length>, B, U>
363 where
364 GenericArray<B, Self::Length>:
365 GenericSequence<B, Length = Self::Length> + MappedGenericSequence<B, U>,
366 Self: MappedGenericSequence<T, U>,
367 Self::Length: ArrayLength<B> + ArrayLength<U>,
368 F: FnMut(B, Self::Item) -> U,
369 {
370 unsafe {
371 let mut left = ArrayConsumer::new(lhs);
372 let mut right = ArrayConsumer::new(self);
373
374 let (left_array_iter, left_position) = left.iter_position();
375 let (right_array_iter, right_position) = right.iter_position();
376
377 FromIterator::from_iter(left_array_iter.zip(right_array_iter).map(|(l, r)| {
378 let left_value = ptr::read(l);
379 let right_value = ptr::read(r);
380
381 *left_position += 1;
382 *right_position += 1;
383
384 f(left_value, right_value)
385 }))
386 }
387 }
388
389 #[doc(hidden)]
390 fn inverted_zip2<B, Lhs, U, F>(self, lhs: Lhs, mut f: F) -> MappedSequence<Lhs, B, U>
391 where
392 Lhs: GenericSequence<B, Length = Self::Length> + MappedGenericSequence<B, U>,
393 Self: MappedGenericSequence<T, U>,
394 Self::Length: ArrayLength<B> + ArrayLength<U>,
395 F: FnMut(Lhs::Item, Self::Item) -> U,
396 {
397 unsafe {
398 let mut right = ArrayConsumer::new(self);
399
400 let (right_array_iter, right_position) = right.iter_position();
401
402 FromIterator::from_iter(
403 lhs.into_iter()
404 .zip(right_array_iter)
405 .map(|(left_value, r)| {
406 let right_value = ptr::read(r);
407
408 *right_position += 1;
409
410 f(left_value, right_value)
411 }),
412 )
413 }
414 }
415 }
416
417 unsafe impl<T, U, N> MappedGenericSequence<T, U> for GenericArray<T, N>
418 where
419 N: ArrayLength<T> + ArrayLength<U>,
420 GenericArray<U, N>: GenericSequence<U, Length = N>,
421 {
422 type Mapped = GenericArray<U, N>;
423 }
424
425 unsafe impl<T, N> FunctionalSequence<T> for GenericArray<T, N>
426 where
427 N: ArrayLength<T>,
428 Self: GenericSequence<T, Item = T, Length = N>,
429 {
430 fn map<U, F>(self, mut f: F) -> MappedSequence<Self, T, U>
431 where
432 Self::Length: ArrayLength<U>,
433 Self: MappedGenericSequence<T, U>,
434 F: FnMut(T) -> U,
435 {
436 unsafe {
437 let mut source = ArrayConsumer::new(self);
438
439 let (array_iter, position) = source.iter_position();
440
441 FromIterator::from_iter(array_iter.map(|src| {
442 let value = ptr::read(src);
443
444 *position += 1;
445
446 f(value)
447 }))
448 }
449 }
450
451 #[inline]
452 fn zip<B, Rhs, U, F>(self, rhs: Rhs, f: F) -> MappedSequence<Self, T, U>
453 where
454 Self: MappedGenericSequence<T, U>,
455 Rhs: MappedGenericSequence<B, U, Mapped = MappedSequence<Self, T, U>>,
456 Self::Length: ArrayLength<B> + ArrayLength<U>,
457 Rhs: GenericSequence<B, Length = Self::Length>,
458 F: FnMut(T, Rhs::Item) -> U,
459 {
460 rhs.inverted_zip(self, f)
461 }
462
463 fn fold<U, F>(self, init: U, mut f: F) -> U
464 where
465 F: FnMut(U, T) -> U,
466 {
467 unsafe {
468 let mut source = ArrayConsumer::new(self);
469
470 let (array_iter, position) = source.iter_position();
471
472 array_iter.fold(init, |acc, src| {
473 let value = ptr::read(src);
474
475 *position += 1;
476
477 f(acc, value)
478 })
479 }
480 }
481 }
482
483 impl<T, N> GenericArray<T, N>
484 where
485 N: ArrayLength<T>,
486 {
487 /// Extracts a slice containing the entire array.
488 #[inline]
489 pub fn as_slice(&self) -> &[T] {
490 self.deref()
491 }
492
493 /// Extracts a mutable slice containing the entire array.
494 #[inline]
495 pub fn as_mut_slice(&mut self) -> &mut [T] {
496 self.deref_mut()
497 }
498
499 /// Converts slice to a generic array reference with inferred length;
500 ///
501 /// Length of the slice must be equal to the length of the array.
502 #[inline]
503 pub fn from_slice(slice: &[T]) -> &GenericArray<T, N> {
504 slice.into()
505 }
506
507 /// Converts mutable slice to a mutable generic array reference
508 ///
509 /// Length of the slice must be equal to the length of the array.
510 #[inline]
511 pub fn from_mut_slice(slice: &mut [T]) -> &mut GenericArray<T, N> {
512 slice.into()
513 }
514 }
515
516 impl<'a, T, N: ArrayLength<T>> From<&'a [T]> for &'a GenericArray<T, N> {
517 /// Converts slice to a generic array reference with inferred length;
518 ///
519 /// Length of the slice must be equal to the length of the array.
520 #[inline]
521 fn from(slice: &[T]) -> &GenericArray<T, N> {
522 assert_eq!(slice.len(), N::to_usize());
523
524 unsafe { &*(slice.as_ptr() as *const GenericArray<T, N>) }
525 }
526 }
527
528 impl<'a, T, N: ArrayLength<T>> From<&'a mut [T]> for &'a mut GenericArray<T, N> {
529 /// Converts mutable slice to a mutable generic array reference
530 ///
531 /// Length of the slice must be equal to the length of the array.
532 #[inline]
533 fn from(slice: &mut [T]) -> &mut GenericArray<T, N> {
534 assert_eq!(slice.len(), N::to_usize());
535
536 unsafe { &mut *(slice.as_mut_ptr() as *mut GenericArray<T, N>) }
537 }
538 }
539
540 impl<T: Clone, N> GenericArray<T, N>
541 where
542 N: ArrayLength<T>,
543 {
544 /// Construct a `GenericArray` from a slice by cloning its content
545 ///
546 /// Length of the slice must be equal to the length of the array
547 #[inline]
548 pub fn clone_from_slice(list: &[T]) -> GenericArray<T, N> {
549 Self::from_exact_iter(list.iter().cloned())
550 .expect("Slice must be the same length as the array")
551 }
552 }
553
554 impl<T, N> GenericArray<T, N>
555 where
556 N: ArrayLength<T>,
557 {
558 /// Creates a new `GenericArray` instance from an iterator with a known exact size.
559 ///
560 /// Returns `None` if the size is not equal to the number of elements in the `GenericArray`.
561 pub fn from_exact_iter<I>(iter: I) -> Option<Self>
562 where
563 I: IntoIterator<Item = T>,
564 <I as IntoIterator>::IntoIter: ExactSizeIterator,
565 {
566 let iter = iter.into_iter();
567
568 if iter.len() == N::to_usize() {
569 unsafe {
570 let mut destination = ArrayBuilder::new();
571
572 {
573 let (destination_iter, position) = destination.iter_position();
574
575 for (dst, src) in destination_iter.zip(iter.into_iter()) {
576 ptr::write(dst, src);
577
578 *position += 1;
579 }
580 }
581
582 Some(destination.into_inner())
583 }
584 } else {
585 None
586 }
587 }
588 }
589
590 /// A reimplementation of the `transmute` function, avoiding problems
591 /// when the compiler can't prove equal sizes.
592 #[inline]
593 #[doc(hidden)]
594 pub unsafe fn transmute<A, B>(a: A) -> B {
595 let b = ::core::ptr::read(&a as *const A as *const B);
596 ::core::mem::forget(a);
597 b
598 }
599
600 #[cfg(test)]
601 mod test {
602 // Compile with:
603 // cargo rustc --lib --profile test --release --
604 // -C target-cpu=native -C opt-level=3 --emit asm
605 // and view the assembly to make sure test_assembly generates
606 // SIMD instructions instead of a niave loop.
607
608 #[inline(never)]
609 pub fn black_box<T>(val: T) -> T {
610 use core::{mem, ptr};
611
612 let ret = unsafe { ptr::read_volatile(&val) };
613 mem::forget(val);
614 ret
615 }
616
617 #[test]
618 fn test_assembly() {
619 use functional::*;
620
621 let a = black_box(arr![i32; 1, 3, 5, 7]);
622 let b = black_box(arr![i32; 2, 4, 6, 8]);
623
624 let c = (&a).zip(b, |l, r| l + r);
625
626 let d = a.fold(0, |a, x| a + x);
627
628 assert_eq!(c, arr![i32; 3, 7, 11, 15]);
629
630 assert_eq!(d, 16);
631 }
632 }