]> git.saurik.com Git - wxWidgets.git/blob - include/wx/dynarray.h
Fixed typo in my last commit (it did break socket detection code :-( ).
[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_ASSERT2(sizeof(T) <= sizeof(long), \
190 TypeIsTooBigToBeStoredInWxArray, \
191 name); \
192 typedef int (CMPFUNC_CONV *CMPFUNC##T)(T *pItem1, T *pItem2); \
193 classexp name : public wxBaseArray \
194 { \
195 public: \
196 name() { } \
197 ~name() { } \
198 \
199 name& operator=(const name& src) \
200 { wxBaseArray* temp = (wxBaseArray*) this; \
201 (*temp) = ((const wxBaseArray&)src); \
202 return *this; } \
203 \
204 T& operator[](size_t uiIndex) const \
205 { return (T&)(wxBaseArray::Item(uiIndex)); } \
206 T& Item(size_t uiIndex) const \
207 { return (T&)(wxBaseArray::Item(uiIndex)); } \
208 T& Last() const \
209 { return (T&)(wxBaseArray::Item(Count() - 1)); } \
210 \
211 int Index(T Item, bool bFromEnd = FALSE) const \
212 { return wxBaseArray::Index((long)Item, bFromEnd); } \
213 \
214 void Add(T Item) \
215 { wxBaseArray::Add((long)Item); } \
216 void Insert(T Item, size_t uiIndex) \
217 { wxBaseArray::Insert((long)Item, uiIndex) ; } \
218 \
219 void RemoveAt(size_t uiIndex) { wxBaseArray::RemoveAt(uiIndex); } \
220 void Remove(T Item) \
221 { int iIndex = Index(Item); \
222 wxCHECK2_MSG( iIndex != wxNOT_FOUND, return, \
223 _WX_ERROR_REMOVE); \
224 wxBaseArray::RemoveAt((size_t)iIndex); } \
225 \
226 void Sort(CMPFUNC##T fCmp) { wxBaseArray::Sort((CMPFUNC)fCmp); } \
227 }
228
229 // ----------------------------------------------------------------------------
230 // _WX_DEFINE_SORTED_ARRAY: sorted array for simple data types
231 // ----------------------------------------------------------------------------
232
233 #define _WX_DEFINE_SORTED_ARRAY(T, name, defcomp, classexp) \
234 wxCOMPILE_TIME_ASSERT2(sizeof(T) <= sizeof(long), \
235 TypeIsTooBigToBeStoredInWxArray, \
236 name); \
237 typedef int (CMPFUNC_CONV *SCMPFUNC##T)(T pItem1, T pItem2); \
238 classexp name : public wxBaseArray \
239 { \
240 public: \
241 name(SCMPFUNC##T fn defcomp) { m_fnCompare = fn; } \
242 \
243 name& operator=(const name& src) \
244 { wxBaseArray* temp = (wxBaseArray*) this; \
245 (*temp) = ((const wxBaseArray&)src); \
246 m_fnCompare = src.m_fnCompare; \
247 return *this; } \
248 \
249 T& operator[](size_t uiIndex) const \
250 { return (T&)(wxBaseArray::Item(uiIndex)); } \
251 T& Item(size_t uiIndex) const \
252 { return (T&)(wxBaseArray::Item(uiIndex)); } \
253 T& Last() const \
254 { return (T&)(wxBaseArray::Item(Count() - 1)); } \
255 \
256 int Index(T Item) const \
257 { return wxBaseArray::Index((long)Item, (CMPFUNC)m_fnCompare); }\
258 \
259 size_t IndexForInsert(T Item) const \
260 { return wxBaseArray::IndexForInsert((long)Item, \
261 (CMPFUNC)m_fnCompare); } \
262 \
263 void AddAt(T item, size_t index) \
264 { wxBaseArray::Insert((long)item, index); } \
265 \
266 void Add(T Item) \
267 { wxBaseArray::Add((long)Item, (CMPFUNC)m_fnCompare); } \
268 \
269 void RemoveAt(size_t uiIndex) { wxBaseArray::RemoveAt(uiIndex); } \
270 void Remove(T Item) \
271 { int iIndex = Index(Item); \
272 wxCHECK2_MSG( iIndex != wxNOT_FOUND, return, \
273 _WX_ERROR_REMOVE ); \
274 wxBaseArray::RemoveAt((size_t)iIndex); } \
275 \
276 private: \
277 SCMPFUNC##T m_fnCompare; \
278 }
279
280 // ----------------------------------------------------------------------------
281 // _WX_DECLARE_OBJARRAY: an array for pointers to type T with owning semantics
282 // ----------------------------------------------------------------------------
283
284 #define _WX_DECLARE_OBJARRAY(T, name, classexp) \
285 typedef int (CMPFUNC_CONV *CMPFUNC##T)(T** pItem1, T** pItem2); \
286 classexp name : public wxBaseArray \
287 { \
288 public: \
289 name() { } \
290 name(const name& src); \
291 name& operator=(const name& src); \
292 \
293 ~name(); \
294 \
295 T& operator[](size_t uiIndex) const \
296 { return *(T*)wxBaseArray::Item(uiIndex); } \
297 T& Item(size_t uiIndex) const \
298 { return *(T*)wxBaseArray::Item(uiIndex); } \
299 T& Last() const \
300 { return *(T*)(wxBaseArray::Item(Count() - 1)); } \
301 \
302 int Index(const T& Item, bool bFromEnd = FALSE) const; \
303 \
304 void Add(const T& Item); \
305 void Add(const T* pItem) \
306 { wxBaseArray::Add((long)pItem); } \
307 \
308 void Insert(const T& Item, size_t uiIndex); \
309 void Insert(const T* pItem, size_t uiIndex) \
310 { wxBaseArray::Insert((long)pItem, uiIndex); } \
311 \
312 void Empty() { DoEmpty(); wxBaseArray::Empty(); } \
313 void Clear() { DoEmpty(); wxBaseArray::Clear(); } \
314 \
315 T* Detach(size_t uiIndex) \
316 { T* p = (T*)wxBaseArray::Item(uiIndex); \
317 wxBaseArray::RemoveAt(uiIndex); return p; } \
318 void RemoveAt(size_t uiIndex); \
319 \
320 void Sort(CMPFUNC##T fCmp) { wxBaseArray::Sort((CMPFUNC)fCmp); } \
321 \
322 private: \
323 void DoEmpty(); \
324 void DoCopy(const name& src); \
325 }
326
327 // ============================================================================
328 // The public macros for declaration and definition of the dynamic arrays
329 // ============================================================================
330
331 // Please note that for each macro WX_FOO_ARRAY we also have
332 // WX_FOO_EXPORTED_ARRAY and WX_FOO_USER_EXPORTED_ARRAY which are exactly the
333 // same except that they use an additional __declspec(dllexport) or equivalent
334 // under Windows if needed.
335 //
336 // The first (just EXPORTED) macros do it if wxWindows was compiled as a DLL
337 // and so must be used used inside the library. The second kind (USER_EXPORTED)
338 // allow the user code to do it when it wants. This is needed if you have a dll
339 // that wants to export a wxArray daubed with your own import/export goo.
340 //
341 // Finally, you can define the macro below as something special to modify the
342 // arrays defined by a simple WX_FOO_ARRAY as well. By default is is empty.
343 #define wxARRAY_DEFAULT_EXPORT
344
345 // ----------------------------------------------------------------------------
346 // WX_DEFINE_ARRAY(T, name) define an array class named "name" containing the
347 // elements of simple type T such that sizeof(T) <= sizeof(long)
348 //
349 // Note that the class defined has only inline function and doesn't take any
350 // space at all so there is no size penalty for defining multiple array classes
351 // ----------------------------------------------------------------------------
352
353 #define WX_DEFINE_ARRAY(T, name) \
354 WX_DEFINE_USER_EXPORTED_ARRAY(T, name, wxARRAY_DEFAULT_EXPORT)
355
356 #define WX_DEFINE_EXPORTED_ARRAY(T, name) \
357 WX_DEFINE_USER_EXPORTED_ARRAY(T, name, WXDLLEXPORT)
358
359 #define WX_DEFINE_USER_EXPORTED_ARRAY(T, name, expmode) \
360 typedef T _wxArray##name; \
361 _WX_DEFINE_ARRAY(_wxArray##name, name, class expmode)
362
363 // ----------------------------------------------------------------------------
364 // WX_DEFINE_SORTED_ARRAY: this is the same as the previous macro, but it
365 // defines a sorted array.
366 //
367 // Differences:
368 // 1) it must be given a COMPARE function in ctor which takes 2 items of type
369 // T* and should return -1, 0 or +1 if the first one is less/greater
370 // than/equal to the second one.
371 // 2) the Add() method inserts the item in such was that the array is always
372 // sorted (it uses the COMPARE function)
373 // 3) it has no Sort() method because it's always sorted
374 // 4) Index() method is much faster (the sorted arrays use binary search
375 // instead of linear one), but Add() is slower.
376 // 5) there is no Insert() method because you can't insert an item into the
377 // given position in a sorted array but there is IndexForInsert()/AddAt()
378 // pair which may be used to optimize a common operation of "insert only if
379 // not found"
380 //
381 // Note that you have to specify the comparison function when creating the
382 // objects of this array type. If, as in 99% of cases, the comparison function
383 // is the same for all objects of a class, WX_DEFINE_SORTED_ARRAY_CMP below is
384 // more convenient.
385 //
386 // Summary: use this class when the speed of Index() function is important, use
387 // the normal arrays otherwise.
388 // ----------------------------------------------------------------------------
389
390 #define wxARRAY_EMPTY_CMP
391
392 #define WX_DEFINE_SORTED_ARRAY(T, name) \
393 WX_DEFINE_SORTED_USER_EXPORTED_ARRAY(T, name, wxARRAY_DEFAULT_EXPORT)
394
395 #define WX_DEFINE_SORTED_EXPORTED_ARRAY(T, name) \
396 WX_DEFINE_SORTED_USER_EXPORTED_ARRAY(T, name, WXDLLEXPORT)
397
398 #define WX_DEFINE_SORTED_USER_EXPORTED_ARRAY(T, name, expmode) \
399 typedef T _wxArray##name; \
400 _WX_DEFINE_SORTED_ARRAY(_wxArray##name, name, wxARRAY_EMPTY_CMP, class expmode)
401
402 // ----------------------------------------------------------------------------
403 // WX_DEFINE_SORTED_ARRAY_CMP: exactly the same as above but the comparison
404 // function is provided by this macro and the objects of this class have a
405 // default constructor which just uses it.
406 //
407 // The arguments are: the element type, the comparison function and the array
408 // name
409 //
410 // NB: this is, of course, how WX_DEFINE_SORTED_ARRAY() should have worked from
411 // the very beginning - unfortunately I didn't think about this earlier :-(
412 // ----------------------------------------------------------------------------
413
414 #define WX_DEFINE_SORTED_ARRAY_CMP(T, cmpfunc, name) \
415 WX_DEFINE_SORTED_USER_EXPORTED_ARRAY_CMP(T, cmpfunc, name, \
416 wxARRAY_DEFAULT_EXPORT)
417
418 #define WX_DEFINE_SORTED_EXPORTED_ARRAY_CMP(T, cmpfunc, name) \
419 WX_DEFINE_SORTED_USER_EXPORTED_ARRAY_CMP(T, cmpfunc, name, WXDLLEXPORT)
420
421 #define WX_DEFINE_SORTED_USER_EXPORTED_ARRAY_CMP(T, cmpfunc, name, expmode) \
422 typedef T _wxArray##name; \
423 _WX_DEFINE_SORTED_ARRAY(_wxArray##name, name, = cmpfunc, class expmode)
424
425 // ----------------------------------------------------------------------------
426 // WX_DECLARE_OBJARRAY(T, name): this macro generates a new array class
427 // named "name" which owns the objects of type T it contains, i.e. it will
428 // delete them when it is destroyed.
429 //
430 // An element is of type T*, but arguments of type T& are taken (see below!)
431 // and T& is returned.
432 //
433 // Don't use this for simple types such as "int" or "long"!
434 // You _may_ use it for "double" but it's awfully inefficient.
435 //
436 // Note on Add/Insert functions:
437 // 1) function(T*) gives the object to the array, i.e. it will delete the
438 // object when it's removed or in the array's dtor
439 // 2) function(T&) will create a copy of the object and work with it
440 //
441 // Also:
442 // 1) Remove() will delete the object after removing it from the array
443 // 2) Detach() just removes the object from the array (returning pointer to it)
444 //
445 // NB1: Base type T should have an accessible copy ctor if Add(T&) is used
446 // NB2: Never ever cast a array to it's base type: as dtor is not virtual
447 // and so you risk having at least the memory leaks and probably worse
448 //
449 // Some functions of this class are not inline, so it takes some space to
450 // define new class from this template even if you don't use it - which is not
451 // the case for the simple (non-object) array classes
452 //
453 //
454 // To use an objarray class you must
455 // #include "dynarray.h"
456 // WX_DECLARE_OBJARRAY(element_type, list_class_name)
457 // #include "arrimpl.cpp"
458 // WX_DEFINE_OBJARRAY(list_class_name) // name must be the same as above!
459 //
460 // This is necessary because at the moment of DEFINE_OBJARRAY class parsing the
461 // element_type must be fully defined (i.e. forward declaration is not
462 // enough), while WX_DECLARE_OBJARRAY may be done anywhere. The separation of
463 // two allows to break cicrcular dependencies with classes which have member
464 // variables of objarray type.
465 // ----------------------------------------------------------------------------
466
467 #define WX_DECLARE_OBJARRAY(T, name) \
468 WX_DECLARE_USER_EXPORTED_OBJARRAY(T, name, wxARRAY_DEFAULT_EXPORT)
469
470 #define WX_DECLARE_EXPORTED_OBJARRAY(T, name) \
471 WX_DECLARE_USER_EXPORTED_OBJARRAY(T, name, WXDLLEXPORT)
472
473 #define WX_DECLARE_USER_EXPORTED_OBJARRAY(T, name, expmode) \
474 typedef T _wxObjArray##name; \
475 _WX_DECLARE_OBJARRAY(_wxObjArray##name, name, class expmode)
476
477 // WX_DEFINE_OBJARRAY is going to be redefined when arrimpl.cpp is included,
478 // try to provoke a human-understandable error if it used incorrectly.
479 //
480 // there is no real need for 3 different macros in the DEFINE case but do it
481 // anyhow for consistency
482 #define WX_DEFINE_OBJARRAY(name) DidYouIncludeArrimplCpp
483 #define WX_DEFINE_EXPORTED_OBJARRAY(name) WX_DEFINE_OBJARRAY(name)
484 #define WX_DEFINE_USER_EXPORTED_OBJARRAY(name) WX_DEFINE_OBJARRAY(name)
485
486 // ----------------------------------------------------------------------------
487 // Some commonly used predefined arrays
488 // ----------------------------------------------------------------------------
489
490 WX_DEFINE_EXPORTED_ARRAY(int, wxArrayInt);
491 WX_DEFINE_EXPORTED_ARRAY(long, wxArrayLong);
492 WX_DEFINE_EXPORTED_ARRAY(void *, wxArrayPtrVoid);
493
494 // -----------------------------------------------------------------------------
495 // convenience macros
496 // -----------------------------------------------------------------------------
497
498 // append all element of one array to another one
499 #define WX_APPEND_ARRAY(array, other) \
500 { \
501 size_t count = (other).Count(); \
502 for ( size_t n = 0; n < count; n++ ) \
503 { \
504 (array).Add((other)[n]); \
505 } \
506 }
507
508 // delete all array elements
509 //
510 // NB: the class declaration of the array elements must be visible from the
511 // place where you use this macro, otherwise the proper destructor may not
512 // be called (a decent compiler should give a warning about it, but don't
513 // count on it)!
514 #define WX_CLEAR_ARRAY(array) \
515 { \
516 size_t count = (array).Count(); \
517 for ( size_t n = 0; n < count; n++ ) \
518 { \
519 delete (array)[n]; \
520 } \
521 \
522 (array).Empty(); \
523 }
524
525 #endif // _DYNARRAY_H
526