Skip to content

Prevent double boxing in boxed #511

Closed
@stepancheg

Description

@stepancheg

future.boxed() creates a new box even if future itself is already a Box<Future>.

This can be inconvenient in this use case:

type SomeFuture = ...;
fn make_future() -> SomeFuture { ... }

fn accept_future<F : Future>(f: F) {
    f.boxed() ...
}

accept_future(make_future());

If SomeFuture is an alias for Box<Future> then accept_future makes a Box<Box<Future>>. Which could be worked around (e. g. by creating another function like

fn accept_future_boxed(future: Box<Future>) { ... }

but that would be inconvenient, and still won't prevent accidental wrapping futures in double boxes.

boxed could implemented like this:

fn boxed<F : Future + Sized + 'static>(f: F) -> Box<Future> {
    if TypeId::of::<F>() == TypeId::of::<Box<Future>>() {
        assert!(mem::size_of::<F>() == mem::size_of::<Box<Future>>());
        unsafe {
            let mut r: Box<Future> = mem::uninitialized();
            ptr::copy_nonoverlapping(&f as *const F, &mut r as *mut Box<Future> as *mut u8 as *mut F, 1);
            mem::forget(f);
            r
        }
    } else {
        Box::new(f)
    }
}

PR #512 implements boxed in Future and Stream this way.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions