Add cJSON_CreateStringReference

This commit is contained in:
Max Bruckner 2017-11-28 02:02:55 +01:00
parent 440390a9a5
commit eaa90a6b74
3 changed files with 27 additions and 0 deletions

12
cJSON.c
View File

@ -2198,6 +2198,18 @@ CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string)
return item; return item;
} }
CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string)
{
cJSON *item = cJSON_New_Item(&global_hooks);
if (item != NULL)
{
item->type = cJSON_String | cJSON_IsReference;
item->valuestring = cast_away_const_from_string(string);
}
return item;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw) CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw)
{ {
cJSON *item = cJSON_New_Item(&global_hooks); cJSON *item = cJSON_New_Item(&global_hooks);

View File

@ -192,6 +192,10 @@ CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw);
CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void); CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void); CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void);
/* Create a string where valuestring references a string so
* it will not be freed by cJSON_Delete */
CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string);
/* These utilities create an Array of count items. */ /* These utilities create an Array of count items. */
CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count); CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count); CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count);

View File

@ -463,6 +463,16 @@ static void cjson_get_string_value_should_get_a_string(void)
cJSON_Delete(string); cJSON_Delete(string);
} }
static void cjson_create_string_reference_should_create_a_string_reference(void) {
const char *string = "I am a string!";
cJSON *string_reference = cJSON_CreateStringReference(string);
TEST_ASSERT_TRUE(string_reference->valuestring == string);
TEST_ASSERT_EQUAL_INT(cJSON_IsReference | cJSON_String, string_reference->type);
cJSON_Delete(string_reference);
}
int main(void) int main(void)
{ {
UNITY_BEGIN(); UNITY_BEGIN();
@ -482,6 +492,7 @@ int main(void)
RUN_TEST(skip_utf8_bom_should_skip_bom); RUN_TEST(skip_utf8_bom_should_skip_bom);
RUN_TEST(skip_utf8_bom_should_not_skip_bom_if_not_at_beginning); RUN_TEST(skip_utf8_bom_should_not_skip_bom_if_not_at_beginning);
RUN_TEST(cjson_get_string_value_should_get_a_string); RUN_TEST(cjson_get_string_value_should_get_a_string);
RUN_TEST(cjson_create_string_reference_should_create_a_string_reference);
return UNITY_END(); return UNITY_END();
} }