minmax.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package congestion
  2. import (
  3. "math"
  4. "time"
  5. "golang.org/x/exp/constraints"
  6. )
  7. // InfDuration is a duration of infinite length
  8. const InfDuration = time.Duration(math.MaxInt64)
  9. func Max[T constraints.Ordered](a, b T) T {
  10. if a < b {
  11. return b
  12. }
  13. return a
  14. }
  15. func Min[T constraints.Ordered](a, b T) T {
  16. if a < b {
  17. return a
  18. }
  19. return b
  20. }
  21. // MinNonZeroDuration return the minimum duration that's not zero.
  22. func MinNonZeroDuration(a, b time.Duration) time.Duration {
  23. if a == 0 {
  24. return b
  25. }
  26. if b == 0 {
  27. return a
  28. }
  29. return Min(a, b)
  30. }
  31. // AbsDuration returns the absolute value of a time duration
  32. func AbsDuration(d time.Duration) time.Duration {
  33. if d >= 0 {
  34. return d
  35. }
  36. return -d
  37. }
  38. // MinTime returns the earlier time
  39. func MinTime(a, b time.Time) time.Time {
  40. if a.After(b) {
  41. return b
  42. }
  43. return a
  44. }
  45. // MinNonZeroTime returns the earlist time that is not time.Time{}
  46. // If both a and b are time.Time{}, it returns time.Time{}
  47. func MinNonZeroTime(a, b time.Time) time.Time {
  48. if a.IsZero() {
  49. return b
  50. }
  51. if b.IsZero() {
  52. return a
  53. }
  54. return MinTime(a, b)
  55. }
  56. // MaxTime returns the later time
  57. func MaxTime(a, b time.Time) time.Time {
  58. if a.After(b) {
  59. return a
  60. }
  61. return b
  62. }