fixed passing empty macro argument for VC++
[wxWidgets.git] / include / wx / dynarray.h
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: dynarray.h
3 // Purpose: auto-resizable (i.e. dynamic) array support
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 12.09.97
7 // RCS-ID: $Id$
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 ///////////////////////////////////////////////////////////////////////////////
11
12 #ifndef _DYNARRAY_H
13 #define _DYNARRAY_H
14
15 #ifdef __GNUG__
16 #pragma interface "dynarray.h"
17 #endif
18
19 #include "wx/defs.h"
20
21 /*
22 This header defines the dynamic arrays and object arrays (i.e. arrays which
23 own their elements). Dynamic means that the arrays grow automatically as
24 needed.
25
26 These macros are ugly (especially if you look in the sources ;-), but they
27 allow us to define "template" classes without actually using templates and so
28 this works with all compilers (and may be also much faster to compile even
29 with a compiler which does support templates). The arrays defined with these
30 macros are type-safe.
31
32 Range checking is performed in debug build for both arrays and objarrays but
33 not in release build - so using an invalid index will just lead to a crash
34 then.
35
36 Note about memory usage: arrays never shrink automatically (although you may
37 use Shrink() function explicitly), they only grow, so loading 10 millions in
38 an array only to delete them 2 lines below might be a bad idea if the array
39 object is not going to be destroyed soon. However, as it does free memory
40 when destroyed, it is ok if the array is a local variable.
41 */
42
43 // ----------------------------------------------------------------------------
44 // constants
45 // ----------------------------------------------------------------------------
46
47 /*
48 The initial size by which an array grows when an element is added default
49 value avoids allocate one or two bytes when the array is created which is
50 rather inefficient
51 */
52 #define WX_ARRAY_DEFAULT_INITIAL_SIZE (16)
53
54 // ----------------------------------------------------------------------------
55 // types
56 // ----------------------------------------------------------------------------
57
58 /*
59 Callback compare function for quick sort.
60
61 It must return negative value, 0 or positive value if the first item is
62 less than, equal to or greater than the second one.
63 */
64 extern "C"
65 {
66 typedef int (wxCMPFUNC_CONV *CMPFUNC)(const void* pItem1, const void* pItem2);
67 }
68
69 // ----------------------------------------------------------------------------
70 // Base class managing data having size of type 'long' (not used directly)
71 //
72 // NB: for efficiency this often used class has no virtual functions (hence no
73 // virtual table), even dtor is *not* virtual. If used as expected it
74 // won't create any problems because ARRAYs from DEFINE_ARRAY have no dtor
75 // at all, so it's not too important if it's not called (this happens when
76 // you cast "SomeArray *" as "BaseArray *" and then delete it)
77 // ----------------------------------------------------------------------------
78
79 class WXDLLEXPORT wxBaseArray
80 {
81 public:
82 /** @name ctors and dtor */
83 //@{
84 /// default ctor
85 wxBaseArray();
86 /// copy ctor
87 wxBaseArray(const wxBaseArray& array);
88 /// assignment operator
89 wxBaseArray& operator=(const wxBaseArray& src);
90 /// not virtual, see above
91 ~wxBaseArray();
92 //@}
93
94 /** @name memory management */
95 //@{
96 /// empties the array, but doesn't release memory
97 void Empty() { m_nCount = 0; }
98 /// empties the array and releases memory
99 void Clear();
100 /// preallocates memory for given number of items
101 void Alloc(size_t uiSize);
102 /// minimizes the memory used by the array (frees unused memory)
103 void Shrink();
104 //@}
105
106 /** @name simple accessors */
107 //@{
108 /// number of elements in the array
109 size_t GetCount() const { return m_nCount; }
110 /// is it empty?
111 bool IsEmpty() const { return m_nCount == 0; }
112 /// this version is obsolete, use GetCount()
113 size_t Count() const { return m_nCount; }
114 //@}
115
116 protected:
117 // these methods are protected because if they were public one could
118 // mistakenly call one of them instead of DEFINE_ARRAY's or OBJARRAY's
119 // type safe methods
120
121 /** @name items access */
122 //@{
123 /// get item at position uiIndex (range checking is done in debug version)
124 long& Item(size_t uiIndex) const
125 { wxASSERT( uiIndex < m_nCount ); return m_pItems[uiIndex]; }
126 /// same as Item()
127 long& operator[](size_t uiIndex) const { return Item(uiIndex); }
128 //@}
129
130 /** @name item management */
131 //@{
132 /**
133 Search the element in the array, starting from the either side
134 @param bFromEnd if TRUE, start from the end
135 @return index of the first item matched or wxNOT_FOUND
136 @see wxNOT_FOUND
137 */
138 int Index(long lItem, bool bFromEnd = FALSE) const;
139 /// search for an item using binary search in a sorted array
140 int Index(long lItem, CMPFUNC fnCompare) const;
141 /// search for a place to insert the element into a sorted array
142 size_t IndexForInsert(long lItem, CMPFUNC fnCompare) const;
143 /// add new element at the end
144 void Add(long lItem);
145 /// add item assuming the array is sorted with fnCompare function
146 void Add(long lItem, CMPFUNC fnCompare);
147 /// add new element at given position (it becomes Item[uiIndex])
148 void Insert(long lItem, size_t uiIndex);
149 /// remove first item matching this value
150 void Remove(long lItem);
151 /// remove item by index
152 void RemoveAt(size_t uiIndex);
153 //@}
154
155 /// sort array elements using given compare function
156 void Sort(CMPFUNC fnCompare);
157
158 private:
159 void Grow(); // makes array bigger if needed
160
161 size_t m_nSize, // current size of the array
162 m_nCount; // current number of elements
163
164 long *m_pItems; // pointer to data
165 };
166
167 // ============================================================================
168 // The private helper macros containing the core of the array classes
169 // ============================================================================
170
171 // Implementation notes:
172 //
173 // JACS: Salford C++ doesn't like 'var->operator=' syntax, as in:
174 // { ((wxBaseArray *)this)->operator=((const wxBaseArray&)src);
175 // so using a temporary variable instead.
176 //
177 // The classes need a (even trivial) ~name() to link under Mac X
178 //
179 // _WX_ERROR_REMOVE is needed to resolve the name conflict between the wxT()
180 // macor and T typedef: we can't use wxT() inside WX_DEFINE_ARRAY!
181
182 #define _WX_ERROR_REMOVE wxT("removing inexisting element in wxArray::Remove")
183
184 // ----------------------------------------------------------------------------
185 // _WX_DEFINE_ARRAY: array for simple types
186 // ----------------------------------------------------------------------------
187
188 #define _WX_DEFINE_ARRAY(T, name, classexp) \
189 wxCOMPILE_TIME_ASSERT(sizeof(T) <= sizeof(long), \
190 TypeIsTooBigToBeStoredInWxArray); \
191 typedef int (CMPFUNC_CONV *CMPFUNC##T)(T *pItem1, T *pItem2); \
192 classexp name : public wxBaseArray \
193 { \
194 public: \
195 name() { } \
196 ~name() { } \
197 \
198 name& operator=(const name& src) \
199 { wxBaseArray* temp = (wxBaseArray*) this; \
200 (*temp) = ((const wxBaseArray&)src); \
201 return *this; } \
202 \
203 T& operator[](size_t uiIndex) const \
204 { return (T&)(wxBaseArray::Item(uiIndex)); } \
205 T& Item(size_t uiIndex) const \
206 { return (T&)(wxBaseArray::Item(uiIndex)); } \
207 T& Last() const \
208 { return (T&)(wxBaseArray::Item(Count() - 1)); } \
209 \
210 int Index(T Item, bool bFromEnd = FALSE) const \
211 { return wxBaseArray::Index((long)Item, bFromEnd); } \
212 \
213 void Add(T Item) \
214 { wxBaseArray::Add((long)Item); } \
215 void Insert(T Item, size_t uiIndex) \
216 { wxBaseArray::Insert((long)Item, uiIndex) ; } \
217 \
218 void RemoveAt(size_t uiIndex) { wxBaseArray::RemoveAt(uiIndex); } \
219 void Remove(T Item) \
220 { int iIndex = Index(Item); \
221 wxCHECK2_MSG( iIndex != wxNOT_FOUND, return, \
222 _WX_ERROR_REMOVE); \
223 wxBaseArray::RemoveAt((size_t)iIndex); } \
224 \
225 void Sort(CMPFUNC##T fCmp) { wxBaseArray::Sort((CMPFUNC)fCmp); } \
226 }
227
228 // ----------------------------------------------------------------------------
229 // _WX_DEFINE_SORTED_ARRAY: sorted array for simple data types
230 // ----------------------------------------------------------------------------
231
232 #define _WX_DEFINE_SORTED_ARRAY(T, name, defcomp, classexp) \
233 wxCOMPILE_TIME_ASSERT(sizeof(T) <= sizeof(long), \
234 TypeIsTooBigToBeStoredInWxArray); \
235 typedef int (CMPFUNC_CONV *SCMPFUNC##T)(T pItem1, T pItem2); \
236 classexp name : public wxBaseArray \
237 { \
238 public: \
239 name(SCMPFUNC##T fn defcomp) { m_fnCompare = fn; } \
240 \
241 name& operator=(const name& src) \
242 { wxBaseArray* temp = (wxBaseArray*) this; \
243 (*temp) = ((const wxBaseArray&)src); \
244 m_fnCompare = src.m_fnCompare; \
245 return *this; } \
246 \
247 T& operator[](size_t uiIndex) const \
248 { return (T&)(wxBaseArray::Item(uiIndex)); } \
249 T& Item(size_t uiIndex) const \
250 { return (T&)(wxBaseArray::Item(uiIndex)); } \
251 T& Last() const \
252 { return (T&)(wxBaseArray::Item(Count() - 1)); } \
253 \
254 int Index(T Item) const \
255 { return wxBaseArray::Index((long)Item, (CMPFUNC)m_fnCompare); }\
256 \
257 size_t IndexForInsert(T Item) const \
258 { return wxBaseArray::IndexForInsert((long)Item, \
259 (CMPFUNC)m_fnCompare); } \
260 \
261 void AddAt(T item, size_t index) \
262 { wxBaseArray::Insert((long)item, index); } \
263 \
264 void Add(T Item) \
265 { wxBaseArray::Add((long)Item, (CMPFUNC)m_fnCompare); } \
266 \
267 void RemoveAt(size_t uiIndex) { wxBaseArray::RemoveAt(uiIndex); } \
268 void Remove(T Item) \
269 { int iIndex = Index(Item); \
270 wxCHECK2_MSG( iIndex != wxNOT_FOUND, return, \
271 _WX_ERROR_REMOVE ); \
272 wxBaseArray::RemoveAt((size_t)iIndex); } \
273 \
274 private: \
275 SCMPFUNC##T m_fnCompare; \
276 }
277
278 // ----------------------------------------------------------------------------
279 // _WX_DECLARE_OBJARRAY: an array for pointers to type T with owning semantics
280 // ----------------------------------------------------------------------------
281
282 #define _WX_DECLARE_OBJARRAY(T, name, classexp) \
283 typedef int (CMPFUNC_CONV *CMPFUNC##T)(T** pItem1, T** pItem2); \
284 classexp name : public wxBaseArray \
285 { \
286 public: \
287 name() { } \
288 name(const name& src); \
289 name& operator=(const name& src); \
290 \
291 ~name(); \
292 \
293 T& operator[](size_t uiIndex) const \
294 { return *(T*)wxBaseArray::Item(uiIndex); } \
295 T& Item(size_t uiIndex) const \
296 { return *(T*)wxBaseArray::Item(uiIndex); } \
297 T& Last() const \
298 { return *(T*)(wxBaseArray::Item(Count() - 1)); } \
299 \
300 int Index(const T& Item, bool bFromEnd = FALSE) const; \
301 \
302 void Add(const T& Item); \
303 void Add(const T* pItem) \
304 { wxBaseArray::Add((long)pItem); } \
305 \
306 void Insert(const T& Item, size_t uiIndex); \
307 void Insert(const T* pItem, size_t uiIndex) \
308 { wxBaseArray::Insert((long)pItem, uiIndex); } \
309 \
310 void Empty() { DoEmpty(); wxBaseArray::Empty(); } \
311 void Clear() { DoEmpty(); wxBaseArray::Clear(); } \
312 \
313 T* Detach(size_t uiIndex) \
314 { T* p = (T*)wxBaseArray::Item(uiIndex); \
315 wxBaseArray::RemoveAt(uiIndex); return p; } \
316 void RemoveAt(size_t uiIndex); \
317 \
318 void Sort(CMPFUNC##T fCmp) { wxBaseArray::Sort((CMPFUNC)fCmp); } \
319 \
320 private: \
321 void DoEmpty(); \
322 void DoCopy(const name& src); \
323 }
324
325 // ============================================================================
326 // The public macros for declaration and definition of the dynamic arrays
327 // ============================================================================
328
329 // Please note that for each macro WX_FOO_ARRAY we also have
330 // WX_FOO_EXPORTED_ARRAY and WX_FOO_USER_EXPORTED_ARRAY which are exactly the
331 // same except that they use an additional __declspec(dllexport) or equivalent
332 // under Windows if needed.
333 //
334 // The first (just EXPORTED) macros do it if wxWindows was compiled as a DLL
335 // and so must be used used inside the library. The second kind (USER_EXPORTED)
336 // allow the user code to do it when it wants. This is needed if you have a dll
337 // that wants to export a wxArray daubed with your own import/export goo.
338 //
339 // Finally, you can define the macro below as something special to modify the
340 // arrays defined by a simple WX_FOO_ARRAY as well. By default is is empty.
341 #define wxARRAY_DEFAULT_EXPORT
342
343 // ----------------------------------------------------------------------------
344 // WX_DEFINE_ARRAY(T, name) define an array class named "name" containing the
345 // elements of simple type T such that sizeof(T) <= sizeof(long)
346 //
347 // Note that the class defined has only inline function and doesn't take any
348 // space at all so there is no size penalty for defining multiple array classes
349 // ----------------------------------------------------------------------------
350
351 #define WX_DEFINE_ARRAY(T, name) \
352 WX_DEFINE_USER_EXPORTED_ARRAY(T, name, wxARRAY_DEFAULT_EXPORT)
353
354 #define WX_DEFINE_EXPORTED_ARRAY(T, name) \
355 WX_DEFINE_USER_EXPORTED_ARRAY(T, name, WXDLLEXPORT)
356
357 #define WX_DEFINE_USER_EXPORTED_ARRAY(T, name, expmode) \
358 typedef T _wxArray##name; \
359 _WX_DEFINE_ARRAY(_wxArray##name, name, class expmode)
360
361 // ----------------------------------------------------------------------------
362 // WX_DEFINE_SORTED_ARRAY: this is the same as the previous macro, but it
363 // defines a sorted array.
364 //
365 // Differences:
366 // 1) it must be given a COMPARE function in ctor which takes 2 items of type
367 // T* and should return -1, 0 or +1 if the first one is less/greater
368 // than/equal to the second one.
369 // 2) the Add() method inserts the item in such was that the array is always
370 // sorted (it uses the COMPARE function)
371 // 3) it has no Sort() method because it's always sorted
372 // 4) Index() method is much faster (the sorted arrays use binary search
373 // instead of linear one), but Add() is slower.
374 // 5) there is no Insert() method because you can't insert an item into the
375 // given position in a sorted array but there is IndexForInsert()/AddAt()
376 // pair which may be used to optimize a common operation of "insert only if
377 // not found"
378 //
379 // Note that you have to specify the comparison function when creating the
380 // objects of this array type. If, as in 99% of cases, the comparison function
381 // is the same for all objects of a class, WX_DEFINE_SORTED_ARRAY_CMP below is
382 // more convenient.
383 //
384 // Summary: use this class when the speed of Index() function is important, use
385 // the normal arrays otherwise.
386 // ----------------------------------------------------------------------------
387
388 #define wxARRAY_EMPTY_CMP
389
390 #define WX_DEFINE_SORTED_ARRAY(T, name) \
391 WX_DEFINE_SORTED_USER_EXPORTED_ARRAY(T, name, wxARRAY_DEFAULT_EXPORT)
392
393 #define WX_DEFINE_SORTED_EXPORTED_ARRAY(T, name) \
394 WX_DEFINE_SORTED_USER_EXPORTED_ARRAY(T, name, WXDLLEXPORT)
395
396 #define WX_DEFINE_SORTED_USER_EXPORTED_ARRAY(T, name, expmode) \
397 typedef T _wxArray##name; \
398 _WX_DEFINE_SORTED_ARRAY(_wxArray##name, name, wxARRAY_EMPTY_CMP, class expmode)
399
400 // ----------------------------------------------------------------------------
401 // WX_DEFINE_SORTED_ARRAY_CMP: exactly the same as above but the comparison
402 // function is provided by this macro and the objects of this class have a
403 // default constructor which just uses it.
404 //
405 // The arguments are: the element type, the comparison function and the array
406 // name
407 //
408 // NB: this is, of course, how WX_DEFINE_SORTED_ARRAY() should have worked from
409 // the very beginning - unfortunately I didn't think about this earlier :-(
410 // ----------------------------------------------------------------------------
411
412 #define WX_DEFINE_SORTED_ARRAY_CMP(T, cmpfunc, name) \
413 WX_DEFINE_SORTED_USER_EXPORTED_ARRAY_CMP(T, cmpfunc, name, \
414 wxARRAY_DEFAULT_EXPORT)
415
416 #define WX_DEFINE_SORTED_EXPORTED_ARRAY_CMP(T, cmpfunc, name) \
417 WX_DEFINE_SORTED_USER_EXPORTED_ARRAY_CMP(T, cmpfunc, name, WXDLLEXPORT)
418
419 #define WX_DEFINE_SORTED_USER_EXPORTED_ARRAY_CMP(T, cmpfunc, name, expmode) \
420 typedef T _wxArray##name; \
421 _WX_DEFINE_SORTED_ARRAY(_wxArray##name, name, = cmpfunc, class expmode)
422
423 // ----------------------------------------------------------------------------
424 // WX_DECLARE_OBJARRAY(T, name): this macro generates a new array class
425 // named "name" which owns the objects of type T it contains, i.e. it will
426 // delete them when it is destroyed.
427 //
428 // An element is of type T*, but arguments of type T& are taken (see below!)
429 // and T& is returned.
430 //
431 // Don't use this for simple types such as "int" or "long"!
432 // You _may_ use it for "double" but it's awfully inefficient.
433 //
434 // Note on Add/Insert functions:
435 // 1) function(T*) gives the object to the array, i.e. it will delete the
436 // object when it's removed or in the array's dtor
437 // 2) function(T&) will create a copy of the object and work with it
438 //
439 // Also:
440 // 1) Remove() will delete the object after removing it from the array
441 // 2) Detach() just removes the object from the array (returning pointer to it)
442 //
443 // NB1: Base type T should have an accessible copy ctor if Add(T&) is used
444 // NB2: Never ever cast a array to it's base type: as dtor is not virtual
445 // and so you risk having at least the memory leaks and probably worse
446 //
447 // Some functions of this class are not inline, so it takes some space to
448 // define new class from this template even if you don't use it - which is not
449 // the case for the simple (non-object) array classes
450 //
451 //
452 // To use an objarray class you must
453 // #include "dynarray.h"
454 // WX_DECLARE_OBJARRAY(element_type, list_class_name)
455 // #include "arrimpl.cpp"
456 // WX_DEFINE_OBJARRAY(list_class_name) // name must be the same as above!
457 //
458 // This is necessary because at the moment of DEFINE_OBJARRAY class parsing the
459 // element_type must be fully defined (i.e. forward declaration is not
460 // enough), while WX_DECLARE_OBJARRAY may be done anywhere. The separation of
461 // two allows to break cicrcular dependencies with classes which have member
462 // variables of objarray type.
463 // ----------------------------------------------------------------------------
464
465 #define WX_DECLARE_OBJARRAY(T, name) \
466 WX_DECLARE_USER_EXPORTED_OBJARRAY(T, name, wxARRAY_DEFAULT_EXPORT)
467
468 #define WX_DECLARE_EXPORTED_OBJARRAY(T, name) \
469 WX_DECLARE_USER_EXPORTED_OBJARRAY(T, name, WXDLLEXPORT)
470
471 #define WX_DECLARE_USER_EXPORTED_OBJARRAY(T, name, expmode) \
472 typedef T _wxObjArray##name; \
473 _WX_DECLARE_OBJARRAY(_wxObjArray##name, name, class expmode)
474
475 // WX_DEFINE_OBJARRAY is going to be redefined when arrimpl.cpp is included,
476 // try to provoke a human-understandable error if it used incorrectly.
477 //
478 // there is no real need for 3 different macros in the DEFINE case but do it
479 // anyhow for consistency
480 #define WX_DEFINE_OBJARRAY(name) DidYouIncludeArrimplCpp
481 #define WX_DEFINE_EXPORTED_OBJARRAY(name) WX_DEFINE_OBJARRAY(name)
482 #define WX_DEFINE_USER_EXPORTED_OBJARRAY(name) WX_DEFINE_OBJARRAY(name)
483
484 // ----------------------------------------------------------------------------
485 // Some commonly used predefined arrays
486 // ----------------------------------------------------------------------------
487
488 WX_DEFINE_EXPORTED_ARRAY(int, wxArrayInt);
489 WX_DEFINE_EXPORTED_ARRAY(long, wxArrayLong);
490 WX_DEFINE_EXPORTED_ARRAY(void *, wxArrayPtrVoid);
491
492 // -----------------------------------------------------------------------------
493 // convenience macros
494 // -----------------------------------------------------------------------------
495
496 // append all element of one array to another one
497 #define WX_APPEND_ARRAY(array, other) \
498 { \
499 size_t count = (other).Count(); \
500 for ( size_t n = 0; n < count; n++ ) \
501 { \
502 (array).Add((other)[n]); \
503 } \
504 }
505
506 // delete all array elements
507 //
508 // NB: the class declaration of the array elements must be visible from the
509 // place where you use this macro, otherwise the proper destructor may not
510 // be called (a decent compiler should give a warning about it, but don't
511 // count on it)!
512 #define WX_CLEAR_ARRAY(array) \
513 { \
514 size_t count = (array).Count(); \
515 for ( size_t n = 0; n < count; n++ ) \
516 { \
517 delete (array)[n]; \
518 } \
519 \
520 (array).Empty(); \
521 }
522
523 #endif // _DYNARRAY_H
524