Skip to content

Use and improve internal iteration support #71

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 14, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 13 additions & 9 deletions src/hex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@
//! ```
//!

use {ArrayLength, GenericArray};
use core::cmp::min;
use core::fmt;
use core::ops::Add;
use core::str;
use typenum::*;
use {ArrayLength, GenericArray};

static LOWER_CHARS: &'static [u8] = b"0123456789abcdef";
static UPPER_CHARS: &'static [u8] = b"0123456789ABCDEF";
Expand All @@ -39,21 +39,23 @@ where
// buffer of 2x number of bytes
let mut res = GenericArray::<u8, Sum<T, T>>::default();

for (i, c) in self.iter().take(max_hex).enumerate() {
self.iter().take(max_hex).enumerate().for_each(|(i, c)| {
res[i * 2] = LOWER_CHARS[(c >> 4) as usize];
res[i * 2 + 1] = LOWER_CHARS[(c & 0xF) as usize];
}
});

f.write_str(unsafe { str::from_utf8_unchecked(&res[..max_digits]) })?;
} else {
// For large array use chunks of up to 1024 bytes (2048 hex chars)
let mut buf = [0u8; 2048];
let mut digits_left = max_digits;

for chunk in self[..max_hex].chunks(1024) {
for (i, c) in chunk.iter().enumerate() {
chunk.iter().enumerate().for_each(|(i, c)| {
buf[i * 2] = LOWER_CHARS[(c >> 4) as usize];
buf[i * 2 + 1] = LOWER_CHARS[(c & 0xF) as usize];
}
});

let n = min(chunk.len() * 2, digits_left);
f.write_str(unsafe { str::from_utf8_unchecked(&buf[..n]) })?;
digits_left -= n;
Expand All @@ -77,21 +79,23 @@ where
// buffer of 2x number of bytes
let mut res = GenericArray::<u8, Sum<T, T>>::default();

for (i, c) in self.iter().take(max_hex).enumerate() {
self.iter().take(max_hex).enumerate().for_each(|(i, c)| {
res[i * 2] = UPPER_CHARS[(c >> 4) as usize];
res[i * 2 + 1] = UPPER_CHARS[(c & 0xF) as usize];
}
});

f.write_str(unsafe { str::from_utf8_unchecked(&res[..max_digits]) })?;
} else {
// For large array use chunks of up to 1024 bytes (2048 hex chars)
let mut buf = [0u8; 2048];
let mut digits_left = max_digits;

for chunk in self[..max_hex].chunks(1024) {
for (i, c) in chunk.iter().enumerate() {
chunk.iter().enumerate().for_each(|(i, c)| {
buf[i * 2] = UPPER_CHARS[(c >> 4) as usize];
buf[i * 2 + 1] = UPPER_CHARS[(c & 0xF) as usize];
}
});

let n = min(chunk.len() * 2, digits_left);
f.write_str(unsafe { str::from_utf8_unchecked(&buf[..n]) })?;
digits_left -= n;
Expand Down
8 changes: 2 additions & 6 deletions src/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ where
N: ArrayLength<T>,
{
fn clone(&self) -> GenericArray<T, N> {
self.map(|x| x.clone())
self.map(Clone::clone)
}
}

Expand All @@ -40,11 +40,7 @@ where
**self == **other
}
}
impl<T: Eq, N> Eq for GenericArray<T, N>
where
N: ArrayLength<T>,
{
}
impl<T: Eq, N> Eq for GenericArray<T, N> where N: ArrayLength<T> {}

impl<T: PartialOrd, N> PartialOrd for GenericArray<T, N>
where
Expand Down
60 changes: 58 additions & 2 deletions src/iter.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
//! `GenericArray` iterator implementation.

use super::{ArrayLength, GenericArray};
use core::{cmp, ptr, fmt, mem};
use core::mem::ManuallyDrop;
use core::{cmp, fmt, mem, ptr};

/// An iterator that moves out of a `GenericArray`
pub struct GenericArrayIter<T, N: ArrayLength<T>> {
Expand Down Expand Up @@ -131,6 +131,34 @@ where
}
}

fn fold<B, F>(mut self, init: B, mut f: F) -> B
where
F: FnMut(B, Self::Item) -> B,
{
let ret = unsafe {
let GenericArrayIter {
ref array,
ref mut index,
index_back,
} = self;

let remaining = &array[*index..index_back];

remaining.iter().fold(init, |acc, src| {
let value = ptr::read(src);

*index += 1;

f(acc, value)
})
};

// ensure the drop happens here after iteration
drop(self);

ret
}

#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.len();
Expand Down Expand Up @@ -176,6 +204,34 @@ where
None
}
}

fn rfold<B, F>(mut self, init: B, mut f: F) -> B
where
F: FnMut(B, Self::Item) -> B,
{
let ret = unsafe {
let GenericArrayIter {
ref array,
index,
ref mut index_back,
} = self;

let remaining = &array[index..*index_back];

remaining.iter().rfold(init, |acc, src| {
let value = ptr::read(src);

*index_back -= 1;

f(acc, value)
})
};

// ensure the drop happens here after iteration
drop(self);

ret
}
}

impl<T, N> ExactSizeIterator for GenericArrayIter<T, N>
Expand All @@ -187,4 +243,4 @@ where
}
}

// TODO: Implement `FusedIterator` and `TrustedLen` when stabilized
// TODO: Implement `FusedIterator` and `TrustedLen` when stabilized
22 changes: 12 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,9 @@ impl<T: Clone, U: Clone> Clone for GenericArrayImplEven<T, U> {
parent1: self.parent1.clone(),
parent2: self.parent2.clone(),
_marker: PhantomData,
}
}
}
}

impl<T: Copy, U: Copy> Copy for GenericArrayImplEven<T, U> {}

Expand All @@ -120,9 +120,9 @@ impl<T: Clone, U: Clone> Clone for GenericArrayImplOdd<T, U> {
parent1: self.parent1.clone(),
parent2: self.parent2.clone(),
data: self.data.clone(),
}
}
}
}

impl<T: Copy, U: Copy> Copy for GenericArrayImplOdd<T, U> {}

Expand Down Expand Up @@ -298,11 +298,13 @@ where
{
let (destination_iter, position) = destination.iter_position();

for (src, dst) in iter.into_iter().zip(destination_iter) {
ptr::write(dst, src);
iter.into_iter()
.zip(destination_iter)
.for_each(|(src, dst)| {
ptr::write(dst, src);

*position += 1;
}
*position += 1;
});
}

if destination.position < N::to_usize() {
Expand Down Expand Up @@ -341,11 +343,11 @@ where
{
let (destination_iter, position) = destination.iter_position();

for (i, dst) in destination_iter.enumerate() {
destination_iter.enumerate().for_each(|(i, dst)| {
ptr::write(dst, f(i));

*position += 1;
}
});
}

destination.into_inner()
Expand Down Expand Up @@ -570,11 +572,11 @@ where
{
let (destination_iter, position) = destination.iter_position();

for (dst, src) in destination_iter.zip(iter.into_iter()) {
destination_iter.zip(iter).for_each(|(dst, src)| {
ptr::write(dst, src);

*position += 1;
}
});
}

Some(destination.into_inner())
Expand Down
12 changes: 5 additions & 7 deletions src/sequence.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
//! Useful traits for manipulating sequences of data stored in `GenericArray`s

use super::*;
use core::{mem, ptr};
use core::ops::{Add, Sub};
use core::{mem, ptr};
use typenum::operator_aliases::*;

/// Defines some sequence with an associated length and iteration capabilities.
Expand Down Expand Up @@ -41,17 +41,15 @@ pub unsafe trait GenericSequence<T>: Sized + IntoIterator {

let (left_array_iter, left_position) = left.iter_position();

FromIterator::from_iter(
left_array_iter
.zip(self.into_iter())
.map(|(l, right_value)| {
FromIterator::from_iter(left_array_iter.zip(self.into_iter()).map(
|(l, right_value)| {
let left_value = ptr::read(l);

*left_position += 1;

f(left_value, right_value)
})
)
},
))
}
}

Expand Down
29 changes: 22 additions & 7 deletions tests/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ extern crate generic_array;
use std::cell::Cell;
use std::ops::Drop;

use generic_array::GenericArray;
use generic_array::typenum::consts::U5;
use generic_array::GenericArray;

#[test]
fn test_into_iter_as_slice() {
Expand Down Expand Up @@ -92,22 +92,37 @@ fn test_into_iter_flat_map() {
assert!((0..5).flat_map(|i| arr![i32; 2 * i, 2 * i + 1]).eq(0..10));
}

#[test]
fn test_into_iter_fold() {
assert_eq!(
arr![i32; 1, 2, 3, 4].into_iter().fold(0, |sum, x| sum + x),
10
);

let mut iter = arr![i32; 0, 1, 2, 3, 4, 5].into_iter();

iter.next();
iter.next_back();

assert_eq!(iter.clone().fold(0, |sum, x| sum + x), 10);

assert_eq!(iter.rfold(0, |sum, x| sum + x), 10);
}

#[test]
fn test_into_iter_drops() {
struct R<'a> {
i: &'a Cell<usize>,
i: &'a Cell<usize>,
}

impl<'a> Drop for R<'a> {
fn drop(&mut self) {
fn drop(&mut self) {
self.i.set(self.i.get() + 1);
}
}

fn r(i: &Cell<usize>) -> R {
R {
i: i
}
R { i: i }
}

fn v(i: &Cell<usize>) -> GenericArray<R, U5> {
Expand Down Expand Up @@ -161,4 +176,4 @@ fn assert_covariance() {
i
}
}
*/
*/
23 changes: 20 additions & 3 deletions tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
extern crate generic_array;
use core::cell::Cell;
use core::ops::{Add, Drop};
use generic_array::GenericArray;
use generic_array::functional::*;
use generic_array::sequence::*;
use generic_array::typenum::{U1, U3, U4, U97};
use generic_array::GenericArray;

#[test]
fn test() {
Expand Down Expand Up @@ -124,8 +124,8 @@ fn test_cmp() {
mod impl_serde {
extern crate serde_json;

use generic_array::GenericArray;
use generic_array::typenum::U6;
use generic_array::GenericArray;

#[test]
fn test_serde_implementation() {
Expand Down Expand Up @@ -178,20 +178,37 @@ fn test_from_iter() {
#[test]
fn test_sizes() {
#![allow(dead_code)]
use core::ffi::c_void;
use core::mem::{size_of, size_of_val};

#[derive(Debug, Copy, Clone)]
enum E {
V,
V2(i32),
V3 { h: bool, i: i32 },
}

#[derive(Debug, Copy, Clone)]
#[repr(C)]
#[repr(packed)]
struct Test {
t: u16,
s: u32,
mm: bool,
r: u16,
f: u16,
p: (),
o: u32,
ff: *const extern "C" fn(*const char) -> *const c_void,
l: *const c_void,
w: bool,
q: bool,
v: E,
}

assert_eq!(size_of::<Test>(), 14);
assert_eq!(size_of::<E>(), 8);

assert_eq!(size_of::<Test>(), 25 + size_of::<usize>() * 2);

assert_eq!(size_of_val(&arr![u8; 1, 2, 3]), size_of::<u8>() * 3);
assert_eq!(size_of_val(&arr![u32; 1]), size_of::<u32>() * 1);
Expand Down