Last active
December 3, 2020 11:24
-
-
Save nkoneko/debd5927599f43f7c7cf869650e76438 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <time.h> | |
#include <unistd.h> | |
#include <sys/types.h> | |
#include <sys/event.h> | |
#include <ctype.h> | |
struct ReaderState { | |
int initialized; | |
int isInStr; | |
unsigned int depth; | |
}; | |
int convert(struct ReaderState *state, char *buffer, ssize_t lenRBytes, char *destBuffer, ssize_t *lenWBytes) { | |
unsigned int curr = 0, oseek = 0; | |
if (!state->initialized) { | |
if (buffer[0] == '[') { | |
state->initialized = 1; | |
curr++; | |
} else { | |
return 0; | |
} | |
} | |
while (curr < lenRBytes) { | |
if (!state->isInStr) { | |
if (buffer[curr] == '{') { | |
state->depth++; | |
} else if (buffer[curr] == '}') { | |
state->depth--; | |
} else if (buffer[curr] == '"' && (curr == 0 || buffer[curr - 1] != '\\')) { | |
state->isInStr = 1; | |
} | |
if (buffer[curr] == ',' && (curr == 0 || buffer[curr - 1] == '}') && state->depth == 0) { | |
destBuffer[oseek++] = '\n'; | |
} else if (buffer[curr] != ' ' && buffer[curr] != '\n' && buffer[curr] != '\t') { | |
destBuffer[oseek++] = buffer[curr]; | |
} | |
} else { | |
if (buffer[curr] == '"' && (curr == 0 || buffer[curr - 1] != '\\')) { | |
state->isInStr = 0; | |
} | |
if (buffer[curr] == '\n') { | |
destBuffer[oseek++] = '\\'; | |
destBuffer[oseek++] = 'n'; | |
} else { | |
destBuffer[oseek++] = buffer[curr]; | |
} | |
} | |
curr++; | |
} | |
*lenWBytes = oseek; | |
return 1; | |
} | |
int main(int argc, char *argv[]) { | |
struct ReaderState state = { 0, 0, 0 }; | |
struct kevent kEvent1, kEvent2; | |
char buffer[4096], destBuffer[4096]; | |
int fd = fileno(stdin), ofd = fileno(stdout); | |
int kq = kqueue(); | |
EV_SET(&kEvent1, fd, EVFILT_READ, EV_ADD, 0, 0, NULL); | |
kevent(kq, &kEvent1, 1, NULL, 0, NULL); | |
while (1) { | |
int ret = kevent(kq, NULL, 0, &kEvent2, 1, NULL); | |
if (ret == -1) { | |
fprintf(stderr, "kevent error"); | |
} | |
ssize_t readBytesLen = read(fd, buffer, sizeof(buffer)); | |
ssize_t writeBytesLen; | |
if (readBytesLen== 0) { | |
break; | |
} else if (readBytesLen== -1) { | |
fprintf(stderr, "IO error. (read)\n"); | |
} | |
if (convert(&state, buffer, readBytesLen, destBuffer, &writeBytesLen)) { | |
write(ofd, destBuffer, writeBytesLen); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment