# Let's talk about unwind safety!

Disclaimer: This article is kinda my own notes and experience with unwind safety (gotchas and ways to handle certain cases to ensure the code remains unwind safe). There are probably certain gaps and holes with explaining unwind safety as a whole.

# A crude intro to unwind safety

### What is unwind safety?

This will be a crude explanation (the [`UnwindSafe`](https://doc.rust-lang.org/nightly/std/panic/trait.UnwindSafe.html) trait documentation will do a much better job explaining it than I will), but the way I think about it is: if a type or a function is unwind-safe, it can safely execute with/without panicking in a [`catch_unwind`](https://doc.rust-lang.org/nightly/std/panic/fn.catch_unwind.html) block without leaving any internal details of the type in an invalid and possibly observable state.

### Why do we care about unwind safety?

In Rust, we can either abort the program immediately on a panic or we can unwind that panic and continue execution of the program. In most cases, an immediate abort might be preferred. However, when you think about services like webservice, it's not ideal for such a service to just crash immediately, cause multiple processes to be aborted, and have to be restarted from scratch; preferably, we would still want to unwind on that panic, report the error, and continue execution on that service.

### Where would we think deeply about unwind safety?

Commonly, from my experience at least, unwind safety is something you may have to be alert of for methods in your data structure that takes a closure. If that closure panics or an element's `Drop` implementation causes a panic in that method, we'd have to make sure that our data structure is not left in an invalid state.

Other areas where unwind safety might matter a lot is if we're writing some FFI code using [`unsafe extern "C-unwind"`](https://doc.rust-lang.org/nomicon/ffi.html#ffi-and-unwinding) and expect panics to occur on the Rust side and we want to unwind through C/C++ stack frame (though do note that catching a Rust panic on the C++ side, or catching an exception from C++ to Rust is still undefined behavior).

There are actually a good number of methods in the Rust standard library's data structures that have to be more cautious about whether the implementation is unwind safe.

## An example of where thinking about unwind safety matters

For example, let's take a look at an existing stable method in Rust: [`Vec::dedup_by`](https://doc.rust-lang.org/nightly/std/vec/struct.Vec.html#method.dedup_by):

```rust
pub fn dedup_by<F>(&mut self, mut same_bucket: F)
    where
        F: FnMut(&mut T, &mut T) -> bool,
{
...
}
```

From the documentation, `Vec::dedup_by` does:

> Removes all but the first of consecutive elements in the vector that are "equal" according to the given predicate function.
>
> The predicate `same_bucket(x, p)` is passed references to two elements. If it returns `true`, the element `x` is removed from the vector.
>
> The element `p` occurs *before* `x` in the vector (`[.., p, .., x, ..]`), so `same_bucket(x, p)` is receiving them in reversed order (unlike \[`windows`\]).
>
> If the vector is sorted, this removes all duplicates. For more complicated predicates however, the order (ascending vs. descending) can matter.

The intent behind `Vec::dedup_by` is to remove (or even merge) duplicate *consecutive* elements. That means if we have a vector like:

```rust
vec!["foo", "bar", "Bar", "baz", "bar"]
```

And we pass in a closure that remove same words ignoring ascii casing (i.e. `|x, p| x.eq_ignore_ascii_case(p)`). Then we should see the vector be modified to this:

```rust
vec!["foo", "bar", "baz", "bar"]
```

Another very useful case with `Vec::dedup_by` is to merge elements together. Take this example:

```rust
let mut ranges = vec![1..2, 2..4, 2..5, 4..8, 8..9];
    
// Sort ranges by start, and if equal, by end (lexicographically)
// Sorting in reverse instead (`x.start.cmp(&p.start)...`) would later fail
ranges.sort_unstable_by(|p, x| p.start.cmp(&x.start).then(p.end.cmp(&x.end)));
    
// Merge all ranges to 1..9
ranges.dedup_by(|x, p| {
    if p.end >= x.start {
        p.end = p.end.max(x.end);
        true
    } else {
        false
    }
});
println!("{:?}", ranges); // ranges = [1..9]
```

In this example, we have a vector of ranges (or intervals). Our closure here checks if the previous element's end part of its interval is greater than the current element's start part of its interval. If it is, we want to update our previous element's end to the greater of the previous's end and current's end part of their ranges and remove our current element. Otherwise, we do nothing and iterate forward viewing the current element as the previous element. By the end, our vector should contain the range `1..9`.

Bringing `Vec::dedup_by` back into the topic of unwind safety. There are multiple ways of implementing `Vec::dedup_by`. For example, we could:

1. We could continuously invoke the closure on the previous and current element. If it evaluates as true, then we could call `Vec::remove` on the current element. If it evaluates as false, then we iterate forward treating the current element as the previous element.
2. Just like 1), we continuously invoke the closure on the previous and current element. When the closures evaluates as true, instead of calling `Vec::remove`, we just call `ptr::drop_in_place`. Otherwise, if it evaluates as false and we've dropped elements before, we can shift the current element to that hole.

The former approach, it trivially appears to be unwind safe. The underlying implementation of `Vec::remove` shifts all elements to the left before it drops the element that we want to remove. We don't have to worry too much about a unwinding a panic here because:

- If a panic occurred from the provided closure to `Vec::dedup_by`, nothing is removed, so our `Vec` should not be in an invalid state.
- If a panic occurred from the drop side of the element, the element is still removed and the hole it left is still covered because we shifted all elements after this one to the left in advance.

However, the latter approach, there's a lot that we need to think about with unwinding a panic here. In particular, if there are multiple elements we dropped in sequence, like seen in the deduped ranges example where we would want to remove `2..4, 2..5, 4..8, 8..9`, we would have to ask ourselves:

- If a panic occurred from the closure, how do we ensure that the `Vec` covers holes created by prior dropped elements?
- Similarly, if a panic occurs by dropping a specific element, how do we also ensure that the `Vec` covers holes created by prior dropped elements? For example, we can conveniently make a wrapper type and have a panicking `Drop` implementation as follows:

```rust
struct Wrapped(Range<i32>);
    
impl Drop for Wrapped {
    fn drop(&mut self) {
        panic!("This element was dropped");
    }
}
```

Leaving observable holes in our `Vec` could wound up causing other panics or undefined behavior, which in a `catch_unwind` block, a double panic will always result in an abort.

Now, one might say that, "Well it looks easier to write unwind-safe code with the former approach, so why not just take that approach?". That's true; the former approach does result in cleaner and neater code. However, the former approach is actually a very suboptimal approach. Incurring a shift of all elements to the left after each `Vec::remove` would result in the `Vec::dedup_by` to have a worst case time complexity of `O(N^2)` whereas the latter approach worst case is `O(N)` since we perform destroying an element in `O(1)` time through `ptr::drop_in_place` and we only shift over one element to cover a hole at a time rather than all elements. We should prefer implementing the latter approach, but how do we write it such that it takes care of panics from closure side or the dropping of an element?

That's where introducing another struct with its own `Drop` implementation comes in (commonly this a `Drop` guard pattern)! In `Vec::dedup_by` it is currently written like so:

```rust
pub fn dedup_by<F>(&mut self, mut same_bucket: F)
where
    F: FnMut(&mut T, &mut T) -> bool,
{
    let len = self.len();
    if len <= 1 {
        return;
    }

    // Check if we ever want to remove anything.
    // This allows to use copy_non_overlapping in next cycle.
    // And avoids any memory writes if we don't need to remove anything.
    let mut first_duplicate_idx: usize = 1;
    let start = self.as_mut_ptr();
    while first_duplicate_idx != len {
        let found_duplicate = {
            // SAFETY: first_duplicate always in range [1..len).
            // Note that we start iteration from 1 so we never overflow.
            let prev = unsafe { start.add(first_duplicate_idx.wrapping_sub(1)) };
            // ignore-tidy-undocumented-unsafe
            let current = unsafe { start.add(first_duplicate_idx) };
            // We explicitly say in docs that references are reversed.
            // ignore-tidy-undocumented-unsafe
            unsafe { same_bucket(&mut *current, &mut *prev) }
        };
        if found_duplicate {
            break;
        }
        first_duplicate_idx += 1;
    }
    // Don't need to remove anything.
    // We cannot get bigger than len.
    if first_duplicate_idx == len {
        return;
    }
    // SAFETY: first_duplicate_idx always in range [1..len)
    unsafe {
        self.dedup_tail(same_bucket, first_duplicate_idx);
    }
}

unsafe fn dedup_tail<F>(&mut self, mut same_bucket: F, first_duplicate: usize)
where
    F: FnMut(&mut T, &mut T) -> bool,
{
    /* INVARIANT: vec.len() > read > write > write-1 >= 0 */
    struct FillGapOnDrop<'a, T, A: core::alloc::Allocator> {
        /* Offset of the element we want to check if it is duplicate */
        read: usize,

        /* Offset of the place where we want to place the non-duplicate
            * when we find it. */
        write: usize,

        /* The Vec that would need correction if `same_bucket` panicked */
        vec: &'a mut Vec<T, A>,
    }

    impl<'a, T, A: core::alloc::Allocator> Drop for FillGapOnDrop<'a, T, A> {
        fn drop(&mut self) {
            /* This code gets executed when `same_bucket` panics */

            // SAFETY: invariant guarantees that `read - write`
            // and `len - read` never overflow and that the copy is always
            // in-bounds.
            unsafe {
                let ptr = self.vec.as_mut_ptr();
                let len = self.vec.len();

                /* How many items were left when `same_bucket` panicked.
                    * Basically vec[read..].len() */
                let items_left = len.wrapping_sub(self.read);

                /* Pointer to first item in vec[write..write+items_left] slice */
                let dropped_ptr = ptr.add(self.write);
                /* Pointer to first item in vec[read..] slice */
                let valid_ptr = ptr.add(self.read);

                /* Copy `vec[read..]` to `vec[write..write+items_left]`.
                    * The slices can overlap, so `copy_nonoverlapping` cannot be used */
                ptr::copy(valid_ptr, dropped_ptr, items_left);

                /* How many items have been already dropped
                    * Basically vec[read..write].len() */
                let dropped = self.read.wrapping_sub(self.write);

                self.vec.set_len(len - dropped);
            }
        }
    }

    let start = self.as_mut_ptr();
    let len = self.len();

    /* Drop items while going through Vec, it should be more efficient than
        * doing slice partition_dedup + truncate */

    // Construct gap first and then drop item to avoid memory corruption if `T::drop` panics.
    let mut gap =
        FillGapOnDrop { read: first_duplicate + 1, write: first_duplicate, vec: self };

    // SAFETY: By this function's safety contract, `first_duplicate < self.len()`.
    // If drop panics, `gap` would remove this item without drop.
    unsafe {
        ptr::drop_in_place(start.add(first_duplicate));
    }

    // SAFETY: Because of the invariant, read_ptr, prev_ptr and write_ptr
    // are always in-bounds and read_ptr never aliases prev_ptr
    unsafe {
        while gap.read < len {
            let read_ptr = start.add(gap.read);
            let prev_ptr = start.add(gap.write.wrapping_sub(1));

            // We explicitly say in docs that references are reversed.
            let found_duplicate = same_bucket(&mut *read_ptr, &mut *prev_ptr);
            if found_duplicate {
                // Increase `gap.read` now since the drop may panic.
                gap.read += 1;
                /* We have found duplicate, drop it in-place */
                ptr::drop_in_place(read_ptr);
            } else {
                let write_ptr = start.add(gap.write);

                /* read_ptr cannot be equal to write_ptr because at this point
                    * we guaranteed to skip at least one element (before loop starts).
                    */
                ptr::copy_nonoverlapping(read_ptr, write_ptr, 1);

                /* We have filled that place, so go further */
                gap.write += 1;
                gap.read += 1;
            }
        }

        /* Technically we could let `gap` clean up with its Drop, but
            * when `same_bucket` is guaranteed to not panic, this bloats a little
            * the codegen, so we just do it manually */
        gap.vec.set_len(gap.write);
        mem::forget(gap);
    }
}
```

I know, I know, using a `Drop` guard here results in some verbose and sometimes pretty unsafe code, but it's necessary to use this guard to ensure that we cover all cases where a panic can occur. The essential flow for `Vec::dedup_by` goes as follows:

- Iterate through the vector and find the first duplicate consecutive element as evaluated by the closure. If we found no duplicate elements, cool we can just return early.
- Otherwise, if we find a duplicate consecutive element, we first create a `Drop` guard (called `FillGapOnDrop`), which contains a `read` index starting right after the first found duplicate, a `write` index at the first found duplicate, and a mutable borrow to the `Vec`. Once we do that, we can drop the duplicate, leaving an uninitialized hole in its area, and continue iterating forward through the `Vec`.
- As we iterate forward through the `Vec`, if our closure evaluates true indicating that the current element is a duplicate to the previous element (the index just before the `write` as it points to a hole), it increments the `read` index and drops that element. Otherwise, if our closure evaluates false indicating that the current element is not a duplicate to the previous element, we can copy over this element to where the `write` index is at, and increment both our `read` and `write` indices.

Importantly, `FillGapOnDrop` handles covering the gaps in the `Vec` appropriately when a panic occurs on both the closure or on drop of an element-- it just simply shifts over the remaining elements from `read`.`self.vec.len()` to `write..` forward.

`Drop` guard patterns are overall pretty neat to potentially write more performant code while ensuring that your code is unwind-safe.

## Now a case where we may not need a `Drop` guard

A month ago, I had the *pleasure* to spend 25+ hours to introduce a new method to the Rust standard library's `Vec` data structure, [`Vec:retain_unstable`](https://doc.rust-lang.org/nightly/std/vec/struct.Vec.html#method.retain_unstable). This method, like the stable [`Vec::retain_mut`](https://doc.rust-lang.org/nightly/std/vec/struct.Vec.html#method.retain_mut) method, filters away elements from a Vec with a closure predicate (a closure that returns `true` or `false`; in this case `true` means we want to keep this element while `false` is for filtering out this element). However, the catch with `Vec::retain_unstable` is that the retained elements are not guaranteed to be kept in order. So a `Vec` like:

```plaintext
[1, 2, 3, 4]
```

If we retain only even elements, it is equally valid for `Vec::retain_unstable` to return

```plaintext
[2, 4]
```

or

```plaintext
[4, 2]
```

In exchange for having less strict ordering guarantees for filtering elements out of a `Vec`, it generally performs noticeably better than `Vec::retain_mut`. A method like `Vec::retain_unstable` has value in improving performance in cases like filtering out certain neighboring nodes of a node in a graph data structure where we don't care about the order of our neighboring nodes.

I'll briefly talk about my attempts working on `Vec::retain_unstable` (omitting a lot of comments, if you'd like to check out my first implementation of `Vec::retain_unstable` and see all the detailed comments you can take a look at this [commit](https://github.com/asder8215/rust/blob/b0adcb5995f4c571b3f3ee8d6b2e2b3f085b8900/library/alloc/src/vec/mod.rs#L2640-L2833) right here; here's the full [PR](https://github.com/rust-lang/rust/pull/164155) as well). Here's my first attempt:

```rust
    pub fn retain_unstable<F>(&mut self, mut f: F)
    where
        F: FnMut(&mut T) -> bool,
    {
        let original_len = self.len();
        if original_len == 0 {
            return;
        }

        struct PanicGuard<'a, T, A: Allocator> {
            v: &'a mut Vec<T, A>,
            read: usize,
            read_back: usize,
            write: usize,
        }

        impl<T, A: Allocator> Drop for PanicGuard<'_, T, A> {
            #[cold]
            fn drop(&mut self) {
                let remaining = self.read_back + 1 - self.read;
                unsafe {
                    ptr::copy_nonoverlapping(
                        self.v.as_ptr().add(self.read_back),
                        self.v.as_mut_ptr().add(self.write),
                        core::cmp::min(remaining, 1), // Overwrite `Hole` with `Swap` or do no copying
                    );
                }
                unsafe {
                    self.v.set_len(self.write + remaining);
                }
            }
        }

        let mut read = 0;
        loop {
            let cur = unsafe { self.get_unchecked_mut(read) };
            if hint::unlikely(!f(cur)) {
                break;
            }
            read += 1;
            if read == original_len {
                return;
            }
        }
        let mut g =
            PanicGuard { v: self, read: read + 1, write: read, read_back: original_len - 1 };
        let mut hole = unsafe { &mut *g.v.as_mut_ptr().add(read) };
        unsafe { ptr::drop_in_place(hole) };
        let swap = loop {
            if g.read_back == g.write {
                unsafe { g.v.set_len(g.write) };
                mem::forget(g);
                return;
            }
            let swap = unsafe { &mut *g.v.as_mut_ptr().add(g.read_back) };
            if hint::unlikely(f(swap)) {
                break swap;
            }
            g.read_back -= 1;
            unsafe { ptr::drop_in_place(swap) };
        };

        unsafe {
            ptr::copy_nonoverlapping(swap, hole, 1);
            g.read_back -= 1;
            g.write += 1;
        }


        'retain: while g.read <= g.read_back {
            hole = unsafe { &mut *g.v.as_mut_ptr().add(g.read) };
            if !f(hole) {
                g.read += 1;
                unsafe { ptr::drop_in_place(hole) };
                let swap = loop {
                    if g.read_back == g.write {
                        break 'retain;
                    }

                    let swap = unsafe { &mut *g.v.as_mut_ptr().add(g.read_back) };
                    if f(swap) {
                        break swap;
                    }
                    g.read_back -= 1;
                    unsafe { ptr::drop_in_place(swap) };
                };

                unsafe {
                    ptr::copy_nonoverlapping(swap, hole, 1);
                    g.read_back -= 1;
                    g.write += 1;
                }
                continue;
            }
            g.read += 1;
            g.write += 1;
        }

        unsafe { g.v.set_len(g.write) };
        mem::forget(g);
    }
```

The essential strategy for this approach is as follow:

1. Scan forward for something we want to remove (closure returns false).
2. Scan backward for something we want to keep (closure returns true).
   - In the reverse search process, we drop elements that the closure evaluated as false.
   - In the event that no elements in the reverse search evaluated to true by the closure, then the vector is simply truncated to remove the current and remaining elements.
3. Overwrite the forward element with the backward element.
4. Rinse and repeat from 1) until there are no elements we can iterate through.

The biggest reason why `Vec::retain_unstable` tends to perform better than `Vec::retain_mut` is because filtering an element only needs one element from the back to cover that hole instead of requiring a shift of all elements to the left.

However, because this algorithm makes our forward scan leave a hole that the backward scan needs to find an element to cover that hole, there's a clear case of `Drop` guards being necessary here. If we unwind at the moment our closure from the backward scan panics on an element or if the drop of an element from either the forward or backward scan causes a panic, it leaves our `Vec` in an invalid state where an uninitialized, yet accessible hole exists (which causes a double drop if we drop our `Vec` at the end of the `catch_unwind` block). The `Drop` guard in this case, `PanicGuard` (which has a `read` index, a `read_back` index, a `write` index, and a mutable reference to the `Vec` itself), resolves this hole with doing an immediate swap of an element from the back of the `Vec` and setting the length of the `Vec` as appropriate using its indices it has access to.

There is a more performant approach that I found out and benchmarked later `Vec::retain_unstable`:

```rust
pub fn retain_unstable<F>(&mut self, mut f: F)
where
    F: FnMut(&mut T) -> bool,
{
    // Currently this does the following:
    // 1) Search backward until you find an element you want to remove
    // 2) Swap this element with an element that was kept in the back
    //    (or if there are no remaining elements, simply truncate the vec)
    // 3) Repeat from 1) until there's no element to iterate through

    let original_len = self.len();

    if original_len == 0 {
        // Empty case: explicit return allows better optimization, vs letting compiler infer it
        return;
    }

    let mut read_back = original_len;
    let mut hole = loop {
        if read_back == 0 {
            // All elements are kept
            return;
        }
        // SAFETY: read_back - 1 < original_len
        let cur = unsafe { &mut *self.as_mut_ptr().add(read_back - 1) };
        if hint::unlikely(!f(cur)) {
            break cur;
        }
        read_back -= 1;
    };

    if read_back < self.len {
        let swap = self.pop().unwrap();
        *hole = swap;
    } else {
        self.truncate(self.len - 1);
    }
    read_back -= 1;

    while read_back > 0 {
        // SAFETY: read_back - 1 is always less than current length of
        // the vector and the loop condition, read_back > 0, prevents
        // read_back from underflowing
        hole = unsafe { &mut *self.as_mut_ptr().add(read_back - 1) };
        if !f(hole) {
            if read_back < self.len {
                let swap = self.pop().unwrap();
                *hole = swap;
            } else {
                self.truncate(self.len - 1);
            }
        }
        read_back -= 1;
    }
}
```

This approach does the following:

1. Search backward until you find an element you want to remove (implicitly that means all elements after the one you want to remove are elements you want to keep)
2. Swap this element with an element that was kept in the back (or if there are no remaining elements, simply truncate the vec)
3. Repeat from 1) until there's no element to iterate through.

Since we know from doing a backward search for an element to remove, it implies that all elements after this element we want to remove (if any element exists after) are elements we want to keep and we can trivially swap this element with an element from the back and then drop the previously held element afterward. A fun fact that I learned here is that doing `*hole = swap` automatically both reassigns the `&mut T` with the new value and drops the previous value safely under a `catch_unwind` even if the previous value's `Drop` implementation causes a panic.

But I bring this case as an example where there may be alternative approaches you can take where a `Drop` guard pattern is not necessary to ensure that your code is unwind-safe and equally efficient. For `Vec::retain_unstable` it was actually more performant to do a pure backward search to preserve some sort of predictable behavior that the compiler can optimize rather than the ping pong behavior of the first approach.

## End Note

Overall, unwind safety is both a complicated and interesting topic; it can sometimes be hard to spot if your code is unwind-safe, and sometimes it may be necessary to use a `Drop` guard pattern to write performant code. Sometimes, there is a different approach that may not need a `Drop` guard pattern.
