Range.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. namespace MonoGame.Extended
  3. {
  4. /// <summary>
  5. /// Represents a closed interval defined by a minimum and a maximum value of a give type.
  6. /// </summary>
  7. [Obsolete("Use new Interval<T> struct. Range<T> will be removed in 6.0")]
  8. public struct Range<T> : IEquatable<Range<T>> where T : IComparable<T>
  9. {
  10. public Range(T min, T max)
  11. {
  12. if (min.CompareTo(max) > 0 || max.CompareTo(min) < 0)
  13. throw new ArgumentException("Min has to be smaller than or equal to max.");
  14. Min = min;
  15. Max = max;
  16. }
  17. public Range(T value)
  18. : this(value, value)
  19. {
  20. }
  21. /// <summary>
  22. /// Gets the minium value of the <see cref="Range{T}" />.
  23. /// </summary>
  24. public T Min { get; }
  25. /// <summary>
  26. /// Gets the maximum value of the <see cref="Range{T}" />.
  27. /// </summary>
  28. public T Max { get; }
  29. /// <summary>
  30. /// Returns wheter or not this <see cref="Range{T}" /> is degenerate.
  31. /// (Min and Max are the same)
  32. /// </summary>
  33. public bool IsDegenerate => Min.Equals(Max);
  34. /// <summary>
  35. /// Returns wheter or not this <see cref="Range{T}" /> is proper.
  36. /// (Min and Max are not the same)
  37. /// </summary>
  38. public bool IsProper => !Min.Equals(Max);
  39. public bool Equals(Range<T> value) => Min.Equals(value.Min) && Max.Equals(value.Max);
  40. public override bool Equals(object obj) => obj is Range<T> && Equals((Range<T>) obj);
  41. public override int GetHashCode() => Min.GetHashCode() ^ Max.GetHashCode();
  42. public static bool operator ==(Range<T> value1, Range<T> value2) => value1.Equals(value2);
  43. public static bool operator !=(Range<T> value1, Range<T> value2) => !value1.Equals(value2);
  44. public static implicit operator Range<T>(T value) => new Range<T>(value, value);
  45. public override string ToString() => $"Range<{typeof(T).Name}> [{Min} {Max}]";
  46. /// <summary>
  47. /// Returns wheter or not the value falls in this <see cref="Range{T}" />.
  48. /// </summary>
  49. public bool IsInBetween(T value, bool minValueExclusive = false, bool maxValueExclusive = false)
  50. {
  51. if (minValueExclusive)
  52. {
  53. if (value.CompareTo(Min) <= 0)
  54. return false;
  55. }
  56. if (value.CompareTo(Min) < 0)
  57. return false;
  58. if (maxValueExclusive)
  59. {
  60. if (value.CompareTo(Max) >= 0)
  61. return false;
  62. }
  63. return value.CompareTo(Max) <= 0;
  64. }
  65. }
  66. }