]>
git.saurik.com Git - apple/icu.git/blob - icuSources/common/cmemory.h
1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
4 ******************************************************************************
6 * Copyright (C) 1997-2016, International Business Machines
7 * Corporation and others. All Rights Reserved.
9 ******************************************************************************
13 * Contains stdlib.h/string.h memory functions
15 * @author Bertrand A. Damiba
17 * Modification History:
19 * Date Name Description
20 * 6/20/98 Bertrand Created.
21 * 05/03/99 stephen Changed from functions to macros.
23 ******************************************************************************
29 #include "unicode/utypes.h"
33 #include "unicode/localpointer.h"
35 #if U_DEBUG && defined(UPRV_MALLOC_COUNT)
40 #define uprv_memcpy(dst, src, size) U_STANDARD_CPP_NAMESPACE memcpy(dst, src, size)
41 #define uprv_memmove(dst, src, size) U_STANDARD_CPP_NAMESPACE memmove(dst, src, size)
45 * Convenience macro to determine the length of a fixed array at compile-time.
46 * @param array A fixed length array
47 * @return The length of the array, in elements
50 #define UPRV_LENGTHOF(array) (int32_t)(sizeof(array)/sizeof((array)[0]))
51 #define uprv_memset(buffer, mark, size) U_STANDARD_CPP_NAMESPACE memset(buffer, mark, size)
52 #define uprv_memcmp(buffer1, buffer2, size) U_STANDARD_CPP_NAMESPACE memcmp(buffer1, buffer2,size)
54 U_CAPI
void * U_EXPORT2
55 uprv_malloc(size_t s
) U_MALLOC_ATTR
U_ALLOC_SIZE_ATTR(1);
57 U_CAPI
void * U_EXPORT2
58 uprv_realloc(void *mem
, size_t size
) U_ALLOC_SIZE_ATTR(2);
63 U_CAPI
void * U_EXPORT2
64 uprv_calloc(size_t num
, size_t size
) U_MALLOC_ATTR
U_ALLOC_SIZE_ATTR2(1,2);
67 * This should align the memory properly on any machine.
68 * This is very useful for the safeClone functions.
77 * Get the least significant bits of a pointer (a memory address).
78 * For example, with a mask of 3, the macro gets the 2 least significant bits,
79 * which will be 0 if the pointer is 32-bit (4-byte) aligned.
81 * ptrdiff_t is the most appropriate integer type to cast to.
82 * size_t should work too, since on most (or all?) platforms it has the same
85 #define U_POINTER_MASK_LSB(ptr, mask) (((ptrdiff_t)(char *)(ptr)) & (mask))
88 * Get the amount of bytes that a pointer is off by from
89 * the previous UAlignedMemory-aligned pointer.
91 #define U_ALIGNMENT_OFFSET(ptr) U_POINTER_MASK_LSB(ptr, sizeof(UAlignedMemory) - 1)
94 * Get the amount of bytes to add to a pointer
95 * in order to get the next UAlignedMemory-aligned address.
97 #define U_ALIGNMENT_OFFSET_UP(ptr) (sizeof(UAlignedMemory) - U_ALIGNMENT_OFFSET(ptr))
100 * Heap clean up function, called from u_cleanup()
101 * Clears any user heap functions from u_setMemoryFunctions()
102 * Does NOT deallocate any remaining allocated memory.
105 cmemory_cleanup(void);
108 * A function called by <TT>uhash_remove</TT>,
109 * <TT>uhash_close</TT>, or <TT>uhash_put</TT> to delete
110 * an existing key or value.
111 * @param obj A key or value stored in a hashtable
112 * @see uprv_deleteUObject
114 typedef void U_CALLCONV
UObjectDeleter(void* obj
);
117 * Deleter for UObject instances.
118 * Works for all subclasses of UObject because it has a virtual destructor.
120 U_CAPI
void U_EXPORT2
121 uprv_deleteUObject(void *obj
);
128 * "Smart pointer" class, deletes memory via uprv_free().
129 * For most methods see the LocalPointerBase base class.
130 * Adds operator[] for array item access.
132 * @see LocalPointerBase
135 class LocalMemory
: public LocalPointerBase
<T
> {
137 using LocalPointerBase
<T
>::operator*;
138 using LocalPointerBase
<T
>::operator->;
140 * Constructor takes ownership.
141 * @param p simple pointer to an array of T items that is adopted
143 explicit LocalMemory(T
*p
=NULL
) : LocalPointerBase
<T
>(p
) {}
145 * Move constructor, leaves src with isNull().
146 * @param src source smart pointer
148 LocalMemory(LocalMemory
<T
> &&src
) U_NOEXCEPT
: LocalPointerBase
<T
>(src
.ptr
) {
152 * Destructor deletes the memory it owns.
155 uprv_free(LocalPointerBase
<T
>::ptr
);
158 * Move assignment operator, leaves src with isNull().
159 * The behavior is undefined if *this and src are the same object.
160 * @param src source smart pointer
163 LocalMemory
<T
> &operator=(LocalMemory
<T
> &&src
) U_NOEXCEPT
{
164 return moveFrom(src
);
167 * Move assignment, leaves src with isNull().
168 * The behavior is undefined if *this and src are the same object.
170 * Can be called explicitly, does not need C++11 support.
171 * @param src source smart pointer
174 LocalMemory
<T
> &moveFrom(LocalMemory
<T
> &src
) U_NOEXCEPT
{
175 delete[] LocalPointerBase
<T
>::ptr
;
176 LocalPointerBase
<T
>::ptr
=src
.ptr
;
182 * @param other other smart pointer
184 void swap(LocalMemory
<T
> &other
) U_NOEXCEPT
{
185 T
*temp
=LocalPointerBase
<T
>::ptr
;
186 LocalPointerBase
<T
>::ptr
=other
.ptr
;
190 * Non-member LocalMemory swap function.
191 * @param p1 will get p2's pointer
192 * @param p2 will get p1's pointer
194 friend inline void swap(LocalMemory
<T
> &p1
, LocalMemory
<T
> &p2
) U_NOEXCEPT
{
198 * Deletes the array it owns,
199 * and adopts (takes ownership of) the one passed in.
200 * @param p simple pointer to an array of T items that is adopted
202 void adoptInstead(T
*p
) {
203 uprv_free(LocalPointerBase
<T
>::ptr
);
204 LocalPointerBase
<T
>::ptr
=p
;
207 * Deletes the array it owns, allocates a new one and reset its bytes to 0.
208 * Returns the new array pointer.
209 * If the allocation fails, then the current array is unchanged and
210 * this method returns NULL.
211 * @param newCapacity must be >0
212 * @return the allocated array pointer, or NULL if the allocation failed
214 inline T
*allocateInsteadAndReset(int32_t newCapacity
=1);
216 * Deletes the array it owns and allocates a new one, copying length T items.
217 * Returns the new array pointer.
218 * If the allocation fails, then the current array is unchanged and
219 * this method returns NULL.
220 * @param newCapacity must be >0
221 * @param length number of T items to be copied from the old array to the new one;
222 * must be no more than the capacity of the old array,
223 * which the caller must track because the LocalMemory does not track it
224 * @return the allocated array pointer, or NULL if the allocation failed
226 inline T
*allocateInsteadAndCopy(int32_t newCapacity
=1, int32_t length
=0);
228 * Array item access (writable).
229 * No index bounds check.
230 * @param i array index
231 * @return reference to the array item
233 T
&operator[](ptrdiff_t i
) const { return LocalPointerBase
<T
>::ptr
[i
]; }
237 inline T
*LocalMemory
<T
>::allocateInsteadAndReset(int32_t newCapacity
) {
239 T
*p
=(T
*)uprv_malloc(newCapacity
*sizeof(T
));
241 uprv_memset(p
, 0, newCapacity
*sizeof(T
));
242 uprv_free(LocalPointerBase
<T
>::ptr
);
243 LocalPointerBase
<T
>::ptr
=p
;
253 inline T
*LocalMemory
<T
>::allocateInsteadAndCopy(int32_t newCapacity
, int32_t length
) {
255 T
*p
=(T
*)uprv_malloc(newCapacity
*sizeof(T
));
258 if(length
>newCapacity
) {
261 uprv_memcpy(p
, LocalPointerBase
<T
>::ptr
, (size_t)length
*sizeof(T
));
263 uprv_free(LocalPointerBase
<T
>::ptr
);
264 LocalPointerBase
<T
>::ptr
=p
;
273 * Simple array/buffer management class using uprv_malloc() and uprv_free().
274 * Provides an internal array with fixed capacity. Can alias another array
277 * The array address is properly aligned for type T. It might not be properly
278 * aligned for types larger than T (or larger than the largest subtype of T).
280 * Unlike LocalMemory and LocalArray, this class never adopts
281 * (takes ownership of) another array.
283 template<typename T
, int32_t stackCapacity
>
284 class MaybeStackArray
{
287 * Default constructor initializes with internal T[stackCapacity] buffer.
289 MaybeStackArray() : ptr(stackArray
), capacity(stackCapacity
), needToRelease(FALSE
) {}
291 * Automatically allocates the heap array if the argument is larger than the stack capacity.
292 * Intended for use when an approximate capacity is known at compile time but the true
293 * capacity is not known until runtime.
295 MaybeStackArray(int32_t newCapacity
) : MaybeStackArray() {
296 if (capacity
< newCapacity
) { resize(newCapacity
); }
299 * Destructor deletes the array (if owned).
301 ~MaybeStackArray() { releaseArray(); }
303 * Move constructor: transfers ownership or copies the stack array.
305 MaybeStackArray(MaybeStackArray
<T
, stackCapacity
> &&src
) U_NOEXCEPT
;
307 * Move assignment: transfers ownership or copies the stack array.
309 MaybeStackArray
<T
, stackCapacity
> &operator=(MaybeStackArray
<T
, stackCapacity
> &&src
) U_NOEXCEPT
;
311 * Returns the array capacity (number of T items).
312 * @return array capacity
314 int32_t getCapacity() const { return capacity
; }
316 * Access without ownership change.
317 * @return the array pointer
319 T
*getAlias() const { return ptr
; }
321 * Returns the array limit. Simple convenience method.
322 * @return getAlias()+getCapacity()
324 T
*getArrayLimit() const { return getAlias()+capacity
; }
325 // No "operator T *() const" because that can make
326 // expressions like mbs[index] ambiguous for some compilers.
328 * Array item access (const).
329 * No index bounds check.
330 * @param i array index
331 * @return reference to the array item
333 const T
&operator[](ptrdiff_t i
) const { return ptr
[i
]; }
335 * Array item access (writable).
336 * No index bounds check.
337 * @param i array index
338 * @return reference to the array item
340 T
&operator[](ptrdiff_t i
) { return ptr
[i
]; }
342 * Deletes the array (if owned) and aliases another one, no transfer of ownership.
343 * If the arguments are illegal, then the current array is unchanged.
344 * @param otherArray must not be NULL
345 * @param otherCapacity must be >0
347 void aliasInstead(T
*otherArray
, int32_t otherCapacity
) {
348 if(otherArray
!=NULL
&& otherCapacity
>0) {
351 capacity
=otherCapacity
;
356 * Deletes the array (if owned) and allocates a new one, copying length T items.
357 * Returns the new array pointer.
358 * If the allocation fails, then the current array is unchanged and
359 * this method returns NULL.
360 * @param newCapacity can be less than or greater than the current capacity;
362 * @param length number of T items to be copied from the old array to the new one
363 * @return the allocated array pointer, or NULL if the allocation failed
365 inline T
*resize(int32_t newCapacity
, int32_t length
=0);
367 * Gives up ownership of the array if owned, or else clones it,
368 * copying length T items; resets itself to the internal stack array.
369 * Returns NULL if the allocation failed.
370 * @param length number of T items to copy when cloning,
371 * and capacity of the clone when cloning
372 * @param resultCapacity will be set to the returned array's capacity (output-only)
373 * @return the array pointer;
374 * caller becomes responsible for deleting the array
376 inline T
*orphanOrClone(int32_t length
, int32_t &resultCapacity
);
381 T stackArray
[stackCapacity
];
382 void releaseArray() {
387 void resetToStackArray() {
389 capacity
=stackCapacity
;
392 /* No comparison operators with other MaybeStackArray's. */
393 bool operator==(const MaybeStackArray
& /*other*/) {return FALSE
;}
394 bool operator!=(const MaybeStackArray
& /*other*/) {return TRUE
;}
395 /* No ownership transfer: No copy constructor, no assignment operator. */
396 MaybeStackArray(const MaybeStackArray
& /*other*/) {}
397 void operator=(const MaybeStackArray
& /*other*/) {}
399 // No heap allocation. Use only on the stack.
400 // (Declaring these functions private triggers a cascade of problems:
401 // MSVC insists on exporting an instantiation of MaybeStackArray, which
402 // requires that all functions be defined.
403 // An empty implementation of new() is rejected, it must return a value.
404 // Returning NULL is rejected by gcc for operator new.
405 // The expedient thing is just not to override operator new.
406 // While relatively pointless, heap allocated instances will function.
407 // static void * U_EXPORT2 operator new(size_t size);
408 // static void * U_EXPORT2 operator new[](size_t size);
409 #if U_HAVE_PLACEMENT_NEW
410 // static void * U_EXPORT2 operator new(size_t, void *ptr);
414 template<typename T
, int32_t stackCapacity
>
415 icu::MaybeStackArray
<T
, stackCapacity
>::MaybeStackArray(
416 MaybeStackArray
<T
, stackCapacity
>&& src
) U_NOEXCEPT
417 : ptr(src
.ptr
), capacity(src
.capacity
), needToRelease(src
.needToRelease
) {
418 if (src
.ptr
== src
.stackArray
) {
420 uprv_memcpy(stackArray
, src
.stackArray
, sizeof(T
) * src
.capacity
);
422 src
.resetToStackArray(); // take ownership away from src
426 template<typename T
, int32_t stackCapacity
>
427 inline MaybeStackArray
<T
, stackCapacity
>&
428 MaybeStackArray
<T
, stackCapacity
>::operator=(MaybeStackArray
<T
, stackCapacity
>&& src
) U_NOEXCEPT
{
429 releaseArray(); // in case this instance had its own memory allocated
430 capacity
= src
.capacity
;
431 needToRelease
= src
.needToRelease
;
432 if (src
.ptr
== src
.stackArray
) {
434 uprv_memcpy(stackArray
, src
.stackArray
, sizeof(T
) * src
.capacity
);
437 src
.resetToStackArray(); // take ownership away from src
442 template<typename T
, int32_t stackCapacity
>
443 inline T
*MaybeStackArray
<T
, stackCapacity
>::resize(int32_t newCapacity
, int32_t length
) {
445 #if U_DEBUG && defined(UPRV_MALLOC_COUNT)
446 ::fprintf(::stderr
,"MaybeStacArray (resize) alloc %d * %lu\n", newCapacity
,sizeof(T
));
448 T
*p
=(T
*)uprv_malloc(newCapacity
*sizeof(T
));
451 if(length
>capacity
) {
454 if(length
>newCapacity
) {
457 uprv_memcpy(p
, ptr
, (size_t)length
*sizeof(T
));
461 capacity
=newCapacity
;
470 template<typename T
, int32_t stackCapacity
>
471 inline T
*MaybeStackArray
<T
, stackCapacity
>::orphanOrClone(int32_t length
, int32_t &resultCapacity
) {
475 } else if(length
<=0) {
478 if(length
>capacity
) {
481 p
=(T
*)uprv_malloc(length
*sizeof(T
));
482 #if U_DEBUG && defined(UPRV_MALLOC_COUNT)
483 ::fprintf(::stderr
,"MaybeStacArray (orphan) alloc %d * %lu\n", length
,sizeof(T
));
488 uprv_memcpy(p
, ptr
, (size_t)length
*sizeof(T
));
490 resultCapacity
=length
;
496 * Variant of MaybeStackArray that allocates a header struct and an array
497 * in one contiguous memory block, using uprv_malloc() and uprv_free().
498 * Provides internal memory with fixed array capacity. Can alias another memory
499 * block or allocate one.
500 * The stackCapacity is the number of T items in the internal memory,
501 * not counting the H header.
502 * Unlike LocalMemory and LocalArray, this class never adopts
503 * (takes ownership of) another memory block.
505 template<typename H
, typename T
, int32_t stackCapacity
>
506 class MaybeStackHeaderAndArray
{
509 * Default constructor initializes with internal H+T[stackCapacity] buffer.
511 MaybeStackHeaderAndArray() : ptr(&stackHeader
), capacity(stackCapacity
), needToRelease(FALSE
) {}
513 * Destructor deletes the memory (if owned).
515 ~MaybeStackHeaderAndArray() { releaseMemory(); }
517 * Returns the array capacity (number of T items).
518 * @return array capacity
520 int32_t getCapacity() const { return capacity
; }
522 * Access without ownership change.
523 * @return the header pointer
525 H
*getAlias() const { return ptr
; }
527 * Returns the array start.
528 * @return array start, same address as getAlias()+1
530 T
*getArrayStart() const { return reinterpret_cast<T
*>(getAlias()+1); }
532 * Returns the array limit.
533 * @return array limit
535 T
*getArrayLimit() const { return getArrayStart()+capacity
; }
537 * Access without ownership change. Same as getAlias().
538 * A class instance can be used directly in expressions that take a T *.
539 * @return the header pointer
541 operator H
*() const { return ptr
; }
543 * Array item access (writable).
544 * No index bounds check.
545 * @param i array index
546 * @return reference to the array item
548 T
&operator[](ptrdiff_t i
) { return getArrayStart()[i
]; }
550 * Deletes the memory block (if owned) and aliases another one, no transfer of ownership.
551 * If the arguments are illegal, then the current memory is unchanged.
552 * @param otherArray must not be NULL
553 * @param otherCapacity must be >0
555 void aliasInstead(H
*otherMemory
, int32_t otherCapacity
) {
556 if(otherMemory
!=NULL
&& otherCapacity
>0) {
559 capacity
=otherCapacity
;
564 * Deletes the memory block (if owned) and allocates a new one,
565 * copying the header and length T array items.
566 * Returns the new header pointer.
567 * If the allocation fails, then the current memory is unchanged and
568 * this method returns NULL.
569 * @param newCapacity can be less than or greater than the current capacity;
571 * @param length number of T items to be copied from the old array to the new one
572 * @return the allocated pointer, or NULL if the allocation failed
574 inline H
*resize(int32_t newCapacity
, int32_t length
=0);
576 * Gives up ownership of the memory if owned, or else clones it,
577 * copying the header and length T array items; resets itself to the internal memory.
578 * Returns NULL if the allocation failed.
579 * @param length number of T items to copy when cloning,
580 * and array capacity of the clone when cloning
581 * @param resultCapacity will be set to the returned array's capacity (output-only)
582 * @return the header pointer;
583 * caller becomes responsible for deleting the array
585 inline H
*orphanOrClone(int32_t length
, int32_t &resultCapacity
);
590 // stackHeader must precede stackArray immediately.
592 T stackArray
[stackCapacity
];
593 void releaseMemory() {
598 /* No comparison operators with other MaybeStackHeaderAndArray's. */
599 bool operator==(const MaybeStackHeaderAndArray
& /*other*/) {return FALSE
;}
600 bool operator!=(const MaybeStackHeaderAndArray
& /*other*/) {return TRUE
;}
601 /* No ownership transfer: No copy constructor, no assignment operator. */
602 MaybeStackHeaderAndArray(const MaybeStackHeaderAndArray
& /*other*/) {}
603 void operator=(const MaybeStackHeaderAndArray
& /*other*/) {}
605 // No heap allocation. Use only on the stack.
606 // (Declaring these functions private triggers a cascade of problems;
607 // see the MaybeStackArray class for details.)
608 // static void * U_EXPORT2 operator new(size_t size);
609 // static void * U_EXPORT2 operator new[](size_t size);
610 #if U_HAVE_PLACEMENT_NEW
611 // static void * U_EXPORT2 operator new(size_t, void *ptr);
615 template<typename H
, typename T
, int32_t stackCapacity
>
616 inline H
*MaybeStackHeaderAndArray
<H
, T
, stackCapacity
>::resize(int32_t newCapacity
,
619 #if U_DEBUG && defined(UPRV_MALLOC_COUNT)
620 ::fprintf(::stderr
,"MaybeStackHeaderAndArray alloc %d + %d * %ul\n", sizeof(H
),newCapacity
,sizeof(T
));
622 H
*p
=(H
*)uprv_malloc(sizeof(H
)+newCapacity
*sizeof(T
));
626 } else if(length
>0) {
627 if(length
>capacity
) {
630 if(length
>newCapacity
) {
634 uprv_memcpy(p
, ptr
, sizeof(H
)+(size_t)length
*sizeof(T
));
637 capacity
=newCapacity
;
646 template<typename H
, typename T
, int32_t stackCapacity
>
647 inline H
*MaybeStackHeaderAndArray
<H
, T
, stackCapacity
>::orphanOrClone(int32_t length
,
648 int32_t &resultCapacity
) {
655 } else if(length
>capacity
) {
658 #if U_DEBUG && defined(UPRV_MALLOC_COUNT)
659 ::fprintf(::stderr
,"MaybeStackHeaderAndArray (orphan) alloc %ul + %d * %lu\n", sizeof(H
),length
,sizeof(T
));
661 p
=(H
*)uprv_malloc(sizeof(H
)+length
*sizeof(T
));
665 uprv_memcpy(p
, ptr
, sizeof(H
)+(size_t)length
*sizeof(T
));
667 resultCapacity
=length
;
669 capacity
=stackCapacity
;
676 #endif /* __cplusplus */
677 #endif /* CMEMORY_H */