]> git.saurik.com Git - wxWidgets.git/blame_incremental - include/wx/vector.h
fixing overrelease and out-of-bounds write, fixes #13725
[wxWidgets.git] / include / wx / vector.h
... / ...
CommitLineData
1///////////////////////////////////////////////////////////////////////////////
2// Name: wx/vector.h
3// Purpose: STL vector clone
4// Author: Lindsay Mathieson
5// Modified by: Vaclav Slavik - make it a template
6// Created: 30.07.2001
7// Copyright: (c) 2001 Lindsay Mathieson <lindsay@mathieson.org>,
8// 2007 Vaclav Slavik <vslavik@fastmail.fm>
9// Licence: wxWindows licence
10///////////////////////////////////////////////////////////////////////////////
11
12#ifndef _WX_VECTOR_H_
13#define _WX_VECTOR_H_
14
15#include "wx/defs.h"
16
17#if wxUSE_STD_CONTAINERS
18
19#include <vector>
20#include <algorithm>
21
22#define wxVector std::vector
23template<typename T>
24inline void wxVectorSort(wxVector<T>& v)
25{
26 std::sort(v.begin(), v.end());
27}
28
29#else // !wxUSE_STD_CONTAINERS
30
31#include "wx/utils.h"
32#include "wx/scopeguard.h"
33#include "wx/meta/movable.h"
34#include "wx/meta/if.h"
35
36#include "wx/beforestd.h"
37#include <new> // for placement new
38#include "wx/afterstd.h"
39
40namespace wxPrivate
41{
42
43// These templates encapsulate memory operations for use by wxVector; there are
44// two implementations, both in generic way for any C++ types and as an
45// optimized version for "movable" types that uses realloc() and memmove().
46
47// version for movable types:
48template<typename T>
49struct wxVectorMemOpsMovable
50{
51 static void Free(T* array)
52 { free(array); }
53
54 static T* Realloc(T* old, size_t newCapacity, size_t WXUNUSED(occupiedSize))
55 { return (T*)realloc(old, newCapacity * sizeof(T)); }
56
57 static void MemmoveBackward(T* dest, T* source, size_t count)
58 { memmove(dest, source, count * sizeof(T)); }
59
60 static void MemmoveForward(T* dest, T* source, size_t count)
61 { memmove(dest, source, count * sizeof(T)); }
62};
63
64// generic version for non-movable types:
65template<typename T>
66struct wxVectorMemOpsGeneric
67{
68 static void Free(T* array)
69 { ::operator delete(array); }
70
71 static T* Realloc(T* old, size_t newCapacity, size_t occupiedSize)
72 {
73 T *mem = (T*)::operator new(newCapacity * sizeof(T));
74 for ( size_t i = 0; i < occupiedSize; i++ )
75 {
76 ::new(mem + i) T(old[i]);
77 old[i].~T();
78 }
79 ::operator delete(old);
80 return mem;
81 }
82
83 static void MemmoveBackward(T* dest, T* source, size_t count)
84 {
85 wxASSERT( dest < source );
86 T* destptr = dest;
87 T* sourceptr = source;
88 for ( size_t i = count; i > 0; --i, ++destptr, ++sourceptr )
89 {
90 ::new(destptr) T(*sourceptr);
91 sourceptr->~T();
92 }
93 }
94
95 static void MemmoveForward(T* dest, T* source, size_t count)
96 {
97 wxASSERT( dest > source );
98 T* destptr = dest + count - 1;
99 T* sourceptr = source + count - 1;
100 for ( size_t i = count; i > 0; --i, --destptr, --sourceptr )
101 {
102 ::new(destptr) T(*sourceptr);
103 sourceptr->~T();
104 }
105 }
106};
107
108
109} // namespace wxPrivate
110
111template<typename T>
112class wxVector
113{
114private:
115 // This cryptic expression means "typedef Ops to wxVectorMemOpsMovable if
116 // type T is movable type, otherwise to wxVectorMemOpsGeneric".
117 //
118 // Note that we use typedef instead of privately deriving from this (which
119 // would allowed us to omit "Ops::" prefixes below) to keep VC6 happy,
120 // it can't compile code that derives from wxIf<...>::value.
121 //
122 // Note that bcc needs the extra parentheses for non-type template
123 // arguments to compile this expression.
124 typedef typename wxIf< (wxIsMovable<T>::value),
125 wxPrivate::wxVectorMemOpsMovable<T>,
126 wxPrivate::wxVectorMemOpsGeneric<T> >::value
127 Ops;
128
129public:
130 typedef size_t size_type;
131 typedef size_t difference_type;
132 typedef T value_type;
133 typedef value_type* pointer;
134 typedef value_type* iterator;
135 typedef const value_type* const_iterator;
136 typedef value_type& reference;
137
138 class reverse_iterator
139 {
140 public:
141 reverse_iterator() : m_ptr(NULL) { }
142 wxEXPLICIT reverse_iterator(iterator it) : m_ptr(it) { }
143 reverse_iterator(const reverse_iterator& it) : m_ptr(it.m_ptr) { }
144
145 reference operator*() const { return *m_ptr; }
146 pointer operator->() const { return m_ptr; }
147
148 iterator base() const { return m_ptr; }
149
150 reverse_iterator& operator++()
151 { --m_ptr; return *this; }
152 reverse_iterator operator++(int)
153 { reverse_iterator tmp = *this; --m_ptr; return tmp; }
154 reverse_iterator& operator--()
155 { ++m_ptr; return *this; }
156 reverse_iterator operator--(int)
157 { reverse_iterator tmp = *this; ++m_ptr; return tmp; }
158
159 reverse_iterator operator+(difference_type n) const
160 { return reverse_iterator(m_ptr - n); }
161 reverse_iterator& operator+=(difference_type n)
162 { m_ptr -= n; return *this; }
163 reverse_iterator operator-(difference_type n) const
164 { return reverse_iterator(m_ptr + n); }
165 reverse_iterator& operator-=(difference_type n)
166 { m_ptr += n; return *this; }
167
168 reference operator[](difference_type n) const
169 { return *(*this + n); }
170
171 bool operator ==(const reverse_iterator& it) const
172 { return m_ptr == it.m_ptr; }
173 bool operator !=(const reverse_iterator& it) const
174 { return m_ptr != it.m_ptr; }
175
176 private:
177 value_type *m_ptr;
178 };
179
180 wxVector() : m_size(0), m_capacity(0), m_values(NULL) {}
181
182 wxVector(size_type p_size)
183 : m_size(0), m_capacity(0), m_values(NULL)
184 {
185 reserve(p_size);
186 for ( size_t n = 0; n < p_size; n++ )
187 push_back(value_type());
188 }
189
190 wxVector(size_type p_size, const value_type& v)
191 : m_size(0), m_capacity(0), m_values(NULL)
192 {
193 reserve(p_size);
194 for ( size_t n = 0; n < p_size; n++ )
195 push_back(v);
196 }
197
198 wxVector(const wxVector& c) : m_size(0), m_capacity(0), m_values(NULL)
199 {
200 Copy(c);
201 }
202
203 ~wxVector()
204 {
205 clear();
206 }
207
208 void assign(size_type p_size, const value_type& v)
209 {
210 clear();
211 reserve(p_size);
212 for ( size_t n = 0; n < p_size; n++ )
213 push_back(v);
214 }
215
216 void swap(wxVector& v)
217 {
218 wxSwap(m_size, v.m_size);
219 wxSwap(m_capacity, v.m_capacity);
220 wxSwap(m_values, v.m_values);
221 }
222
223 void clear()
224 {
225 // call destructors of stored objects:
226 for ( size_type i = 0; i < m_size; i++ )
227 {
228 m_values[i].~T();
229 }
230
231 Ops::Free(m_values);
232 m_values = NULL;
233 m_size =
234 m_capacity = 0;
235 }
236
237 void reserve(size_type n)
238 {
239 if ( n <= m_capacity )
240 return;
241
242 // increase the size twice, unless we're already too big or unless
243 // more is requested
244 //
245 // NB: casts to size_type are needed to suppress mingw32 warnings about
246 // mixing enums and ints in the same expression
247 const size_type increment = m_size > 0
248 ? wxMin(m_size, (size_type)ALLOC_MAX_SIZE)
249 : (size_type)ALLOC_INITIAL_SIZE;
250 if ( m_capacity + increment > n )
251 n = m_capacity + increment;
252
253 m_values = Ops::Realloc(m_values, n * sizeof(value_type), m_size);
254 m_capacity = n;
255 }
256
257 void resize(size_type n)
258 {
259 if ( n < m_size )
260 Shrink(n);
261 else if ( n > m_size )
262 Extend(n, value_type());
263 }
264
265 void resize(size_type n, const value_type& v)
266 {
267 if ( n < m_size )
268 Shrink(n);
269 else if ( n > m_size )
270 Extend(n, v);
271 }
272
273 size_type size() const
274 {
275 return m_size;
276 }
277
278 size_type capacity() const
279 {
280 return m_capacity;
281 }
282
283 bool empty() const
284 {
285 return size() == 0;
286 }
287
288 wxVector& operator=(const wxVector& vb)
289 {
290 if (this != &vb)
291 {
292 clear();
293 Copy(vb);
294 }
295 return *this;
296 }
297
298 void push_back(const value_type& v)
299 {
300 reserve(size() + 1);
301
302 // use placement new to initialize new object in preallocated place in
303 // m_values and store 'v' in it:
304 void* const place = m_values + m_size;
305 ::new(place) value_type(v);
306
307 // only increase m_size if the ctor didn't throw an exception; notice
308 // that if it _did_ throw, everything is OK, because we only increased
309 // vector's capacity so far and possibly written some data to
310 // uninitialized memory at the end of m_values
311 m_size++;
312 }
313
314 void pop_back()
315 {
316 erase(end() - 1);
317 }
318
319 const value_type& at(size_type idx) const
320 {
321 wxASSERT(idx < m_size);
322 return m_values[idx];
323 }
324
325 value_type& at(size_type idx)
326 {
327 wxASSERT(idx < m_size);
328 return m_values[idx];
329 }
330
331 const value_type& operator[](size_type idx) const { return at(idx); }
332 value_type& operator[](size_type idx) { return at(idx); }
333 const value_type& front() const { return at(0); }
334 value_type& front() { return at(0); }
335 const value_type& back() const { return at(size() - 1); }
336 value_type& back() { return at(size() - 1); }
337
338 const_iterator begin() const { return m_values; }
339 iterator begin() { return m_values; }
340 const_iterator end() const { return m_values + size(); }
341 iterator end() { return m_values + size(); }
342
343 reverse_iterator rbegin() { return reverse_iterator(end() - 1); }
344 reverse_iterator rend() { return reverse_iterator(begin() - 1); }
345
346 iterator insert(iterator it, const value_type& v = value_type())
347 {
348 // NB: this must be done before reserve(), because reserve()
349 // invalidates iterators!
350 const size_t idx = it - begin();
351 const size_t after = end() - it;
352
353 reserve(size() + 1);
354
355 // the place where the new element is going to be inserted
356 value_type * const place = m_values + idx;
357
358 // unless we're inserting at the end, move following elements out of
359 // the way:
360 if ( after > 0 )
361 Ops::MemmoveForward(place + 1, place, after);
362
363 // if the ctor called below throws an exception, we need to move all
364 // the elements back to their original positions in m_values
365 wxScopeGuard moveBack = wxMakeGuard(
366 Ops::MemmoveBackward, place, place + 1, after);
367 if ( !after )
368 moveBack.Dismiss();
369
370 // use placement new to initialize new object in preallocated place in
371 // m_values and store 'v' in it:
372 ::new(place) value_type(v);
373
374 // now that we did successfully add the new element, increment the size
375 // and disable moving the items back
376 moveBack.Dismiss();
377 m_size++;
378
379 return begin() + idx;
380 }
381
382 iterator erase(iterator it)
383 {
384 return erase(it, it + 1);
385 }
386
387 iterator erase(iterator first, iterator last)
388 {
389 if ( first == last )
390 return first;
391 wxASSERT( first < end() && last <= end() );
392
393 const size_type idx = first - begin();
394 const size_type count = last - first;
395 const size_type after = end() - last;
396
397 // erase elements by calling their destructors:
398 for ( iterator i = first; i < last; ++i )
399 i->~T();
400
401 // once that's done, move following elements over to the freed space:
402 if ( after > 0 )
403 {
404 Ops::MemmoveBackward(m_values + idx, m_values + idx + count, after);
405 }
406
407 m_size -= count;
408
409 return begin() + idx;
410 }
411
412#if WXWIN_COMPATIBILITY_2_8
413 wxDEPRECATED( size_type erase(size_type n) );
414#endif // WXWIN_COMPATIBILITY_2_8
415
416private:
417 // VC6 can't compile static const int members
418 enum { ALLOC_INITIAL_SIZE = 16 };
419 enum { ALLOC_MAX_SIZE = 4096 };
420
421 void Copy(const wxVector& vb)
422 {
423 reserve(vb.size());
424
425 for ( const_iterator i = vb.begin(); i != vb.end(); ++i )
426 push_back(*i);
427 }
428
429private:
430 void Shrink(size_type n)
431 {
432 for ( size_type i = n; i < m_size; i++ )
433 m_values[i].~T();
434 m_size = n;
435 }
436
437 void Extend(size_type n, const value_type& v)
438 {
439 reserve(n);
440 for ( size_type i = m_size; i < n; i++ )
441 push_back(v);
442 }
443
444 size_type m_size,
445 m_capacity;
446 value_type *m_values;
447};
448
449#if WXWIN_COMPATIBILITY_2_8
450template<typename T>
451inline typename wxVector<T>::size_type wxVector<T>::erase(size_type n)
452{
453 erase(begin() + n);
454 return n;
455}
456#endif // WXWIN_COMPATIBILITY_2_8
457
458
459
460namespace wxPrivate
461{
462
463// This is a helper for the wxVectorSort function, and should not be used
464// directly in user's code.
465template<typename T>
466struct wxVectorComparator
467{
468 static int
469 Compare(const void* pitem1, const void* pitem2, const void* )
470 {
471 const T& item1 = *reinterpret_cast<const T*>(pitem1);
472 const T& item2 = *reinterpret_cast<const T*>(pitem2);
473
474 if (item1 < item2)
475 return -1;
476 else if (item2 < item1)
477 return 1;
478 else
479 return 0;
480 }
481};
482
483} // namespace wxPrivate
484
485
486
487template<typename T>
488void wxVectorSort(wxVector<T>& v)
489{
490 wxQsort(v.begin(), v.size(), sizeof(T),
491 wxPrivate::wxVectorComparator<T>::Compare, NULL);
492}
493
494
495
496#endif // wxUSE_STD_CONTAINERS/!wxUSE_STD_CONTAINERS
497
498#if WXWIN_COMPATIBILITY_2_8
499 #define WX_DECLARE_VECTORBASE(obj, cls) typedef wxVector<obj> cls
500 #define _WX_DECLARE_VECTOR(obj, cls, exp) WX_DECLARE_VECTORBASE(obj, cls)
501 #define WX_DECLARE_VECTOR(obj, cls) WX_DECLARE_VECTORBASE(obj, cls)
502#endif // WXWIN_COMPATIBILITY_2_8
503
504#endif // _WX_VECTOR_H_