Any way to set capacity of the result when using Vec::split_off?

Is there any way to set capacity of the result when using Vec::split_off?

( without allocating twice )

Apparently not, but if not, is there any way to accomplish the same thing without allocating twice? In other words is there a way to move the end of an existing Vec into a newly allocated Vec ( where the capacity has been set with with_capacity )?

[ The only way I can see would be to repeatedly pop and insert, but this is not efficient ]

Edit: maybe I can use swap_remove, but that seems a bit complicated...! I tried, and it seems to work, but not an ideal solution?

        // let right = self.0.split_off(LEAF_SPLIT);
        
        let mut right = Vec::with_capacity(LEAF_FULL);
        let mut i = LEAF_SPLIT;
        while i + 1 < self.0.len()
        {
           right.push( self.0.swap_remove(i) );
           i += 1;
        }
        while self.0.len() > LEAF_SPLIT
        {
           right.push( self.0.pop().unwrap() );
        }
    let mut b = Vec::with_capacity(10);
    b.extend(a.drain(3..));
3 Likes