start_end.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package codec
  2. import (
  3. "fmt"
  4. )
  5. // startEnd represents the start and end of some data. It mainly exists as a
  6. // helper when referencing the values
  7. type startEnd struct {
  8. start int
  9. end int
  10. }
  11. // sub subtracts the values of two startEnds
  12. func (s startEnd) sub(o startEnd) startEnd {
  13. return startEnd{
  14. s.start - o.start,
  15. s.end - o.end,
  16. }
  17. }
  18. // add adds the values of two startEnds
  19. func (s startEnd) add(o startEnd) startEnd {
  20. return startEnd{
  21. s.start + o.start,
  22. s.end + o.end,
  23. }
  24. }
  25. // overlaps returns true if two startEnds overlap
  26. func (s startEnd) overlaps(o startEnd) bool {
  27. return o.start <= s.end && o.end >= s.start
  28. }
  29. // contains returns true if the other is fully contained within this one
  30. func (s startEnd) contains(o startEnd) bool {
  31. return s.start <= o.start && o.end <= s.end
  32. }
  33. // overflow returns a startEnd that tells how much the other goes outside the
  34. // bounds of this one
  35. func (s startEnd) overflow(o startEnd) startEnd {
  36. return s.merge(o).sub(s)
  37. }
  38. // merge takes two start/ends and returns a single one that encompasses both
  39. func (s startEnd) merge(o startEnd) startEnd {
  40. return startEnd{
  41. min(s.start, o.start),
  42. max(s.end, o.end),
  43. }
  44. }
  45. // String returns a string representation for clearer debugging
  46. func (s startEnd) String() string {
  47. return fmt.Sprintf("[%d,%d]", s.start, s.end)
  48. }