Range.m 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. //
  2. // Range.m
  3. //
  4. // Created by Giles Payne on 2019/10/08.
  5. //
  6. #import "Range.h"
  7. @implementation Range
  8. - (instancetype)init {
  9. return [self initWithStart:0 end: 0];
  10. }
  11. - (instancetype)initWithStart:(int)start end:(int)end {
  12. self = [super init];
  13. if (self != nil) {
  14. self.start = start;
  15. self.end = end;
  16. }
  17. return self;
  18. }
  19. - (instancetype)initWithVals:(NSArray<NSNumber*>*)vals {
  20. self = [self init];
  21. if (self != nil) {
  22. [self set:vals];
  23. }
  24. return self;
  25. }
  26. - (void)set:(NSArray<NSNumber*>*)vals {
  27. self.start = (vals != nil && vals.count > 0) ? vals[0].intValue : 0;
  28. self.end = (vals != nil && vals.count > 1 ) ? vals[1].intValue : 0;
  29. }
  30. - (int)size {
  31. return [self empty] ? 0 : self.end - self.start;
  32. }
  33. - (BOOL)empty {
  34. return self.end <= self.start;
  35. }
  36. + (Range*)all {
  37. return [[Range alloc] initWithStart:INT_MIN end:INT_MAX];
  38. }
  39. - (Range*)intersection:(Range*)r1 {
  40. Range* out = [[Range alloc] initWithStart:MAX(r1.start, self.start) end:MIN(r1.end, self.end)];
  41. out.end = MAX(out.end, out.start);
  42. return out;
  43. }
  44. - (Range*)shift:(int)delta {
  45. return [[Range alloc] initWithStart:self.start + delta end:self.end + delta];
  46. }
  47. - (Range*)clone {
  48. return [[Range alloc] initWithStart:self.start end:self.end];
  49. }
  50. - (BOOL)isEqual:(id)other {
  51. if (other == self) {
  52. return YES;
  53. } else if (![other isKindOfClass:[Range class]]) {
  54. return NO;
  55. } else {
  56. Range* it = (Range*)other;
  57. return self.start == it.start && self.end == it.end;
  58. }
  59. }
  60. - (NSUInteger)hash {
  61. int prime = 31;
  62. uint32_t result = 1;
  63. result = prime * result + self.start;
  64. result = prime * result + self.end;
  65. return result;
  66. }
  67. - (NSString *)description {
  68. return [NSString stringWithFormat:@"Range {%d, %d}", self.start, self.end];
  69. }
  70. @end