OLD | NEW |
| (Empty) |
1 // Common/MyVector.cpp | |
2 | |
3 #include "StdAfx.h" | |
4 | |
5 #include <string.h> | |
6 | |
7 #include "MyVector.h" | |
8 | |
9 CBaseRecordVector::~CBaseRecordVector() { ClearAndFree(); } | |
10 | |
11 void CBaseRecordVector::ClearAndFree() | |
12 { | |
13 Clear(); | |
14 delete []((unsigned char *)_items); | |
15 _capacity = 0; | |
16 _size = 0; | |
17 _items = 0; | |
18 } | |
19 | |
20 void CBaseRecordVector::Clear() { DeleteFrom(0); } | |
21 void CBaseRecordVector::DeleteBack() { Delete(_size - 1); } | |
22 void CBaseRecordVector::DeleteFrom(int index) { Delete(index, _size - index); } | |
23 | |
24 void CBaseRecordVector::ReserveOnePosition() | |
25 { | |
26 if (_size != _capacity) | |
27 return; | |
28 int delta = 1; | |
29 if (_capacity >= 64) | |
30 delta = _capacity / 4; | |
31 else if (_capacity >= 8) | |
32 delta = 8; | |
33 Reserve(_capacity + delta); | |
34 } | |
35 | |
36 void CBaseRecordVector::Reserve(int newCapacity) | |
37 { | |
38 // if (newCapacity <= _capacity) | |
39 if (newCapacity == _capacity) | |
40 return; | |
41 if ((unsigned)newCapacity >= ((unsigned)1 << (sizeof(unsigned) * 8 - 1))) | |
42 throw 1052353; | |
43 size_t newSize = (size_t)(unsigned)newCapacity * _itemSize; | |
44 if (newSize / _itemSize != (size_t)(unsigned)newCapacity) | |
45 throw 1052354; | |
46 unsigned char *p = NULL; | |
47 if (newSize > 0) | |
48 { | |
49 p = new unsigned char[newSize]; | |
50 if (p == 0) | |
51 throw 1052355; | |
52 int numRecordsToMove = (_size < newCapacity ? _size : newCapacity); | |
53 memcpy(p, _items, _itemSize * numRecordsToMove); | |
54 } | |
55 delete [](unsigned char *)_items; | |
56 _items = p; | |
57 _capacity = newCapacity; | |
58 } | |
59 | |
60 void CBaseRecordVector::ReserveDown() | |
61 { | |
62 Reserve(_size); | |
63 } | |
64 | |
65 void CBaseRecordVector::MoveItems(int destIndex, int srcIndex) | |
66 { | |
67 memmove(((unsigned char *)_items) + destIndex * _itemSize, | |
68 ((unsigned char *)_items) + srcIndex * _itemSize, | |
69 _itemSize * (_size - srcIndex)); | |
70 } | |
71 | |
72 void CBaseRecordVector::InsertOneItem(int index) | |
73 { | |
74 ReserveOnePosition(); | |
75 MoveItems(index + 1, index); | |
76 _size++; | |
77 } | |
78 | |
79 void CBaseRecordVector::Delete(int index, int num) | |
80 { | |
81 TestIndexAndCorrectNum(index, num); | |
82 if (num > 0) | |
83 { | |
84 MoveItems(index, index + num); | |
85 _size -= num; | |
86 } | |
87 } | |
OLD | NEW |