123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144 |
- #include "json.h"
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- #include <stdbool.h>
- bool json_print_string(const unsigned char *input, unsigned char *output_buffer)
- {
- const unsigned char *input_pointer = NULL;
- unsigned char *output = NULL;
- unsigned char *output_pointer = NULL;
- size_t output_length = 0;
-
- size_t escape_characters = 0;
- if (output_buffer == NULL)
- {
- return false;
- }
-
- if (input == NULL)
- {
-
- if (output == NULL)
- {
- return false;
- }
- strcpy((char*)output, "\"\"");
- return true;
- }
-
- for (input_pointer = input; *input_pointer; input_pointer++)
- {
- if (strchr("\"\\\b\f\n\r\t", *input_pointer))
- {
-
- escape_characters++;
- }
- else if (*input_pointer < 32)
- {
-
- escape_characters += 5;
- }
- }
- output_length = (size_t)(input_pointer - input) + escape_characters;
-
- output = output_buffer;
-
- if (escape_characters == 0)
- {
- output[0] = '\"';
- memcpy(output + 1, input, output_length);
- output[output_length + 1] = '\"';
- output[output_length + 2] = '\0';
- return true;
- }
- output[0] = '\"';
- output_pointer = output + 1;
-
- for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++)
- {
- if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\'))
- {
-
- *output_pointer = *input_pointer;
- }
- else
- {
-
- *output_pointer++ = '\\';
- switch (*input_pointer)
- {
- case '\\':
- *output_pointer = '\\';
- break;
- case '\"':
- *output_pointer = '\"';
- break;
- case '\b':
- *output_pointer = 'b';
- break;
- case '\f':
- *output_pointer = 'f';
- break;
- case '\n':
- *output_pointer = 'n';
- break;
- case '\r':
- *output_pointer = 'r';
- break;
- case '\t':
- *output_pointer = 't';
- break;
- default:
-
- sprintf((char*)output_pointer, "u%04x", *input_pointer);
- output_pointer += 4;
- break;
- }
- }
- }
- output[output_length + 1] = '\"';
- output[output_length + 2] = '\0';
- return true;
- }
|