3 #include <boost/flyweight.hpp>
4 #include <boost/flyweight/set_factory.hpp>
5 #include <boost/flyweight/no_tracking.hpp>
6 #include <boost/flyweight/no_locking.hpp>
7 #include <boost/smart_ptr.hpp>
10 #include "mru_cache.h"
13 struct std::equal_to
<CRect
>
14 { // functor for operator==
15 bool operator()(const CRect
& _Left
, const CRect
& _Right
) const
16 { // apply operator== to operands
17 return (_Left
== _Right
)==TRUE
;
21 typedef ::boost::flyweights::flyweight
<CRect
, ::boost::flyweights::no_locking
> FwRect
;
25 int DEFAULT_CACHE_SIZE
= 1024,
26 class VTraits
=CElementTraits
<V
>
31 typedef std::size_t IdType
;
32 typedef ::boost::shared_ptr
<const V
> SharedConstV
;
34 class SharedVElementTraits
:public CElementTraits
<SharedConstV
>
37 static ULONG
Hash(const SharedConstV
& v
)
39 return VTraits::Hash(*v
);
41 static bool CompareElements(
42 const SharedConstV
& element1
,
43 const SharedConstV
& element2
)
45 return VTraits::CompareElements(*element1
, *element2
);
47 static int CompareElementsOrdered(
48 const SharedConstV
& element1
,
49 const SharedConstV
& element2
)
51 return VTraits::CompareElementsOrdered(*element1
, *element2
);
55 typedef EnhancedXyMru
<SharedConstV
, IdType
, SharedVElementTraits
> Cacher
;
57 static const int INVALID_ID
= 0;
59 // v will be assigned to a shared pointer
60 XyFlyWeight(const V
*v
):_v(v
)
62 Cacher
* cacher
= GetCacher();
64 bool new_item_added
= false;
65 POSITION pos
= cacher
->AddHeadIfNotExists(_v
, INVALID_ID
, &new_item_added
);
66 if ( !new_item_added
)
68 cacher
->UpdateCache(pos
);
69 _v
= cacher
->GetKeyAt(pos
);
70 _id
= cacher
->GetAt(pos
);
75 cacher
->GetAt(pos
) = _id
;
78 inline const V
& Get() const { return *_v
; }
79 inline IdType
GetId() const { return _id
; }
81 static inline Cacher
* GetCacher();
86 static inline IdType
AllocId();
89 template<typename V
, int DEFAULT_CACHE_SIZE
, class VTraits
>
91 typename XyFlyWeight
<V
, DEFAULT_CACHE_SIZE
, VTraits
>::Cacher
* XyFlyWeight
<V
, DEFAULT_CACHE_SIZE
, VTraits
>::GetCacher()
93 static Cacher
cacher(DEFAULT_CACHE_SIZE
);
97 template<typename V
, int DEFAULT_CACHE_SIZE
, class VTraits
>
99 typename XyFlyWeight
<V
, DEFAULT_CACHE_SIZE
, VTraits
>::IdType XyFlyWeight
<V
, DEFAULT_CACHE_SIZE
, VTraits
>::AllocId()
101 static IdType cur_id
=INVALID_ID
;
103 if (cur_id
==INVALID_ID
)
110 typedef XyFlyWeight
<CStringW
, 16*1024, CStringElementTraits
<CStringW
>> XyFwStringW
;
112 static inline std::size_t hash_value(const double& d
)
114 std::size_t hash
= 515;
115 const int32_t* tmp
= reinterpret_cast<const int32_t*>(&d
);
123 static inline std::size_t hash_value(const CStringW
& s
)
125 return CStringElementTraits
<CStringW
>::Hash(s
);
128 static inline std::size_t hash_value(const CStringA
& s
)
130 return CStringElementTraits
<CStringA
>::Hash(s
);
133 static inline std::size_t hash_value(const CRect
& s
)
135 std::size_t hash
= 515;