Unreachable `else` branch of source code in `bytes::Bytes`

impl From<Box<[u8]>> for Bytes {
    fn from(slice: Box<[u8]>) -> Bytes {
        // Box<[u8]> doesn't contain a heap allocation for empty slices,
        // so the pointer isn't aligned enough for the KIND_VEC stashing to
        // work.
        if slice.is_empty() {
            return Bytes::new();
        }

        let len = slice.len();
        let ptr = Box::into_raw(slice) as *mut u8;

        if ptr as usize & 0x1 == 0 {
            let data = ptr_map(ptr, |addr| addr | KIND_VEC);
            Bytes {
                ptr,
                len,
                data: AtomicPtr::new(data.cast()),
                vtable: &PROMOTABLE_EVEN_VTABLE,
            }
        } else {
            Bytes {
                ptr,
                len,
                data: AtomicPtr::new(ptr.cast()),
                vtable: &PROMOTABLE_ODD_VTABLE,
            }
        }
    }
}

source code here

The question is I think the ptr as usize & 0x1 == 0 is always true because:

  1. the code already handles this special case with the empty check at the start:
// Handle empty slice case separately since it might not be properly aligned
if slice.is_empty() {
    return Bytes::new();
}
  1. ptr is created by Box::new() which means it is already aligned properly in my opinion for any modern platform to not align Box allocations to at least 2 bytes

Is there some case can reach the else branch?

There's nothing in the language that requires that.

Here are some boxes at odd addresses. Allocator code copied from here.

4 Likes

Oh, I see. the alignment of the pointee type [u8] is 0x01 so there is no constraint of the LSB in ptr which may be 0 or 1, Ty!