]> git.lyx.org Git - lyx.git/blob - src/ShareContainer.h
0ca488485e4d2a1599a624ff4745febca2e80050
[lyx.git] / src / ShareContainer.h
1 // -*- C++ -*-
2
3 #ifndef SHARECONTAINER_H
4 #define SHARECONTAINER_H
5
6 #include <vector>
7 #include <algorithm>
8 #include <boost/utility.hpp>
9 #include <boost/smart_ptr.hpp>
10
11 ///
12 template<class Share>
13 class ShareContainer : public noncopyable {
14 public:
15         ///
16         typedef std::vector<boost::shared_ptr<Share> > Params;
17         ///
18         Params::value_type
19         get(Share const & ps) const {
20                 // First see if we already have this ps in the container
21                 Params::iterator it = params.begin();
22                 Params::iterator end = params.end();
23                 for (; it != end; ++it) {
24                         if (ps == *(*it).get())
25                                 break;
26                 }
27                 Params::value_type tmp;
28                 if (it == end) {
29                         // ok we don't have it so we should
30                         // insert it.
31                         tmp.reset(new Share(ps));
32                         params.push_back(tmp);
33                         // We clean here. This can cause us to have
34                         // some (one) unique elemements some times
35                         // but we should gain a lot in speed.
36                         clean();
37                         std::sort(params.rbegin(), params.rend(), comp());
38                 } else {
39                         // yes we have it already
40                         tmp = *it;
41                 }
42                 return tmp;
43         }
44 private:
45         ///
46         struct comp {
47                 int operator()(Params::value_type const & p1,
48                                Params::value_type const & p2) {
49                         return p1.use_count() < p2.use_count();
50                 }
51         };
52         ///
53         struct isUnique {
54                 bool operator()(Params::value_type const & p) const {
55                         return p.unique();
56                 }
57         };
58
59         ///
60         void clean() const {
61                 // Remove all unique items. (i.e. entries that only
62                 // exists in the conatainer and does not have a
63                 // corresponding paragrah.
64                 Params::iterator it = std::remove_if(params.begin(),
65                                                      params.end(),
66                                                      isUnique());
67                 params.erase(it, params.end());
68         }
69         
70         ///
71         mutable Params params;
72 };
73 #endif