Search Unity

Feature Request Support for ValueTuple<T1, T2>.CompareTo

Discussion in 'Burst' started by R2-RT, Apr 20, 2021.

  1. R2-RT

    R2-RT

    Joined:
    May 8, 2019
    Posts:
    38
    Writing specialized CompareTo is boring. In C++ I can use std::tie and in C# ValueTuples to overcome this.

    e.g.

    Code (CSharp):
    1.  
    2.             public struct Pair : IComparable<Pair>
    3.             {
    4.                 public float x;
    5.                 public int y;
    6.                 public int CompareTo(Pair other) => (x, y).CompareTo((other.x, other.y));
    7.             }
    8.  
    unfortunatelly, this code cannot be compiled by Burst, due to error:

    Code (CSharp):
    1. (0,0): Burst error BC1016: The managed function `System.Collections.Generic.Comparer`1<float>.get_Default()` is not supported
    2.  
    3. at System.ValueTuple`2<System.Single,System.Int32>.CompareTo(System.ValueTuple`2<float,int>* this, System.ValueTuple`2<float,int> other)
    4. at
    5. ...
    Since `ValueTuple` has no requirement on its generic field types to be IComparable, internally default comparers are used.

    I can "fix" it with adding manually written static method:

    Code (CSharp):
    1.  
    2.             public static class ValueTupleComparer
    3.             {
    4.                 public static int CompareTo<T1, T2>(ValueTuple<T1, T2> x, ValueTuple<T1, T2> y)
    5.                     where T1 : IComparable<T1>
    6.                     where T2 : IComparable<T2>
    7.                 {
    8.                     var comp1 = x.Item1.CompareTo(y.Item1);
    9.                     return comp1 != 0 ? comp1 : x.Item2.CompareTo(y.Item2);
    10.                 }
    11.             }
    12.  
    13.             public struct Pair : IComparable<Pair>
    14.             {
    15.                 public float x;
    16.                 public int y;
    17.                 public int CompareTo(Pair other) => ValueTupleComparer.CompareTo((x, y), (other.x, other.y));
    18.             }
    19.  
    But I think it should be supported as is, without any extra code. It is easy for tuple with two types, but expanding it for tuples with 3-4-5... well, boring.
     
    jasonboukheir and andywiecko like this.