فهرست منبع

Add cJSON_CreateStringReference

Max Bruckner 7 سال پیش
والد
کامیت
eaa90a6b74
3فایلهای تغییر یافته به همراه27 افزوده شده و 0 حذف شده
  1. 12 0
      cJSON.c
  2. 4 0
      cJSON.h
  3. 11 0
      tests/misc_tests.c

+ 12 - 0
cJSON.c

@@ -2198,6 +2198,18 @@ CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string)
     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 *item = cJSON_New_Item(&global_hooks);

+ 4 - 0
cJSON.h

@@ -192,6 +192,10 @@ CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw);
 CJSON_PUBLIC(cJSON *) cJSON_CreateArray(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. */
 CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count);
 CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count);

+ 11 - 0
tests/misc_tests.c

@@ -463,6 +463,16 @@ static void cjson_get_string_value_should_get_a_string(void)
     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)
 {
     UNITY_BEGIN();
@@ -482,6 +492,7 @@ int main(void)
     RUN_TEST(skip_utf8_bom_should_skip_bom);
     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_create_string_reference_should_create_a_string_reference);
 
     return UNITY_END();
 }