Logo Search packages:      
Sourcecode: scummvm version File versions  Download package

void Common::String::ensureCapacity ( uint32  new_len,
bool  keep_old 
) [protected]

Ensure that enough storage is available to store at least new_len characters plus a null byte. In addition, if we currently share the storage with another string, unshare it, so that we can safely write to the storage.

Definition at line 281 of file str.cpp.

References _builtinCapacity, _extern, _storage, and _str.

                                                         {
      bool isShared;
      uint32 curCapacity, newCapacity;
      char *newStorage;
      int *oldRefCount = _extern._refCount;

      if (isStorageIntern()) {
            isShared = false;
            curCapacity = _builtinCapacity - 1;
      } else {
            isShared = (oldRefCount && *oldRefCount > 1);
            curCapacity = _extern._capacity;
      }

      // Special case: If there is enough space, and we do not share
      // the storage, then there is nothing to do.
      if (!isShared && new_len <= curCapacity)
            return;

      if (isShared && new_len <= _builtinCapacity - 1) {
            // We share the storage, but there is enough internal storage: Use that.
            newStorage = _storage;
            newCapacity = _builtinCapacity - 1;
      } else {
            // We need to allocate storage on the heap!

            // Compute a suitable new capacity limit
            newCapacity = computeCapacity(new_len);

            // Allocate new storage
            newStorage = (char *)malloc(newCapacity+1);
            assert(newStorage);
      }

      // Copy old data if needed, elsewise reset the new storage.
      if (keep_old) {
            assert(_len <= newCapacity);
            memcpy(newStorage, _str, _len + 1);
      } else {
            _len = 0;
            newStorage[0] = 0;
      }

      // Release hold on the old storage ...
      decRefCount(oldRefCount);

      // ... in favor of the new storage
      _str = newStorage;

      if (!isStorageIntern()) {
            // Set the ref count & capacity if we use an external storage.
            // It is important to do this *after* copying any old content,
            // else we would override data that has not yet been copied!
            _extern._refCount = 0;
            _extern._capacity = newCapacity;
      }
}


Generated by  Doxygen 1.6.0   Back to index