Skip to content

Commit

Permalink
[fix] Special case ESC
Browse files Browse the repository at this point in the history
This escapes '\x1b' to '\u001b' in JSON as a special case, since '\x1b'
is used in coloring output.

Change the way we allocate memory for escaping JSON - actually count
characters we'll use instead of blindly shooting for maximum number of
characters.

Fixes #33.
  • Loading branch information
mmalecki committed Sep 27, 2013
1 parent 002572c commit 586ea84
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 16 deletions.
43 changes: 31 additions & 12 deletions src/json.c
Expand Up @@ -6,26 +6,45 @@
#include <forza.h>

char* forza__json_escape(char* string) {
char* result = malloc((2 * strlen(string) + 1) * sizeof(char));
char* result;
int i;
int length = 0;
int str_len = strlen(string);

for (i = 0; i < str_len; i++) {
switch (string[i]) {
case '\\':
case '"':
case '\b':
case '\f':
case '\n':
case '\r':
case '\t': length += 2; break;
case '\x1b': length += 6; break;
default: length++;
}
}

result = malloc(sizeof(*result) * (length + 1));

if (result == NULL) {
return NULL;
}

result[0] = '\0';

while (*string != '\0') {
switch (*string) {
case '\\': strcat(result, "\\\\"); break;
case '"': strcat(result, "\\\""); break;
case '\b': strcat(result, "\\b"); break;
case '\f': strcat(result, "\\f"); break;
case '\n': strcat(result, "\\n"); break;
case '\r': strcat(result, "\\r"); break;
case '\t': strcat(result, "\\t"); break;
default: strncat(result, string, 1); break;
for (i = 0; i < str_len; i++) {
switch (string[i]) {
case '\\': strcat(result, "\\\\"); break;
case '"': strcat(result, "\\\""); break;
case '\b': strcat(result, "\\b"); break;
case '\f': strcat(result, "\\f"); break;
case '\n': strcat(result, "\\n"); break;
case '\r': strcat(result, "\\r"); break;
case '\t': strcat(result, "\\t"); break;
case '\x1b': strcat(result, "\\u001b"); break;
default: strncat(result, &string[i], 1); break;
}
++string;
}

return result;
Expand Down
4 changes: 2 additions & 2 deletions test/fixtures/output.js
@@ -1,4 +1,4 @@
for (var i = 0; i < 1024; i++) {
process.stdout.write('Hello, stdout!\n');
process.stderr.write('Hello, stderr!\n');
process.stdout.write('Hello, \x1B[32mstdout\x1B[39m!\n');
process.stderr.write('Hello, \x1B[31mstderr\x1B[39m!\n');
}
4 changes: 2 additions & 2 deletions test/logs-test.js
Expand Up @@ -18,8 +18,8 @@ var server = net.createServer(cb(function (socket) {
if (chunk && chunk.service.indexOf('logs/') === 0) {
service[chunk.service] += chunk.description.split('\n').filter(Boolean).length;
assert(chunk.description.match(chunk.service === 'logs/stdout'
? /Hello, stdout!\n/
: /Hello, stderr!\n/
? /Hello, \x1b\[32mstdout\x1b\[39m!\n/
: /Hello, \x1b\[31mstderr\x1b\[39m!\n/
));
}
}));
Expand Down

0 comments on commit 586ea84

Please sign in to comment.