-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrange.c
133 lines (102 loc) · 2.54 KB
/
range.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>
#include "range.h"
Range* range_new(int start, int end) {
Range* self = (Range*) calloc(1, sizeof(Range));
self->min = 0;
self->max = 0x10000;
self->start = start;
self->end = end;
return self;
}
Range* range_new_from_int(int range) {
int start = ((unsigned int) range) >> 16;
int end = range & 0xffff;
if(end == 0) end = 0x10000;
return range_new(start, end);
}
Range* range_parse(char *str) {
Range* self = range_new(0, 0x10000);
if(strlen(str) == 0) {
return self;
}
char *start = str;
char *end = strstr(str, "-");
if(end != NULL) {
end++;
}
while(isspace(start[0])) start++;
if(strlen(start) > 0 && start[0] != '-') {
self->start = (int) strtol(start, NULL, 0);
}
if(end == NULL) {
self->end = -1;
}
else {
while(isspace(end[0])) end++;
if(strlen(end) > 0) {
self->end = (int) strtol(end, NULL, 0);
}
}
return self;
}
bool range_valid(Range* self) {
return
self->start >= self->min &&
self->start <= self->max &&
self->end >= self->min &&
self->end <= self->max &&
self->end >= self->start;
}
void range_print(Range* self) {
printf("$%04X-$%04X\n", self->start, self->end);
}
int range_size(Range* self) {
return self->end - self->start;
}
bool range_equals(Range* self, Range* range) {
return self->start == range->start && self->end == range->end;
}
bool range_ends(Range* self) {
return self->end != -1;
}
void range_move(Range* self, int amount) {
if(amount == 0) return;
if(amount > 0) {
if(self->end + amount > self->max) {
amount -= (self->end + amount) - self->max;
}
}
if(amount < 0) {
if(self->start + amount < self->min) {
amount -= (self->start + amount);
}
}
self->start += amount;
self->end += amount;
}
bool range_inside(Range* self, Range* range) {
if(range_equals(self, range)) {
return true;
}
return self->start >= range->start && self->end <= range->end;
}
bool range_outside(Range* self, Range* range) {
return !range_inside(self, range);
}
bool range_overlaps(Range* self, Range* range) {
if(range_equals(self, range)) {
return true;
}
return
(self->start >= range->start && self->start <= range->end) ||
(self->end >= range->start && self->end <= range->end) ||
(range->start >= self->start && range->start <= self->end) ||
(range->end >= self->start && range->end <= self->end);
}
void range_free(Range* self) {
free(self);
}