leevis.com
leevis.com copied to clipboard
Hyperscan 学习
概述
Hyperscan是Intel开发的正则表达式匹配库,基于X86平台以PCRE为原型而开发的。以BSD协议开源。通常被用于网络防护上。
代码:https://github.com/intel/hyperscan 例子:https://github.com/intel/hyperscan/blob/develop/examples/simplegrep.c 文档:http://intel.github.io/hyperscan/dev-reference/ 相关介绍:https://www.sdnlab.com/18773.html
安装
macOSX: 直接brew install hyperscan
~ brew list hyperscan
/usr/local/Cellar/hyperscan/5.0.0/include/hs/ (4 files)
/usr/local/Cellar/hyperscan/5.0.0/lib/libhs.5.0.0.dylib
/usr/local/Cellar/hyperscan/5.0.0/lib/libhs_runtime.5.0.0.dylib
/usr/local/Cellar/hyperscan/5.0.0/lib/pkgconfig/libhs.pc
/usr/local/Cellar/hyperscan/5.0.0/lib/ (6 other files)
/usr/local/Cellar/hyperscan/5.0.0/share/doc/ (4 files)
例子
- 输出hs版本
#include <stdio.h>
#include <hs/hs.h>
int main(void)
{
const char *version = hs_version();
fprintf(stderr, "hs version: %s\n", version);
hs_error_t err = hs_valid_platform();
if (err == HS_ARCH_ERROR) {
fprintf(stderr, "%s\n", "the system does not support Hyperscan");
return -1;
}
return 0;
}
#include <stdio.h>
#include <string.h>
#include <hs/hs.h>
#include <hs/hs_runtime.h>
int eventHandler(unsigned int id, unsigned long long from, unsigned long long to, unsigned int flags, void *context) {
fprintf(stderr, "%u:%llu:%llu:%u\n", id, from, to, flags);
*((int*)context) = 1;
return 0;
}
int main(void)
{
const char *version = hs_version();
fprintf(stderr, "hs version: %s\n", version);
hs_error_t err = hs_valid_platform();
if (err == HS_ARCH_ERROR) {
fprintf(stderr, "%s\n", "the system does not support Hyperscan");
return -1;
}
const char *expression = "abc{1,3}";
hs_database_t *db = NULL;
hs_compile_error_t *error = NULL;
hs_scratch_t *scratch = NULL;
err = hs_compile(expression,
HS_FLAG_DOTALL,
HS_MODE_BLOCK, NULL, &db, &error);
if (err != HS_SUCCESS) {
fprintf(stderr, "hs_compile error. %d:%s\n", error->expression, error->message);
hs_free_compile_error(error);
return -1;
}
err = hs_alloc_scratch(db, &scratch);
if (err != HS_SUCCESS) {
hs_free_database(db);
fprintf(stderr, "hs_alloc_scratch error. %d\n", err);
return -1;
}
const char *data = "xfdafabccfdaf";
int xx = 0;
err = hs_scan(db, data, strlen(data), 0, scratch, eventHandler, &xx);
if (err != HS_SUCCESS) {
fprintf(stderr, "hs_scan error. %d\n", err);
return -1;
}
fprintf(stderr, "%d\n", xx);
hs_free_database(db);
hs_free_scratch(scratch);
return 0;
}
编译:gcc -o test test.c -lhs
执行:
~ ./test
hs version: 5.0.0 2018-07-09