1 // Common/MyVector.cpp
2 
3 #include "StdAfx.h"
4 
5 #include <string.h>
6 
7 #include "MyVector.h"
8 
~CBaseRecordVector()9 CBaseRecordVector::~CBaseRecordVector() { ClearAndFree(); }
10 
ClearAndFree()11 void CBaseRecordVector::ClearAndFree()
12 {
13   Clear();
14   delete []((unsigned char *)_items);
15   _capacity = 0;
16   _size = 0;
17   _items = 0;
18 }
19 
Clear()20 void CBaseRecordVector::Clear() { DeleteFrom(0); }
DeleteBack()21 void CBaseRecordVector::DeleteBack() { Delete(_size - 1); }
DeleteFrom(int index)22 void CBaseRecordVector::DeleteFrom(int index) { Delete(index, _size - index); }
23 
ReserveOnePosition()24 void CBaseRecordVector::ReserveOnePosition()
25 {
26   if (_size != _capacity)
27     return;
28   unsigned delta = 1;
29   if (_capacity >= 64)
30     delta = (unsigned)_capacity / 4;
31   else if (_capacity >= 8)
32     delta = 8;
33   Reserve(_capacity + (int)delta);
34 }
35 
Reserve(int newCapacity)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 
ReserveDown()60 void CBaseRecordVector::ReserveDown()
61 {
62   Reserve(_size);
63 }
64 
MoveItems(int destIndex,int srcIndex)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 
InsertOneItem(int index)72 void CBaseRecordVector::InsertOneItem(int index)
73 {
74   ReserveOnePosition();
75   MoveItems(index + 1, index);
76   _size++;
77 }
78 
Delete(int index,int num)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 }
88