Is `alloc` allowed to violate a methods safety requirements?

⚓ Rust    📅 2025-12-13    👤 surdeus    👁️ 7      

surdeus

Warning

This post was published 34 days ago. The information described in this article may have changed.

Consider the current definition of Vec::split_off:

    pub fn split_off(&mut self, at: usize) -> Self
    where
        A: Clone,
    {
        #[cold]
        #[cfg_attr(not(panic = "immediate-abort"), inline(never))]
        #[track_caller]
        #[optimize(size)]
        fn assert_failed(at: usize, len: usize) -> ! {
            panic!("`at` split index (is {at}) should be <= len (is {len})");
        }

        if at > self.len() {
            assert_failed(at, self.len());
        }

        let other_len = self.len - at;
        let mut other = Vec::with_capacity_in(other_len, self.allocator().clone());

        // Unsafely `set_len` and copy items to `other`.
        unsafe {
            self.set_len(at);
            other.set_len(other_len);

            ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
        }
        other
    }

it calls set_len before it initialized any of others elements, yet the safety requirements on set_len clearly state:

The elements at old_len..new_len must be initialized.

Is there a reason I'm not seeing that this isn't technically UB?

Should this be fixed?

6 posts - 4 participants

Read full topic

🏷️ Rust_feed