/* $Id$ */
/*
* This file is part of OpenTTD.
* OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
* OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see .
*/
/** @file blob.hpp Support for storing random binary data. */
#ifndef BLOB_HPP
#define BLOB_HPP
#include "../core/alloc_func.hpp"
#include "../core/mem_func.hpp"
#include
/** Base class for simple binary blobs.
* Item is byte.
* The word 'simple' means:
* - no configurable allocator type (always made from heap)
* - no smart deallocation - deallocation must be called from the same
* module (DLL) where the blob was allocated
* - no configurable allocation policy (how big blocks should be allocated)
* - no extra ownership policy (i.e. 'copy on write') when blob is copied
* - no thread synchronization at all
*
* Internal member layout:
* 1. The only class member is pointer to the first item (see union ptr_u).
* 2. Allocated block contains the blob header (see CHdr) followed by the raw byte data.
* Always, when it allocates memory the allocated size is:
* sizeof(CHdr) +
* 3. Two 'virtual' members (m_size and m_max_size) are stored in the CHdr at beginning
* of the alloated block.
* 4. The pointter (in ptr_u) pobsize_ts behind the header (to the first data byte).
* When memory block is allocated, the sizeof(CHdr) it added to it.
* 5. Benefits of this layout:
* - items are accessed in the simplest possible way - just dereferencing the pointer,
* which is good for performance (assuming that data are accessed most often).
* - sizeof(blob) is the same as the size of any other pointer
* 6. Drawbacks of this layout:
* - the fact, that pointer to the alocated block is adjusted by sizeof(CHdr) before
* it is stored can lead to several confusions:
* - it is not common pattern so the implementation code is bit harder to read
* - valgrind can generate warning that allocated block is lost (not accessible)
*/
class CBlobBaseSimple {
protected:
/** header of the allocated memory block */
struct CHdr {
uint m_size; ///< actual blob size in bytes
uint m_max_size; ///< maximum (allocated) size in bytes
};
/** type used as class member */
union {
byte *m_pData; ///< ptr to the first byte of data
CHdr *m_pHdr_1; ///< ptr just after the CHdr holding m_size and m_max_size
} ptr_u;
private:
/**
* Just to silence an unsilencable GCC 4.4+ warning
* Note: This cannot be 'const' as we do a lot of 'hdrEmpty[0]->m_size += 0;' and 'hdrEmpty[0]->m_max_size += 0;'
* after const_casting.
*/
static CHdr hdrEmpty[];
public:
static const uint Ttail_reserve = 4; ///< four extra bytes will be always allocated and zeroed at the end
/** default constructor - initializes empty blob */
FORCEINLINE CBlobBaseSimple() { InitEmpty(); }
/** constructor - create blob with data */
FORCEINLINE CBlobBaseSimple(const byte *p, uint num_bytes)
{
InitEmpty();
AppendRaw(p, num_bytes);
}
/** copy constructor */
FORCEINLINE CBlobBaseSimple(const CBlobBaseSimple& src)
{
InitEmpty();
AppendRaw(src);
}
/** move constructor - take ownership of blob data */
FORCEINLINE CBlobBaseSimple(CHdr * const & pHdr_1)
{
assert(pHdr_1 != NULL);
ptr_u.m_pHdr_1 = pHdr_1;
*const_cast(&pHdr_1) = NULL;
}
/** destructor */
FORCEINLINE ~CBlobBaseSimple()
{
Free();
}
protected:
/** initialize the empty blob by setting the ptr_u.m_pHdr_1 pointer to the static CHdr with
* both m_size and m_max_size containing zero */
FORCEINLINE void InitEmpty()
{
ptr_u.m_pHdr_1 = const_cast(&CBlobBaseSimple::hdrEmpty[1]);
}
/** initialize blob by attaching it to the given header followed by data */
FORCEINLINE void Init(CHdr *hdr)
{
ptr_u.m_pHdr_1 = &hdr[1];
}
/** blob header accessor - use it rather than using the pointer arithmetics directly - non-const version */
FORCEINLINE CHdr& Hdr()
{
return *(ptr_u.m_pHdr_1 - 1);
}
/** blob header accessor - use it rather than using the pointer arithmetics directly - const version */
FORCEINLINE const CHdr& Hdr() const
{
return *(ptr_u.m_pHdr_1 - 1);
}
/** return reference to the actual blob size - used when the size needs to be modified */
FORCEINLINE uint& RawSizeRef()
{
return Hdr().m_size;
};
public:
/** return true if blob doesn't contain valid data */
FORCEINLINE bool IsEmpty() const
{
return RawSize() == 0;
}
/** return the number of valid data bytes in the blob */
FORCEINLINE uint RawSize() const
{
return Hdr().m_size;
};
/** return the current blob capacity in bytes */
FORCEINLINE uint MaxRawSize() const
{
return Hdr().m_max_size;
};
/** return pointer to the first byte of data - non-const version */
FORCEINLINE byte *RawData()
{
return ptr_u.m_pData;
}
/** return pointer to the first byte of data - const version */
FORCEINLINE const byte *RawData() const
{
return ptr_u.m_pData;
}
/** return the 32 bit CRC of valid data in the blob */
//FORCEINLINE uint Crc32() const
//{
// return CCrc32::Calc(RawData(), RawSize());
//}
/** invalidate blob's data - doesn't free buffer */
FORCEINLINE void Clear()
{
RawSizeRef() = 0;
}
/** free the blob's memory */
FORCEINLINE void Free()
{
if (MaxRawSize() > 0) {
RawFree(&Hdr());
InitEmpty();
}
}
/** copy data from another blob - replaces any existing blob's data */
FORCEINLINE void CopyFrom(const CBlobBaseSimple& src)
{
Clear();
AppendRaw(src);
}
/** overtake ownership of data buffer from the source blob - source blob will become empty */
FORCEINLINE void MoveFrom(CBlobBaseSimple& src)
{
Free();
ptr_u.m_pData = src.ptr_u.m_pData;
src.InitEmpty();
}
/** swap buffers (with data) between two blobs (this and source blob) */
FORCEINLINE void Swap(CBlobBaseSimple& src)
{
byte *tmp = ptr_u.m_pData; ptr_u.m_pData = src.ptr_u.m_pData;
src.ptr_u.m_pData = tmp;
}
/** append new bytes at the end of existing data bytes - reallocates if necessary */
FORCEINLINE void AppendRaw(const void *p, uint num_bytes)
{
assert(p != NULL);
if (num_bytes > 0) {
memcpy(GrowRawSize(num_bytes), p, num_bytes);
}
}
/** append bytes from given source blob to the end of existing data bytes - reallocates if necessary */
FORCEINLINE void AppendRaw(const CBlobBaseSimple& src)
{
if (!src.IsEmpty())
memcpy(GrowRawSize(src.RawSize()), src.RawData(), src.RawSize());
}
/** Reallocate if there is no free space for num_bytes bytes.
* @return pointer to the new data to be added */
FORCEINLINE byte *MakeRawFreeSpace(uint num_bytes)
{
uint new_size = RawSize() + num_bytes;
if (new_size > MaxRawSize()) SmartAlloc(new_size);
return ptr_u.m_pData + RawSize();
}
/** Increase RawSize() by num_bytes.
* @return pointer to the new data added */
FORCEINLINE byte *GrowRawSize(uint num_bytes)
{
byte *pNewData = MakeRawFreeSpace(num_bytes);
RawSizeRef() += num_bytes;
return pNewData;
}
/** Decrease RawSize() by num_bytes. */
FORCEINLINE void ReduceRawSize(uint num_bytes)
{
if (MaxRawSize() > 0 && num_bytes > 0) {
assert(num_bytes <= RawSize());
if (num_bytes < RawSize()) {
RawSizeRef() -= num_bytes;
} else {
RawSizeRef() = 0;
}
}
}
/** reallocate blob data if needed */
void SmartAlloc(uint new_size)
{
uint old_max_size = MaxRawSize();
if (old_max_size >= new_size) return;
/* calculate minimum block size we need to allocate */
uint min_alloc_size = sizeof(CHdr) + new_size + Ttail_reserve;
/* ask allocation policy for some reasonable block size */
uint alloc_size = AllocPolicy(min_alloc_size);
/* allocate new block */
CHdr *pNewHdr = RawAlloc(alloc_size);
/* setup header */
pNewHdr->m_size = RawSize();
pNewHdr->m_max_size = alloc_size - (sizeof(CHdr) + Ttail_reserve);
/* copy existing data */
if (RawSize() > 0)
memcpy(pNewHdr + 1, ptr_u.m_pData, pNewHdr->m_size);
/* replace our block with new one */
CHdr *pOldHdr = &Hdr();
Init(pNewHdr);
if (old_max_size > 0)
RawFree(pOldHdr);
}
/** simple allocation policy - can be optimized later */
FORCEINLINE static uint AllocPolicy(uint min_alloc)
{
if (min_alloc < (1 << 9)) {
if (min_alloc < (1 << 5)) return (1 << 5);
return (min_alloc < (1 << 7)) ? (1 << 7) : (1 << 9);
}
if (min_alloc < (1 << 15)) {
if (min_alloc < (1 << 11)) return (1 << 11);
return (min_alloc < (1 << 13)) ? (1 << 13) : (1 << 15);
}
if (min_alloc < (1 << 20)) {
if (min_alloc < (1 << 17)) return (1 << 17);
return (min_alloc < (1 << 19)) ? (1 << 19) : (1 << 20);
}
min_alloc = (min_alloc | ((1 << 20) - 1)) + 1;
return min_alloc;
}
/** all allocation should happen here */
static FORCEINLINE CHdr *RawAlloc(uint num_bytes)
{
return (CHdr*)MallocT(num_bytes);
}
/** all deallocations should happen here */
static FORCEINLINE void RawFree(CHdr *p)
{
/* Just to silence an unsilencable GCC 4.4+ warning. */
assert(p != CBlobBaseSimple::hdrEmpty);
/* In case GCC warns about the following, see GCC's PR38509 why it is bogus. */
free(p);
}
/** fixing the four bytes at the end of blob data - useful when blob is used to hold string */
FORCEINLINE void FixTail() const
{
if (MaxRawSize() > 0) {
byte *p = &ptr_u.m_pData[RawSize()];
for (uint i = 0; i < Ttail_reserve; i++) {
p[i] = 0;
}
}
}
};
/** Blob - simple dynamic T array. T (template argument) is a placeholder for any type.
* T can be any integral type, pointer, or structure. Using Blob instead of just plain C array
* simplifies the resource management in several ways:
* 1. When adding new item(s) it automatically grows capacity if needed.
* 2. When variable of type Blob comes out of scope it automatically frees the data buffer.
* 3. Takes care about the actual data size (number of used items).
* 4. Dynamically constructs only used items (as opposite of static array which constructs all items) */
template
class CBlobT : public CBlobBaseSimple {
/* make template arguments public: */
public:
typedef CBlobBaseSimple base;
static const uint type_size = sizeof(T);
struct OnTransfer {
typename base::CHdr *m_pHdr_1;
OnTransfer(const OnTransfer& src) : m_pHdr_1(src.m_pHdr_1) {assert(src.m_pHdr_1 != NULL); *const_cast(&src.m_pHdr_1) = NULL;}
OnTransfer(CBlobT& src) : m_pHdr_1(src.ptr_u.m_pHdr_1) {src.InitEmpty();}
~OnTransfer() {assert(m_pHdr_1 == NULL);}
};
/** Default constructor - makes new Blob ready to accept any data */
FORCEINLINE CBlobT()
: base()
{}
/** Constructor - makes new Blob with data */
FORCEINLINE CBlobT(const T *p, uint num_items)
: base((byte *)p, num_items * type_size)
{}
/** Copy constructor - make new blob to become copy of the original (source) blob */
FORCEINLINE CBlobT(const base& src)
: base(src)
{
assert((base::RawSize() % type_size) == 0);
}
/** Take ownership constructor */
FORCEINLINE CBlobT(const OnTransfer& ot)
: base(ot.m_pHdr_1)
{}
/** Destructor - ensures that allocated memory (if any) is freed */
FORCEINLINE ~CBlobT()
{
Free();
}
/** Check the validity of item index (only in debug mode) */
FORCEINLINE void CheckIdx(uint idx) const
{
assert(idx < Size());
}
/** Return pointer to the first data item - non-const version */
FORCEINLINE T *Data()
{
return (T*)base::RawData();
}
/** Return pointer to the first data item - const version */
FORCEINLINE const T *Data() const
{
return (const T*)base::RawData();
}
/** Return pointer to the idx-th data item - non-const version */
FORCEINLINE T *Data(uint idx)
{
CheckIdx(idx);
return (Data() + idx);
}
/** Return pointer to the idx-th data item - const version */
FORCEINLINE const T *Data(uint idx) const
{
CheckIdx(idx);
return (Data() + idx);
}
/** Return number of items in the Blob */
FORCEINLINE uint Size() const
{
return (base::RawSize() / type_size);
}
/** Return total number of items that can fit in the Blob without buffer reallocation */
FORCEINLINE uint MaxSize() const
{
return (base::MaxRawSize() / type_size);
}
/** Return number of additional items that can fit in the Blob without buffer reallocation */
FORCEINLINE uint GetReserve() const
{
return ((base::MaxRawSize() - base::RawSize()) / type_size);
}
/** Free the memory occupied by Blob destroying all items */
FORCEINLINE void Free()
{
assert((base::RawSize() % type_size) == 0);
uint old_size = Size();
if (old_size > 0) {
/* destroy removed items; */
T *pI_last_to_destroy = Data(0);
for (T *pI = Data(old_size - 1); pI >= pI_last_to_destroy; pI--) pI->~T();
}
base::Free();
}
/** Grow number of data items in Blob by given number - doesn't construct items */
FORCEINLINE T *GrowSizeNC(uint num_items)
{
return (T*)base::GrowRawSize(num_items * type_size);
}
/** Grow number of data items in Blob by given number - constructs new items (using T's default constructor) */
FORCEINLINE T *GrowSizeC(uint num_items)
{
T *pI = GrowSizeNC(num_items);
for (uint i = num_items; i > 0; i--, pI++) new (pI) T();
}
/** Destroy given number of items and reduce the Blob's data size */
FORCEINLINE void ReduceSize(uint num_items)
{
assert((base::RawSize() % type_size) == 0);
uint old_size = Size();
assert(num_items <= old_size);
uint new_size = (num_items <= old_size) ? (old_size - num_items) : 0;
/* destroy removed items; */
T *pI_last_to_destroy = Data(new_size);
for (T *pI = Data(old_size - 1); pI >= pI_last_to_destroy; pI--) pI->~T();
/* remove them */
base::ReduceRawSize(num_items * type_size);
}
/** Append one data item at the end (calls T's default constructor) */
FORCEINLINE T *AppendNew()
{
T& dst = *GrowSizeNC(1); // Grow size by one item
T *pNewItem = new (&dst) T(); // construct the new item by calling in-place new operator
return pNewItem;
}
/** Append the copy of given item at the end of Blob (using copy constructor) */
FORCEINLINE T *Append(const T& src)
{
T& dst = *GrowSizeNC(1); // Grow size by one item
T *pNewItem = new (&dst) T(src); // construct the new item by calling in-place new operator with copy ctor()
return pNewItem;
}
/** Add given items (ptr + number of items) at the end of blob */
FORCEINLINE T *Append(const T *pSrc, uint num_items)
{
T *pDst = GrowSizeNC(num_items);
T *pDstOrg = pDst;
T *pDstEnd = pDst + num_items;
while (pDst < pDstEnd) new (pDst++) T(*(pSrc++));
return pDstOrg;
}
/** Remove item with the given index by replacing it by the last item and reducing the size by one */
FORCEINLINE void RemoveBySwap(uint idx)
{
CheckIdx(idx);
/* destroy removed item */
T *pRemoved = Data(idx);
RemoveBySwap(pRemoved);
}
/** Remove item given by pointer replacing it by the last item and reducing the size by one */
FORCEINLINE void RemoveBySwap(T *pItem)
{
T *pLast = Data(Size() - 1);
assert(pItem >= Data() && pItem <= pLast);
/* move last item to its new place */
if (pItem != pLast) {
pItem->~T();
new (pItem) T(*pLast);
}
/* destroy the last item */
pLast->~T();
/* and reduce the raw blob size */
base::ReduceRawSize(type_size);
}
/** Ensures that given number of items can be added to the end of Blob. Returns pointer to the
* first free (unused) item */
FORCEINLINE T *MakeFreeSpace(uint num_items)
{
return (T*)base::MakeRawFreeSpace(num_items * type_size);
}
FORCEINLINE OnTransfer Transfer()
{
return OnTransfer(*this);
};
};
#endif /* BLOB_HPP */