Ragel is a State Machine Compiler that supports generating code from Ragel’s regular expressions. Ragel provides code generation for C, C++, Objective-C, D, Java, and Ruby. Regular expressions and finite automata can be used in protocol analysis, data parsing, lexical analysis, and input validation. Implementing Ragel’s C code is very easy. Here is an atoi implementation for C’s standard library. It is several times faster than C standard library’s implementation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
/* * Convert a string to an integer. */ #include <stdlib.h> #include <string.h> #include <stdio.h> %%{ machine atoi; write data; }%% long long atoi( char *str ) { char *p = str, *pe = str + strlen( str ); int cs; long long val = 0; bool neg = false; %%{ action see_neg { neg = true; } action add_digit { val = val * 10 + (fc - '0'); } main := ( '-'@see_neg | '+' )? ( digit @add_digit )+ 'n'; # Initialize and execute. write init; write exec; }%% if ( neg ) val = -1 * val; if ( cs < atoi_first_final ) fprintf( stderr, "atoi: there was an errorn" ); return val; }; #define BUFSIZE 1024 int main() { char buf[BUFSIZE]; while ( fgets( buf, sizeof(buf), stdin ) != 0 ) { long long value = atoi( buf ); printf( "%lldn", value ); } return 0; } |