noislabs / nois

The Nois standard library
10 stars 4 forks source link

refactor int conversion #45

Open DoTheBestToGetTheBest opened 10 months ago

DoTheBestToGetTheBest commented 10 months ago
DoTheBestToGetTheBest commented 10 months ago

Why this change? Looks more complicated than before. Introducing TryFrom is not needed in the original code

hello, yes i used tryfrom for fallible conversions

when using tryfrom it attempts to convert one type into another, but unlike a direct cast, it can handle cases where the conversion might not be possible

if you are not okey with TryFrom i could remove it :)

thanks

webmaster128 commented 10 months ago

I'm primarily wondering what the advantage of the change is

DoTheBestToGetTheBest commented 10 months ago

I'm primarily wondering what the advantage of the change is

hey, so basically, it handles errors that can occur during type conversion

ref : https://doc.rust-lang.org/std/convert/trait.TryFrom.html

thanks:)

webmaster128 commented 10 months ago

Right, but we already checked

  1. the input is an integer
  2. the input is in the expected value range

So the cast to u32 is always safe. What other errors can happen here that T::try_from(converted).ok() handles?

DoTheBestToGetTheBest commented 10 months ago

Right, but we already checked

  1. the input is an integer
  2. the input is in the expected value range

So the cast to u32 is always safe. What other errors can happen here that T::try_from(converted).ok() handles?

for example when converting a f64 to a smaller integer type , there's a risk of overflow. TryFrom safely handles these cases by returning an Err