Skip to content

Instantly share code, notes, and snippets.

@zzl0
Created October 8, 2015 16:29
Show Gist options
  • Save zzl0/7f39e7e74ae4fbc3afbb to your computer and use it in GitHub Desktop.
Save zzl0/7f39e7e74ae4fbc3afbb to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#define METRIC_BUFSIZ 8192
int
clean_metric(char *metric, char *allowed_chars) {
char cleaned_metric[METRIC_BUFSIZ];
char *p, *q, *lastnl;
char *firstspace = NULL;
q = cleaned_metric;
for (p = metric; *p != '\0'; p++) {
if (*p == '\n' || *p == '\r') {
/* end of metric */
lastnl = p;
/* just a newline on its own? some random garbage? skip */
if (q == cleaned_metric || firstspace == NULL) {
q = cleaned_metric;
firstspace = NULL;
continue;
}
*q++ = '\n';
*q = '\0'; /* can do this because we substract one from buf */
return strcmp(cleaned_metric, metric);
} else if (*p == ' ' || *p == '\t' || *p == '.') {
/* separator */
if (q == cleaned_metric) {
/* make sure we skip this on next iteration to
* avoid an infinite loop, issues #8 and #51 */
lastnl = p;
continue;
}
if (*p == '\t')
*p = ' ';
if (*p == ' ' && firstspace == NULL) {
if (*(q - 1) == '.')
q--; /* strip trailing separator */
firstspace = q;
*q++ = ' ';
} else {
/* metric_path separator or space,
* - duplicate elimination
* - don't start with separator/space */
if (*(q - 1) != *p && (q - 1) != firstspace)
*q++ = *p;
}
} else if (firstspace != NULL ||
(*p >= 'a' && *p <= 'z') ||
(*p >= 'A' && *p <= 'Z') ||
(*p >= '0' && *p <= '9') ||
strchr(allowed_chars, *p)) {
/* copy char */
*q++ = *p;
} else {
/* something barf, replace by underscore */
*q++ = '_';
}
}
return 1;
}
int
main(int argc, char **argv) {
if (argc < 2) {
printf("Usage: ./a.out <metric_file>\n");
return 1;
}
char *metric_file = argv[1];
char metric[METRIC_BUFSIZ];
char metric_name[METRIC_BUFSIZ];
char *allowed_chars = "-_:#";
FILE *fp = fopen(metric_file, "r");
while (fgets(metric_name, METRIC_BUFSIZ, fp) != NULL) {
int size = strlen(metric_name);
metric_name[size - 1] = '\0'; /* strip trailing '\n' */
snprintf(metric, METRIC_BUFSIZ, "%s %d %d\n", metric_name, 123, 1444320007);
if (clean_metric(metric, allowed_chars) != 0) {
printf("metric=%s\n", metric);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment