Skip to content

Commit c3c2a13

Browse files
committed
Document safety, fix bug
1 parent 6d5afb7 commit c3c2a13

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

src/arraystring.rs

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -871,19 +871,22 @@ where
871871
// Will never overflow since start < end and str.len() cannot be bigger than 255
872872
is_inside_boundary(self.len() + str.len() + start - end, Self::capacity())?;
873873

874-
let this_len = self.len();
874+
let ptr = self.array.as_mut_ptr();
875+
// Safety: we ensure that `start <= end <= self.len()`
876+
// and that the difference in size between `str.len()` and `start..end` fits in the available space (`Self::capacity() - self.len()`)
875877
unsafe {
876-
let ptr = self.array.as_mut_ptr();
877-
core::ptr::copy(
878-
ptr.add(end),
879-
ptr.add(str.len()).add(start),
880-
this_len - end,
881-
);
878+
let cut_start = ptr.add(start);
879+
let cut_end = ptr.add(end);
880+
let str_end = cut_start.add(str.len());
881+
882+
if cut_end != str_end {
883+
core::ptr::copy(cut_end, str_end, self.len() - end);
884+
}
882885
if !str.is_empty() {
883-
core::ptr::copy(str.as_ptr(), ptr.add(start), str.len());
886+
core::ptr::copy_nonoverlapping(str.as_ptr(), cut_start, str.len());
884887
}
885888
}
886-
self.size += str.len() + start + end;
889+
self.size = (self.len() + str.len() + start - end).into_lossy();
887890
Ok(())
888891
}
889892
}

0 commit comments

Comments
 (0)