Skip to content

Instantly share code, notes, and snippets.

@rofl0r

rofl0r/ragel_test.rl Secret

Created Oct 16, 2020
Embed
What would you like to do?
#include <assert.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
static const uint64_t ERROR = ~0lu;
struct match {
size_t so, eo;
};
#define YYMAXNMATCH 32
%%{
machine foo;
action A {
matches[nmatches++].so = p-start;
}
action E {
for(int i = nmatches-1; i>=0; --i) if(!defined[i]) {
matches[i].eo = p-start;
defined[i] = 1;
break;
}
}
main := [ \t]*[ \t]+(((((([0-9]{1,3}) >A %E [.]){3} >A %E [0-9]{1,3}) >A %E ([/][0-9]+){0,1} >A %E ) >A %E |(((([0-9a-f:]{2,39}) >A %E ) >A %E |(([0-9a-f:]{0,29}[:]((([0-9]{1,3}) >A %E [.]){3} >A %E [0-9]{1,3}) >A %E ) >A %E ) >A %E ) >A %E ([/][0-9]+){0,1} >A %E ) >A %E ) >A %E |([a-z0-9._]+) >A %E ) >A %E [ \t\n]* ;
}%%
static int lex(const char *p, struct match matches[])
{
const char *start = p, *pe = p + strlen(p), *eof = pe;
size_t cs;
char defined[YYMAXNMATCH] = {0};
size_t nmatches = 0;
%% write data;
%% write init;
%% write exec;
if(cs < %%{ write first_final; }%% ) return -1;
else return nmatches;
}
char* display_match(const char* s, struct match matches[], int mno) {
static char buf[1024];
snprintf(buf, sizeof buf, "%.*s", (int)(matches[mno].eo - matches[mno].so), s+matches[mno].so);
return buf;
}
#include <regex.h>
int main()
{
struct match matches[YYMAXNMATCH];
const char *expr = " 127.0.0.1/24";
int mno = lex(expr, matches);
if(mno == -1) {
fprintf(stderr, "fail\n");
return 1;
} else {
printf("n matches: %d\n", mno);
for(int i=0; i< mno; ++i)
printf("%s\n", display_match(expr, matches, i));
}
return mno;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment