#How to avoid specialization?

20 messages · Page 1 of 1 (latest)

shy prawn
#

negative trait bounds is not a thing in rust afaik so you can't really do that without using this kind of specialization

#

Also if you own Encode you could probably do this instead

pub trait Encode {
  fn maybe_max_encoded_len() -> Option<usize>;
}

pub trait MaxEncodedLen: Encode {
    fn max_encoded_len() -> usize;
}
gusty wyvern
#

You could just do it like this:

pub trait Encode {
  fn max_encoded_len() -> Option<usize>
}
pub trait MaxEncodedLen {
  fn max_encoded_len() -> usize
}
impl<T: MaxEncodedLen> Encode for T {
  fn max_encoded_len() -> Option<usize> {
    Some(<Self as MaxEncodedLen>::max_encoded_len())
  }
}
#

Then specialization doesn't get you anything

#

By the way, specialization is unsound.

#

I sincerely recommend not using it. Ever

#

It's Deeply Broken

#

I mean, you're creating a new trait anyway

#

You could just create two new traits corresponding to the two ttaits from the crate

#

And implement them as I suggested

#

But the crate doesn't use MaybeMaxEncodedLength, so this is only useful in your own code, where you could also "wrap" their traits

#

What impl?

#

... what are you trying to do here

#

This is neither my suggestion nor specialization

#

That's unnecessary

#

You can already replace it, because of the impl<T: Encode> MaybeMaxEncodedLen for T

#

But of course, those impls will still conflict.

Let's take a step back: why are you trying to do this?

#

This specific problem is unsolvable except by specialization. Also, I have yet to see a use of specialization for anything other than performance that was necessary. So, what are you doing? There's probably a better way

#

I'd recommend just making two variants of with_optimized_encode with different trait bounds.

#

That's what everyone else does