Skip to content

Commit cdfef61

Browse files
committed
byteyarn: Fix (essentially harmless) UB when converting empty yarns to Box
1 parent 7407782 commit cdfef61

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

byteyarn/src/boxed.rs

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use std::hash::Hasher;
66
use std::marker::PhantomData;
77
use std::mem;
88
use std::ops::Deref;
9+
use std::ptr::NonNull;
910
use std::slice;
1011
use std::str;
1112
use std::str::Utf8Error;
@@ -314,14 +315,22 @@ where
314315
///
315316
/// ```
316317
/// # use byteyarn::*;
317-
/// let boxed = yarn!("jellybeans").into_boxed_bytes();
318-
/// assert_eq!(&boxed[..], b"jellybeans");
318+
/// let boxed = yarn!("jellybeans").into_box();
319+
/// assert_eq!(&*boxed, "jellybeans");
320+
///
321+
/// # // This tickles a weird edge case that MIRI caught.
322+
/// let empty = yarn!("").into_box();
323+
/// assert_eq!(&*empty, "");
319324
/// ```
320325
pub fn into_box(self) -> Box<Buf> {
321326
if !self.raw.on_heap() {
322327
unsafe {
323328
let layout = buf_trait::layout_of(self.as_slice());
324-
let ptr = std::alloc::alloc(layout);
329+
let ptr = match layout.size() {
330+
0 => NonNull::<Buf::Element>::dangling().as_ptr() as *mut u8,
331+
_ => std::alloc::alloc(layout),
332+
};
333+
325334
if ptr.is_null() {
326335
std::alloc::handle_alloc_error(layout);
327336
}

0 commit comments

Comments
 (0)