-
Notifications
You must be signed in to change notification settings - Fork 142
Add from iterator impl #289
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
base: master
Are you sure you want to change the base?
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -295,6 +295,36 @@ impl<const CAP: usize> ArrayString<CAP> | |
Ok(()) | ||
} | ||
|
||
pub fn try_push_iterator<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); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why is this implemented as There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Sure, here are results on my machune:
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_push_iterator(value)?; | ||
Ok(string) | ||
} | ||
|
||
/// Removes the last character from the string and returns it. | ||
/// | ||
/// Returns `None` if this `ArrayString` is empty. | ||
|
Uh oh!
There was an error while loading. Please reload this page.