Skip to content

SmallVec can not coerce lifetimes of wrapped value #217

@Luro02

Description

@Luro02

I could not get the following code to compile with SmallVec (I heavily simplified the code):

use std::borrow::Cow;

pub struct SmallVec<T> {
    data: *mut T,
}

pub struct Example<'a>(SmallVec<[Cow<'a, str>; 2]>);

impl<'a> Example<'a> {
    pub fn into_owned(self) -> Example<'static> { unimplemented!() }
}

fn transform<'a>(input: Example<'a>) -> Example<'a> {
    input.into_owned()
}

fn main() {}

playground

error[E0308]: mismatched types
  --> src/main.rs:14:5
   |
14 |     input.into_owned()
   |     ^^^^^^^^^^^^^^^^^^ lifetime mismatch
   |
   = note: expected struct `Example<'a>`
              found struct `Example<'static>`
note: the lifetime `'a` as defined on the function body at 13:14...
  --> src/main.rs:13:14
   |
13 | fn transform<'a>(input: Example<'a>) -> Example<'a> {
   |              ^^
   = note: ...does not necessarily outlive the static lifetime

error: aborting due to previous error

which does compile when you replace SmallVec with Vec.

This works with Vec, because internally the pointer is wrapped in Unique<T>:

https://github.com/rust-lang/rust/blob/fb5615a4771ea3d54256f969dc84d2dfd38d812c/src/liballoc/raw_vec.rs#L47

whereas SmallVec contains a raw pointer:

Heap((*mut A::Item, usize)),

This issue can be solved by changing *mut A::Item to Option<NonNull<A::Item>>, because NonNull implements the CoerceUnsized trait.

This might be related to #146

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