Skip to content

Instantly share code, notes, and snippets.

@pcostesi
Created March 4, 2012 04:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pcostesi/1970637 to your computer and use it in GitHub Desktop.
Save pcostesi/1970637 to your computer and use it in GitHub Desktop.
Toy implementation of netstrings
#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