Skip to content

Instantly share code, notes, and snippets.

@oseiskar
Created May 31, 2020 18:41
Show Gist options
  • Save oseiskar/d06b37bf98558b6845164156c7ac27fb to your computer and use it in GitHub Desktop.
Save oseiskar/d06b37bf98558b6845164156c7ac27fb to your computer and use it in GitHub Desktop.
Decodes "varint-delimited" protocol buffer messages and wraps them into a normal protocol buffer repeated message container with tag 1
#include <stdio.h>
static int convertHeaderAndGetLength(FILE *in, FILE *out, int typedTag) {
int value = 0;
int bitshift = 0;
int first = 1;
while (1) {
int byte = fgetc(in);
if (byte == EOF) {
if (!first) fprintf(stderr, "unexpected EOF on length read\n");
return -1;
}
if (first) {
if (byte > 0) {
fputc(typedTag, out);
first = 0;
} else {
fprintf(stderr, "empty chunk!\n");
return 0;
}
}
fputc(byte, out);
value = value | ((byte & 0x7f) << bitshift);
bitshift += 7;
if ((byte & 0x80) == 0) return value;
}
}
int main() {
const int TAG = 0xa; // wire type = buffer/string, tag = 1
int length, i;
while ((length = convertHeaderAndGetLength(stdin, stdout, TAG)) != -1) {
fprintf(stderr, "length %d\n", length);
for (i = 0; i < length; ++i) {
int b = fgetc(stdin);
if (b == EOF) {
fprintf(stderr, "unexpected EOF!\n");
break;
}
fputc(b, stdout);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment