Skip to content

Commit

Permalink
Refactor: Further improved Str_Copy() and its apidoc
Browse files Browse the repository at this point in the history
The apidoc for Str_Copy() now very explicitly states what the function does.
Modified the copy behavior so that for regular strings, the source string's
buffer is duplicated exactly (entire reserved size) while static strings will get
new memory allocated for them.
  • Loading branch information
skyjake committed Jun 28, 2012
1 parent fbfa49f commit ef72791
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
13 changes: 12 additions & 1 deletion doomsday/engine/api/dd_string.h
Expand Up @@ -216,9 +216,20 @@ boolean Str_IsEmpty(const ddstring_t* ds);
char* Str_Text(const ddstring_t* ds);

/**
* Makes a true copy.
* Makes a copy of @a src and replaces the previous contents of @a dest with
* it. The copy will have least as much memory reserved in its internal buffer
* as the original.
*
* If @a src is a static string (i.e., no memory allocated for its buffer), new
* memory will be allocated for the copy.
*
* @param dest String where the copy is stored.
* @param src Original string to copy.
*
* @return The @a dest string with the copied content.
*/
ddstring_t* Str_Copy(ddstring_t* dest, const ddstring_t* src);

ddstring_t* Str_CopyOrClear(ddstring_t* dest, const ddstring_t* src);

/**
Expand Down
18 changes: 15 additions & 3 deletions doomsday/engine/portable/src/m_string.c
Expand Up @@ -449,9 +449,21 @@ ddstring_t* Str_Copy(ddstring_t* str, const ddstring_t* other)
#endif
return str;
}
allocateString(str, other->length, false);
strcpy(str->str, other->str);
str->length = other->length;
if(!other->size)
{
// The original string has no memory allocated; it's a static string.
allocateString(str, other->length, false);
strcpy(str->str, other->str);
str->length = other->length;
}
else
{
// Duplicate the other string's buffer in its entirety.
str->str = str->memAlloc(other->size);
memcpy(str->str, other->str, other->size);
str->size = other->size;
str->length = other->length;
}
return str;
}

Expand Down

0 comments on commit ef72791

Please sign in to comment.