2 Copyright (c) 2006 Paolo Capriotti <p.capriotti@sns.it>
3 (c) 2006 Maurizio Monge <maurizio.monge@kdemail.net>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
11 #ifndef LOADER__CONTEXT_H
12 #define LOADER__CONTEXT_H
16 #include <boost/any.hpp>
22 * @class Context <loader/context.h>
23 * @brief A resource loading context
25 * This class offers a set of references in a global cache, to access
26 * a global cache remembering which elements of the cache are being used.
37 Key(const QString
& name
, const char *type
)
42 bool operator<(const Key
& ref
) const {
43 return (m_name
< ref
.m_name
) ||
44 ((m_name
== ref
.m_name
) && (strcmp(m_type
, ref
.m_type
) < 0));
57 Resource(const T
& data
)
63 typedef std::map
<Key
, Resource
> Cache
;
64 typedef std::set
<Key
> KeySet
;
70 /** Destructor (flushes the context) */
73 /** Flushes all the references in this context. */
77 * Gets a resource by name.
78 * @param name The resource name
79 * @return The resource pointer, or null if not found.
82 T
* get(const QString
& name
) {
83 Key
key(name
, typeid(T
).name());
84 Cache::iterator it
= s_cache
.find(key
);
86 if(it
== s_cache
.end())
88 if(!m_references
.count(key
)) {
89 it
->second
.m_ref_count
++;
90 m_references
.insert(key
);
92 return boost::any_cast
<T
>(&it
->second
.m_data
);
96 * Puts a new resource in the global cache, and makes it
97 * referenced by this context.
98 * @param name The resource name
101 void put(const QString
& name
, const T
& data
) {
102 Key
key(name
, typeid(T
).name());
103 Q_ASSERT(!s_cache
.count(key
));
104 Q_ASSERT(!m_references
.count(key
));
106 s_cache
[key
] = Resource(data
);
107 m_references
.insert(key
);
116 } //end namespace Loader
118 #endif //LOADER__CONTEXT_H