- } else {
- int32_t newCap = capacity * 2;
- if (newCap < minimumCapacity) {
- newCap = minimumCapacity;
- }
- int32_t* newElems = (int32_t *)uprv_malloc(sizeof(int32_t)*newCap);
- if (newElems == 0) {
- status = U_MEMORY_ALLOCATION_ERROR;
- return FALSE;
- }
- uprv_memcpy(newElems, elements, sizeof(elements[0]) * count);
- uprv_free(elements);
- elements = newElems;
- capacity = newCap;
- return TRUE;
+ }
+ if (maxCapacity>0 && minimumCapacity>maxCapacity) {
+ status = U_BUFFER_OVERFLOW_ERROR;
+ return FALSE;
+ }
+ int32_t newCap = capacity * 2;
+ if (newCap < minimumCapacity) {
+ newCap = minimumCapacity;
+ }
+ if (maxCapacity > 0 && newCap > maxCapacity) {
+ newCap = maxCapacity;
+ }
+ int32_t* newElems = (int32_t *)uprv_realloc(elements, sizeof(int32_t)*newCap);
+ if (newElems == NULL) {
+ // We keep the original contents on the memory failure on realloc.
+ status = U_MEMORY_ALLOCATION_ERROR;
+ return FALSE;
+ }
+ elements = newElems;
+ capacity = newCap;
+ return TRUE;
+}
+
+void UVector32::setMaxCapacity(int32_t limit) {
+ U_ASSERT(limit >= 0);
+ maxCapacity = limit;
+ if (maxCapacity < 0) {
+ maxCapacity = 0;
+ }
+ if (capacity <= maxCapacity || maxCapacity == 0) {
+ // Current capacity is within the new limit.
+ return;
+ }
+
+ // New maximum capacity is smaller than the current size.
+ // Realloc the storage to the new, smaller size.
+ int32_t* newElems = (int32_t *)uprv_realloc(elements, sizeof(int32_t)*maxCapacity);
+ if (newElems == NULL) {
+ // Realloc to smaller failed.
+ // Just keep what we had. No need to call it a failure.
+ return;
+ }
+ elements = newElems;
+ capacity = maxCapacity;
+ if (count > capacity) {
+ count = capacity;