Created
March 4, 2012 04:17
-
-
Save pcostesi/1970637 to your computer and use it in GitHub Desktop.
Toy implementation of netstrings
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 <ctype.h> | |
#define MAX_BYTES 1 << 24 | |
int | |
read_netstring(char * buffer, size_t limit, FILE * f){ | |
size_t msgSize = 0; | |
size_t readSize = 0; | |
int c = 0; | |
/* read header (and at most MAX_BYTES - 1 bytes later) */ | |
while ((c = fgetc(f)) != EOF && msgSize < MAX_BYTES){ | |
/* We've got a malformed message and this channel can no longer be | |
trusted, so we just discard everything. */ | |
if (!isdigit(c) && c != ':'){ | |
return EOF; | |
} | |
msgSize += (char)c - '0'; | |
} | |
limit = limit < MAX_BYTES? limit : MAX_BYTES; | |
if (msgSize > limit){ | |
return EOF; | |
} | |
/* consume the rest of the message */ | |
readSize = (int)fread((void *) buffer, sizeof(char), msgSize, f); | |
if (readSize < msgSize){ | |
return EOF; | |
} | |
/* consume the string indicator (optional) */ | |
c = fgetc(f); | |
if (c != ',' && c != EOF){ | |
ungetc(c, f); | |
} | |
return readSize; | |
} | |
int | |
write_netstring(char * buffer, size_t limit, FILE * f){ | |
int header = 0; | |
int body = 0; | |
if (limit > MAX_BYTES - 1){ | |
return EOF; | |
} | |
if ((header = fprintf(f, "%d:", (int)limit)) < 0){ | |
return EOF; | |
} | |
if ((body = fwrite((void *) buffer, sizeof(char), limit, f)) < limit){ | |
return EOF; | |
} | |
if (fputc(',', f) == EOF){ | |
return EOF; | |
} | |
return header + body + 1; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment