]> gitweb.ps.run Git - toc/blob - antlr4-cpp-runtime-4.9.2-source/runtime/src/misc/Interval.cpp
add antlr source code and ReadMe
[toc] / antlr4-cpp-runtime-4.9.2-source / runtime / src / misc / Interval.cpp
1 /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
2  * Use of this file is governed by the BSD 3-clause license that
3  * can be found in the LICENSE.txt file in the project root.
4  */
5
6 #include "misc/Interval.h"
7
8 using namespace antlr4::misc;
9
10 size_t antlr4::misc::numericToSymbol(ssize_t v) {
11   return static_cast<size_t>(v);
12 }
13
14 ssize_t antlr4::misc::symbolToNumeric(size_t v) {
15   return static_cast<ssize_t>(v);
16 }
17
18 Interval const Interval::INVALID;
19
20 Interval::Interval() : Interval(static_cast<ssize_t>(-1), -2) { // Need an explicit cast here for VS.
21 }
22
23 Interval::Interval(size_t a_, size_t b_) : Interval(symbolToNumeric(a_), symbolToNumeric(b_)) {
24 }
25
26 Interval::Interval(ssize_t a_, ssize_t b_) : a(a_), b(b_) {
27 }
28
29 size_t Interval::length() const {
30   if (b < a) {
31     return 0;
32   }
33   return size_t(b - a + 1);
34 }
35
36 bool Interval::operator == (const Interval &other) const {
37   return a == other.a && b == other.b;
38 }
39
40 size_t Interval::hashCode() const {
41   size_t hash = 23;
42   hash = hash * 31 + static_cast<size_t>(a);
43   hash = hash * 31 + static_cast<size_t>(b);
44   return hash;
45 }
46
47 bool Interval::startsBeforeDisjoint(const Interval &other) const {
48   return a < other.a && b < other.a;
49 }
50
51 bool Interval::startsBeforeNonDisjoint(const Interval &other) const {
52   return a <= other.a && b >= other.a;
53 }
54
55 bool Interval::startsAfter(const Interval &other) const {
56   return a > other.a;
57 }
58
59 bool Interval::startsAfterDisjoint(const Interval &other) const {
60   return a > other.b;
61 }
62
63 bool Interval::startsAfterNonDisjoint(const Interval &other) const {
64   return a > other.a && a <= other.b; // b >= other.b implied
65 }
66
67 bool Interval::disjoint(const Interval &other) const {
68   return startsBeforeDisjoint(other) || startsAfterDisjoint(other);
69 }
70
71 bool Interval::adjacent(const Interval &other) const {
72   return a == other.b + 1 || b == other.a - 1;
73 }
74
75 bool Interval::properlyContains(const Interval &other) const {
76   return other.a >= a && other.b <= b;
77 }
78
79 Interval Interval::Union(const Interval &other) const {
80   return Interval(std::min(a, other.a), std::max(b, other.b));
81 }
82
83 Interval Interval::intersection(const Interval &other) const {
84   return Interval(std::max(a, other.a), std::min(b, other.b));
85 }
86
87 std::string Interval::toString() const {
88   return std::to_string(a) + ".." + std::to_string(b);
89 }