2 ******************************************************************************
4 * Copyright (C) 1997-2012, International Business Machines
5 * Corporation and others. All Rights Reserved.
7 ******************************************************************************
11 * Contains stdlib.h/string.h memory functions
13 * @author Bertrand A. Damiba
15 * Modification History:
17 * Date Name Description
18 * 6/20/98 Bertrand Created.
19 * 05/03/99 stephen Changed from functions to macros.
21 ******************************************************************************
27 #include "unicode/utypes.h"
31 #include "unicode/localpointer.h"
33 #if U_DEBUG && defined(UPRV_MALLOC_COUNT)
40 * The C++ standard requires that the source pointer for memcpy() & memmove()
41 * is valid, not NULL, and not at the end of an allocated memory block.
42 * In debug mode, we read one byte from the source point to verify that it's
43 * a valid, readable pointer.
46 U_CAPI
void uprv_checkValidMemory(const void *p
, size_t n
);
48 #define uprv_memcpy(dst, src, size) ( \
49 uprv_checkValidMemory(src, 1), \
50 U_STANDARD_CPP_NAMESPACE memcpy(dst, src, size))
51 #define uprv_memmove(dst, src, size) ( \
52 uprv_checkValidMemory(src, 1), \
53 U_STANDARD_CPP_NAMESPACE memmove(dst, src, size))
57 #define uprv_memcpy(dst, src, size) U_STANDARD_CPP_NAMESPACE memcpy(dst, src, size)
58 #define uprv_memmove(dst, src, size) U_STANDARD_CPP_NAMESPACE memmove(dst, src, size)
62 #define uprv_memset(buffer, mark, size) U_STANDARD_CPP_NAMESPACE memset(buffer, mark, size)
63 #define uprv_memcmp(buffer1, buffer2, size) U_STANDARD_CPP_NAMESPACE memcmp(buffer1, buffer2,size)
65 U_CAPI
void * U_EXPORT2
66 uprv_malloc(size_t s
) U_MALLOC_ATTR
U_ALLOC_SIZE_ATTR(1);
68 U_CAPI
void * U_EXPORT2
69 uprv_realloc(void *mem
, size_t size
) U_ALLOC_SIZE_ATTR(2);
74 U_CAPI
void * U_EXPORT2
75 uprv_calloc(size_t num
, size_t size
) U_MALLOC_ATTR
U_ALLOC_SIZE_ATTR2(1,2);
78 * This should align the memory properly on any machine.
79 * This is very useful for the safeClone functions.
88 * Get the least significant bits of a pointer (a memory address).
89 * For example, with a mask of 3, the macro gets the 2 least significant bits,
90 * which will be 0 if the pointer is 32-bit (4-byte) aligned.
92 * ptrdiff_t is the most appropriate integer type to cast to.
93 * size_t should work too, since on most (or all?) platforms it has the same
96 #define U_POINTER_MASK_LSB(ptr, mask) (((ptrdiff_t)(char *)(ptr)) & (mask))
99 * Get the amount of bytes that a pointer is off by from
100 * the previous UAlignedMemory-aligned pointer.
102 #define U_ALIGNMENT_OFFSET(ptr) U_POINTER_MASK_LSB(ptr, sizeof(UAlignedMemory) - 1)
105 * Get the amount of bytes to add to a pointer
106 * in order to get the next UAlignedMemory-aligned address.
108 #define U_ALIGNMENT_OFFSET_UP(ptr) (sizeof(UAlignedMemory) - U_ALIGNMENT_OFFSET(ptr))
111 * Indicate whether the ICU allocation functions have been used.
112 * This is used to determine whether ICU is in an initial, unused state.
118 * Heap clean up function, called from u_cleanup()
119 * Clears any user heap functions from u_setMemoryFunctions()
120 * Does NOT deallocate any remaining allocated memory.
123 cmemory_cleanup(void);
126 * A function called by <TT>uhash_remove</TT>,
127 * <TT>uhash_close</TT>, or <TT>uhash_put</TT> to delete
128 * an existing key or value.
129 * @param obj A key or value stored in a hashtable
130 * @see uprv_deleteUObject
132 typedef void U_CALLCONV
UObjectDeleter(void* obj
);
135 * Deleter for UObject instances.
136 * Works for all subclasses of UObject because it has a virtual destructor.
138 U_CAPI
void U_EXPORT2
139 uprv_deleteUObject(void *obj
);
146 * "Smart pointer" class, deletes memory via uprv_free().
147 * For most methods see the LocalPointerBase base class.
148 * Adds operator[] for array item access.
150 * @see LocalPointerBase
153 class LocalMemory
: public LocalPointerBase
<T
> {
156 * Constructor takes ownership.
157 * @param p simple pointer to an array of T items that is adopted
159 explicit LocalMemory(T
*p
=NULL
) : LocalPointerBase
<T
>(p
) {}
161 * Destructor deletes the memory it owns.
164 uprv_free(LocalPointerBase
<T
>::ptr
);
167 * Deletes the array it owns,
168 * and adopts (takes ownership of) the one passed in.
169 * @param p simple pointer to an array of T items that is adopted
171 void adoptInstead(T
*p
) {
172 uprv_free(LocalPointerBase
<T
>::ptr
);
173 LocalPointerBase
<T
>::ptr
=p
;
176 * Deletes the array it owns, allocates a new one and reset its bytes to 0.
177 * Returns the new array pointer.
178 * If the allocation fails, then the current array is unchanged and
179 * this method returns NULL.
180 * @param newCapacity must be >0
181 * @return the allocated array pointer, or NULL if the allocation failed
183 inline T
*allocateInsteadAndReset(int32_t newCapacity
=1);
185 * Deletes the array it owns and allocates a new one, copying length T items.
186 * Returns the new array pointer.
187 * If the allocation fails, then the current array is unchanged and
188 * this method returns NULL.
189 * @param newCapacity must be >0
190 * @param length number of T items to be copied from the old array to the new one;
191 * must be no more than the capacity of the old array,
192 * which the caller must track because the LocalMemory does not track it
193 * @return the allocated array pointer, or NULL if the allocation failed
195 inline T
*allocateInsteadAndCopy(int32_t newCapacity
=1, int32_t length
=0);
197 * Array item access (writable).
198 * No index bounds check.
199 * @param i array index
200 * @return reference to the array item
202 T
&operator[](ptrdiff_t i
) const { return LocalPointerBase
<T
>::ptr
[i
]; }
206 inline T
*LocalMemory
<T
>::allocateInsteadAndReset(int32_t newCapacity
) {
208 T
*p
=(T
*)uprv_malloc(newCapacity
*sizeof(T
));
210 uprv_memset(p
, 0, newCapacity
*sizeof(T
));
211 uprv_free(LocalPointerBase
<T
>::ptr
);
212 LocalPointerBase
<T
>::ptr
=p
;
222 inline T
*LocalMemory
<T
>::allocateInsteadAndCopy(int32_t newCapacity
, int32_t length
) {
224 T
*p
=(T
*)uprv_malloc(newCapacity
*sizeof(T
));
227 if(length
>newCapacity
) {
230 uprv_memcpy(p
, LocalPointerBase
<T
>::ptr
, length
*sizeof(T
));
232 uprv_free(LocalPointerBase
<T
>::ptr
);
233 LocalPointerBase
<T
>::ptr
=p
;
242 * Simple array/buffer management class using uprv_malloc() and uprv_free().
243 * Provides an internal array with fixed capacity. Can alias another array
246 * The array address is properly aligned for type T. It might not be properly
247 * aligned for types larger than T (or larger than the largest subtype of T).
249 * Unlike LocalMemory and LocalArray, this class never adopts
250 * (takes ownership of) another array.
252 template<typename T
, int32_t stackCapacity
>
253 class MaybeStackArray
{
256 * Default constructor initializes with internal T[stackCapacity] buffer.
258 MaybeStackArray() : ptr(stackArray
), capacity(stackCapacity
), needToRelease(FALSE
) {}
260 * Destructor deletes the array (if owned).
262 ~MaybeStackArray() { releaseArray(); }
264 * Returns the array capacity (number of T items).
265 * @return array capacity
267 int32_t getCapacity() const { return capacity
; }
269 * Access without ownership change.
270 * @return the array pointer
272 T
*getAlias() const { return ptr
; }
274 * Returns the array limit. Simple convenience method.
275 * @return getAlias()+getCapacity()
277 T
*getArrayLimit() const { return getAlias()+capacity
; }
278 // No "operator T *() const" because that can make
279 // expressions like mbs[index] ambiguous for some compilers.
281 * Array item access (const).
282 * No index bounds check.
283 * @param i array index
284 * @return reference to the array item
286 const T
&operator[](ptrdiff_t i
) const { return ptr
[i
]; }
288 * Array item access (writable).
289 * No index bounds check.
290 * @param i array index
291 * @return reference to the array item
293 T
&operator[](ptrdiff_t i
) { return ptr
[i
]; }
295 * Deletes the array (if owned) and aliases another one, no transfer of ownership.
296 * If the arguments are illegal, then the current array is unchanged.
297 * @param otherArray must not be NULL
298 * @param otherCapacity must be >0
300 void aliasInstead(T
*otherArray
, int32_t otherCapacity
) {
301 if(otherArray
!=NULL
&& otherCapacity
>0) {
304 capacity
=otherCapacity
;
309 * Deletes the array (if owned) and allocates a new one, copying length T items.
310 * Returns the new array pointer.
311 * If the allocation fails, then the current array is unchanged and
312 * this method returns NULL.
313 * @param newCapacity can be less than or greater than the current capacity;
315 * @param length number of T items to be copied from the old array to the new one
316 * @return the allocated array pointer, or NULL if the allocation failed
318 inline T
*resize(int32_t newCapacity
, int32_t length
=0);
320 * Gives up ownership of the array if owned, or else clones it,
321 * copying length T items; resets itself to the internal stack array.
322 * Returns NULL if the allocation failed.
323 * @param length number of T items to copy when cloning,
324 * and capacity of the clone when cloning
325 * @param resultCapacity will be set to the returned array's capacity (output-only)
326 * @return the array pointer;
327 * caller becomes responsible for deleting the array
329 inline T
*orphanOrClone(int32_t length
, int32_t &resultCapacity
);
334 T stackArray
[stackCapacity
];
335 void releaseArray() {
340 /* No comparison operators with other MaybeStackArray's. */
341 bool operator==(const MaybeStackArray
& /*other*/) {return FALSE
;}
342 bool operator!=(const MaybeStackArray
& /*other*/) {return TRUE
;}
343 /* No ownership transfer: No copy constructor, no assignment operator. */
344 MaybeStackArray(const MaybeStackArray
& /*other*/) {}
345 void operator=(const MaybeStackArray
& /*other*/) {}
347 // No heap allocation. Use only on the stack.
348 // (Declaring these functions private triggers a cascade of problems:
349 // MSVC insists on exporting an instantiation of MaybeStackArray, which
350 // requires that all functions be defined.
351 // An empty implementation of new() is rejected, it must return a value.
352 // Returning NULL is rejected by gcc for operator new.
353 // The expedient thing is just not to override operator new.
354 // While relatively pointless, heap allocated instances will function.
355 // static void * U_EXPORT2 operator new(size_t size);
356 // static void * U_EXPORT2 operator new[](size_t size);
357 #if U_HAVE_PLACEMENT_NEW
358 // static void * U_EXPORT2 operator new(size_t, void *ptr);
362 template<typename T
, int32_t stackCapacity
>
363 inline T
*MaybeStackArray
<T
, stackCapacity
>::resize(int32_t newCapacity
, int32_t length
) {
365 #if U_DEBUG && defined(UPRV_MALLOC_COUNT)
366 ::fprintf(::stderr
,"MaybeStacArray (resize) alloc %d * %lu\n", newCapacity
,sizeof(T
));
368 T
*p
=(T
*)uprv_malloc(newCapacity
*sizeof(T
));
371 if(length
>capacity
) {
374 if(length
>newCapacity
) {
377 uprv_memcpy(p
, ptr
, length
*sizeof(T
));
381 capacity
=newCapacity
;
390 template<typename T
, int32_t stackCapacity
>
391 inline T
*MaybeStackArray
<T
, stackCapacity
>::orphanOrClone(int32_t length
, int32_t &resultCapacity
) {
395 } else if(length
<=0) {
398 if(length
>capacity
) {
401 p
=(T
*)uprv_malloc(length
*sizeof(T
));
402 #if U_DEBUG && defined(UPRV_MALLOC_COUNT)
403 ::fprintf(::stderr
,"MaybeStacArray (orphan) alloc %d * %lu\n", length
,sizeof(T
));
408 uprv_memcpy(p
, ptr
, length
*sizeof(T
));
410 resultCapacity
=length
;
412 capacity
=stackCapacity
;
418 * Variant of MaybeStackArray that allocates a header struct and an array
419 * in one contiguous memory block, using uprv_malloc() and uprv_free().
420 * Provides internal memory with fixed array capacity. Can alias another memory
421 * block or allocate one.
422 * The stackCapacity is the number of T items in the internal memory,
423 * not counting the H header.
424 * Unlike LocalMemory and LocalArray, this class never adopts
425 * (takes ownership of) another memory block.
427 template<typename H
, typename T
, int32_t stackCapacity
>
428 class MaybeStackHeaderAndArray
{
431 * Default constructor initializes with internal H+T[stackCapacity] buffer.
433 MaybeStackHeaderAndArray() : ptr(&stackHeader
), capacity(stackCapacity
), needToRelease(FALSE
) {}
435 * Destructor deletes the memory (if owned).
437 ~MaybeStackHeaderAndArray() { releaseMemory(); }
439 * Returns the array capacity (number of T items).
440 * @return array capacity
442 int32_t getCapacity() const { return capacity
; }
444 * Access without ownership change.
445 * @return the header pointer
447 H
*getAlias() const { return ptr
; }
449 * Returns the array start.
450 * @return array start, same address as getAlias()+1
452 T
*getArrayStart() const { return reinterpret_cast<T
*>(getAlias()+1); }
454 * Returns the array limit.
455 * @return array limit
457 T
*getArrayLimit() const { return getArrayStart()+capacity
; }
459 * Access without ownership change. Same as getAlias().
460 * A class instance can be used directly in expressions that take a T *.
461 * @return the header pointer
463 operator H
*() const { return ptr
; }
465 * Array item access (writable).
466 * No index bounds check.
467 * @param i array index
468 * @return reference to the array item
470 T
&operator[](ptrdiff_t i
) { return getArrayStart()[i
]; }
472 * Deletes the memory block (if owned) and aliases another one, no transfer of ownership.
473 * If the arguments are illegal, then the current memory is unchanged.
474 * @param otherArray must not be NULL
475 * @param otherCapacity must be >0
477 void aliasInstead(H
*otherMemory
, int32_t otherCapacity
) {
478 if(otherMemory
!=NULL
&& otherCapacity
>0) {
481 capacity
=otherCapacity
;
486 * Deletes the memory block (if owned) and allocates a new one,
487 * copying the header and length T array items.
488 * Returns the new header pointer.
489 * If the allocation fails, then the current memory is unchanged and
490 * this method returns NULL.
491 * @param newCapacity can be less than or greater than the current capacity;
493 * @param length number of T items to be copied from the old array to the new one
494 * @return the allocated pointer, or NULL if the allocation failed
496 inline H
*resize(int32_t newCapacity
, int32_t length
=0);
498 * Gives up ownership of the memory if owned, or else clones it,
499 * copying the header and length T array items; resets itself to the internal memory.
500 * Returns NULL if the allocation failed.
501 * @param length number of T items to copy when cloning,
502 * and array capacity of the clone when cloning
503 * @param resultCapacity will be set to the returned array's capacity (output-only)
504 * @return the header pointer;
505 * caller becomes responsible for deleting the array
507 inline H
*orphanOrClone(int32_t length
, int32_t &resultCapacity
);
512 // stackHeader must precede stackArray immediately.
514 T stackArray
[stackCapacity
];
515 void releaseMemory() {
520 /* No comparison operators with other MaybeStackHeaderAndArray's. */
521 bool operator==(const MaybeStackHeaderAndArray
& /*other*/) {return FALSE
;}
522 bool operator!=(const MaybeStackHeaderAndArray
& /*other*/) {return TRUE
;}
523 /* No ownership transfer: No copy constructor, no assignment operator. */
524 MaybeStackHeaderAndArray(const MaybeStackHeaderAndArray
& /*other*/) {}
525 void operator=(const MaybeStackHeaderAndArray
& /*other*/) {}
527 // No heap allocation. Use only on the stack.
528 // (Declaring these functions private triggers a cascade of problems;
529 // see the MaybeStackArray class for details.)
530 // static void * U_EXPORT2 operator new(size_t size);
531 // static void * U_EXPORT2 operator new[](size_t size);
532 #if U_HAVE_PLACEMENT_NEW
533 // static void * U_EXPORT2 operator new(size_t, void *ptr);
537 template<typename H
, typename T
, int32_t stackCapacity
>
538 inline H
*MaybeStackHeaderAndArray
<H
, T
, stackCapacity
>::resize(int32_t newCapacity
,
541 #if U_DEBUG && defined(UPRV_MALLOC_COUNT)
542 ::fprintf(::stderr
,"MaybeStackHeaderAndArray alloc %d + %d * %ul\n", sizeof(H
),newCapacity
,sizeof(T
));
544 H
*p
=(H
*)uprv_malloc(sizeof(H
)+newCapacity
*sizeof(T
));
548 } else if(length
>0) {
549 if(length
>capacity
) {
552 if(length
>newCapacity
) {
556 uprv_memcpy(p
, ptr
, sizeof(H
)+length
*sizeof(T
));
559 capacity
=newCapacity
;
568 template<typename H
, typename T
, int32_t stackCapacity
>
569 inline H
*MaybeStackHeaderAndArray
<H
, T
, stackCapacity
>::orphanOrClone(int32_t length
,
570 int32_t &resultCapacity
) {
577 } else if(length
>capacity
) {
580 #if U_DEBUG && defined(UPRV_MALLOC_COUNT)
581 ::fprintf(::stderr
,"MaybeStackHeaderAndArray (orphan) alloc %ul + %d * %lu\n", sizeof(H
),length
,sizeof(T
));
583 p
=(H
*)uprv_malloc(sizeof(H
)+length
*sizeof(T
));
587 uprv_memcpy(p
, ptr
, sizeof(H
)+length
*sizeof(T
));
589 resultCapacity
=length
;
591 capacity
=stackCapacity
;
598 #endif /* __cplusplus */
599 #endif /* CMEMORY_H */