3 Copyright (C) 2006 and later, Cockos Incorporated
5 This software is provided 'as-is', without any express or implied
6 warranty. In no event will the authors be held liable for any damages
7 arising from the use of this software.
9 Permission is granted to anyone to use this software for any purpose,
10 including commercial applications, and to alter it and redistribute it
11 freely, subject to the following restrictions:
13 1. The origin of this software must not be misrepresented; you must not
14 claim that you wrote the original software. If you use this software
15 in a product, an acknowledgment in the product documentation would be
16 appreciated but is not required.
17 2. Altered source versions must be plainly marked as such, and must not be
18 misrepresented as being the original software.
19 3. This notice may not be removed or altered from any source distribution.
23 This file defines a template for a simple object pool.
25 Objects are keyed by string (filename, or otherwise). The caller can add or get an object,
26 increase or decrease its reference count (if it reaches zero the object is deleted).
29 If you delete the pool itself, all objects are deleted, regardless of their reference count.
34 #ifndef _WDL_SHAREDPOOL_H_
35 #define _WDL_SHAREDPOOL_H_
39 template<class OBJ
> class WDL_SharedPool
43 ~WDL_SharedPool() { m_listobjk
.Empty(true); /* do not release m_list since it's redundant */ }
45 void Add(OBJ
*obj
, const char *n
) // no need to AddRef() after add, it defaults to a reference count of 1.
49 Ent
*p
= new Ent(obj
,n
);
50 m_list
.InsertSorted(p
,_sortfunc_name
);
51 m_listobjk
.InsertSorted(p
,_sortfunc_obj
);
55 OBJ
*Get(const char *s
)
57 struct { void *obj
; const char *name
; } tmp
= { NULL
, s
};
58 Ent
*t
= m_list
.Get(m_list
.FindSorted((Ent
*)&tmp
,_sortfunc_name
));
72 Ent
*ent
= m_listobjk
.Get(m_listobjk
.FindSorted((Ent
*)&obj
,_sortfunc_obj
));
73 if (ent
) ent
->refcnt
++;
76 void Release(OBJ
*obj
)
78 int x
= m_listobjk
.FindSorted((Ent
*)&obj
,_sortfunc_obj
);
79 Ent
*ent
= m_listobjk
.Get(x
);
80 if (ent
&& !--ent
->refcnt
)
82 m_list
.Delete(m_list
.FindSorted(ent
,_sortfunc_name
));
83 m_listobjk
.Delete(x
,true);
98 OBJ
*obj
; // this order is used elsewhere for its own advantage
103 Ent(OBJ
*o
, const char *n
) { obj
=o
; name
=strdup(n
); refcnt
=1; }
104 ~Ent() { delete obj
; free(name
); }
110 static int _sortfunc_name(const Ent
**a
, const Ent
**b
)
112 return stricmp((*a
)->name
,(*b
)->name
);
114 static int _sortfunc_obj(const Ent
**a
, const Ent
**b
)
116 if ((INT_PTR
)(*a
)->obj
< (INT_PTR
)(*b
)->obj
) return -1;
117 if ((INT_PTR
)(*a
)->obj
> (INT_PTR
)(*b
)->obj
) return 1;
121 WDL_PtrList
<Ent
> m_list
, // keyed by name
122 m_listobjk
; // keyed by OBJ
128 #endif//_WDL_SHAREDPOOL_H_