tinyvec icon indicating copy to clipboard operation
tinyvec copied to clipboard

Suggestion: Default-less safe implementation with small overhead

Open kkolyan opened this issue 2 years ago • 3 comments

Hi. I just had an idea that there could be and option to avoid Default bound on user side by using Option to wrap items under the hood. Of course, that's additional overhead, but seems like the whole point of TinyVec is to be optimal in cases when size is small, when such overhead seems acceptable. Maybe worth to have it as additional type?

kkolyan avatar Aug 08 '23 07:08 kkolyan

This has been explored already and found to be unworkable, see #155 and #70

Shnatsel avatar Aug 08 '23 09:08 Shnatsel

yeah, I faced with the impossibility to make &[T] from &[Option<T>] when tried to implement suggested idea via custom implementation of tinyvec::array::Array. but I suppose this suggestion would be implemented as dedicated type, and I don't think lack of slices on user level is so big loss. After all, a lot of (if not majority) use cases for Vec-like structures in business-domain-code are push/remove/iterate.

kkolyan avatar Aug 08 '23 10:08 kkolyan

To reuse good solutions from tinyvec, one could use something like that:

use tinyvec::{tiny_vec, TinyVec};

const LIMIT: usize = 2;

#[derive(Default, Debug, Clone)]
pub struct OptTinyVec<T> {
    inner: TinyVec<[Option<T>; LIMIT]>,
}

impl<T> OptTinyVec<T> {

    #[inline]
    pub fn push(&mut self, value: T) {
        self.inner.push(Some(value));
    }

    #[inline]
    pub fn iter(&self) -> impl Iterator<Item=&T> + '_ {
        self.inner
            .iter()
            .map(|it| it.as_ref().unwrap())
    }
}

I think it's ok to have this on the user project level.

Of course, that would be nice to have something like that as library, but LIMIT is hardcoded and cannot be parameterized easily. The only approach I see is to generate OptArray impls like Array impls are generated. It means extra efforts to synchronize it with tinyvec. I'm not sure that worth...

kkolyan avatar Aug 08 '23 10:08 kkolyan