Range.cs 2.6 KB

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