Skip to content

Implement extend_from_slice #34

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 4 commits into from
May 26, 2025
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
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,11 @@ The goal is to allocate only when needed. When first constructed, the vector wil

All operations are O(1) except:

| Method | Time Complexity | Space Complexity |
|-------------|----------------------------------|---------------------------------|
| `clear` | O(current length) | O(1) |
| `set_len` | O(new length - current length) | O(new length - current length) |
| Method | Time Complexity | Space Complexity |
|-----------------------|----------------------------------|---------------------------------|
| `clear` | O(current length) | O(1) |
| `set_len` | O(new length - current length) | O(new length - current length) |
| `extend_from_slice` | O(slice length) | O(slice length) |

## Add to project

Expand Down
2 changes: 1 addition & 1 deletion fuzz/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions fuzz/fuzz_targets/static_vector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ fuzz_target!(|data: &[u8]| {

if is_full_after_push {
assert!(vec.is_full());
assert!(vec.extend_from_slice(&[0]).is_err());
} else {
assert!(!vec.is_full());
}
Expand All @@ -53,6 +54,13 @@ fuzz_target!(|data: &[u8]| {
assert_eq!(vec.get_mut(i).unwrap(), &byte);

prev_byte = Some(byte);

if vec.len() + 1 > vec.capacity() {
assert!(vec.extend_from_slice(&[0]).is_err());
} else {
assert!(vec.extend_from_slice(&[0]).is_ok());
vec.pop().unwrap();
}
}
}

Expand Down
145 changes: 145 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,62 @@ impl<T, const CAPACITY: usize> Vec<T, CAPACITY> {
unsafe { slice::from_raw_parts_mut(self.data[0].as_mut_ptr(), self.len()) }
}

/// Inserts elements of given slice at the end of the vector.
///
/// # Errors
///
/// Returns [`CapacityError`] if adding elements of given slice would result in vector exceeding its capacity.
///
/// # Example
///
/// ```rust
/// use static_vector::{CapacityError, Vec};
///
/// #[derive(Debug)]
/// enum AppError {
/// VectorCapacityError(CapacityError),
/// }
///
/// fn my_fn(src: &[i32], vec: &mut Vec<i32, 2>) -> Result<(), AppError> {
/// vec.extend_from_slice(src).map_err(AppError::VectorCapacityError)?;
///
/// // other operations that could return errors
/// Ok(())
/// }
///
/// fn main() -> Result<(), AppError> {
/// let src = [1, 2, 3];
/// let mut vec = Vec::<i32, 2>::new();
///
/// if let Err(err) = my_fn(&src, &mut vec) {
/// match err {
/// AppError::VectorCapacityError(_) => {
/// // handle case
/// },
/// }
/// }
///
/// Ok(())
/// }
/// ```
#[inline]
pub fn extend_from_slice(&mut self, slice: &[T]) -> Result<(), CapacityError>
where
T: Clone,
{
if self.len() + slice.len() > CAPACITY {
return Err(CapacityError);
}

for (index, value) in slice.iter().enumerate() {
self.data[self.len() + index].write(value.clone());
}

self.length += slice.len();

Ok(())
}

/// Drops all elements in given range. Needed when elements are considered to be going out of scope.
/// E.g.: when the vector is going out of scope, when methods such as [`Vec::clear()`] and [`Vec::set_len()`] are called.
fn drop_range(&mut self, from: usize, to: usize) {
Expand Down Expand Up @@ -988,6 +1044,95 @@ mod tests {
assert_eq!(vec.as_slice().iter().sum::<i32>(), 2000);
}

#[test]
fn extend_from_slice_with_empty_vector_and_empty_slice() {
let src = [];
let mut dst = Vec::<i32, 3>::new();
let result = dst.extend_from_slice(&src);

assert!(result.is_ok());
assert!(dst.is_empty());
}

#[test]
fn extend_from_slice_with_empty_vector_and_non_empty_slice_within_capacity() {
let src = [1, 2];
let mut dst = Vec::<i32, 3>::new();
let result = dst.extend_from_slice(&src);

assert!(result.is_ok());
assert_eq!(dst.len(), 2);
assert_eq!(dst.as_slice(), [1, 2]);
}

#[test]
fn extend_from_slice_with_non_empty_vector_and_empty_slice() {
let src = [];
let mut dst = Vec::<i32, 3>::new();
dst.push(1).unwrap();
dst.push(2).unwrap();
let result = dst.extend_from_slice(&src);

assert!(result.is_ok());
assert_eq!(dst.len(), 2);
assert_eq!(dst.as_slice(), [1, 2]);
}

#[test]
fn extend_from_slice_with_non_empty_vector_and_slice_fits_exactly_into_capacity() {
let src = [3, 4, 5];
let mut dst = Vec::<i32, 5>::new();
dst.push(1).unwrap();
dst.push(2).unwrap();
let result = dst.extend_from_slice(&src);

assert!(result.is_ok());
assert_eq!(dst.len(), 5);
assert!(dst.is_full());
assert_eq!(dst.as_slice(), [1, 2, 3, 4, 5]);
}

#[test]
fn extend_from_slice_with_non_empty_vector_and_slice_exceeds_capacity() {
let src = [3, 4, 5, 6];
let mut dst = Vec::<i32, 5>::new();
dst.push(1).unwrap();
dst.push(2).unwrap();
let result = dst.extend_from_slice(&src);

assert!(result.is_err());
assert_eq!(dst.len(), 2);
assert_eq!(dst.as_slice(), [1, 2]);
}

#[test]
fn extend_from_slice_with_vector_full_and_non_empty_slice() {
let src = [3, 4, 5, 6];
let mut dst = Vec::<i32, 2>::new();
dst.push(1).unwrap();
dst.push(2).unwrap();
let result = dst.extend_from_slice(&src);

assert!(result.is_err());
assert_eq!(dst.len(), 2);
assert!(dst.is_full());
assert_eq!(dst.as_slice(), [1, 2]);
}

#[test]
fn extend_from_slice_with_non_empty_vector_and_non_empty_slice() {
let src = [3];
let mut dst = Vec::<i32, 5>::new();
dst.push(1).unwrap();
dst.push(2).unwrap();
let result = dst.extend_from_slice(&src);

assert!(result.is_ok());
assert_eq!(dst.len(), 3);
assert!(!dst.is_full());
assert_eq!(dst.as_slice(), [1, 2, 3]);
}

#[test]
fn construct_should_not_create_default_elements() {
let _ = Vec::<Struct, 10>::new();
Expand Down