castaway icon indicating copy to clipboard operation
castaway copied to clipboard

Feature Request: is it possible to delay running expression until type matches?

Open clouds56 opened this issue 5 months ago • 1 comments

I'm writing a function use match_type to improve performance, the main idea looks like this

trait MyConvert {
  type Raw: 'static;
  fn into_raw(self) -> Self::Raw;
  fn into_f64(self) -> f64;

  fn into_i64(self) -> i64 {
    match_type!(self.into_raw(), {
      i64 as a => return a,
      i32 as a => return a as i64,
      i128 as a => return a as i64,
      _ => {},
    });
    self.into_f64() as i64
  }
}

The into_raw and into_f64 are required method in trait. Now this code couldn't compile without Self: Copy, shall we improve it like this

match_type!(self.into_raw(): Self::Raw, {
  i64 as a => return a,
  i32 as a => return a as i64,
  i128 as a => return a as i64
}

and check CastToken::<Self::Raw>::of() == CastToken::<i32>::of() first before self.into_raw(), so that self wouldn't be consumed in unmatched arms.

We could keep both 2 usages:

  • if explicit type exists, we do the lazy evaluation,
  • when it presence, keep it as is.

clouds56 avatar Sep 30 '25 04:09 clouds56

or I have a new idea: have 2 helper macros from! and to! automatically convert from src_token to dst_token or vice versa.

match_ty!(Self::Raw, {
  i64 => to!(self.into_raw()),
  i32 => to!(self.into_raw()) as i64,
  i128 => to!(self.into_raw()) as i64,
  _ => self.into_f64() as i64,
}

or more simplified

match_ty!(Self::Raw, {
  i64 | i32 | i128 => to!(self.into_raw()) as i64,
  _ => self.into_f64() as i64,
}

so we could have another direction

let value: i64 = todo!();
match_ty!(Self::Raw, {
  i64 | i32 | i128 => self::from_raw(from!(value)),
  _ => self.from_f64(value as f64)
}

clouds56 avatar Sep 30 '25 04:09 clouds56