Skip to content

SmallVec<[T; N]> is invariant over T #146

Open
@zakarumych

Description

@zakarumych

SmallVec<[T; N]> is invariant over T.
Although [T; N] is covariant over T as expected.

This is due to SmallVec<A> having field of type <A as Array>::Item in underlying union.
I propose to change that field type to A and remove A: Array bound from type declaration.

Activity

mbrubeck

mbrubeck commented on Apr 16, 2019

@mbrubeck
Collaborator

For reference, this is similar to bluss/arrayvec#96, and is caused by rust-lang/rust#21726.

Nadrieril

Nadrieril commented on Nov 28, 2019

@Nadrieril

The following trick (can't remember where I found it):

enum SmallVec<A: Array<Item=Item>, Item=<A as Array>::Item> {
    Inline(MaybeUninit<A>),
    Heap((NonNull<Item>, usize)),
}

fixes the variance issue (playground link).
Would that be possible to use or would it be a breaking change to the API ?

bkolobara

bkolobara commented on Nov 23, 2020

@bkolobara

I just spent a few hours debugging a lifetime compilation error related to this after replacing Vec with SmallVec. It took me a long time to figure out that the error originated in SmallVec. This can be really a tricky issue.

mbrubeck

mbrubeck commented on Nov 23, 2020

@mbrubeck
Collaborator

Fortunately, I expect this issue will be fixed in smallvec 2.0 when we replace the Array trait with const generics (#240).

That work depends on the min_const_generics feature, which the Rust team is planning to ship in early 2021: rust-lang/rust#79135

tesujimath

tesujimath commented on Nov 13, 2023

@tesujimath

Having stumbled upon a lifetime problem caused by this, I found the very new 2.0.0-alpha.1 version, tried it, and found it fixed my problem, so yay! And thanks!

Nadrieril

Nadrieril commented on Dec 11, 2023

@Nadrieril

min_const_generics was stabilized 3 years ago: rust-lang/rust#79135, are there any plans to provide a SmallVec<T, N> alternative that has the right variance?

Nadrieril

Nadrieril commented on Dec 11, 2023

@Nadrieril

Oh wait, it looks like master has that already, I guess it's not finalized yet?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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

        Participants

        @mbrubeck@bkolobara@tesujimath@zakarumych@Nadrieril

        Issue actions

          SmallVec<[T; N]> is invariant over T · Issue #146 · servo/rust-smallvec