Skip to content
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

Add from iterator impl #289

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
40 changes: 33 additions & 7 deletions benches/arraystring.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ fn try_push_c(b: &mut Bencher) {
v.clear();
while v.try_push('c').is_ok() {
}
v.len()
std::hint::black_box(v)
});
b.bytes = v.capacity() as u64;
}
Expand All @@ -23,7 +23,7 @@ fn try_push_alpha(b: &mut Bencher) {
v.clear();
while v.try_push('α').is_ok() {
}
v.len()
std::hint::black_box(v)
});
b.bytes = v.capacity() as u64;
}
Expand All @@ -39,7 +39,7 @@ fn try_push_string(b: &mut Bencher) {
break;
}
}
v.len()
std::hint::black_box(v)
});
b.bytes = v.capacity() as u64;
}
Expand All @@ -51,7 +51,7 @@ fn push_c(b: &mut Bencher) {
while !v.is_full() {
v.push('c');
}
v.len()
std::hint::black_box(v)
});
b.bytes = v.capacity() as u64;
}
Expand All @@ -63,7 +63,7 @@ fn push_alpha(b: &mut Bencher) {
while !v.is_full() {
v.push('α');
}
v.len()
std::hint::black_box(v)
});
b.bytes = v.capacity() as u64;
}
Expand All @@ -80,11 +80,37 @@ fn push_string(b: &mut Bencher) {
break;
}
}
v.len()
std::hint::black_box(v)
});
b.bytes = v.capacity() as u64;
}

fn try_extend_bench(b: &mut Bencher) {
let mut v = ArrayString::<4096>::new();
b.iter(|| {
v.clear();

v.try_extend(std::iter::repeat('a').take(v.capacity())).unwrap();

std::hint::black_box(v);
});
b.bytes = v.capacity() as u64;
}

fn try_push_loop(b: &mut Bencher) {
let mut v = ArrayString::<4096>::new();
b.iter(|| {
v.clear();

for c in std::iter::repeat('a').take(v.capacity()) {
v.try_push(c).unwrap();
}

std::hint::black_box(v)
});
b.bytes = v.capacity() as u64;
}

benchmark_group!(benches, try_push_c, try_push_alpha, try_push_string, push_c,
push_alpha, push_string);
push_alpha, push_string, try_extend_bench, try_push_loop);
benchmark_main!(benches);
30 changes: 30 additions & 0 deletions src/array_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,36 @@ impl<const CAP: usize> ArrayString<CAP>
Ok(())
}

pub fn try_extend<I: IntoIterator<Item = char>>(&mut self, value: I) -> Result<(), CapacityError<()>> {
let mut len = self.len();
let value = value.into_iter();
if value.size_hint().0 > self.capacity() - len {
return Err(CapacityError::new(()));
}

unsafe {
let mut ptr = self.as_mut_ptr().add(self.len());
for c in value {
let remaining_cap = self.capacity() - len;
match encode_utf8(c, ptr, remaining_cap) {
Ok(n) => {
len += n;
ptr = ptr.add(n);
}
Err(_) => return Err(CapacityError::new(())),
}
}
self.set_len(len);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this implemented as unsafe instead of using ArrayString::try_push?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because I think that this function should be as performant as possible, and calling try_push will modify the len on every iteration. This way we can set it once when we're done, which seems to be more efficient.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you write a quick benchmark verifying that this improves performance over the naive try_push loop?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, here are results on my machune:

test try_extend_bench ... bench:          28 ns/iter (+/- 2) = 146285 MB/s
test try_push_loop    ... bench:         336 ns/iter (+/- 13) = 12190 MB/s

I also fixed the other benches (at they were all optimized on my machine in just one LOAD of a capacity constant)

Ok(())
}
}

pub fn try_from_iterator<I: IntoIterator<Item = char>>(value: I) -> Result<Self, CapacityError<()>> {
let mut string = Self::new();
string.try_extend(value)?;
Ok(string)
}

/// Removes the last character from the string and returns it.
///
/// Returns `None` if this `ArrayString` is empty.
Expand Down
25 changes: 25 additions & 0 deletions tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -774,3 +774,28 @@ fn test_arraystring_zero_filled_has_some_sanity_checks() {
assert_eq!(string.as_str(), "\0\0\0\0");
assert_eq!(string.len(), 4);
}

#[test]
fn test_string_collect() {
let text = "hello world";
let u = ArrayString::<11>::try_from_iterator(text.chars()).unwrap();
assert_eq!(u.as_str(), text);
assert_eq!(u.len(), text.len());
}

#[test]
fn test_string_collect_seveal_times() {
let text = "hello world";
let mut u = ArrayString::<22>::try_from_iterator(text.chars()).unwrap();
u.try_extend(text.chars()).unwrap();
assert_eq!(u.as_str(), &format!("{}{}", text, text));
assert_eq!(u.len(), text.len()*2);
}


#[test]
fn test_string_collect_error_on_overflow() {
let text = "hello world";
ArrayString::<10>::try_from_iterator(text.chars()).unwrap_err();
}