Ragel状态机生成器

Ragel可以把正则表达式翻译成有限状态机(FA)的各种语言表示,包括C、C++、Objective-C、D、Java和Ruby。Regular Expression和FA的用途很广,可以用于协议分析、数据解析、词法分析、用户数据校验等。在Ragel的帮助下,写一个atoi的函数非常容易,而且比标准库提供的atoi函数性能要高。

/*
 * Convert a string to an integer.
 */
 
#include <stdio.h>
#include <stdlib.h>
#include <string.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 &lt; atoi_first_final )
		fprintf( stderr, "atoi: there was an error\n" );
 
	return val;
};
 
#define BUFSIZE 1024
 
int main()
{
	char buf[BUFSIZE];
	while ( fgets( buf, sizeof(buf), stdin ) != 0 ) {
		long long value = atoi( buf );
		printf( "%lld\n", value );
	}
	return 0;
}

Comment (1)

  1. wayne wrote::

    挺有意思的东西, 研究一下
    PS: 新主题不错

    Thursday, December 4, 2008 at 1:07 pm #

Supported by Webinit Consulting