Skip to content

Commit 71d07b1

Browse files
peter-jerry-yebobzhang
authored andcommitted
refactor(deque): make truncate safe
1 parent d911ec4 commit 71d07b1

2 files changed

Lines changed: 4 additions & 9 deletions

File tree

deque/deque.mbt

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -861,8 +861,8 @@ pub fn shrink_to_fit[A](self : T[A]) -> Unit {
861861
/// Shortens the deque in-place, keeping the first `len` elements and dropping
862862
/// the rest.
863863
///
864-
/// If `len` is greater than or equal to the deque's current length, this has no
865-
/// effect; if `len` is negative, the function will panic.
864+
/// If `len` is greater than or equal to the deque's current length or negative,
865+
/// this has no effect
866866
///
867867
/// Parameters:
868868
///
@@ -879,8 +879,7 @@ pub fn shrink_to_fit[A](self : T[A]) -> Unit {
879879
/// }
880880
/// ```
881881
pub fn truncate[A](self : T[A], len : Int) -> Unit {
882-
guard len < self.len else { return }
883-
guard len >= 0
882+
guard len >= 0 && len < self.len else { return }
884883
if len == 0 {
885884
self.clear()
886885
return

deque/deque_test.mbt

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -832,12 +832,8 @@ test "deque truncate" {
832832
// Current layout: [X, X, X, 4, 5, X]
833833
dq.truncate(2)
834834
@json.inspect!(dq.as_views(), content=[[4, 5], []])
835-
}
836-
837-
///|
838-
test "panic deque truncate" {
839-
let dq = @deque.of([1, 2, 3, 4, 5])
840835
dq.truncate(-1)
836+
@json.inspect!(dq.as_views(), content=[[4, 5], []])
841837
}
842838

843839
///|

0 commit comments

Comments
 (0)