]> git.donarmstrong.com Git - lilypond.git/blob - flower/include/interval.tcc
* flower/include/interval.hh (struct Interval_t):
[lilypond.git] / flower / include / interval.tcc
1 /*
2   interval.tcc -- implement Interval_t
3
4   source file of the Flower Library
5
6   (c) 1996--2005 Han-Wen Nienhuys <hanwen@cs.uu.nl>
7 */
8
9 #ifndef INTERVAL_TCC
10 #define INTERVAL_TCC
11
12 #include <cassert>
13 #include <cmath>
14
15 #include "interval.hh"
16 #include "string.hh"
17
18 template<class T>
19 int
20 _Interval__compare (const Interval_t<T> &a, Interval_t<T> const &b)
21 {
22   if (a.elem (LEFT) == b.elem (LEFT) && a.elem (RIGHT) == b.elem (RIGHT))
23     return 0;
24
25   if (a.elem (LEFT) <= b.elem (LEFT) && a.elem (RIGHT) >= b.elem (RIGHT))
26     return 1;
27
28   if (a.elem (LEFT) >= b.elem (LEFT) && a.elem (RIGHT) <= b.elem (RIGHT))
29     return -1;
30
31   return -2;
32 }
33
34 template<class T>
35 bool
36 Interval_t<T>::superset (Interval_t<T> const &a) const
37 {
38   int c_i = _Interval__compare (*this, a);
39   if (c_i == -2)
40     return false;
41   return c_i >= 0;
42 }
43
44 template<class T>
45 int
46 Interval__compare (Interval_t<T> const &a, Interval_t<T> const &b)
47 {
48   int i = _Interval__compare (a, b);
49   if (i < -1)
50     assert (false);
51   return i;
52 }
53
54 template<class T>
55 void
56 Interval_t<T>::set_empty ()
57 {
58   elem_ref (LEFT) = (T) infinity ();
59   elem_ref (RIGHT) = (T) -infinity ();
60 }
61
62 template<class T>
63 void
64 Interval_t<T>::set_full ()
65 {
66   elem_ref (LEFT) = (T) -infinity ();
67   elem_ref (RIGHT) = (T) infinity ();
68 }
69
70 template<class T>
71 T
72 Interval_t<T>::length () const
73 {
74   if (elem (RIGHT) <= elem (LEFT))
75     return 0;
76   else
77     return elem (RIGHT) - elem (LEFT);
78 }
79
80 template<class T>
81 T
82 Interval_t<T>::delta () const
83 {
84   return elem (RIGHT) - elem (LEFT);
85 }
86
87 /* smallest Interval which includes *this and #h#  */
88 template<class T>
89 void
90 Interval_t<T>::unite (Interval_t<T> h)
91 {
92   elem_ref (LEFT) = min (h.elem (LEFT), elem (LEFT));
93   elem_ref (RIGHT) = max (h.elem (RIGHT), elem (RIGHT));
94 }
95
96 template<class T>
97 void
98 Interval_t<T>::intersect (Interval_t<T> h)
99 {
100   elem_ref (LEFT) = max (h.elem (LEFT), elem (LEFT));
101   elem_ref (RIGHT) = min (h.elem (RIGHT), elem (RIGHT));
102 }
103
104 template<class T>
105 String
106 Interval_t<T>::to_string () const
107 {
108   if (is_empty ())
109     return "[empty]";
110   String s ("[");
111
112   return (s + T_to_string (elem (LEFT)) + String (",")
113           + T_to_string (elem (RIGHT)) + String ("]"));
114 }
115
116 template<class T>
117 bool
118 Interval_t<T>::contains (T r) const
119 {
120   return r >= elem (LEFT) && r <= elem (RIGHT);
121 }
122
123 #define INTERVAL__INSTANTIATE(T) struct Interval_t<T>;                  \
124   template int Interval__compare (const Interval_t<T> &, Interval_t<T> const &)
125
126 #endif // INTERVAL_TCC