]> git.donarmstrong.com Git - lilypond.git/blob - flower/include/interval.hh
release: 0.0.52
[lilypond.git] / flower / include / interval.hh
1 /*
2   interval.hh -- part of flowerlib
3   
4   (c) 1996 Han-Wen Nienhuys
5 */
6
7 #ifndef INTERVAL_HH
8 #define INTERVAL_HH
9
10 #include <assert.h> 
11 #include "fproto.hh"
12 #include "real.hh"
13
14
15 /** a T interval.  this represents the closed interval [left,right].
16   No invariants. T must be a totally ordered ring (with division, anyway ..)
17   At instantiation, the function infinity() has to be defined explicitely.
18   
19   */
20 template<class T>
21 struct Interval_t {
22     T left, right;
23
24     /* ************** */
25     
26     static T infinity() ;
27     
28     T center() { return (left + right) / T(2);}
29     void translate(T t) {
30         left += t;
31         right += t;
32     }
33     T& idx(int j) {
34         if (j==-1)
35             return left;
36         else if (j==1)
37             return right;
38         else
39             assert(false);
40         return left;            
41     }
42     T& operator[](int j) {
43         return idx(j);
44     }
45     T operator[](int j) const {
46         return ((Interval_t<T> *)this)->idx(j);
47     }
48     T &max() { return right;}
49     T max()const { return right;}
50     T min()const{ return left; }
51     T &min(){ return left; }
52     /**
53       PRE
54       *this and h are comparable
55       */
56     void unite(Interval_t<T> h);
57     void intersect(Interval_t<T> h);
58
59     T length() const;
60     void set_empty() ;
61     bool empty_b() const { return left > right; }
62     bool contains_b(Interval_t<T> const&) const;
63     Interval_t() {
64         set_empty();
65     }
66     Interval_t(T m, T M) {
67         left =m;
68         right = M;
69     }
70     Interval_t<T> &operator += (T r) {
71         left += r;
72         right +=r;
73         return *this;
74     }
75     String str() const;    
76     bool elt_b(T r);
77 };
78
79
80 /**
81   inclusion ordering. Crash if not comparable.
82   */
83 template<class T>
84 int Interval__compare(const Interval_t<T>&,Interval_t<T> const&);
85
86 /*
87   INLINE
88  */
89
90 #include "compare.hh"
91
92 template_instantiate_compare(Interval_t<T>&, Interval__compare, template<class T>);
93
94
95 template<class T>
96 inline Interval_t<T>
97 intersection(Interval_t<T> a, Interval_t<T> const&b)
98 {
99     a.intersect(b);
100     return a;
101     
102 }
103
104
105 template<class T>
106 inline
107 Interval_t<T> operator +(T a,Interval_t<T> i )
108 {
109     i += a;
110     return i;
111 }
112
113 template<class T>
114 inline
115 Interval_t<T> operator +(Interval_t<T> i,T a ){
116     return a+i;
117 }
118
119 typedef Interval_t<Real> Interval;
120
121
122 #define Interval__instantiate(T) template struct Interval_t<T>;\
123   template  int Interval__compare(const Interval_t<T>&,Interval_t<T> const&)
124
125
126 #endif // INTERVAL_HH
127
128
129