aboutsummaryrefslogtreecommitdiff
path: root/interval.c
blob: df9c14c07c79c2bb21b0f375959924cccedb4fe2 (plain)
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
/*
 * for reference:
 * - James F. Allen, Maintaining Knowledge about Temporal Intervals, CACM November 1983, Vol. 26, No. 11
 * - https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6188649/
 */
#include <u.h>
#include <libc.h>
#include "interval.h"

static int
interval_before(Interval *i, Interval *ii)
{
	return i->t1 < ii->t0;
}

static int
interval_equals(Interval *i, Interval *ii)
{
	return i->t0 == ii->t0 &&
		i->t1 == ii->t1;
}

static int
interval_overlaps(Interval *i, Interval *ii)
{
	return i->t0 < ii->t0 &&
		i->t1 > ii->t0 &&
		i->t1 < ii->t1;
}

static int
interval_meets(Interval *i, Interval *ii)
{
	return i->t1 == ii->t0;
}

static int
interval_during(Interval *i, Interval *ii)
{
	return (i->t0 > ii->t0 && i->t1 <= ii->t1) ||
		(i->t0 >= ii->t0 && i->t1 < ii->t1);
}

static int
interval_intersects(Interval *i, Interval *ii)
{
	return i->equals(i, ii) ||
		i->overlaps(i, ii) ||
		ii->overlaps(ii, i) ||
		i->during(i, ii) ||
		ii->during(ii, i);
}

Interval *
mkinterval(uvlong t0, uvlong t1)
{
	Interval *i;

	assert(t0 <= t1);

	i = malloc(sizeof(Interval));
	if(i == nil)
		sysfatal("mkinterval: %r");

	i->t0 = t0;
	i->t1 = t1;
	i->∆t = t1-t0;
	i->before = interval_before;
	i->equals = interval_equals;
	i->overlaps = interval_overlaps;
	i->meets = interval_meets;
	i->during = interval_during;
	i->intersects = interval_intersects;

	return i;
}

void
rminterval(Interval *i)
{
	free(i);
}